blade-code 0.10.185 → 0.10.187

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-yhxjr3xd.js → chunk-0dsqjvg8.js} +1 -1
  3. package/dist/{chunk-y6zhrc3p.js → chunk-0gwf5gkf.js} +1 -1
  4. package/dist/{chunk-r0c46wjn.js → chunk-0x87kf3z.js} +1 -1
  5. package/dist/{chunk-r12j677w.js → chunk-17pbcdyk.js} +1 -1
  6. package/dist/{chunk-va15gerc.js → chunk-1h19j4h5.js} +1 -1
  7. package/dist/{chunk-8jbt21qv.js → chunk-1s51njkf.js} +1 -1
  8. package/dist/{chunk-v9fm0jk4.js → chunk-2x0z6tm0.js} +1 -1
  9. package/dist/{chunk-z3dadjwb.js → chunk-5te08d1r.js} +1 -1
  10. package/dist/{chunk-bs5fh600.js → chunk-67xepbbh.js} +1 -1
  11. package/dist/{chunk-y8qs0rys.js → chunk-7z0ah4z0.js} +1 -1
  12. package/dist/chunk-a1379svb.js +1 -0
  13. package/dist/{chunk-qw1ktyac.js → chunk-a9qm5jtz.js} +17 -17
  14. package/dist/{chunk-4c8q1dbe.js → chunk-aazwy1r8.js} +1 -1
  15. package/dist/{chunk-by2txwsv.js → chunk-azbwg9vk.js} +1 -1
  16. package/dist/{chunk-6vxwjck7.js → chunk-b5s67sc5.js} +1 -1
  17. package/dist/{chunk-wz5ewfe2.js → chunk-bfjp7za5.js} +1 -1
  18. package/dist/{chunk-1zx3pb13.js → chunk-cbqmf0vm.js} +1 -1
  19. package/dist/{chunk-rc136hks.js → chunk-cprb73sh.js} +1 -1
  20. package/dist/{chunk-wr1m9dr0.js → chunk-dd5jptem.js} +1 -1
  21. package/dist/{chunk-hn0p92n5.js → chunk-dgx8b825.js} +1 -1
  22. package/dist/{chunk-qpjppna7.js → chunk-dqfwgj7g.js} +1 -1
  23. package/dist/{chunk-eb93bmdq.js → chunk-dszeb34b.js} +1 -1
  24. package/dist/{chunk-e3r2zfct.js → chunk-ewaw877d.js} +1 -1
  25. package/dist/chunk-fpdb3a5z.js +1 -0
  26. package/dist/{chunk-vq1gmwap.js → chunk-fv86z092.js} +2 -2
  27. package/dist/{chunk-7gya2kat.js → chunk-hwyqk6bh.js} +1 -1
  28. package/dist/{chunk-jjj852tg.js → chunk-j14160j3.js} +1 -1
  29. package/dist/{chunk-m2gh9f07.js → chunk-jwb09kyr.js} +3 -3
  30. package/dist/{chunk-mtz7g64v.js → chunk-m6bz8fh9.js} +1 -1
  31. package/dist/{chunk-kpm2hztn.js → chunk-n3z4hr06.js} +1 -1
  32. package/dist/{chunk-p9rx0a48.js → chunk-r2qv7nx5.js} +45 -45
  33. package/dist/{chunk-ne2pax68.js → chunk-t8xynv04.js} +1 -1
  34. package/dist/{chunk-tej54yg9.js → chunk-te08f57k.js} +1 -1
  35. package/dist/{chunk-wbbeb520.js → chunk-vn9x5zs8.js} +1 -1
  36. package/dist/{chunk-1nkczacx.js → chunk-wcrxh6rm.js} +1 -1
  37. package/dist/{chunk-cbctk8hh.js → chunk-xjvq4ee8.js} +1 -1
  38. package/dist/{chunk-9fqzj0gd.js → chunk-xk938s1h.js} +2 -2
  39. package/dist/{chunk-j1xkhc0r.js → chunk-zacyth0b.js} +1 -1
  40. package/dist/web/assets/{ChatView-BX7rb06X.js → ChatView-DYA3np_l.js} +4 -4
  41. package/dist/web/assets/{CodeBlockHighlighter-CX2mKmrg.js → CodeBlockHighlighter-B9sgXWAy.js} +1 -1
  42. package/dist/web/assets/{FilePreview-SPp4ITBA.js → FilePreview-PKalr8bi.js} +1 -1
  43. package/dist/web/assets/{KanbanBoard-U3BgVhg1.js → KanbanBoard-GjH7MyZk.js} +1 -1
  44. package/dist/web/assets/{MarkdownRenderer-EJcCwZWz.js → MarkdownRenderer-C03DrI8Q.js} +3 -3
  45. package/dist/web/assets/{ScrollArea-DBEk2glU.js → ScrollArea-CbOr9e7X.js} +1 -1
  46. package/dist/web/assets/{SessionHistorySurface-Ddoyjhed.js → SessionHistorySurface-BZEOUN2M.js} +1 -1
  47. package/dist/web/assets/{SettingsModal-Xswk4roW.js → SettingsModal-DAMGwO-E.js} +1 -1
  48. package/dist/web/assets/{Sidebar-gk-K-Uxx.js → Sidebar-CiCsK7EK.js} +1 -1
  49. package/dist/web/assets/{TaskSwitcher-DVClRGkP.js → TaskSwitcher-BLdgv--U.js} +1 -1
  50. package/dist/web/assets/{TerminalPanel-C0Q00yTZ.js → TerminalPanel-uctuzvle.js} +1 -1
  51. package/dist/web/assets/{archive-AaV6lNva.js → archive-BHntc9gt.js} +1 -1
  52. package/dist/web/assets/{arrow-left-BlbtLILw.js → arrow-left-DkXe02NZ.js} +1 -1
  53. package/dist/web/assets/{calendar-clock-CPHb2snw.js → calendar-clock-_-EyQ_16.js} +1 -1
  54. package/dist/web/assets/{chevron-right-DUiFY332.js → chevron-right-DXuaFbE2.js} +1 -1
  55. package/dist/web/assets/{clock-3-D0a2jix4.js → clock-3-DHOWUt-Y.js} +1 -1
  56. package/dist/web/assets/{copy-n9ov0sVM.js → copy-wCV3sjrM.js} +1 -1
  57. package/dist/web/assets/{download-Cn1EYGIT.js → download-CEXHgQhj.js} +1 -1
  58. package/dist/web/assets/{external-link-fVfC-V3I.js → external-link-D5pUXtvQ.js} +1 -1
  59. package/dist/web/assets/{folder-CLpRtdCV.js → folder-Bm-uBrFM.js} +1 -1
  60. package/dist/web/assets/{index-C9QDf8IR.js → index-E1WG_htm.js} +3 -3
  61. package/dist/web/assets/{message-square-plus-OPQt-NKJ.js → message-square-plus-ChP8ZEgZ.js} +1 -1
  62. package/dist/web/assets/{pause-Da64_5n8.js → pause-D8MeccMe.js} +1 -1
  63. package/dist/web/assets/{pencil-BvhxypSH.js → pencil-DNEy8lVY.js} +1 -1
  64. package/dist/web/assets/{play-DLbh_DdV.js → play-DhdTbY0j.js} +1 -1
  65. package/dist/web/assets/{plus-8MoTdKMW.js → plus-B2PxWoNi.js} +1 -1
  66. package/dist/web/assets/{settings-ubuKiw0x.js → settings-D9Kkb31b.js} +1 -1
  67. package/dist/web/assets/{team-DxQqc5vl.js → team-ktBP7cND.js} +1 -1
  68. package/dist/web/assets/{teamService-CekpUoot.js → teamService-CxPZcCrA.js} +1 -1
  69. package/dist/web/assets/{terminal-FRpir_wA.js → terminal-DcSGZkEA.js} +1 -1
  70. package/dist/web/index.html +1 -1
  71. package/package.json +1 -1
  72. package/dist/chunk-p7zf8d4f.js +0 -1
  73. package/dist/chunk-yhrset5k.js +0 -1
@@ -1,4 +1,4 @@
1
- import{e as $X,f as JX,h as S$,i as M4}from"./chunk-wr1m9dr0.js";import{l as eX,m as $Z,n as JZ}from"./chunk-e3r2zfct.js";import{A as q4,y as A9,z as b9}from"./chunk-yhxjr3xd.js";import{Aa as XY,Ca as ZY,Ea as uY,I as cY,M as WZ,O as h6,P as R6,Q as vY,W as wY,X as PY,_ as AY,da as r$,fa as y9,ga as I9,ia as bY,ka as K8,la as LX,ma as BX,pa as wX,qa as PX,ua as lJ,va as B3,xa as H3,ya as F3,za as HZ}from"./chunk-m2gh9f07.js";import"./chunk-g01mth5d.js";import{Ma as E5,Na as h5,Oa as g5,Ra as NZ}from"./chunk-1nkczacx.js";import{Ta as BY}from"./chunk-30x3mcsb.js";import{Mb as FY,Nb as F4,Zb as LY,hc as P6}from"./chunk-p9rx0a48.js";import{sc as O8}from"./chunk-zzvs471p.js";import{Cd as zY,Md as P9,Nd as h2,Rd as R9,Wd as C9,Yd as t8,ee as U8,he as a0}from"./chunk-j1xkhc0r.js";import"./chunk-53fc0yrq.js";import{Le as D9,Me as w6,Ne as f9}from"./chunk-y5wngtz0.js";import{if as e9,jf as G4}from"./chunk-w33zjw8m.js";import{wf as tX}from"./chunk-nheny8xp.js";import{Af as J1,xf as N8,yf as _4}from"./chunk-wbbeb520.js";import"./chunk-jj4ggb04.js";import{Ef as R2,Ff as L$,Gf as r1,Hf as UJ,If as o8,Jf as M9,Kf as t3,Lf as CJ,Mf as r5,Nf as s3,Of as f2,Pf as m0,Qf as _Z,Rf as B$,Sf as nX,Tf as a4,Uf as q8,Xf as s9,cg as z$}from"./chunk-qw1ktyac.js";import"./chunk-v508x7cg.js";import"./chunk-t0gm0pn1.js";import"./chunk-1yq72zb7.js";import"./chunk-kqvzmnja.js";import{ug as yJ}from"./chunk-0mr8nexh.js";import"./chunk-50vwafn5.js";import"./chunk-1zx3pb13.js";import{Hg as H4,Jg as hX,Og as FX,Xg as OZ}from"./chunk-by2txwsv.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import{xh as qJ,zh as E$}from"./chunk-cbctk8hh.js";import"./chunk-3y2x6fb6.js";import{Mi as zZ,Ri as HX,Si as qZ}from"./chunk-4c8q1dbe.js";import{Ui as h9}from"./chunk-kv458q06.js";import{Vi as g2,Wi as e8,Yi as _J}from"./chunk-5v0jcyea.js";import{bj as K$}from"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import{Aj as KZ,Dj as O1}from"./chunk-2mk914vk.js";import{Lj as t5,Mj as s5,Pj as T1}from"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import{$j as x5}from"./chunk-y8qs0rys.js";import{ck as uJ}from"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import{fk as G8,zk as t9}from"./chunk-4wx5sya5.js";import{Mk as Y4}from"./chunk-eg3ms291.js";import{useMemoizedFn as Q6}from"ahooks";import{useEffect as Gz,useState as G6}from"react";import{useMemoizedFn as i0}from"ahooks";import iX from"ansi-escapes";import{Box as h1,useStdout as eK}from"ink";import{useEffect as $1,useMemo as $z,useRef as y2,useState as oX}from"react";import{useShallow as BZ}from"zustand/react/shallow";import{useStore as LZ}from"zustand";function z0($){return LZ(f2,$)}var wZ=[],v2=()=>z0(($)=>$.session.sessionId),_1=()=>z0(($)=>$.session.workspaceRoot),v8=()=>z0(($)=>$.session.messages),rJ=()=>z0(($)=>$.session.clearCount),aJ=()=>z0(($)=>$.session.isCompacting),iJ=()=>z0(($)=>$.session.tokenUsage.estimatedCostUsd),oJ=()=>z0(($)=>{let{totalInputTokens:J,cacheReadTokens:Y,cacheWriteTokens:Z}=$.session.tokenUsage;return lJ({totalInputTokens:J,cacheReadTokens:Y,cacheWriteTokens:Z}).hitRate});var V8=()=>z0(($)=>$.session.providerRecovery),nJ=()=>z0(($)=>$.session.turnActivity),tJ=()=>z0(($)=>$.session.actionStationarity),c1=()=>z0(($)=>$.session.actions),sJ=()=>z0(($)=>{let{totalTokens:J,maxContextTokens:Y}=$.session.tokenUsage;if(Y<=0)return 100;let Z=Math.max(0,100-J/Y*100);return Math.round(Z)}),eJ=()=>z0(($)=>$.app.initializationStatus),$9=()=>z0(($)=>$.app.initializationError),j8=()=>z0(($)=>$.app.activeModal),J9=()=>z0(($)=>$.app.tasks),Y9=()=>z0(($)=>$.app.modelEditorTarget),X9=()=>z0(($)=>$.app.sessionSelectorData),Z9=()=>z0(($)=>$.app.sessionHistoryViewerData),Q9=()=>z0(($)=>$.app.taskAttentionStatus),E8=()=>z0(($)=>$.app.taskAttentionUnreadKeys),G9=()=>z0(($)=>$.app.awaitingSecondCtrlC),u1=()=>z0(($)=>$.app.actions),V2=()=>z0(($)=>$.app.sideConversation),U9=()=>z0(($)=>$.app.teams),h8=()=>z0(($)=>$.app.initializationStatus==="ready"),K9=()=>z0(($)=>$.app.tasks.length>0),j2=()=>z0(($)=>$.config.config?.permissionMode||"default"),z9=()=>z0(($)=>$.config.config?.models??wZ),g8=()=>z0(($)=>{let J=$.config.config;if(!J)return;let Y=J.currentModelId;return J.models.find((X)=>X.id===Y)??J.models[0]}),m8=()=>z0(($)=>$.config.config?.currentModelId),q9=()=>z0(($)=>$.config.config?.agentTeamsEnabled===!0),D0=()=>z0(($)=>{return L$.getTheme()}),_9=()=>z0(($)=>$.config.config?.codeTheme??"default"),Z$=()=>z0(($)=>$.focus.currentFocus),O9=()=>z0(($)=>$.focus.actions),E2=()=>z0(($)=>$.command.isProcessing),N9=()=>z0(($)=>$.command.actions),p8=()=>z0(($)=>$.app.followUpQueue),W9=()=>z0(($)=>$.app.followUpQueueMutation),H9=()=>z0(($)=>$.command.recoveredSteeringCount),x8=()=>z0(($)=>$.app.reasoningEffort!=="off"),c8=()=>z0(($)=>$.app.reasoningEffort),u8=()=>z0(($)=>$.app.serviceTier),d8=()=>z0(($)=>$.app.responseVerbosity),l8=()=>z0(($)=>$.app.communicationStyle),r8=()=>z0(($)=>$.session.currentThinkingContent),F9=()=>z0(($)=>$.session.thinkingExpanded),a8=()=>z0(($)=>$.session.currentStreamingMessageId),i8=()=>z0(BZ(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),L9=()=>z0(($)=>$.session.finalizingStreamingMessageId),B9=()=>z0(($)=>$.session.historyExpanded),w9=()=>z0(($)=>$.session.expandedMessageCount);import{randomUUID as _7}from"node:crypto";import{useMemoizedFn as Y1}from"ahooks";import{useEffect as d1,useMemo as WY,useRef as N4}from"react";function PZ($,J){try{return $.code===J.code&&$.message===J.message&&$.retryable===J.retryable&&$.resource===J.resource}catch{return!1}}class K6{options;requested=!1;waitingForIdle=!1;disposed=!1;generation=0;wakeEpoch=0;idleEpoch=0;attempt=0;recoveryStartedAt=null;scheduledToken=null;activeAttemptToken=null;activeRunController=null;retryTimer=null;deadlineTimer=null;now;scheduleCallback;setTimerCallback;clearTimerCallback;constructor($){this.options=$;this.now=$.now??Date.now,this.scheduleCallback=$.scheduleMicrotask??queueMicrotask,this.setTimerCallback=$.setTimer??setTimeout,this.clearTimerCallback=$.clearTimer??clearTimeout}request(){if(this.disposed)return;if(this.wakeEpoch++,this.requested=!0,this.waitingForIdle||this.retryTimer)return;this.scheduleIfRunnable()}notifyIdle(){if(this.disposed)return;if(this.idleEpoch++,this.retryTimer)return;this.waitingForIdle=!1,this.scheduleIfRunnable()}dispose(){if(this.disposed)return;this.disposed=!0,this.generation++,this.requested=!1,this.waitingForIdle=!1,this.scheduledToken=null,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.activeAttemptToken=null;let $=this.activeRunController;this.activeRunController=null,$?.abort("pending-resume-coordinator-disposed"),this.resetEpisodeBudget()}scheduleIfRunnable(){if(this.disposed||!this.requested||this.scheduledToken||this.activeAttemptToken||this.retryTimer||this.waitingForIdle)return;if(!this.options.canRun()){this.waitingForIdle=!0;return}let $=this.generation,J={};this.scheduledToken=J;try{this.scheduleCallback(()=>{if(this.disposed||$!==this.generation||this.scheduledToken!==J)return;this.scheduledToken=null,this.flush($).catch((Y)=>{this.handleUnexpectedFailure(Y,$)})})}catch(Y){this.handleUnexpectedFailure(Y,$)}}async flush($){if(this.disposed||$!==this.generation||this.activeAttemptToken||!this.requested||this.retryTimer||this.waitingForIdle)return;if(!this.options.canRun()){this.waitingForIdle=!0;return}let J={},Y=new AbortController,Z=this.wakeEpoch,X=this.idleEpoch;if(this.attempt++,this.recoveryStartedAt===null)this.recoveryStartedAt=this.now(),this.installDeadlineTimer($);this.activeAttemptToken=J,this.activeRunController=Y;let Q;try{Q=await this.options.run(Y.signal)}finally{if(this.activeAttemptToken===J){if(this.activeAttemptToken=null,this.activeRunController=null,!this.disposed&&$!==this.generation)this.scheduleIfRunnable()}}if(this.disposed||$!==this.generation)return;if(Q.status==="completed"){let G=this.wakeEpoch!==Z;if(this.clearEpisode(),G)this.requested=!0,this.scheduleIfRunnable();return}if(Q.status==="deferred"){if(this.attempt--,this.attempt===0)this.clearOwnedTimer("deadline"),this.resetEpisodeBudget();if(this.requested=!0,this.idleEpoch!==X)this.waitingForIdle=!1,this.scheduleIfRunnable();else this.waitingForIdle=!0;return}this.handleFailure(Q,$)}handleFailure($,J){let Y=h2($.taskFailure),Z=this.options.sessionIdentity;if($.workKind!=="pending_input"||!$.evidence||!Z||!PZ($.taskFailure,$.evidence.taskFailure)){this.terminate("failed",this.attempt,Y);return}let X=b9({sessionIdentity:Z,failedAttempt:this.attempt,recoveryStartedAt:this.recoveryStartedAt??this.now(),now:this.now(),workStillPending:$.workStillPending,evidence:$.evidence});if(X.phase!=="retry_scheduled"){this.terminate(X.phase,this.attempt,Y);return}this.requested=!0,this.waitingForIdle=!1;let Q={},G=this.setTimerCallback(()=>{if(this.disposed||J!==this.generation||this.retryTimer?.token!==Q)return;this.retryTimer=null,this.scheduleIfRunnable()},X.delayMs);this.retryTimer={handle:G,token:Q},G.unref?.()}handleUnexpectedFailure($,J){if(this.disposed||J!==this.generation)return;this.terminate("failed",Math.max(1,this.attempt),h2($),"pending-resume-coordinator-failed")}installDeadlineTimer($){let J={},Y=this.setTimerCallback(()=>{if(this.disposed||$!==this.generation||this.deadlineTimer?.token!==J)return;this.deadlineTimer=null,this.terminate("exhausted",Math.max(1,this.attempt),P9("timeout"),"pending-resume-recovery-deadline-exceeded")},A9);this.deadlineTimer={handle:Y,token:J},Y.unref?.()}terminate($,J,Y,Z){let X=this.activeRunController;if(this.generation++,this.requested=!1,this.waitingForIdle=!1,this.scheduledToken=null,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.resetEpisodeBudget(),Z)X?.abort(Z);try{this.options.onTerminalFailure?.({phase:$,attempt:J,taskFailure:Y})}catch{}}clearEpisode(){this.requested=!1,this.waitingForIdle=!1,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.resetEpisodeBudget()}resetEpisodeBudget(){this.attempt=0,this.recoveryStartedAt=null}clearOwnedTimer($){let J=$==="retry"?this.retryTimer:this.deadlineTimer;if(!J)return;if($==="retry")this.retryTimer=null;else this.deadlineTimer=null;this.clearTimerCallback(J.handle)}}class Z8{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)o8(J,$.extraContent);M9(J)}this.options.finalizeStreamingMessage($.extraContent,$.extraThinking)}}function AZ($){if(!($ instanceof Error))return"未知错误";let Z=$.lastError??$;if(Z.responseBody)try{let G=JSON.parse(Z.responseBody)?.error?.message;if(G){let U=Z.statusCode?` (HTTP ${Z.statusCode})`:"";return`${G}${U}`}}catch{}let X=$.message.match(/Last error:\s*(.+)$/);if(X)return X[1];return $.message}function bZ($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function MZ($){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 n8($){let J=bZ($),Y=MZ($),Z;if(Y)Z="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else Z=AZ($);return{displayMessage:Z,isAbort:J,isVisionNotSupported:Y}}import{appendFileSync as TZ,mkdirSync as RZ,writeFileSync as CZ}from"node:fs";import yZ from"node:os";import z6 from"node:path";var T9=null;function IZ(){let $=process.env.BLADE_STORAGE_ROOT||z6.join(yZ.homedir(),".blade");return z6.join($,"logs","stream-debug.log")}function SZ($){if(T9===$)return;let J=z6.dirname($);RZ(J,{recursive:!0,mode:493}),CZ($,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
1
+ import{e as $X,f as JX,h as S$,i as M4}from"./chunk-dd5jptem.js";import{l as eX,m as $Z,n as JZ}from"./chunk-ewaw877d.js";import{A as q4,y as A9,z as b9}from"./chunk-0dsqjvg8.js";import{Aa as XY,Ca as ZY,Ea as uY,I as cY,M as WZ,O as h6,P as R6,Q as vY,W as wY,X as PY,_ as AY,da as r$,fa as y9,ga as I9,ia as bY,ka as K8,la as LX,ma as BX,pa as wX,qa as PX,ua as lJ,va as B3,xa as H3,ya as F3,za as HZ}from"./chunk-jwb09kyr.js";import"./chunk-g01mth5d.js";import{Ma as E5,Na as h5,Oa as g5,Ra as NZ}from"./chunk-wcrxh6rm.js";import{Ta as BY}from"./chunk-30x3mcsb.js";import{Mb as FY,Nb as F4,Zb as LY,hc as P6}from"./chunk-r2qv7nx5.js";import{sc as O8}from"./chunk-zzvs471p.js";import{Cd as zY,Md as P9,Nd as h2,Rd as R9,Wd as C9,Yd as t8,ee as U8,he as a0}from"./chunk-zacyth0b.js";import"./chunk-53fc0yrq.js";import{Le as D9,Me as w6,Ne as f9}from"./chunk-y5wngtz0.js";import{if as e9,jf as G4}from"./chunk-w33zjw8m.js";import{wf as tX}from"./chunk-nheny8xp.js";import{Af as J1,xf as N8,yf as _4}from"./chunk-vn9x5zs8.js";import"./chunk-jj4ggb04.js";import{Ef as R2,Ff as L$,Gf as r1,Hf as UJ,If as o8,Jf as M9,Kf as t3,Lf as CJ,Mf as r5,Nf as s3,Of as f2,Pf as m0,Qf as _Z,Rf as B$,Sf as nX,Tf as a4,Uf as q8,Xf as s9,cg as z$}from"./chunk-a9qm5jtz.js";import"./chunk-v508x7cg.js";import"./chunk-t0gm0pn1.js";import"./chunk-1yq72zb7.js";import"./chunk-kqvzmnja.js";import{ug as yJ}from"./chunk-0mr8nexh.js";import"./chunk-50vwafn5.js";import"./chunk-cbqmf0vm.js";import{Hg as H4,Jg as hX,Og as FX,Xg as OZ}from"./chunk-azbwg9vk.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import{xh as qJ,zh as E$}from"./chunk-xjvq4ee8.js";import"./chunk-3y2x6fb6.js";import{Mi as zZ,Ri as HX,Si as qZ}from"./chunk-aazwy1r8.js";import{Ui as h9}from"./chunk-kv458q06.js";import{Vi as g2,Wi as e8,Yi as _J}from"./chunk-5v0jcyea.js";import{bj as K$}from"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import{Aj as KZ,Dj as O1}from"./chunk-2mk914vk.js";import{Lj as t5,Mj as s5,Pj as T1}from"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import{$j as x5}from"./chunk-7z0ah4z0.js";import{ck as uJ}from"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import{fk as G8,zk as t9}from"./chunk-4wx5sya5.js";import{Mk as Y4}from"./chunk-eg3ms291.js";import{useMemoizedFn as Q6}from"ahooks";import{useEffect as Gz,useState as G6}from"react";import{useMemoizedFn as i0}from"ahooks";import iX from"ansi-escapes";import{Box as h1,useStdout as eK}from"ink";import{useEffect as $1,useMemo as $z,useRef as y2,useState as oX}from"react";import{useShallow as BZ}from"zustand/react/shallow";import{useStore as LZ}from"zustand";function z0($){return LZ(f2,$)}var wZ=[],v2=()=>z0(($)=>$.session.sessionId),_1=()=>z0(($)=>$.session.workspaceRoot),v8=()=>z0(($)=>$.session.messages),rJ=()=>z0(($)=>$.session.clearCount),aJ=()=>z0(($)=>$.session.isCompacting),iJ=()=>z0(($)=>$.session.tokenUsage.estimatedCostUsd),oJ=()=>z0(($)=>{let{totalInputTokens:J,cacheReadTokens:Y,cacheWriteTokens:Z}=$.session.tokenUsage;return lJ({totalInputTokens:J,cacheReadTokens:Y,cacheWriteTokens:Z}).hitRate});var V8=()=>z0(($)=>$.session.providerRecovery),nJ=()=>z0(($)=>$.session.turnActivity),tJ=()=>z0(($)=>$.session.actionStationarity),c1=()=>z0(($)=>$.session.actions),sJ=()=>z0(($)=>{let{totalTokens:J,maxContextTokens:Y}=$.session.tokenUsage;if(Y<=0)return 100;let Z=Math.max(0,100-J/Y*100);return Math.round(Z)}),eJ=()=>z0(($)=>$.app.initializationStatus),$9=()=>z0(($)=>$.app.initializationError),j8=()=>z0(($)=>$.app.activeModal),J9=()=>z0(($)=>$.app.tasks),Y9=()=>z0(($)=>$.app.modelEditorTarget),X9=()=>z0(($)=>$.app.sessionSelectorData),Z9=()=>z0(($)=>$.app.sessionHistoryViewerData),Q9=()=>z0(($)=>$.app.taskAttentionStatus),E8=()=>z0(($)=>$.app.taskAttentionUnreadKeys),G9=()=>z0(($)=>$.app.awaitingSecondCtrlC),u1=()=>z0(($)=>$.app.actions),V2=()=>z0(($)=>$.app.sideConversation),U9=()=>z0(($)=>$.app.teams),h8=()=>z0(($)=>$.app.initializationStatus==="ready"),K9=()=>z0(($)=>$.app.tasks.length>0),j2=()=>z0(($)=>$.config.config?.permissionMode||"default"),z9=()=>z0(($)=>$.config.config?.models??wZ),g8=()=>z0(($)=>{let J=$.config.config;if(!J)return;let Y=J.currentModelId;return J.models.find((X)=>X.id===Y)??J.models[0]}),m8=()=>z0(($)=>$.config.config?.currentModelId),q9=()=>z0(($)=>$.config.config?.agentTeamsEnabled===!0),D0=()=>z0(($)=>{return L$.getTheme()}),_9=()=>z0(($)=>$.config.config?.codeTheme??"default"),Z$=()=>z0(($)=>$.focus.currentFocus),O9=()=>z0(($)=>$.focus.actions),E2=()=>z0(($)=>$.command.isProcessing),N9=()=>z0(($)=>$.command.actions),p8=()=>z0(($)=>$.app.followUpQueue),W9=()=>z0(($)=>$.app.followUpQueueMutation),H9=()=>z0(($)=>$.command.recoveredSteeringCount),x8=()=>z0(($)=>$.app.reasoningEffort!=="off"),c8=()=>z0(($)=>$.app.reasoningEffort),u8=()=>z0(($)=>$.app.serviceTier),d8=()=>z0(($)=>$.app.responseVerbosity),l8=()=>z0(($)=>$.app.communicationStyle),r8=()=>z0(($)=>$.session.currentThinkingContent),F9=()=>z0(($)=>$.session.thinkingExpanded),a8=()=>z0(($)=>$.session.currentStreamingMessageId),i8=()=>z0(BZ(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),L9=()=>z0(($)=>$.session.finalizingStreamingMessageId),B9=()=>z0(($)=>$.session.historyExpanded),w9=()=>z0(($)=>$.session.expandedMessageCount);import{randomUUID as _7}from"node:crypto";import{useMemoizedFn as Y1}from"ahooks";import{useEffect as d1,useMemo as WY,useRef as N4}from"react";function PZ($,J){try{return $.code===J.code&&$.message===J.message&&$.retryable===J.retryable&&$.resource===J.resource}catch{return!1}}class K6{options;requested=!1;waitingForIdle=!1;disposed=!1;generation=0;wakeEpoch=0;idleEpoch=0;attempt=0;recoveryStartedAt=null;scheduledToken=null;activeAttemptToken=null;activeRunController=null;retryTimer=null;deadlineTimer=null;now;scheduleCallback;setTimerCallback;clearTimerCallback;constructor($){this.options=$;this.now=$.now??Date.now,this.scheduleCallback=$.scheduleMicrotask??queueMicrotask,this.setTimerCallback=$.setTimer??setTimeout,this.clearTimerCallback=$.clearTimer??clearTimeout}request(){if(this.disposed)return;if(this.wakeEpoch++,this.requested=!0,this.waitingForIdle||this.retryTimer)return;this.scheduleIfRunnable()}notifyIdle(){if(this.disposed)return;if(this.idleEpoch++,this.retryTimer)return;this.waitingForIdle=!1,this.scheduleIfRunnable()}dispose(){if(this.disposed)return;this.disposed=!0,this.generation++,this.requested=!1,this.waitingForIdle=!1,this.scheduledToken=null,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.activeAttemptToken=null;let $=this.activeRunController;this.activeRunController=null,$?.abort("pending-resume-coordinator-disposed"),this.resetEpisodeBudget()}scheduleIfRunnable(){if(this.disposed||!this.requested||this.scheduledToken||this.activeAttemptToken||this.retryTimer||this.waitingForIdle)return;if(!this.options.canRun()){this.waitingForIdle=!0;return}let $=this.generation,J={};this.scheduledToken=J;try{this.scheduleCallback(()=>{if(this.disposed||$!==this.generation||this.scheduledToken!==J)return;this.scheduledToken=null,this.flush($).catch((Y)=>{this.handleUnexpectedFailure(Y,$)})})}catch(Y){this.handleUnexpectedFailure(Y,$)}}async flush($){if(this.disposed||$!==this.generation||this.activeAttemptToken||!this.requested||this.retryTimer||this.waitingForIdle)return;if(!this.options.canRun()){this.waitingForIdle=!0;return}let J={},Y=new AbortController,Z=this.wakeEpoch,X=this.idleEpoch;if(this.attempt++,this.recoveryStartedAt===null)this.recoveryStartedAt=this.now(),this.installDeadlineTimer($);this.activeAttemptToken=J,this.activeRunController=Y;let Q;try{Q=await this.options.run(Y.signal)}finally{if(this.activeAttemptToken===J){if(this.activeAttemptToken=null,this.activeRunController=null,!this.disposed&&$!==this.generation)this.scheduleIfRunnable()}}if(this.disposed||$!==this.generation)return;if(Q.status==="completed"){let G=this.wakeEpoch!==Z;if(this.clearEpisode(),G)this.requested=!0,this.scheduleIfRunnable();return}if(Q.status==="deferred"){if(this.attempt--,this.attempt===0)this.clearOwnedTimer("deadline"),this.resetEpisodeBudget();if(this.requested=!0,this.idleEpoch!==X)this.waitingForIdle=!1,this.scheduleIfRunnable();else this.waitingForIdle=!0;return}this.handleFailure(Q,$)}handleFailure($,J){let Y=h2($.taskFailure),Z=this.options.sessionIdentity;if($.workKind!=="pending_input"||!$.evidence||!Z||!PZ($.taskFailure,$.evidence.taskFailure)){this.terminate("failed",this.attempt,Y);return}let X=b9({sessionIdentity:Z,failedAttempt:this.attempt,recoveryStartedAt:this.recoveryStartedAt??this.now(),now:this.now(),workStillPending:$.workStillPending,evidence:$.evidence});if(X.phase!=="retry_scheduled"){this.terminate(X.phase,this.attempt,Y);return}this.requested=!0,this.waitingForIdle=!1;let Q={},G=this.setTimerCallback(()=>{if(this.disposed||J!==this.generation||this.retryTimer?.token!==Q)return;this.retryTimer=null,this.scheduleIfRunnable()},X.delayMs);this.retryTimer={handle:G,token:Q},G.unref?.()}handleUnexpectedFailure($,J){if(this.disposed||J!==this.generation)return;this.terminate("failed",Math.max(1,this.attempt),h2($),"pending-resume-coordinator-failed")}installDeadlineTimer($){let J={},Y=this.setTimerCallback(()=>{if(this.disposed||$!==this.generation||this.deadlineTimer?.token!==J)return;this.deadlineTimer=null,this.terminate("exhausted",Math.max(1,this.attempt),P9("timeout"),"pending-resume-recovery-deadline-exceeded")},A9);this.deadlineTimer={handle:Y,token:J},Y.unref?.()}terminate($,J,Y,Z){let X=this.activeRunController;if(this.generation++,this.requested=!1,this.waitingForIdle=!1,this.scheduledToken=null,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.resetEpisodeBudget(),Z)X?.abort(Z);try{this.options.onTerminalFailure?.({phase:$,attempt:J,taskFailure:Y})}catch{}}clearEpisode(){this.requested=!1,this.waitingForIdle=!1,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.resetEpisodeBudget()}resetEpisodeBudget(){this.attempt=0,this.recoveryStartedAt=null}clearOwnedTimer($){let J=$==="retry"?this.retryTimer:this.deadlineTimer;if(!J)return;if($==="retry")this.retryTimer=null;else this.deadlineTimer=null;this.clearTimerCallback(J.handle)}}class Z8{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)o8(J,$.extraContent);M9(J)}this.options.finalizeStreamingMessage($.extraContent,$.extraThinking)}}function AZ($){if(!($ instanceof Error))return"未知错误";let Z=$.lastError??$;if(Z.responseBody)try{let G=JSON.parse(Z.responseBody)?.error?.message;if(G){let U=Z.statusCode?` (HTTP ${Z.statusCode})`:"";return`${G}${U}`}}catch{}let X=$.message.match(/Last error:\s*(.+)$/);if(X)return X[1];return $.message}function bZ($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function MZ($){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 n8($){let J=bZ($),Y=MZ($),Z;if(Y)Z="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else Z=AZ($);return{displayMessage:Z,isAbort:J,isVisionNotSupported:Y}}import{appendFileSync as TZ,mkdirSync as RZ,writeFileSync as CZ}from"node:fs";import yZ from"node:os";import z6 from"node:path";var T9=null;function IZ(){let $=process.env.BLADE_STORAGE_ROOT||z6.join(yZ.homedir(),".blade");return z6.join($,"logs","stream-debug.log")}function SZ($){if(T9===$)return;let J=z6.dirname($);RZ(J,{recursive:!0,mode:493}),CZ($,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
2
2
  `),T9=$}function q6($,J,Y){try{let Z=IZ();SZ(Z);let X=new Date().toISOString(),Q=Y?` | ${JSON.stringify(Y)}`:"",G=`[${X}] [${$}] ${J}${Q}
3
3
  `;TZ(Z,G)}catch{}}var Q8=O1("UI");function _6($,J){if(J.state==="requires_attention"){let Y=J.reason==="interrupted_tool_call";$.addToolMessage("Turn recovery requires attention",{toolName:"Runtime Recovery",phase:"complete",summary:Y?"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 S9($,J){let Y=$.streamSession??new Z8({signal:$.signal,streamingBuffer:$.streamingBuffer,getStreamingMessageId:$.getStreamingMessageId,finalizeStreamingMessage:$.sessionActions.finalizeStreamingMessage,discardStreamingMessage:$.sessionActions.discardStreamingMessage,clearThinking:()=>$.sessionActions.setCurrentThinkingContent(null)}),Z=(X)=>{for(let Q of X){if((Q.origin??"user")!=="user")continue;let G=$.commandActions.takeFollowUpPresentation(Q.id);if(G){$.sessionActions.addUserMessage(G.displayText);continue}if(!Q.recovered||Q.persisted)continue;let U=typeof Q.content==="string"?Q.content:Q.content.map((z)=>z.type==="text"?z.text:"[Image]").join(`
4
4
  `);$.sessionActions.addUserMessage(U)}};return(X)=>{switch(X.kind){case"content_delta":if(X.delta.length>0)J.outputStarted=!0;if(!Y.acceptsDeltas())break;J.contentDeltaCount++,J.contentDeltaTotalLen+=X.delta.length,q6("loopEventHandler","onContentDelta",{callCount:J.contentDeltaCount,deltaLen:X.delta.length,totalLen:J.contentDeltaTotalLen}),$.streamingBuffer.batchAppendContent(X.delta);break;case"thinking_delta":if(X.delta.length>0)J.outputStarted=!0;if(!Y.acceptsDeltas())break;if($.thinkingModeEnabled)$.streamingBuffer.batchAppendThinking(X.delta);break;case"stream_end":{$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),Q8.debug("[loopEventHandler] stream_end",{contentDeltaCount:J.contentDeltaCount,contentDeltaTotalLen:J.contentDeltaTotalLen,streamFinalized:Y.isFinalized,signalAborted:$.signal.aborted}),q6("loopEventHandler","onStreamEnd",{contentDeltaCallCount:J.contentDeltaCount,contentDeltaTotalLen:J.contentDeltaTotalLen,streamFinalized:Y.isFinalized,signalAborted:$.signal.aborted}),Y.finalize();break}case"model_fallback":$.sessionActions.setProviderAdmission(null),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),Y.discard();break;case"provider_admission":{let{kind:Q,...G}=X;$.sessionActions.setProviderAdmission(X.phase==="queued"?G:null);break}case"provider_circuit":{let{kind:Q,...G}=X;$.sessionActions.setProviderCircuit(X.phase==="closed"?null:G);break}case"provider_retry":{let{kind:Q,...G}=X;$.sessionActions.setProviderRetry(X.phase==="recovered"?null:G);break}case"provider_stall":{let{kind:Q,...G}=X;$.sessionActions.setProviderStall(X.phase==="detected"?G:null);break}case"provider_recovery":$.sessionActions.setProviderRecovery(X.recovery);break;case"action_stationarity":{let{kind:Q,...G}=X;$.sessionActions.setActionStationarity(X.phase==="recovered"?null:G);break}case"turn_recovery":{_6($.sessionActions,X.assessment);break}case"tool_start":{J.toolExecutionStarted=!0;let Q=X.toolCall;if(!("function"in Q))break;if(Q.function.name===t8)break;if(Q8.debug("[loopEventHandler] tool_start",{toolName:Q.function.name,toolKind:X.toolKind}),["TaskCreate","TaskUpdate","TaskList"].includes(Q.function.name))break;try{let G=JSON.parse(Q.function.arguments),U=y9(Q.function.name,G);$.sessionActions.addToolMessage(U,{toolCallId:Q.id,toolName:Q.function.name,phase:"start",summary:U,params:G})}catch(G){Q8.error("[loopEventHandler] onToolStart error:",G)}break}case"tool_progress":{J.toolExecutionStarted=!0;let Q=X.toolCall;if(!("function"in Q))break;if(Q.function.name===t8)break;let G=X.update.total!==void 0?` ${Math.max(0,Math.min(100,Math.round((X.update.progress??0)/X.update.total*100)))}%`:"",U=`${Q.function.name}${G}: ${X.update.message}`;$.sessionActions.addToolMessage(U,{toolCallId:Q.id,toolName:Q.function.name,phase:"progress",summary:U,...X.update.admission?{admission:X.update.admission}:{}});break}case"tool_result":{J.toolExecutionStarted=!0;let Q=X.toolCall;if(!("function"in Q))break;if(Q.function.name===t8)break;Q8.debug("[loopEventHandler] tool_result",{toolName:Q.function.name,success:X.result.success});let G=C9(I9(Q.function.name,X.result),R9);$.sessionActions.addToolMessage(G.summary,{toolCallId:Q.id,toolName:Q.function.name,phase:"complete",summary:G.summary,detail:G.detail});break}case"structured_output":J.outputStarted=!0,$.sessionActions.replaceLastAssistantMessage(JSON.stringify(X.output,null,2));break;case"token_usage":$.sessionActions.updateTokenUsage(X.usage);break;case"compaction":if($.sessionActions.setCompacting(X.phase==="start"),X.phase==="end"){if($.sessionActions.resetContextUsage(),X.outcome!=="failed")J.compactionCount=(J.compactionCount??0)+1;if(X.memory?.outcome==="written"){let Q=`Saved ${X.memory.entries} project memories`;$.sessionActions.addToolMessage(Q,{toolName:"Project Memory",phase:"complete",summary:Q})}}break;case"turn_start":Q8.debug("[loopEventHandler] turn_start",{turn:X.turn,maxTurns:X.maxTurns}),$.sessionActions.updateTokenUsage({turnCount:X.turn}),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),Y.startTurn();break;case"task_update":$.appActions.setTasks(X.tasks);break;case"goal_frontier_updated":$.appActions.setTasks(X.tasks);break;case"mcp_catalog_changed":{let Q=`MCP catalog r${X.revision}: +${X.added.length} -${X.removed.length} ~${X.updated.length}`;$.sessionActions.addToolMessage(Q,{toolName:"MCP Catalog",phase:"complete",summary:Q,detail:[X.added.length>0?`Added: ${X.added.join(", ")}`:"",X.removed.length>0?`Removed: ${X.removed.join(", ")}`:"",X.updated.length>0?`Updated: ${X.updated.join(", ")}`:""].filter(Boolean).join(`
@@ -31,7 +31,7 @@ ${L}
31
31
  ---
32
32
 
33
33
  Remember: Follow the above instructions carefully to complete the user's request.`;return{type:"continue_as_agent",result:{userDisplayMessage:T,agentInput:{displayText:T,text:y,images:[],parts:[{type:"text",text:y}]},userMessageAlreadyAdded:!0}}}if(X7(B.data)){let{modelId:F,prompt:b}=B.data;return Y.addUserMessage(b),{type:"continue_as_agent",result:{userDisplayMessage:b,agentInput:{displayText:b,text:b,images:[],parts:[{type:"text",text:b}]},userMessageAlreadyAdded:!0,onceModelId:F}}}if(Z7(B.data)){let F=B.data.goal.objective;return Y.addUserMessage(T),{type:"continue_as_agent",result:{userDisplayMessage:T,agentInput:{displayText:T,text:F,images:[],parts:[{type:"text",text:F}]},userMessageAlreadyAdded:!0,goalContinuationOnly:!0}}}if(!B.success&&B.error)return Y.addAssistantMessage(`${B.error}`),{type:"handled",commandResult:{success:B.success,output:B.message,error:B.error,metadata:B.data}};let R=B.message;if(B.success&&typeof R==="string"&&R.trim()!=="")Y.addAssistantMessage(R);return{type:"handled",commandResult:{success:B.success,output:B.message,error:B.error,metadata:B.data}}}import{useMemoizedFn as p0}from"ahooks";import{useEffect as K7,useRef as M1}from"react";function z7($,J){return $.sessionId===J.sessionId&&$.workspaceRoot===J.workspaceRoot}function UY($,J){return $.factory===J.factory&&$.sessionId===J.sessionId&&$.workspaceRoot===J.workspaceRoot&&$.runtime===J.runtime&&$.systemPrompt===J.systemPrompt&&$.appendSystemPrompt===J.appendSystemPrompt&&$.maxTurns===J.maxTurns&&$.modelId===J.modelId&&$.permissionMode===J.permissionMode&&$.reasoningEffort===J.reasoningEffort&&$.serviceTier===J.serviceTier&&$.responseVerbosity===J.responseVerbosity&&$.communicationStyle===J.communicationStyle&&$.agents===J.agents}var qY=new WeakSet;function j$(){let $=new DOMException("TUI Agent lifecycle was invalidated","AbortError");return qY.add($),$}function KY($){return typeof $==="object"&&$!==null&&qY.has($)}function _Y($){let J=M1(void 0),Y=M1(void 0),Z=M1(void 0),X=M1(void 0),Q=M1(0),G=M1(!1),U=M1(void 0),z=M1(void 0),K=M1(void 0),O=(I)=>{let D=K.current;if(D?.agent===I)return D.promise;let p={agent:I,promise:Promise.resolve()};return p.promise=Promise.resolve().then(()=>I.destroy()).finally(()=>{if(K.current===p)K.current=void 0}),K.current=p,p.promise},q=p0(()=>{Q.current++;let I=U.current;if(I)I.invalidated=!0;let D=z.current;if(D)D.invalidated=!0;if(X.current)return X.current.promise;let p=J.current,h=Y.current;J.current=void 0,Y.current=void 0,Z.current=void 0;let n=z.current,O0=U.current,X0=K.current?.promise,R0,Q0=(async()=>{let Y0,h0=async(F$)=>{if(!F$)return;try{await F$}catch(g0){if(!KY(g0))Y0??=g0}};if(await h0(n?.promise),n?.cleanupError!==void 0)Y0??=n.cleanupError;if(await h0(X0),p)await h0(O(p));if(await h0(O0?.promise),O0?.cleanupError!==void 0)Y0??=O0.cleanupError;if(h)await h0(h.dispose());if(Y0!==void 0)throw Y0})();R0={promise:Q0},X.current=R0;let S0=()=>{if(X.current===R0)X.current=void 0};return Q0.then(S0,S0),Q0}),N=p0(async(I)=>{let D=X.current;if(D){if(await D.promise,!G.current)throw j$();return N(I)}let p=$.workspaceRoot??Y.current?.workspaceRoot??K$(),h={sessionId:I,workspaceRoot:p};if(!G.current)throw j$();let n=U.current;if(n&&!n.invalidated&&n.generation===Q.current&&z7(n.target,h))return n.promise;if(n){let Q0=q(),S0=Q.current;if(await Q0,!G.current||Q.current!==S0)throw j$();return N(I)}if(Y.current&&(Y.current.sessionId!==I||Y.current.workspaceRoot!==p)){let Q0=q(),S0=Q.current;if(await Q0,!G.current||Q.current!==S0)throw j$();return N(I)}if(!G.current)throw j$();if(Y.current)return Y.current;let O0=Q.current,X0,R0=Promise.resolve().then(async()=>{let Q0,S0=()=>{if(!G.current||X0.invalidated||Q.current!==O0||U.current!==X0)throw j$()};try{S0();let Y0=await a0.findSessionMetadata(I,p);S0();let h0=Y0!==void 0&&(await a0.loadSession(I,p)).length>0;S0(),Q0=await r$.create({sessionId:I,workspaceRoot:p,modelId:$.modelId,permissionMode:$.permissionMode??Y0?.permissionMode,reasoningEffort:Y0?.reasoningEffort??$.reasoningEffort,serviceTier:Y0?.serviceTier??$.serviceTier,responseVerbosity:Y0?.responseVerbosity??$.responseVerbosity,communicationStyle:Y0?.communicationStyle??$.communicationStyle,communicationStyleDigest:Y0?.communicationStyleDigest,agents:$.agents,...h0?{sessionStart:{isResume:!0,resumeSessionId:I}}:{}}),S0();let F$={sessionId:I,modelId:Y0?.selectedModelId,permissionMode:Y0?.permissionMode,reasoningEffort:Y0?.reasoningEffort,serviceTier:Y0?.serviceTier,responseVerbosity:Y0?.responseVerbosity,communicationStyle:Y0?.communicationStyle,communicationStyleDigest:Y0?.communicationStyleDigest},g0=Q0.getReasoningConfiguration().selection,N$=Q0.getServiceTierConfiguration().selection,d$=Q0.getResponseVerbosityConfiguration().selection,r0=Q0.getCommunicationStyleConfiguration().selection;return S0(),B$().setReasoningEffort(g0),B$().setServiceTier(N$),B$().setResponseVerbosity(d$),B$().setCommunicationStyle(r0),S0(),Y.current=Q0,Z.current=F$,Q0}catch(Y0){if(Q0&&Y.current!==Q0)await Q0.dispose().catch((h0)=>{X0.cleanupError??=h0});if(X0.invalidated||Q.current!==O0||!G.current)throw j$();throw Y0}finally{if(U.current===X0)U.current=void 0}});return X0={generation:O0,target:h,invalidated:!1,promise:R0},U.current=X0,R0}),_=async(I,D,p,h,n)=>{let O0;if(p&&D){let X0=I?.modelId??$.modelId,R0=I?.reasoningEffort??(h?$.reasoningEffort:p.getReasoningConfiguration().selection),Q0=I?.serviceTier??(h?$.serviceTier:p.getServiceTierConfiguration().selection),S0=I?.responseVerbosity??(h?$.responseVerbosity:p.getResponseVerbosityConfiguration().selection),Y0=I?.communicationStyle??(h?$.communicationStyle:p.getCommunicationStyleConfiguration().selection),h0=p.getCurrentModelId(),F$=p.getReasoningConfiguration(),g0=p.getServiceTierConfiguration(),N$=p.getResponseVerbosityConfiguration(),d$=p.getCommunicationStyleConfiguration();if($.permissionMode&&(Z.current?.sessionId!==D||Z.current.permissionMode!==$.permissionMode)){let d0=await a0.setSessionPermissionMode(D,p.workspaceRoot,$.permissionMode);n(),Z.current={...Z.current,sessionId:D,permissionMode:d0.permissionMode}}await p.refresh({modelId:X0,...R0?{reasoningEffort:R0}:{},...Q0?{serviceTier:Q0}:{},...S0?{responseVerbosity:S0}:{},...Y0?{communicationStyle:Y0}:{}}),n();let r0=p.getCommunicationStyleConfiguration();if(r0.source!=="built-in"&&!r0.contentSha256)throw Error("Custom communication style has no provenance");let U$={...X0&&X0!=="inherit"&&(Z.current?.sessionId!==D||Z.current.modelId!==X0)?{selectedModelId:X0}:{},...R0&&(Z.current?.sessionId!==D||Z.current.reasoningEffort!==R0)?{reasoningEffort:R0}:{},...Q0&&(Z.current?.sessionId!==D||Z.current.serviceTier!==Q0)?{serviceTier:Q0}:{},...S0&&(Z.current?.sessionId!==D||Z.current.responseVerbosity!==S0)?{responseVerbosity:S0}:{},...Y0&&(Z.current?.sessionId!==D||Z.current.communicationStyle!==Y0||Z.current.communicationStyleDigest!==r0.contentSha256)?{communicationStyle:Y0,communicationStyleDigest:r0.source==="built-in"?null:r0.contentSha256}:{}};if(Object.keys(U$).length>0)try{let d0=await a0.updateSessionMetadata(D,p.workspaceRoot,U$);n(),Z.current={sessionId:D,modelId:d0.selectedModelId,permissionMode:d0.permissionMode,reasoningEffort:d0.reasoningEffort,serviceTier:d0.serviceTier,responseVerbosity:d0.responseVerbosity,communicationStyle:d0.communicationStyle,communicationStyleDigest:d0.communicationStyleDigest}}catch(d0){if(KY(d0))throw d0;throw await p.refresh({...h0?{modelId:h0}:{},reasoningEffort:F$.selection,serviceTier:g0.selection,responseVerbosity:N$.selection,communicationStyle:d$.selection}).catch(()=>{return}),d0}O0=await K8.createWithRuntime(p,{sessionId:D,systemPrompt:I?.systemPrompt??$.systemPrompt,appendSystemPrompt:I?.appendSystemPrompt??$.appendSystemPrompt,maxTurns:I?.maxTurns??$.maxTurns,modelId:I?.modelId??$.modelId,permissionMode:I?.permissionMode??$.permissionMode,agents:$.agents})}else O0=await K8.create({systemPrompt:I?.systemPrompt??$.systemPrompt,appendSystemPrompt:I?.appendSystemPrompt??$.appendSystemPrompt,maxTurns:I?.maxTurns??$.maxTurns,modelId:I?.modelId??$.modelId,permissionMode:I?.permissionMode??$.permissionMode,agents:$.agents});return O0},H=p0(async(I)=>{let D=X.current;if(D){if(await D.promise,!G.current)throw j$();return H(I)}if(!G.current)throw j$();let p=I?.sessionId??$.sessionId,h=!!I?.modelId&&I.modelId!==$.modelId,n=Y.current,O0={factory:!h&&p?"session":"standalone",sessionId:p,workspaceRoot:!h&&p?$.workspaceRoot??n?.workspaceRoot??K$():$.workspaceRoot??K$(),runtime:!h&&p&&n&&n.sessionId===p&&n.workspaceRoot===($.workspaceRoot??n.workspaceRoot)?n:void 0,systemPrompt:I?.systemPrompt??$.systemPrompt,appendSystemPrompt:I?.appendSystemPrompt??$.appendSystemPrompt,maxTurns:I?.maxTurns??$.maxTurns,modelId:I?.modelId??$.modelId,permissionMode:I?.permissionMode??$.permissionMode,reasoningEffort:I?.reasoningEffort??$.reasoningEffort,serviceTier:I?.serviceTier??$.serviceTier,responseVerbosity:I?.responseVerbosity??$.responseVerbosity,communicationStyle:I?.communicationStyle??$.communicationStyle,agents:$.agents},X0=z.current;if(X0){if(!X0.invalidated&&X0.generation===Q.current&&UY(X0.target,O0))return X0.promise;X0.invalidated=!0,Q.current++;let U$=Q.current;if(await X0.promise.catch(()=>{return}),X0.cleanupError!==void 0)throw X0.cleanupError;if(!G.current||Q.current!==U$)throw j$();return H(I)}let R0=Y.current!==void 0,Q0=!h&&p?await N(p):void 0;if(!G.current||Q0!==void 0&&Y.current!==Q0)throw j$();let S0={factory:Q0?"session":"standalone",sessionId:p,workspaceRoot:Q0?.workspaceRoot??$.workspaceRoot??K$(),runtime:Q0,systemPrompt:I?.systemPrompt??$.systemPrompt,appendSystemPrompt:I?.appendSystemPrompt??$.appendSystemPrompt,maxTurns:I?.maxTurns??$.maxTurns,modelId:I?.modelId??$.modelId,permissionMode:I?.permissionMode??$.permissionMode,reasoningEffort:I?.reasoningEffort??$.reasoningEffort,serviceTier:I?.serviceTier??$.serviceTier,responseVerbosity:I?.responseVerbosity??$.responseVerbosity,communicationStyle:I?.communicationStyle??$.communicationStyle,agents:$.agents},Y0=z.current;if(Y0&&!Y0.invalidated&&Y0.generation===Q.current&&UY(Y0.target,S0))return Y0.promise;if(Y0){Y0.invalidated=!0,Q.current++;let r0=Q.current;if(await Y0.promise.catch(()=>{return}),Y0.cleanupError!==void 0)throw Y0.cleanupError;if(!G.current||Q.current!==r0)throw j$();return H(I)}let h0=Q.current,F$=J.current,g0;if(F$)J.current=void 0,g0=O(F$);let N$,d$=Promise.resolve().then(async()=>{let r0,U$=()=>{if(!G.current||N$.invalidated||Q.current!==h0||z.current!==N$||Q0!==void 0&&Y.current!==Q0)throw j$()};try{if(U$(),g0){try{await g0}catch(d0){throw N$.cleanupError??=d0,U$(),d0}U$()}return r0=await _(I,p,Q0,R0,U$),U$(),J.current=r0,r0}catch(d0){if(r0&&J.current!==r0)await O(r0).catch((B1)=>{N$.cleanupError??=B1});if(N$.invalidated||Q.current!==h0||!G.current)throw j$();throw d0}finally{if(z.current===N$)z.current=void 0}});return N$={generation:h0,target:S0,invalidated:!1,promise:d$},z.current=N$,d$}),W=p0(async()=>{if(!$.sessionId)throw Error("No active session to rewind");return(await N($.sessionId)).listRewindCheckpoints()}),A=p0(async(I)=>{if(!$.sessionId)throw Error("No active session to rewind");let p=await(await N($.sessionId)).rewindSession(I);return await q(),p}),T=p0(async()=>{if(!$.sessionId)throw Error("No active session for subagent control");return(await N($.sessionId)).listSubagents()}),w=p0(async(I,D)=>{if(!$.sessionId)throw Error("No active session for subagent control");let p=await N($.sessionId),h=!1,n,O0=I,X0=(Q0)=>{let S0=Q0.status==="completed"?Q0.result?.message:Q0.result?.error||Q0.result?.message;f2.getState().app.actions.completeSubagentProgress(O0,Q0.status==="completed",S0)},R0=p.resumeSubagent({agentId:I,prompt:D,onEvent:(Q0)=>{if(Q0.kind==="tool_start"&&"function"in Q0.toolCall)f2.getState().app.actions.updateSubagentTool(O0,Q0.toolCall.function.name)},onCompleted:(Q0)=>{if(h)X0(Q0);else n=Q0}});if(O0=R0.session.id,f2.getState().app.actions.startSubagentProgress(R0.session.id,R0.session.subagentType,`Resumed from ${R0.source.id}: ${R0.session.description}`),h=!0,n)X0(n);return R0}),B=p0(async()=>{if(!$.sessionId)throw Error("No active session for MCP content");return(await N($.sessionId)).getMcpContentCatalog()}),R=p0(async(I)=>{if(!$.sessionId)throw Error("No active session for MCP content");await(await N($.sessionId)).refreshMcpContentCatalogs(I)}),F=p0(async(I,D,p)=>{if(!$.sessionId)throw Error("No active session for MCP prompts");return(await N($.sessionId)).getMcpPrompt(I,D,p)}),b=p0(async(I,D,p)=>{if(!$.sessionId)throw Error("No active session for MCP completion");return(await N($.sessionId)).completeMcpArgument(I,D,p)}),L=p0(async(I,D={})=>{if(!$.sessionId)throw Error("No active session for MCP logs");return(await N($.sessionId)).getMcpLogs(I,D)}),y=p0(async(I)=>{if(!$.sessionId)throw Error("No active session for MCP tasks");return(await N($.sessionId)).listMcpTasks(I)}),S=p0(async(I)=>{if(!$.sessionId)throw Error("No active session for MCP tasks");return(await N($.sessionId)).getMcpTask(I)}),M=p0(async(I,D)=>{if(!$.sessionId)throw Error("No active session for MCP tasks");return(await N($.sessionId)).cancelMcpTask(I,D)}),C=p0(async(I,D)=>{if(!$.sessionId)throw Error("No active session for MCP logging");await(await N($.sessionId)).setMcpLoggingLevel(I,D)}),P=p0(async()=>{if(!$.sessionId)throw Error("No active session for MCP instructions");return(await N($.sessionId)).getMcpInstructions()}),j=p0(async()=>{if(!$.sessionId)throw Error("No active session for reasoning effort");return(await N($.sessionId)).getReasoningConfiguration()}),o=p0(async(I)=>{if(!$.sessionId)throw Error("No active session for reasoning effort");let D=await N($.sessionId);if(D.hasTurnOwner())throw Error("Cannot switch reasoning effort while a turn is active");let p=D.getReasoningConfiguration();if(D.resolveReasoningConfiguration(I),p.selection===I)return p;await D.refresh({reasoningEffort:I});try{let h;try{h=await a0.updateSessionMetadata($.sessionId,D.workspaceRoot,{reasoningEffort:I})}catch(n){if(!(n instanceof U8)&&n.code!=="ENOENT")throw n;h=await a0.createSessionMetadata($.sessionId,D.workspaceRoot,{taskStatus:"completed",selectedModelId:D.getCurrentModelId(),reasoningEffort:I,serviceTier:D.getServiceTierConfiguration().selection,responseVerbosity:D.getResponseVerbosityConfiguration().selection,communicationStyle:D.getCommunicationStyleConfiguration().selection})}return Z.current={sessionId:$.sessionId,modelId:h.selectedModelId,permissionMode:h.permissionMode,reasoningEffort:h.reasoningEffort,serviceTier:h.serviceTier,responseVerbosity:h.responseVerbosity,communicationStyle:h.communicationStyle,communicationStyleDigest:h.communicationStyleDigest},B$().setReasoningEffort(I),D.getReasoningConfiguration()}catch(h){throw await D.refresh({reasoningEffort:p.selection}),h}}),u=p0(async()=>{if(!$.sessionId)throw Error("No active session for service tier");return(await N($.sessionId)).getServiceTierConfiguration()}),J0=p0(async(I)=>{if(!$.sessionId)throw Error("No active session for service tier");let D=await N($.sessionId);if(D.hasTurnOwner())throw Error("Cannot switch service tier while a turn is active");let p=D.getServiceTierConfiguration();if(D.resolveServiceTierConfiguration(I),p.selection===I)return p;await D.refresh({serviceTier:I});try{let h;try{h=await a0.updateSessionMetadata($.sessionId,D.workspaceRoot,{serviceTier:I})}catch(n){if(!(n instanceof U8)&&n.code!=="ENOENT")throw n;h=await a0.createSessionMetadata($.sessionId,D.workspaceRoot,{taskStatus:"completed",selectedModelId:D.getCurrentModelId(),reasoningEffort:D.getReasoningConfiguration().selection,serviceTier:I,responseVerbosity:D.getResponseVerbosityConfiguration().selection,communicationStyle:D.getCommunicationStyleConfiguration().selection})}return Z.current={sessionId:$.sessionId,modelId:h.selectedModelId,permissionMode:h.permissionMode,reasoningEffort:h.reasoningEffort,serviceTier:h.serviceTier,responseVerbosity:h.responseVerbosity,communicationStyle:h.communicationStyle,communicationStyleDigest:h.communicationStyleDigest},B$().setServiceTier(I),D.getServiceTierConfiguration()}catch(h){throw await D.refresh({serviceTier:p.selection}),h}}),K0=p0(async()=>{if(!$.sessionId)throw Error("No active session for response verbosity");return(await N($.sessionId)).getResponseVerbosityConfiguration()}),q0=p0(async(I)=>{if(!$.sessionId)throw Error("No active session for response verbosity");let D=await N($.sessionId);if(D.hasTurnOwner())throw Error("Cannot switch response verbosity while a turn is active");let p=D.getResponseVerbosityConfiguration();if(D.resolveResponseVerbosityConfiguration(I),p.selection===I)return p;await D.refresh({responseVerbosity:I});try{let h;try{h=await a0.updateSessionMetadata($.sessionId,D.workspaceRoot,{responseVerbosity:I})}catch(n){if(!(n instanceof U8)&&n.code!=="ENOENT")throw n;h=await a0.createSessionMetadata($.sessionId,D.workspaceRoot,{taskStatus:"completed",selectedModelId:D.getCurrentModelId(),reasoningEffort:D.getReasoningConfiguration().selection,serviceTier:D.getServiceTierConfiguration().selection,responseVerbosity:I,communicationStyle:D.getCommunicationStyleConfiguration().selection})}return Z.current={sessionId:$.sessionId,modelId:h.selectedModelId,permissionMode:h.permissionMode,reasoningEffort:h.reasoningEffort,serviceTier:h.serviceTier,responseVerbosity:h.responseVerbosity,communicationStyle:h.communicationStyle,communicationStyleDigest:h.communicationStyleDigest},B$().setResponseVerbosity(I),D.getResponseVerbosityConfiguration()}catch(h){throw await D.refresh({responseVerbosity:p.selection}),h}}),a=p0(async()=>{if(!$.sessionId)throw Error("No active session for communication style");return(await N($.sessionId)).getCommunicationStyleConfiguration()}),f=p0(async(I)=>{if(!$.sessionId)throw Error("No active session for communication style");let D=await N($.sessionId);if(D.hasTurnOwner())throw Error("Cannot switch communication style while a turn is active");let p=D.getCommunicationStyleConfiguration(),h=D.resolveCommunicationStyleConfiguration(I);if(h.source!=="built-in"&&!h.contentSha256)throw Error("Custom communication style has no provenance");if(p.selection===I)return p;await D.refresh({communicationStyle:I});try{let n;try{n=await a0.updateSessionMetadata($.sessionId,D.workspaceRoot,{communicationStyle:I,communicationStyleDigest:h.source==="built-in"?null:h.contentSha256})}catch(O0){if(!(O0 instanceof U8)&&O0.code!=="ENOENT")throw O0;n=await a0.createSessionMetadata($.sessionId,D.workspaceRoot,{taskStatus:"completed",selectedModelId:D.getCurrentModelId(),reasoningEffort:D.getReasoningConfiguration().selection,serviceTier:D.getServiceTierConfiguration().selection,responseVerbosity:D.getResponseVerbosityConfiguration().selection,communicationStyle:I,...h.source!=="built-in"&&h.contentSha256?{communicationStyleDigest:h.contentSha256}:{}})}return Z.current={sessionId:$.sessionId,modelId:n.selectedModelId,permissionMode:n.permissionMode,reasoningEffort:n.reasoningEffort,serviceTier:n.serviceTier,responseVerbosity:n.responseVerbosity,communicationStyle:n.communicationStyle,communicationStyleDigest:n.communicationStyleDigest},B$().setCommunicationStyle(I),D.getCommunicationStyleConfiguration()}catch(n){throw await D.refresh({communicationStyle:p.selection}),n}}),v=p0(async(I)=>{if(!Y.current)return{accepted:!1,queued:0,reason:"no_active_turn"};return Y.current.enqueueSteering(I,{allowBeforeTurn:!0})}),U0=p0(async(I,D)=>{let p=$.sessionId;if(!p)return{accepted:!1,queued:0,reason:"no_active_turn"};return(await N(p)).enqueueSteering(I,{allowBeforeTurn:!0,...D})}),V=p0(async()=>{let I=$.sessionId;if(!I)throw Error("Follow-up queue requires a Session");return(await N(I)).getFollowUpQueueSnapshot()}),x=p0(async(I)=>{let D=$.sessionId;if(!D)throw Error("Follow-up queue requires a Session");return(await N(D)).mutateFollowUpQueue(I)}),l=p0(async(I,D)=>{let p=$.sessionId;if(!p)throw Error("Side conversation requires a Session");return(await N(p)).askSideQuestion(I,{signal:D,systemPrompt:$.systemPrompt,appendSystemPrompt:$.appendSystemPrompt})}),W0=p0(async(I,D)=>{let p=$.sessionId;if(!p)throw Error("User shell command requires a Session");return(await N(p)).executeUserShellCommand(I,D)}),F0=p0(()=>Y.current?.getTurnRecoveryAssessment()??{state:"none"}),T0=p0(async(I,D)=>{let p=$.sessionId;if(!p)throw Error("Code review requires a Session");let h=await N(p);await q4.recoverInterrupted(h.workspaceRoot,p,h);let n=await q4.start({sessionId:p,projectPath:h.workspaceRoot,runtime:h,request:I,signal:D}),O0=await n.completion,X0=(await q4.list(h.workspaceRoot,p)).find((R0)=>R0.start.reviewId===n.reviewId);if(!X0)throw Error(`Review not found after completion: ${n.reviewId}`);return{reviewId:n.reviewId,status:O0.status,findings:O0.findings.length,content:zY(X0.start,O0)}});return K7(()=>{G.current=!0;let D=_4(async()=>{G.current=!1,await q()});return()=>{D(),G.current=!1,q().catch(()=>{return})}},[q]),{agentRef:J,createAgent:H,cleanupAgent:q,steerActiveTurn:v,enqueueSessionInput:U0,getFollowUpQueue:V,mutateFollowUpQueue:x,askSideQuestion:l,runCodeReview:T0,executeUserShellCommand:W0,getTurnRecoveryAssessment:F0,listRewindCheckpoints:W,rewindSession:A,listSubagents:T,resumeSubagent:w,getMcpContentCatalog:B,refreshMcpContentCatalogs:R,getMcpPrompt:F,completeMcpArgument:b,listMcpTasks:y,getMcpTask:S,cancelMcpTask:M,getMcpLogs:L,setMcpLoggingLevel:C,getMcpInstructions:P,getReasoningConfiguration:j,setReasoningEffort:o,getServiceTierConfiguration:u,setServiceTier:J0,getResponseVerbosityConfiguration:K0,setResponseVerbosity:q0,getCommunicationStyleConfiguration:a,setCommunicationStyle:f}}import{useMemoizedFn as p2}from"ahooks";import{useEffect as q7,useRef as O4}from"react";function OY($){let J=0;for(let Y of $)if(Y===`
34
- `)J++;return J}function NY($,J){let Y=J?.flushTimeout??300,Z=J?.minLinesToFlush??5,X=J?.minCharsToFlush??400,Q=O4(""),G=O4(null),U=O4(""),z=O4(null),K=p2(()=>{if(Q.current){let W=Q.current,A=$.appendAssistantContent(W);o8(A,W),Q.current=""}if(G.current)clearTimeout(G.current),G.current=null}),O=p2(()=>{if(U.current)$.appendThinkingContent(U.current),U.current="";if(z.current)clearTimeout(z.current),z.current=null}),q=p2((W)=>{Q.current+=W;let A=Q.current;if(OY(A)>=Z||A.length>=X){K();return}if(!G.current)G.current=setTimeout(K,Y)}),N=p2((W)=>{U.current+=W;let A=U.current;if(OY(A)>=Z||A.length>=X){O();return}if(!z.current)z.current=setTimeout(O,Y)}),_=p2(()=>{if(Q.current="",G.current)clearTimeout(G.current),G.current=null;if(U.current="",z.current)clearTimeout(z.current),z.current=null}),H=p2(()=>{if(G.current)clearTimeout(G.current),G.current=null;if(z.current)clearTimeout(z.current),z.current=null;let W=Q.current,A=U.current;return Q.current="",U.current="",{extraContent:W,extraThinking:A}});return q7(()=>{return()=>{_()}},[_]),{batchAppendContent:q,batchAppendThinking:N,flushContentBuffer:K,flushThinkingBuffer:O,resetStreamingBuffers:_,drainPendingBuffers:H}}var z8=O1("UI");function W4($,J){return[...($??[]).filter((Y)=>Y!==J),J].slice(-16)}function HY($){return $.error?.type==="canceled"||$.error?.type==="aborted"||$.metadata?.abortReason==="interrupt"}var MY=($,J,Y,Z,X,Q,G)=>{let U=E2(),z=v2(),K=_1(),O=m8(),q=j2(),N=x8(),_=c8(),H=u8(),W=d8(),A=l8(),T=V2(),w=q9(),B=c1(),R=u1(),F=N9(),b=N4(!1),L=N4(null),y=N4(null),S=N4(null),{createAgent:M,cleanupAgent:C,steerActiveTurn:P,enqueueSessionInput:j,getFollowUpQueue:o,mutateFollowUpQueue:u,listRewindCheckpoints:J0,rewindSession:K0,listSubagents:q0,resumeSubagent:a,getMcpContentCatalog:f,refreshMcpContentCatalogs:v,getMcpPrompt:U0,completeMcpArgument:V,listMcpTasks:x,getMcpTask:l,cancelMcpTask:W0,getMcpLogs:F0,setMcpLoggingLevel:T0,getMcpInstructions:I,getReasoningConfiguration:D,setReasoningEffort:p,getServiceTierConfiguration:h,setServiceTier:n,getResponseVerbosityConfiguration:O0,setResponseVerbosity:X0,getCommunicationStyleConfiguration:R0,setCommunicationStyle:Q0,runCodeReview:S0,askSideQuestion:Y0,executeUserShellCommand:h0,getTurnRecoveryAssessment:F$}=_Y({sessionId:z,workspaceRoot:K,systemPrompt:$,appendSystemPrompt:J,maxTurns:Z,modelId:O,permissionMode:q,reasoningEffort:_,serviceTier:H,responseVerbosity:W,communicationStyle:A,agents:Q}),g0=WY(()=>[K,z,_7()].join("\x00"),[z,K]),N$=Y1(async()=>{let k=m0().app.followUpQueue?.version,E=m0().app.followUpQueueMutation;try{let m=await o(),c=m0().app.followUpQueue?.version,r=c===k||c===m.version;if(r)R.projectFollowUpQueue(m,g0);let P0=m0().app.followUpQueueMutation.supersededVersions;R.setFollowUpQueueMutation(E.errorCode==="revision_conflict"?{pending:!1,errorCode:E.errorCode,errorMessage:E.errorMessage,supersededVersions:r?P0:W4(P0,m.version)}:{pending:!1,supersededVersions:r?P0:W4(P0,m.version)},g0)}catch{R.setFollowUpQueueMutation({pending:!1,errorMessage:"Follow-up queue is unavailable"},g0)}}),d$=Y1(async(k)=>{let E=m0().app.followUpQueue;if(!E||m0().app.followUpQueueMutation.pending)return!1;R.setFollowUpQueueMutation({pending:!0,messageId:k.messageId},g0);try{let m=await u({expectedVersion:E.version,operation:k}),c=m0().app.followUpQueue?.version;if(c===E.version||c===m.snapshot.version)R.projectFollowUpQueue(m.snapshot,g0);let r=c===E.version||c===m.snapshot.version,P0=m0().app.followUpQueueMutation.supersededVersions;if(R.setFollowUpQueueMutation({pending:!1,supersededVersions:r?P0:W4(P0,m.snapshot.version)},g0),k.type==="remove")F.takeFollowUpPresentation(k.messageId);return!0}catch(m){if(m instanceof AY){let c=m0().app.followUpQueue?.version,r=c===E.version||c===m.snapshot.version;if(r)R.projectFollowUpQueue(m.snapshot,g0);let P0=m0().app.followUpQueueMutation.supersededVersions;R.setFollowUpQueueMutation({pending:!1,errorCode:m.code,errorMessage:m.message,supersededVersions:r?P0:W4(P0,m.snapshot.version)},g0)}else R.setFollowUpQueueMutation({pending:!1,errorMessage:"Follow-up queue is unavailable"},g0);return!1}}),r0=NY(B),U$=Y1((k)=>new Z8({signal:k,streamingBuffer:r0,getStreamingMessageId:()=>m0().session.currentStreamingMessageId,finalizeStreamingMessage:B.finalizeStreamingMessage,discardStreamingMessage:B.discardStreamingMessage,clearThinking:()=>B.setCurrentThinkingContent(null)})),d0=Y1(async()=>{if(!w||!z){R.setTeams([]);return}try{let E=await new bY({configDir:G8(),subagentRegistry:H4(K)}).list({sessionId:z,projectPath:K});if(m0().session.sessionId===z&&m0().session.workspaceRoot===K)R.setTeams(E)}catch(k){z8.warn("[useCommandHandler] Failed to refresh Agent Teams",k)}}),B1=Y1(async(k,E)=>{if(k.images.length>0)return{success:!1,error:"User shell commands do not accept image attachments"};let m=k.text.trimStart().slice(1).trim();if(!m)return{success:!1,error:"User shell command cannot be empty"};B.setCommand(`! ${m}`);try{let c=await h0(m,{signal:E});if(B.addMessage({id:`user-shell-${c.executionId}`,role:"user",content:w6(c.record),timestamp:Date.now(),metadata:{userShellCommand:c.record}}),c.delivery==="next_turn"){let r=m0().session;if(r.sessionId===z&&r.workspaceRoot===K)y.current?.request()}return{success:c.record.status!=="spawn_error",output:w6(c.record),...c.record.status==="spawn_error"?{error:c.record.stderr||"User shell command failed"}:{}}}finally{B.setCommand(null)}});d1(()=>{return()=>{L.current=null,r0.resetStreamingBuffers()}},[r0.resetStreamingBuffers]),d1(()=>{return()=>{S.current?.abort("side-conversation-session-change"),S.current=null,R.dismissSideConversation()}},[R,z,K]),d1(()=>{R.setTeams([]),d0()},[w,R,d0,z,K]),d1(()=>{if(!N)B.setCurrentThinkingContent(null)},[N,B]);let w1=Y1(()=>{if(S.current){S.current.abort("user-cancel"),S.current=null,R.dismissSideConversation();return}if(!U)return;X?.();let k=F.getAbortController()?.signal??new AbortController().signal;if((L.current??U$(k)).abortAndFinalize(()=>{F.abort("user-cancel"),R.setTasks([])}),!b.current)B.addAssistantMessage("任务已停止"),b.current=!0}),X8=Y1(async(k,E)=>{let m=`side-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;if(R.startSideConversation(m,E),k.images.length>0){R.failSideConversation(m,"Side conversations do not accept image attachments");return}if(!E){R.failSideConversation(m,"Usage: /btw <question>");return}S.current?.abort("side-conversation-replaced");let c=new AbortController;S.current=c;try{let r=await Y0(E,c.signal);if(c.signal.aborted||S.current!==c)return;if(R.completeSideConversation(m,r),r.usage)B.updateTokenUsage({inputTokens:r.usage.promptTokens,outputTokens:r.usage.completionTokens,totalTokens:r.usage.totalTokens,cacheReadTokens:r.usage.cacheReadInputTokens??0,cacheWriteTokens:r.usage.cacheCreationInputTokens??0,costUsd:r.usage.costUsd})}catch(r){if(c.signal.aborted||S.current!==c)return;R.failSideConversation(m,r instanceof Error?r.message:String(r))}finally{if(S.current===c)S.current=null}}),p1=Y1(async(k,E)=>{let m={contentDeltaCount:0,contentDeltaTotalLen:0,outputStarted:!1,toolExecutionStarted:!1,compactionCount:0},c=U$(E.signal);L.current=c;let r=S9({sessionActions:B,appActions:R,commandActions:F,streamingBuffer:r0,thinkingModeEnabled:N,getStreamingMessageId:()=>m0().session.currentStreamingMessageId,signal:E.signal,streamSession:c,followUpQueueOwner:g0},m);try{return{loopResult:await LY(k,r),stats:m}}finally{if(L.current===c)L.current=null}}),S2=Y1(async(k)=>{let E=!1,m,c=!1,r=k;try{if(k.text.trimStart().startsWith("!")){let X$=F.getAbortController()??F.createAbortController();return await B1(k,X$.signal)}await q8();let P0=F.getAbortController()??F.createAbortController(),l0=$4(m0().session),c0=await B6(k,R,B,P0.signal,C,z,$4(m0().session),{listCheckpoints:J0,execute:K0},{list:q0,resume:a},{getCatalog:f,refresh:v,getPrompt:U0,complete:V,listTasks:x,getTask:l,cancelTask:W0,getLogs:F0,setLoggingLevel:T0,getInstructions:I},{get:D,set:p},{get:h,set:n},{get:O0,set:X0},{get:R0,set:Q0},K,{run:S0},G);if(c0.type==="handled")return c0.commandResult;if(c0.type==="continue_as_agent")E=c0.result.userMessageAlreadyAdded,m=c0.result.onceModelId,c=c0.result.goalContinuationOnly===!0,r=c0.result.agentInput;let b$=E$.getInstance(),q1;if(!c){let X$=await b$.executeUserPromptSubmitHooks(r.text,{projectDir:K,sessionId:z,permissionMode:q,hasImages:r.images.length>0,imageCount:r.images.length});if(!X$.proceed){if(X$.warning)B.addAssistantMessage(`${X$.warning}`);return{success:!1,error:"blocked by hook"}}if(X$.updatedPrompt)r={...r,text:X$.updatedPrompt,displayText:X$.updatedPrompt,parts:[{type:"text",text:X$.updatedPrompt},...r.parts.filter((k2)=>k2.type==="image")]};if(X$.contextInjection)q1=X$.contextInjection}if(!E)B.addUserMessage(r.displayText);let Q2=O6(r),w$=await M(m?{modelId:m}:void 0);if(P0.signal.aborted)return z8.info("[handleCommandSubmit] Agent 创建期间已被中止"),{success:!1,error:"aborted"};if(q1)l0.push({role:"system",content:`<user-prompt-submit-hook>
34
+ `)J++;return J}function NY($,J){let Y=J?.flushTimeout??300,Z=J?.minLinesToFlush??5,X=J?.minCharsToFlush??400,Q=O4(""),G=O4(null),U=O4(""),z=O4(null),K=p2(()=>{if(Q.current){let W=Q.current,A=$.appendAssistantContent(W);o8(A,W),Q.current=""}if(G.current)clearTimeout(G.current),G.current=null}),O=p2(()=>{if(U.current)$.appendThinkingContent(U.current),U.current="";if(z.current)clearTimeout(z.current),z.current=null}),q=p2((W)=>{Q.current+=W;let A=Q.current;if(OY(A)>=Z||A.length>=X){K();return}if(!G.current)G.current=setTimeout(K,Y)}),N=p2((W)=>{U.current+=W;let A=U.current;if(OY(A)>=Z||A.length>=X){O();return}if(!z.current)z.current=setTimeout(O,Y)}),_=p2(()=>{if(Q.current="",G.current)clearTimeout(G.current),G.current=null;if(U.current="",z.current)clearTimeout(z.current),z.current=null}),H=p2(()=>{if(G.current)clearTimeout(G.current),G.current=null;if(z.current)clearTimeout(z.current),z.current=null;let W=Q.current,A=U.current;return Q.current="",U.current="",{extraContent:W,extraThinking:A}});return q7(()=>{return()=>{_()}},[_]),{batchAppendContent:q,batchAppendThinking:N,flushContentBuffer:K,flushThinkingBuffer:O,resetStreamingBuffers:_,drainPendingBuffers:H}}var z8=O1("UI");function W4($,J){return[...($??[]).filter((Y)=>Y!==J),J].slice(-16)}function HY($){return $.error?.type==="canceled"||$.error?.type==="aborted"||$.metadata?.abortReason==="interrupt"}var MY=($,J,Y,Z,X,Q,G)=>{let U=E2(),z=v2(),K=_1(),O=m8(),q=j2(),N=x8(),_=c8(),H=u8(),W=d8(),A=l8(),T=V2(),w=q9(),B=c1(),R=u1(),F=N9(),b=N4(!1),L=N4(null),y=N4(null),S=N4(null),{createAgent:M,cleanupAgent:C,steerActiveTurn:P,enqueueSessionInput:j,getFollowUpQueue:o,mutateFollowUpQueue:u,listRewindCheckpoints:J0,rewindSession:K0,listSubagents:q0,resumeSubagent:a,getMcpContentCatalog:f,refreshMcpContentCatalogs:v,getMcpPrompt:U0,completeMcpArgument:V,listMcpTasks:x,getMcpTask:l,cancelMcpTask:W0,getMcpLogs:F0,setMcpLoggingLevel:T0,getMcpInstructions:I,getReasoningConfiguration:D,setReasoningEffort:p,getServiceTierConfiguration:h,setServiceTier:n,getResponseVerbosityConfiguration:O0,setResponseVerbosity:X0,getCommunicationStyleConfiguration:R0,setCommunicationStyle:Q0,runCodeReview:S0,askSideQuestion:Y0,executeUserShellCommand:h0,getTurnRecoveryAssessment:F$}=_Y({sessionId:z,workspaceRoot:K,systemPrompt:$,appendSystemPrompt:J,maxTurns:Z,modelId:O,permissionMode:q,reasoningEffort:_,serviceTier:H,responseVerbosity:W,communicationStyle:A,agents:Q}),g0=WY(()=>[K,z,_7()].join("\x00"),[z,K]),N$=Y1(async()=>{let k=m0().app.followUpQueue?.version,E=m0().app.followUpQueueMutation;try{let m=await o(),c=m0().app.followUpQueue?.version,r=c===k||c===m.version;if(r)R.projectFollowUpQueue(m,g0);let P0=m0().app.followUpQueueMutation.supersededVersions;R.setFollowUpQueueMutation(E.errorCode==="revision_conflict"?{pending:!1,errorCode:E.errorCode,errorMessage:E.errorMessage,supersededVersions:r?P0:W4(P0,m.version)}:{pending:!1,supersededVersions:r?P0:W4(P0,m.version)},g0)}catch{R.setFollowUpQueueMutation({pending:!1,errorMessage:"Follow-up queue is unavailable"},g0)}}),d$=Y1(async(k)=>{let E=m0().app.followUpQueue;if(!E||m0().app.followUpQueueMutation.pending)return!1;R.setFollowUpQueueMutation({pending:!0,messageId:k.messageId},g0);try{let m=await u({expectedVersion:E.version,operation:k}),c=m0().app.followUpQueue?.version;if(c===E.version||c===m.snapshot.version)R.projectFollowUpQueue(m.snapshot,g0);let r=c===E.version||c===m.snapshot.version,P0=m0().app.followUpQueueMutation.supersededVersions;if(R.setFollowUpQueueMutation({pending:!1,supersededVersions:r?P0:W4(P0,m.snapshot.version)},g0),k.type==="remove")F.takeFollowUpPresentation(k.messageId);return!0}catch(m){if(m instanceof AY){let c=m0().app.followUpQueue?.version,r=c===E.version||c===m.snapshot.version;if(r)R.projectFollowUpQueue(m.snapshot,g0);let P0=m0().app.followUpQueueMutation.supersededVersions;R.setFollowUpQueueMutation({pending:!1,errorCode:m.code,errorMessage:m.message,supersededVersions:r?P0:W4(P0,m.snapshot.version)},g0)}else R.setFollowUpQueueMutation({pending:!1,errorMessage:"Follow-up queue is unavailable"},g0);return!1}}),r0=NY(B),U$=Y1((k)=>new Z8({signal:k,streamingBuffer:r0,getStreamingMessageId:()=>m0().session.currentStreamingMessageId,finalizeStreamingMessage:B.finalizeStreamingMessage,discardStreamingMessage:B.discardStreamingMessage,clearThinking:()=>B.setCurrentThinkingContent(null)})),d0=Y1(async()=>{if(!w||!z){R.setTeams([]);return}try{let E=await new bY({configDir:G8(),subagentRegistry:H4(K)}).list({sessionId:z,projectPath:K});if(m0().session.sessionId===z&&m0().session.workspaceRoot===K)R.setTeams(E)}catch(k){z8.warn("[useCommandHandler] Failed to refresh Agent Teams",k)}}),B1=Y1(async(k,E)=>{if(k.images.length>0)return{success:!1,error:"User shell commands do not accept image attachments"};let m=k.text.trimStart().slice(1).trim();if(!m)return{success:!1,error:"User shell command cannot be empty"};B.setCommand(`! ${m}`);try{let c=await h0(m,{signal:E});if(B.addMessage({id:`user-shell-${c.executionId}`,role:"user",content:w6(c.record),timestamp:Date.now(),metadata:{userShellCommand:c.record}}),c.delivery==="next_turn"){let r=m0().session;if(r.sessionId===z&&r.workspaceRoot===K)y.current?.request()}return{success:c.record.status!=="spawn_error",output:w6(c.record),...c.record.status==="spawn_error"?{error:c.record.stderr||"User shell command failed"}:{}}}finally{B.setCommand(null)}});d1(()=>{return()=>{L.current=null,r0.resetStreamingBuffers()}},[r0.resetStreamingBuffers]),d1(()=>{return()=>{S.current?.abort("side-conversation-session-change"),S.current=null,R.dismissSideConversation()}},[R,z,K]),d1(()=>{R.setTeams([]),d0()},[w,R,d0,z,K]),d1(()=>{if(!N)B.setCurrentThinkingContent(null)},[N,B]);let w1=Y1(()=>{if(S.current){S.current.abort("user-cancel"),S.current=null,R.dismissSideConversation();return}if(!U)return;X?.();let k=F.getAbortController()?.signal??new AbortController().signal;if((L.current??U$(k)).abortAndFinalize(()=>{F.abort("user-cancel"),R.setTasks([])}),!b.current)B.addAssistantMessage("任务已停止"),b.current=!0}),X8=Y1(async(k,E)=>{let m=`side-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;if(R.startSideConversation(m,E),k.images.length>0){R.failSideConversation(m,"Side conversations do not accept image attachments");return}if(!E){R.failSideConversation(m,"Usage: /btw <question>");return}S.current?.abort("side-conversation-replaced");let c=new AbortController;S.current=c;try{let r=await Y0(E,c.signal);if(c.signal.aborted||S.current!==c)return;if(R.completeSideConversation(m,r),r.usage)B.updateTokenUsage({scope:"auxiliary",inputTokens:r.usage.promptTokens,outputTokens:r.usage.completionTokens,totalTokens:r.usage.totalTokens,cacheReadTokens:r.usage.cacheReadInputTokens??0,cacheWriteTokens:r.usage.cacheCreationInputTokens??0,costUsd:r.usage.costUsd})}catch(r){if(c.signal.aborted||S.current!==c)return;R.failSideConversation(m,r instanceof Error?r.message:String(r))}finally{if(S.current===c)S.current=null}}),p1=Y1(async(k,E)=>{let m={contentDeltaCount:0,contentDeltaTotalLen:0,outputStarted:!1,toolExecutionStarted:!1,compactionCount:0},c=U$(E.signal);L.current=c;let r=S9({sessionActions:B,appActions:R,commandActions:F,streamingBuffer:r0,thinkingModeEnabled:N,getStreamingMessageId:()=>m0().session.currentStreamingMessageId,signal:E.signal,streamSession:c,followUpQueueOwner:g0},m);try{return{loopResult:await LY(k,r),stats:m}}finally{if(L.current===c)L.current=null}}),S2=Y1(async(k)=>{let E=!1,m,c=!1,r=k;try{if(k.text.trimStart().startsWith("!")){let X$=F.getAbortController()??F.createAbortController();return await B1(k,X$.signal)}await q8();let P0=F.getAbortController()??F.createAbortController(),l0=$4(m0().session),c0=await B6(k,R,B,P0.signal,C,z,$4(m0().session),{listCheckpoints:J0,execute:K0},{list:q0,resume:a},{getCatalog:f,refresh:v,getPrompt:U0,complete:V,listTasks:x,getTask:l,cancelTask:W0,getLogs:F0,setLoggingLevel:T0,getInstructions:I},{get:D,set:p},{get:h,set:n},{get:O0,set:X0},{get:R0,set:Q0},K,{run:S0},G);if(c0.type==="handled")return c0.commandResult;if(c0.type==="continue_as_agent")E=c0.result.userMessageAlreadyAdded,m=c0.result.onceModelId,c=c0.result.goalContinuationOnly===!0,r=c0.result.agentInput;let b$=E$.getInstance(),q1;if(!c){let X$=await b$.executeUserPromptSubmitHooks(r.text,{projectDir:K,sessionId:z,permissionMode:q,hasImages:r.images.length>0,imageCount:r.images.length});if(!X$.proceed){if(X$.warning)B.addAssistantMessage(`${X$.warning}`);return{success:!1,error:"blocked by hook"}}if(X$.updatedPrompt)r={...r,text:X$.updatedPrompt,displayText:X$.updatedPrompt,parts:[{type:"text",text:X$.updatedPrompt},...r.parts.filter((k2)=>k2.type==="image")]};if(X$.contextInjection)q1=X$.contextInjection}if(!E)B.addUserMessage(r.displayText);let Q2=O6(r),w$=await M(m?{modelId:m}:void 0);if(P0.signal.aborted)return z8.info("[handleCommandSubmit] Agent 创建期间已被中止"),{success:!1,error:"aborted"};if(q1)l0.push({role:"system",content:`<user-prompt-submit-hook>
35
35
  ${q1}
36
36
  </user-prompt-submit-hook>`});let l$={messages:l0,userId:"cli-user",sessionId:z,workspaceRoot:K,signal:P0.signal,confirmationHandler:Y,permissionMode:q,onPermissionModeChange:async(X$)=>{await z$().setPermissionMode(X$)}},{loopResult:O$,stats:P1}=await p1(w$.chatStream(Q2,l$,{stream:!0,goalContinuationOnly:c,onTurnLimitReached:Y?async(X$)=>{let k2=await Y.requestConfirmation({type:"maxTurnsExceeded",message:`已进行 ${X$.turnsCount} 轮对话。是否继续?`,risks:["继续执行可能导致更长的等待时间","可能产生更多的 API 费用"]});return{continue:k2.approved,reason:k2.reason}}:void 0}),P0);if(P1.compactionCount>0)B.setCompactedContext(l$.messages);if(O$.success&&O$.metadata?.outputTruncated)B.addAssistantMessage("输出因达到 token 上限被截断,部分内容可能不完整。");let A1=O$.finalMessage||"";if(z8.debug("[handleCommandSubmit] final reply",{success:O$.success,outputLength:A1.length,turnsCount:O$.metadata?.turnsCount,toolCallsCount:O$.metadata?.toolCallsCount}),!O$.success&&!HY(O$)){let X$=O$.error?.message||"任务执行失败";return B.addAssistantMessage(X$),{success:!1,error:X$}}if(!A1||A1.trim()===""){let X$=O$.metadata?.abortReason;if(!b.current&&P1.contentDeltaCount===0&&X$!=="interrupt")return B.addAssistantMessage("已取消"),{success:!0,output:"已取消"};return{success:!0,output:A1??""}}return{success:!0,output:A1}}catch(P0){if(b.current)return{success:!1,error:"aborted"};let l0=n8(P0),c0=typeof P0==="object"&&P0!==null&&"name"in P0&&P0.name==="AbortError";if(l0.isAbort||c0)return{success:!1,error:"aborted"};return B.addAssistantMessage(`${l0.displayMessage}`),{success:!1,error:l0.displayMessage}}}),Z2=Y1(async(k)=>{if(k.aborted)return{status:"completed"};if(m0().command.isProcessing)return{status:"deferred"};let E=await r$.hasPendingInbox(K,z),m=!E&&await r$.hasActiveGoal(K,z),c=!E&&!m&&await r$.hasRecoverableTurn(K,z);if(k.aborted)return{status:"completed"};if(!E&&!m&&!c)return{status:"completed"};if(m0().command.isProcessing)return{status:"deferred"};if(await q8(),k.aborted)return{status:"completed"};if(m0().command.isProcessing)return{status:"deferred"};let r=F.createAbortController(),P0="preflight",l0=()=>{if(!r.signal.aborted)r.abort("pending-resume-coordinator-disposed")};if(k.addEventListener("abort",l0,{once:!0}),k.aborted)l0();r0.resetStreamingBuffers(),B.clearFinalizingStreamingMessageId(),F.setProcessing(!0);try{let c0=await M();if(r.signal.aborted)return r.signal.reason==="interrupted-by-new-command"?{status:"deferred"}:{status:"completed"};let b$=await r$.hasPendingInbox(K,z),q1=!b$&&await r$.hasActiveGoal(K,z);if(r.signal.aborted)return r.signal.reason==="interrupted-by-new-command"?{status:"deferred"}:{status:"completed"};if(!b$&&!q1){let O$=F$();if(O$.state!=="none")_6(B,O$);return{status:"completed"}}P0=b$?"pending_input":"goal";let Q2={messages:$4(m0().session),userId:"cli-user",sessionId:z,workspaceRoot:K,signal:r.signal,confirmationHandler:Y,permissionMode:q,onPermissionModeChange:async(O$)=>{await z$().setPermissionMode(O$)}},{loopResult:w$,stats:l$}=await p1(c0.chatStream("",Q2,{stream:!0,pendingInputOnly:b$,goalContinuationOnly:q1}),r);if(l$.compactionCount>0)B.setCompactedContext(Q2.messages);if(r.signal.aborted)return r.signal.reason==="interrupted-by-new-command"?{status:"deferred"}:{status:"completed"};if(w$.success&&w$.metadata?.outputTruncated)B.addAssistantMessage("输出因达到 token 上限被截断,部分内容可能不完整。");if(!w$.success&&!HY(w$)){let O$=h2(w$.error?.details??w$.error?.message??"恢复排队指令失败");if(P0==="pending_input"){let P1=w$.metadata?.toolCallsCount,A1=typeof P1==="number"&&Number.isInteger(P1)&&P1>=0?P1:-1,X$=await r$.hasPendingInbox(K,z);if(r.signal.aborted)return r.signal.reason==="interrupted-by-new-command"?{status:"deferred"}:{status:"completed"};return{status:"failed",workKind:P0,workStillPending:X$,taskFailure:O$,evidence:{taskFailure:O$,outputStarted:l$.outputStarted,toolExecutionStarted:l$.toolExecutionStarted,toolCallsCount:A1}}}return{status:"failed",workKind:P0,workStillPending:!1,taskFailure:O$}}return{status:"completed"}}catch(c0){let b$=n8(c0);if(r.signal.reason==="interrupted-by-new-command")return{status:"deferred"};if(b$.isAbort||k.aborted)return{status:"completed"};return{status:"failed",workKind:P0,workStillPending:!1,taskFailure:h2(c0)}}finally{if(k.removeEventListener("abort",l0),F.getAbortController()===r)F.setProcessing(!1),F.clearAbortController(r),B.setCurrentThinkingContent(null),y.current?.notifyIdle()}}),I$=WY(()=>{let k="preflight";return new K6({canRun:()=>!m0().command.isProcessing,run:async(E)=>{k="preflight";let m=await Z2(E);if(m.status==="failed")k=m.workKind;return m},sessionIdentity:JSON.stringify([K,z]),onTerminalFailure:({taskFailure:E})=>{if(k==="preflight")B.setError(`恢复排队指令失败: ${E.message}`);else B.addAssistantMessage(E.message)}})},[Z2,B,z,K]);d1(()=>{return y.current=I$,()=>{if(I$.dispose(),y.current===I$)y.current=null}},[I$]),d1(()=>{return R.claimFollowUpQueueOwner(g0),()=>{R.clearFollowUpQueue(g0)}},[R,g0]);let e=Y1(async(k)=>{if(m0().app.activeModal==="sessionHistoryViewer")return;if(!k.text.trim()&&k.images.length===0)return;let E=BY(k.text);if(E){await X8(k,E.question);return}if(S.current?.abort("main-conversation-submitted"),S.current=null,R.dismissSideConversation(),k.text.trimStart().startsWith("!")&&U){let c=F.getAbortController();if(!c){B.addAssistantMessage("当前任务没有可用的取消边界,无法执行用户 Shell 命令。");return}let r=await B1(k,c.signal);if(!r.success&&r.error&&r.error!=="aborted")B.setError(r.error);return}if(U){if(k.text.trimStart().startsWith("/")){let c0=k.text.trim();if(/^\/(?:goal|queue)(?:\s|$)/i.test(c0)){await q8();let b$=F.getAbortController(),q1=/^\/queue(?:\s|$)/i.test(c0)?b$?.signal??new AbortController().signal:(b$??F.createAbortController()).signal;await B6(k,R,B,q1,C,z,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,K);return}B.addAssistantMessage("活动回合中不能执行 slash command;请先停止任务或等待完成。");return}await q8();let c=await E$.getInstance().executeUserPromptSubmitHooks(k.text,{projectDir:K,sessionId:z,permissionMode:q,hasImages:k.images.length>0,imageCount:k.images.length});if(!c.proceed){if(c.warning)B.addAssistantMessage(c.warning);return}let r=k;if(c.updatedPrompt)r={...k,text:c.updatedPrompt,parts:[{type:"text",text:c.updatedPrompt},...k.parts.filter((c0)=>c0.type==="image")]};if(c.contextInjection){let c0=`<user-prompt-submit-hook>
37
37
  ${c.contextInjection}
@@ -1,4 +1,4 @@
1
- import{e as U3,f as H3,g as R3,h as s0,i as q3}from"./chunk-wr1m9dr0.js";import{j as o1}from"./chunk-zj1g4nbq.js";import{v as a0,w as y2}from"./chunk-y6zhrc3p.js";import{A as m0,x as g2,y as p2,z as v2}from"./chunk-yhxjr3xd.js";import{B as C2,C as U$,D as H$,E as F$,F as z0,G as N$}from"./chunk-va15gerc.js";import{$ as I2,Ea as u3,J as B2,K as u1,L as v3,O as D2,P as e0,Q as d4,R as i1,S as g$,T as A4,U as j4,V as K0,W as L2,X as M2,Y as D$,Z as w1,aa as R2,ba as b4,ca as j0,da as H0,ga as q1,ha as E1,ia as O5,ja as q2,ka as E2,la as r2,ma as e2,na as O3,oa as $3,pa as Q3,qa as Z3,ra as J3,sa as Y3,ta as X3,wa as w3,za as W5}from"./chunk-m2gh9f07.js";import{La as q$,Ra as uO}from"./chunk-1nkczacx.js";import{Ua as A2,Wa as j2,Xa as b2,Ya as T2,cb as V4,fb as c3,gb as c4,hb as S2,ib as f2,jb as i3,kb as l3,lb as i4,mb as a3,nb as g0,ob as N3,pb as B3,qb as D3,rb as P2,sb as k2,tb as m2,ub as h2,vb as W$,wb as r4}from"./chunk-30x3mcsb.js";import{Kb as dO,Lb as a,Nb as P,Ob as x2,Zb as M4,hc as y0}from"./chunk-p9rx0a48.js";import{sc as T4}from"./chunk-zzvs471p.js";import{$c as W2,$d as D4,Cd as w2,Ic as V2,Md as A1,Nd as h0,Sc as z2,Ud as I1,Vd as I4,Wd as R1,Yd as o0,Zc as G2,_c as B4,ad as D1,bd as K2,ed as U4,ee as N2,fe as x4,ge as L4,he as g,rd as _2}from"./chunk-j1xkhc0r.js";import{Fe as U2,Me as H2,Ne as F2}from"./chunk-y5wngtz0.js";import{gf as L3,kf as M3,lf as A3,mf as j3,nf as b3,of as y4,pf as T3,qf as I3}from"./chunk-w33zjw8m.js";import{Pf as r3,Tf as MO,Xf as f$,cg as nO}from"./chunk-qw1ktyac.js";import{dg as c1}from"./chunk-t0gm0pn1.js";import{wg as J2}from"./chunk-50vwafn5.js";import{yg as B1}from"./chunk-1zx3pb13.js";import{Hg as e3,Lg as s2,Pg as H1,Qg as F1,Ug as B5,Xg as eO,Yg as N1,_g as X2,ah as s4}from"./chunk-by2txwsv.js";import{th as P$,uh as Y2}from"./chunk-vbjgcn49.js";import{yh as b$,zh as l0}from"./chunk-cbctk8hh.js";import{Mi as T$,Rh as R$,Ri as U1,fi as s$,ii as r$,ki as e$,li as O2,mi as h$,ni as y$,oi as K$,ui as $2,xi as Q2,zi as Z2}from"./chunk-4c8q1dbe.js";import{Ui as F4}from"./chunk-kv458q06.js";import{Wi as a1,Zi as N4}from"./chunk-5v0jcyea.js";import{bj as GO}from"./chunk-2f8d0km4.js";import{Dj as ZO,Fj as y,Hj as G,Ij as oO,Kj as zO}from"./chunk-2mk914vk.js";import{Pj as f0}from"./chunk-j8hbddjp.js";import{Rj as C$,Sj as o$,Uj as S$,Vj as t$}from"./chunk-4cdk4mds.js";import{Xj as i0}from"./chunk-y8qs0rys.js";import{ck as t4}from"./chunk-rvs364rz.js";import{Bk as g1,Jk as L$,fk as l1,zk as wO}from"./chunk-4wx5sya5.js";import{Mk as a4}from"./chunk-eg3ms291.js";var H8={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function F8(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{existsSync as e4,readFileSync as f1}from"node:fs";import{createServer as c6}from"node:http";import{networkInterfaces as i6}from"node:os";import{dirname as l6,extname as a6,join as E0}from"node:path";import{fileURLToPath as n6}from"node:url";import{brotliCompressSync as o6,gzipSync as t6,constants as s6}from"node:zlib";import{Hono as r6}from"hono";import{cors as e6}from"hono/cors";import{WebSocketServer as O8}from"ws";var c0=ZO("Service"),f5=30000,P5=new Set(["completed","failed","cancelled","interrupted"]);class z4{dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor(O){this.dispatch=O.dispatch,this.store=O.store??W$.getInstance(),this.tickMs=O.tickMs??f5}start(){if(this.timer)return;c0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=P.subscribe((O)=>{if(O.type!=="task.status")return;let $=O.properties.taskStatus;if(typeof $!=="string"||!P5.has($))return;this.recordTerminalStatus(O.sessionId,$,typeof O.properties.taskStatusReason==="string"?O.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,c0.info("[TaskScheduler] Stopped scheduler tick loop")}async tick(O=new Date){if(this.ticking)return;this.ticking=!0;try{let $=await this.store.list();for(let Q of $)await this.evaluate(Q,O)}catch($){c0.warn("[TaskScheduler] Tick failed:",$)}finally{this.ticking=!1}}async evaluate(O,$){if(!O.enabled)return;if(this.inFlight.has(O.id))return;if(O.expiresAt&&new Date(O.expiresAt).getTime()<=$.getTime()){await this.store.update(O.id,{enabled:!1,nextRunAt:null}),c0.info(`[TaskScheduler] Schedule ${O.id} expired; disabled`);return}if(!O.nextRunAt)return;if(!(new Date(O.nextRunAt).getTime()<=$.getTime()))return;await this.fire(O,$)}async fire(O,$=new Date,Q={}){if(this.inFlight.has(O.id))throw Error(`Schedule ${O.id} is already dispatching`);this.inFlight.add(O.id);let Z=$.toISOString();try{let J=await this.dispatch({prompt:O.prompt,title:O.title??k5(O),sourceProjectPath:O.projectPath,isolation:O.dispatch.isolation??"worktree",permissionMode:O.dispatch.permissionMode??"default",modelId:O.dispatch.modelId,reasoningEffort:O.dispatch.reasoningEffort,serviceTier:O.dispatch.serviceTier,responseVerbosity:O.dispatch.responseVerbosity,communicationStyle:O.dispatch.communicationStyle}),X=O.trigger.kind==="once"?null:Q.manual?O.nextRunAt?new Date(O.nextRunAt):null:V4(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:Z,lastRunSessionId:J.session.sessionId,lastStatus:J.status,lastError:void 0,runCount:O.runCount+1,nextRunAt:X?X.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled}),P.publish({sessionId:J.session.sessionId,projectPath:O.projectPath},"schedule.fired",{scheduleId:O.id,firedAt:Z,sessionId:J.session.sessionId,runId:J.runId,status:J.status}),c0.info(`[TaskScheduler] Fired schedule ${O.id} -> session ${J.session.sessionId} (${J.status})`)}catch(J){let X=J instanceof Error?J.message:String(J);c0.warn(`[TaskScheduler] Schedule ${O.id} dispatch failed:`,J);let V=O.trigger.kind==="once"?null:Q.manual?O.nextRunAt?new Date(O.nextRunAt):null:V4(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:Z,lastStatus:"error",lastError:X,nextRunAt:V?V.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled})}finally{this.inFlight.delete(O.id)}}async recordTerminalStatus(O,$,Q){let J=(await this.store.list()).find((X)=>X.lastRunSessionId===O);if(!J)return;await this.store.update(J.id,{lastStatus:$,...Q?{lastError:Q}:{lastError:void 0}})}}function k5(O){return`Scheduled: ${O.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class _O extends Error{code;statusCode;details;constructor(O,$,Q=500,Z){super($);this.code=O;this.statusCode=Q;this.details=Z;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class i extends _O{constructor(O,$){super("NOT_FOUND",$?`${O} not found: ${$}`:`${O} not found`,404)}}class F extends _O{constructor(O){super("BAD_REQUEST",O,400)}}class v extends _O{constructor(O){super("CONFLICT",O,409)}}class rO extends _O{constructor(O,$){super("TOO_MANY_REQUESTS",O,429,$)}}class LO extends _O{constructor(O="Server is shutting down"){super("SERVICE_UNAVAILABLE",O,503)}}class A0 extends _O{constructor(O){super("SESSION_WORKSPACE_UNAVAILABLE","This session workspace is no longer available",409,{reason:O})}}class vO extends _O{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class VO extends _O{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var j8=G.Object({error:G.Object({code:G.String(),message:G.String(),details:G.Optional(G.Record(G.String(),G.Unknown()))})});import{Hono as m5}from"hono";var G4=ZO("Service"),h5=G.Object({updates:G.Record(G.String(),G.Any()),options:G.Optional(G.Object({scope:G.Optional(zO(["local","project","global"])),immediate:G.Optional(G.Boolean())}))});function y5(O){return{currentModelId:O.currentModelId,permissionMode:O.permissionMode,language:O.language,codeTheme:O.codeTheme,uiTheme:O.uiTheme,autoSaveSessions:O.autoSaveSessions,notifyBuild:O.notifyBuild,notifyErrors:O.notifyErrors,notifySounds:O.notifySounds,privacyTelemetry:O.privacyTelemetry,privacyCrash:O.privacyCrash,agentTeamsEnabled:O.agentTeamsEnabled===!0,communicationStyle:O.communicationStyle,maxConcurrentTasks:O.maxConcurrentTasks,maxQueuedTasks:O.maxQueuedTasks,maxQueuedTaskBytes:O.maxQueuedTaskBytes,maxResidentSessionRuntimes:O.maxResidentSessionRuntimes,sessionRuntimeIdleMs:O.sessionRuntimeIdleMs,maxResidentSessionProjections:O.maxResidentSessionProjections,sessionProjectionIdleMs:O.sessionProjectionIdleMs}}var _$=()=>{let O=new m5;return O.get("/",async($)=>{try{let Q=MO();return $.json(Q?y5(Q):{})}catch(Q){return G4.error("[ConfigRoutes] Failed to get config:",Q),$.json({})}}),O.put("/",async($)=>{try{let Q=await $.req.json(),Z=y(h5,Q);if(!Z.success)throw new F("Invalid config update format");let{updates:J,options:X}=Z.data;return await nO().updateConfig(J,X),$.json({success:!0,updates:J})}catch(Q){if(Q instanceof K$)throw new F(Q.message);throw G4.error("[ConfigRoutes] Failed to update config:",Q),Q}}),O.get("/permissions",async($)=>{try{let Q=MO();return $.json(Q?.permissions||{})}catch(Q){return G4.error("[ConfigRoutes] Failed to get permissions:",Q),$.json({})}}),O};import{Hono as g5}from"hono";import{streamSSE as p5}from"hono/streaming";function w$(O){let $="";if(O.id!==void 0)$+=`id: ${O.id}
1
+ import{e as U3,f as H3,g as R3,h as s0,i as q3}from"./chunk-dd5jptem.js";import{j as o1}from"./chunk-zj1g4nbq.js";import{v as a0,w as y2}from"./chunk-0gwf5gkf.js";import{A as m0,x as g2,y as p2,z as v2}from"./chunk-0dsqjvg8.js";import{B as C2,C as U$,D as H$,E as F$,F as z0,G as N$}from"./chunk-1h19j4h5.js";import{$ as I2,Ea as u3,J as B2,K as u1,L as v3,O as D2,P as e0,Q as d4,R as i1,S as g$,T as A4,U as j4,V as K0,W as L2,X as M2,Y as D$,Z as w1,aa as R2,ba as b4,ca as j0,da as H0,ga as q1,ha as E1,ia as O5,ja as q2,ka as E2,la as r2,ma as e2,na as O3,oa as $3,pa as Q3,qa as Z3,ra as J3,sa as Y3,ta as X3,wa as w3,za as W5}from"./chunk-jwb09kyr.js";import{La as q$,Ra as uO}from"./chunk-wcrxh6rm.js";import{Ua as A2,Wa as j2,Xa as b2,Ya as T2,cb as V4,fb as c3,gb as c4,hb as S2,ib as f2,jb as i3,kb as l3,lb as i4,mb as a3,nb as g0,ob as N3,pb as B3,qb as D3,rb as P2,sb as k2,tb as m2,ub as h2,vb as W$,wb as r4}from"./chunk-30x3mcsb.js";import{Kb as dO,Lb as a,Nb as P,Ob as x2,Zb as M4,hc as y0}from"./chunk-r2qv7nx5.js";import{sc as T4}from"./chunk-zzvs471p.js";import{$c as W2,$d as D4,Cd as w2,Ic as V2,Md as A1,Nd as h0,Sc as z2,Ud as I1,Vd as I4,Wd as R1,Yd as o0,Zc as G2,_c as B4,ad as D1,bd as K2,ed as U4,ee as N2,fe as x4,ge as L4,he as g,rd as _2}from"./chunk-zacyth0b.js";import{Fe as U2,Me as H2,Ne as F2}from"./chunk-y5wngtz0.js";import{gf as L3,kf as M3,lf as A3,mf as j3,nf as b3,of as y4,pf as T3,qf as I3}from"./chunk-w33zjw8m.js";import{Pf as r3,Tf as MO,Xf as f$,cg as nO}from"./chunk-a9qm5jtz.js";import{dg as c1}from"./chunk-t0gm0pn1.js";import{wg as J2}from"./chunk-50vwafn5.js";import{yg as B1}from"./chunk-cbqmf0vm.js";import{Hg as e3,Lg as s2,Pg as H1,Qg as F1,Ug as B5,Xg as eO,Yg as N1,_g as X2,ah as s4}from"./chunk-azbwg9vk.js";import{th as P$,uh as Y2}from"./chunk-vbjgcn49.js";import{yh as b$,zh as l0}from"./chunk-xjvq4ee8.js";import{Mi as T$,Rh as R$,Ri as U1,fi as s$,ii as r$,ki as e$,li as O2,mi as h$,ni as y$,oi as K$,ui as $2,xi as Q2,zi as Z2}from"./chunk-aazwy1r8.js";import{Ui as F4}from"./chunk-kv458q06.js";import{Wi as a1,Zi as N4}from"./chunk-5v0jcyea.js";import{bj as GO}from"./chunk-2f8d0km4.js";import{Dj as ZO,Fj as y,Hj as G,Ij as oO,Kj as zO}from"./chunk-2mk914vk.js";import{Pj as f0}from"./chunk-j8hbddjp.js";import{Rj as C$,Sj as o$,Uj as S$,Vj as t$}from"./chunk-4cdk4mds.js";import{Xj as i0}from"./chunk-7z0ah4z0.js";import{ck as t4}from"./chunk-rvs364rz.js";import{Bk as g1,Jk as L$,fk as l1,zk as wO}from"./chunk-4wx5sya5.js";import{Mk as a4}from"./chunk-eg3ms291.js";var H8={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function F8(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{existsSync as e4,readFileSync as f1}from"node:fs";import{createServer as c6}from"node:http";import{networkInterfaces as i6}from"node:os";import{dirname as l6,extname as a6,join as E0}from"node:path";import{fileURLToPath as n6}from"node:url";import{brotliCompressSync as o6,gzipSync as t6,constants as s6}from"node:zlib";import{Hono as r6}from"hono";import{cors as e6}from"hono/cors";import{WebSocketServer as O8}from"ws";var c0=ZO("Service"),f5=30000,P5=new Set(["completed","failed","cancelled","interrupted"]);class z4{dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor(O){this.dispatch=O.dispatch,this.store=O.store??W$.getInstance(),this.tickMs=O.tickMs??f5}start(){if(this.timer)return;c0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=P.subscribe((O)=>{if(O.type!=="task.status")return;let $=O.properties.taskStatus;if(typeof $!=="string"||!P5.has($))return;this.recordTerminalStatus(O.sessionId,$,typeof O.properties.taskStatusReason==="string"?O.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,c0.info("[TaskScheduler] Stopped scheduler tick loop")}async tick(O=new Date){if(this.ticking)return;this.ticking=!0;try{let $=await this.store.list();for(let Q of $)await this.evaluate(Q,O)}catch($){c0.warn("[TaskScheduler] Tick failed:",$)}finally{this.ticking=!1}}async evaluate(O,$){if(!O.enabled)return;if(this.inFlight.has(O.id))return;if(O.expiresAt&&new Date(O.expiresAt).getTime()<=$.getTime()){await this.store.update(O.id,{enabled:!1,nextRunAt:null}),c0.info(`[TaskScheduler] Schedule ${O.id} expired; disabled`);return}if(!O.nextRunAt)return;if(!(new Date(O.nextRunAt).getTime()<=$.getTime()))return;await this.fire(O,$)}async fire(O,$=new Date,Q={}){if(this.inFlight.has(O.id))throw Error(`Schedule ${O.id} is already dispatching`);this.inFlight.add(O.id);let Z=$.toISOString();try{let J=await this.dispatch({prompt:O.prompt,title:O.title??k5(O),sourceProjectPath:O.projectPath,isolation:O.dispatch.isolation??"worktree",permissionMode:O.dispatch.permissionMode??"default",modelId:O.dispatch.modelId,reasoningEffort:O.dispatch.reasoningEffort,serviceTier:O.dispatch.serviceTier,responseVerbosity:O.dispatch.responseVerbosity,communicationStyle:O.dispatch.communicationStyle}),X=O.trigger.kind==="once"?null:Q.manual?O.nextRunAt?new Date(O.nextRunAt):null:V4(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:Z,lastRunSessionId:J.session.sessionId,lastStatus:J.status,lastError:void 0,runCount:O.runCount+1,nextRunAt:X?X.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled}),P.publish({sessionId:J.session.sessionId,projectPath:O.projectPath},"schedule.fired",{scheduleId:O.id,firedAt:Z,sessionId:J.session.sessionId,runId:J.runId,status:J.status}),c0.info(`[TaskScheduler] Fired schedule ${O.id} -> session ${J.session.sessionId} (${J.status})`)}catch(J){let X=J instanceof Error?J.message:String(J);c0.warn(`[TaskScheduler] Schedule ${O.id} dispatch failed:`,J);let V=O.trigger.kind==="once"?null:Q.manual?O.nextRunAt?new Date(O.nextRunAt):null:V4(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:Z,lastStatus:"error",lastError:X,nextRunAt:V?V.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled})}finally{this.inFlight.delete(O.id)}}async recordTerminalStatus(O,$,Q){let J=(await this.store.list()).find((X)=>X.lastRunSessionId===O);if(!J)return;await this.store.update(J.id,{lastStatus:$,...Q?{lastError:Q}:{lastError:void 0}})}}function k5(O){return`Scheduled: ${O.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class _O extends Error{code;statusCode;details;constructor(O,$,Q=500,Z){super($);this.code=O;this.statusCode=Q;this.details=Z;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class i extends _O{constructor(O,$){super("NOT_FOUND",$?`${O} not found: ${$}`:`${O} not found`,404)}}class F extends _O{constructor(O){super("BAD_REQUEST",O,400)}}class v extends _O{constructor(O){super("CONFLICT",O,409)}}class rO extends _O{constructor(O,$){super("TOO_MANY_REQUESTS",O,429,$)}}class LO extends _O{constructor(O="Server is shutting down"){super("SERVICE_UNAVAILABLE",O,503)}}class A0 extends _O{constructor(O){super("SESSION_WORKSPACE_UNAVAILABLE","This session workspace is no longer available",409,{reason:O})}}class vO extends _O{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class VO extends _O{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var j8=G.Object({error:G.Object({code:G.String(),message:G.String(),details:G.Optional(G.Record(G.String(),G.Unknown()))})});import{Hono as m5}from"hono";var G4=ZO("Service"),h5=G.Object({updates:G.Record(G.String(),G.Any()),options:G.Optional(G.Object({scope:G.Optional(zO(["local","project","global"])),immediate:G.Optional(G.Boolean())}))});function y5(O){return{currentModelId:O.currentModelId,permissionMode:O.permissionMode,language:O.language,codeTheme:O.codeTheme,uiTheme:O.uiTheme,autoSaveSessions:O.autoSaveSessions,notifyBuild:O.notifyBuild,notifyErrors:O.notifyErrors,notifySounds:O.notifySounds,privacyTelemetry:O.privacyTelemetry,privacyCrash:O.privacyCrash,agentTeamsEnabled:O.agentTeamsEnabled===!0,communicationStyle:O.communicationStyle,maxConcurrentTasks:O.maxConcurrentTasks,maxQueuedTasks:O.maxQueuedTasks,maxQueuedTaskBytes:O.maxQueuedTaskBytes,maxResidentSessionRuntimes:O.maxResidentSessionRuntimes,sessionRuntimeIdleMs:O.sessionRuntimeIdleMs,maxResidentSessionProjections:O.maxResidentSessionProjections,sessionProjectionIdleMs:O.sessionProjectionIdleMs}}var _$=()=>{let O=new m5;return O.get("/",async($)=>{try{let Q=MO();return $.json(Q?y5(Q):{})}catch(Q){return G4.error("[ConfigRoutes] Failed to get config:",Q),$.json({})}}),O.put("/",async($)=>{try{let Q=await $.req.json(),Z=y(h5,Q);if(!Z.success)throw new F("Invalid config update format");let{updates:J,options:X}=Z.data;return await nO().updateConfig(J,X),$.json({success:!0,updates:J})}catch(Q){if(Q instanceof K$)throw new F(Q.message);throw G4.error("[ConfigRoutes] Failed to update config:",Q),Q}}),O.get("/permissions",async($)=>{try{let Q=MO();return $.json(Q?.permissions||{})}catch(Q){return G4.error("[ConfigRoutes] Failed to get permissions:",Q),$.json({})}}),O};import{Hono as g5}from"hono";import{streamSSE as p5}from"hono/streaming";function w$(O){let $="";if(O.id!==void 0)$+=`id: ${O.id}
2
2
  `;if(O.event!==void 0)$+=`event: ${O.event}
3
3
  `;for(let Q of O.data.split(/\r\n|\r|\n/))$+=`data: ${Q}
4
4
  `;if(O.retry!==void 0)$+=`retry: ${O.retry}
@@ -1 +1 @@
1
- import{$b as h,Qb as a,Rb as b,Tb as c,Xb as d,Yb as e,Zb as f,_b as g,ac as i,bc as j,cc as k,kc as l,lc as m,mc as n,nc as o,pc as p,qc as q,rc as r}from"./chunk-p9rx0a48.js";import"./chunk-zzvs471p.js";import"./chunk-j1xkhc0r.js";import"./chunk-53fc0yrq.js";import"./chunk-y5wngtz0.js";import"./chunk-w33zjw8m.js";import"./chunk-t0gm0pn1.js";import"./chunk-1yq72zb7.js";import"./chunk-kqvzmnja.js";import"./chunk-50vwafn5.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-cbctk8hh.js";import"./chunk-3y2x6fb6.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-y8qs0rys.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.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
+ import{$b as h,Qb as a,Rb as b,Tb as c,Xb as d,Yb as e,Zb as f,_b as g,ac as i,bc as j,cc as k,kc as l,lc as m,mc as n,nc as o,pc as p,qc as q,rc as r}from"./chunk-r2qv7nx5.js";import"./chunk-zzvs471p.js";import"./chunk-zacyth0b.js";import"./chunk-53fc0yrq.js";import"./chunk-y5wngtz0.js";import"./chunk-w33zjw8m.js";import"./chunk-t0gm0pn1.js";import"./chunk-1yq72zb7.js";import"./chunk-kqvzmnja.js";import"./chunk-50vwafn5.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-xjvq4ee8.js";import"./chunk-3y2x6fb6.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-7z0ah4z0.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.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,4 +1,4 @@
1
- import{Ga as W3}from"./chunk-g01mth5d.js";import{Ja as T,Ka as $$,Pa as HW,Qa as fY,Ra as e0}from"./chunk-1nkczacx.js";import{$a as BX,Sa as Y5,Va as pZ,Za as tZ,_a as zX,bb as nW,db as aW,eb as A9,wb as sW}from"./chunk-30x3mcsb.js";import{Ab as p7,Bb as D2,Cb as GY,Db as x1,Eb as s7,Fb as DY,Gb as ZY,Hb as qY,Ib as wY,Jb as UQ,Lb as YX,Nb as V0,Pb as F2,Sb as p4,Ub as FZ,Vb as l4,Wb as i4,Yb as MJ,Zb as R$,dc as sX,ec as G8,fc as oX,gc as JX,ic as u1,jc as kX,oc as rY,rc as nY,xb as s5,yb as g7,zb as J1}from"./chunk-p9rx0a48.js";import{$c as r8,$d as iY,Ac as k3,Bc as T1,Cc as ZJ,Dc as F0,Ec as S2,Fc as N1,Gc as S6,Hc as f9,Ic as m4,Jc as c4,Kc as YY,Lc as QY,Mc as TX,Nc as X3,Nd as V8,Oc as A1,Pc as Y3,Pd as f0,Qc as i8,Qd as b$,Rc as $1,Sc as Z1,Tc as l2,Uc as p2,Vc as i2,Wc as g6,Xc as u6,Xd as YW,Yc as d2,Yd as HX,Zc as z3,_c as m2,ad as M1,bd as e1,cd as c2,dd as $2,ed as Z2,ee as PX,fd as d6,fe as SX,gd as J2,hd as m6,he as o,id as c6,jd as k$,kd as p6,ld as O3,md as r2,nd as l6,od as i6,pd as r6,qd as n6,rd as N3,sd as b3,ud as j3,xc as v$,yc as CX,zc as r3}from"./chunk-j1xkhc0r.js";import{ie as i,je as GQ,ke as KQ,le as hJ,ne as _2}from"./chunk-53fc0yrq.js";import{Ge as P9,He as J$,Ie as q2,Je as $9,Ke as RX,Le as fX,Ue as $V,ff as ZV,pe as tW,se as eW}from"./chunk-y5wngtz0.js";import{Bf as NJ,Cf as LJ}from"./chunk-jj4ggb04.js";import{Of as r4,Pf as q0,Qf as d,Tf as j0,Uf as P4,Vf as L2,Wf as G1,Xf as CZ,Yf as R1,Zf as pY,cg as B2}from"./chunk-qw1ktyac.js";import{dg as d1}from"./chunk-t0gm0pn1.js";import{hg as jZ,ig as lY,ng as mY,og as cX,pg as S4}from"./chunk-1yq72zb7.js";import{qg as nZ}from"./chunk-kqvzmnja.js";import{tg as m0,ug as O1}from"./chunk-0mr8nexh.js";import{vg as eX}from"./chunk-50vwafn5.js";import{Ag as jX,xg as OX,yg as NX,zg as bX}from"./chunk-1zx3pb13.js";import{$g as MX,Bg as I4,Cg as h4,Dg as g4,Fg as u4,Gg as d4,Hg as F1,Ig as FQ,Jg as I$,Kg as j$,Lg as G$,Mg as $5,Ng as V2,Og as z8,Pg as l1,Qg as i1,Rg as AX,Vg as J9,Xg as c0,Yg as f$,_g as k4,ah as vX}from"./chunk-by2txwsv.js";import{ch as D1,eh as T$,fh as O4}from"./chunk-3kszepm6.js";import{gh as d3,hh as W2,ih as m3,jh as s2,kh as c3,lh as p3,mh as Z4,nh as $4,oh as l3,ph as i3,qh as e6}from"./chunk-wcps5gjm.js";import{rh as LW,th as EX,uh as W8,vh as bJ}from"./chunk-vbjgcn49.js";import{xh as L9,zh as x0}from"./chunk-cbctk8hh.js";import{Ah as E6,Bh as R9,Ch as A6,Dh as r1}from"./chunk-3y2x6fb6.js";import{Ci as SY,Di as kY,Ei as vY,Fh as XJ,Fi as yY,Gi as AZ,Hi as xY,Ii as B1,Ji as IY,Kh as WJ,Ki as hY,Li as gY,Mh as D9,Ni as t3,Pi as xX,Qi as LX,Rh as UW,Ri as B0,Vh as VJ,Xh as wX,Zh as zY,_h as BY,pi as h1,si as $Y}from"./chunk-4c8q1dbe.js";import{Ui as L$}from"./chunk-kv458q06.js";import{Wi as $X,Yi as ZX}from"./chunk-5v0jcyea.js";import{$i as X4,bj as C}from"./chunk-2f8d0km4.js";import{Dj as e,Fj as a6,Gj as X2,Hj as K,Ij as R3,Jj as P,Kj as u}from"./chunk-2mk914vk.js";import{Oj as _X,Pj as FX}from"./chunk-j8hbddjp.js";import{Qj as NW,Tj as _W}from"./chunk-4cdk4mds.js";import{Xj as AW}from"./chunk-y8qs0rys.js";import{bk as yX,ck as a0}from"./chunk-rvs364rz.js";import{Bk as E$,Gk as u3,fk as t,gk as N$,hk as D$,ik as t1,jk as o9,kk as u2,lk as X$,mk as e7,pk as I6,yk as P6}from"./chunk-4wx5sya5.js";import{Mk as Y$}from"./chunk-eg3ms291.js";import{randomUUID as M8}from"crypto";import{randomUUID as LV}from"node:crypto";var DV=String.raw`
1
+ import{Ga as W3}from"./chunk-g01mth5d.js";import{Ja as T,Ka as $$,Pa as HW,Qa as fY,Ra as e0}from"./chunk-wcrxh6rm.js";import{$a as BX,Sa as Y5,Va as pZ,Za as tZ,_a as zX,bb as nW,db as aW,eb as A9,wb as sW}from"./chunk-30x3mcsb.js";import{Ab as p7,Bb as D2,Cb as GY,Db as x1,Eb as s7,Fb as DY,Gb as ZY,Hb as qY,Ib as wY,Jb as UQ,Lb as YX,Nb as V0,Pb as F2,Sb as p4,Ub as FZ,Vb as l4,Wb as i4,Yb as MJ,Zb as R$,dc as sX,ec as G8,fc as oX,gc as JX,ic as u1,jc as kX,oc as rY,rc as nY,xb as s5,yb as g7,zb as J1}from"./chunk-r2qv7nx5.js";import{$c as r8,$d as iY,Ac as k3,Bc as T1,Cc as ZJ,Dc as F0,Ec as S2,Fc as N1,Gc as S6,Hc as f9,Ic as m4,Jc as c4,Kc as YY,Lc as QY,Mc as TX,Nc as X3,Nd as V8,Oc as A1,Pc as Y3,Pd as f0,Qc as i8,Qd as b$,Rc as $1,Sc as Z1,Tc as l2,Uc as p2,Vc as i2,Wc as g6,Xc as u6,Xd as YW,Yc as d2,Yd as HX,Zc as z3,_c as m2,ad as M1,bd as e1,cd as c2,dd as $2,ed as Z2,ee as PX,fd as d6,fe as SX,gd as J2,hd as m6,he as o,id as c6,jd as k$,kd as p6,ld as O3,md as r2,nd as l6,od as i6,pd as r6,qd as n6,rd as N3,sd as b3,ud as j3,xc as v$,yc as CX,zc as r3}from"./chunk-zacyth0b.js";import{ie as i,je as GQ,ke as KQ,le as hJ,ne as _2}from"./chunk-53fc0yrq.js";import{Ge as P9,He as J$,Ie as q2,Je as $9,Ke as RX,Le as fX,Ue as $V,ff as ZV,pe as tW,se as eW}from"./chunk-y5wngtz0.js";import{Bf as NJ,Cf as LJ}from"./chunk-jj4ggb04.js";import{Of as r4,Pf as q0,Qf as d,Tf as j0,Uf as P4,Vf as L2,Wf as G1,Xf as CZ,Yf as R1,Zf as pY,cg as B2}from"./chunk-a9qm5jtz.js";import{dg as d1}from"./chunk-t0gm0pn1.js";import{hg as jZ,ig as lY,ng as mY,og as cX,pg as S4}from"./chunk-1yq72zb7.js";import{qg as nZ}from"./chunk-kqvzmnja.js";import{tg as m0,ug as O1}from"./chunk-0mr8nexh.js";import{vg as eX}from"./chunk-50vwafn5.js";import{Ag as jX,xg as OX,yg as NX,zg as bX}from"./chunk-cbqmf0vm.js";import{$g as MX,Bg as I4,Cg as h4,Dg as g4,Fg as u4,Gg as d4,Hg as F1,Ig as FQ,Jg as I$,Kg as j$,Lg as G$,Mg as $5,Ng as V2,Og as z8,Pg as l1,Qg as i1,Rg as AX,Vg as J9,Xg as c0,Yg as f$,_g as k4,ah as vX}from"./chunk-azbwg9vk.js";import{ch as D1,eh as T$,fh as O4}from"./chunk-3kszepm6.js";import{gh as d3,hh as W2,ih as m3,jh as s2,kh as c3,lh as p3,mh as Z4,nh as $4,oh as l3,ph as i3,qh as e6}from"./chunk-wcps5gjm.js";import{rh as LW,th as EX,uh as W8,vh as bJ}from"./chunk-vbjgcn49.js";import{xh as L9,zh as x0}from"./chunk-xjvq4ee8.js";import{Ah as E6,Bh as R9,Ch as A6,Dh as r1}from"./chunk-3y2x6fb6.js";import{Ci as SY,Di as kY,Ei as vY,Fh as XJ,Fi as yY,Gi as AZ,Hi as xY,Ii as B1,Ji as IY,Kh as WJ,Ki as hY,Li as gY,Mh as D9,Ni as t3,Pi as xX,Qi as LX,Rh as UW,Ri as B0,Vh as VJ,Xh as wX,Zh as zY,_h as BY,pi as h1,si as $Y}from"./chunk-aazwy1r8.js";import{Ui as L$}from"./chunk-kv458q06.js";import{Wi as $X,Yi as ZX}from"./chunk-5v0jcyea.js";import{$i as X4,bj as C}from"./chunk-2f8d0km4.js";import{Dj as e,Fj as a6,Gj as X2,Hj as K,Ij as R3,Jj as P,Kj as u}from"./chunk-2mk914vk.js";import{Oj as _X,Pj as FX}from"./chunk-j8hbddjp.js";import{Qj as NW,Tj as _W}from"./chunk-4cdk4mds.js";import{Xj as AW}from"./chunk-7z0ah4z0.js";import{bk as yX,ck as a0}from"./chunk-rvs364rz.js";import{Bk as E$,Gk as u3,fk as t,gk as N$,hk as D$,ik as t1,jk as o9,kk as u2,lk as X$,mk as e7,pk as I6,yk as P6}from"./chunk-4wx5sya5.js";import{Mk as Y$}from"./chunk-eg3ms291.js";import{randomUUID as M8}from"crypto";import{randomUUID as LV}from"node:crypto";var DV=String.raw`
2
2
  const { spawn } = require('node:child_process');
3
3
  const [ownerPidValue, command, ...args] = process.argv.slice(1);
4
4
  const ownerPid = Number(ownerPidValue);
@@ -861,7 +861,7 @@ ${A0}
861
861
  </approved-plan>
862
862
 
863
863
  IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof O==="string")S$=O+j6;else S$=[...O,{type:"text",text:j6}]}S=yield*this.runLoop(S$,b,{...x,inputMessageId:void 0})}if(!this.sessionRuntime||!I)return S;let l=await this.sessionRuntime.recordGoalProgress({tokens:S.metadata?.tokensUsed??0,elapsedMs:S.metadata?.duration??0,...v?{goalId:v.goalId,objective:v.objective,turnId:I.id}:{},executionHostFailureCategory:S.metadata?.executionHostFailureCategory,prematureStopPattern:S.success?HY(S.finalMessage):void 0});if(l)yield{kind:"goal_updated",goal:l};if(!S.success||b.signal?.aborted){if(l=await this.sessionRuntime.pauseActiveGoal(b.signal?.aborted?"goal paused after user cancellation":S.error?.message??"goal paused after turn failure"),l)yield{kind:"goal_updated",goal:l}}if(S.success&&!b.signal?.aborted&&h<20)await this.sessionRuntime.waitForBackgroundSubagentFollowUp(I,b.signal);let a=S.success&&!b.signal?.aborted&&h<20,p0=WG(S)||!S.success&&S.error?.type==="max_turns_exceeded";if(R=await this.sessionRuntime.finishTurn(I,{continuePending:a,...p0?{acknowledgeInput:!0}:{},outcome:S.success&&!b.signal?.aborted?{status:"completed",turnsCount:S.metadata?.turnsCount??0,toolCallsCount:S.metadata?.toolCallsCount??0,durationMs:S.metadata?.duration??0}:{status:"aborted",cause:b.signal?.aborted?"cancelled":"failed",turnsCount:S.metadata?.turnsCount??0,toolCallsCount:S.metadata?.toolCallsCount??0,durationMs:S.metadata?.duration??0}}),R){h++,N=!0,A=!1,j=null,O="",p=void 0,M="",k=void 0,E=Z0(),yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:$0(),queue:await this.sessionRuntime.getFollowUpQueueSnapshot()};continue}if(yield{kind:"follow_up_queue_changed",queue:await this.sessionRuntime.getFollowUpQueueSnapshot()},!S.success||b.signal?.aborted)return S;if(l=await this.sessionRuntime.getGoal(),!l||l.status!=="active"&&l.status!=="verifying")return S;let J0=await this.sessionRuntime.prepareGoalContinuation(l);if(!J0.ok){if(J0.goal)yield{kind:"goal_updated",goal:J0.goal};return{success:!1,error:{type:"goal_frontier_unavailable",message:J0.error.message},metadata:{turnsCount:S.metadata?.turnsCount??0,toolCallsCount:S.metadata?.toolCallsCount??0,duration:S.metadata?.duration??0}}}let h0=await this.sessionRuntime.beginGoalTurn(J0.goal);if(!h0)return S;j=h0.goal,q={...J0,goal:h0.goal},R=h0.handle,N=!1,A=!0,O=S5(j),p=void 0,E=void 0,yield{kind:"goal_frontier_updated",goal:j,frontier:J0.frontier,tasks:J0.tasks},yield{kind:"goal_continuation_started",goal:j,continuation:j.continuationCount,...j.prematureStop?{prematureStopPattern:j.prematureStop.pattern,prematureStopCount:j.prematureStop.consecutiveCount}:{}},yield{kind:"goal_updated",goal:j}}}finally{if(this.sessionRuntime&&R)await this.sessionRuntime.finishTurn(R)}}let F=typeof z==="string"?z:z.filter((O)=>O.type==="text").map((O)=>O.text).join(`
864
- `),L={id:this.generateTaskId(),type:"simple",prompt:F};return{success:!0,finalMessage:(await this.executeTask(L)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-jjj852tg.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){s.debug("Processing Plan mode message...");let{prompt:Y}=await Y1({...Z.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:Z.workspaceRoot||C()},mode:"plan",includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:Z.executionRoot??Z.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...Z.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}}),Q;if(typeof $==="string")Q=t2($);else{let X=$.filter((W)=>W.type==="text");if(X.length>0){let W=X[0];Q=$.map((V)=>V===W?{type:"text",text:t2(W.text)}:V)}else Q=[{type:"text",text:t2("")},...$]}return yield*this.executeLoop(Q,Z,J,Y)}async*runLoop($,Z,J){s.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z);return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await Y1({...$.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:$.workspaceRoot||C()},replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:$.executionRoot??$.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...$.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let Q=this.buildLoopDependencies();return nY(Q,$,Z,J,Y)}takeStartupAdoptedToolResultEvents(){return(this.sessionRuntime?.takeStartupAdoptedToolResults()??[]).flatMap(({call:Z,result:J})=>{let Y={id:Z.toolCallId,type:"function",function:{name:Z.toolName,arguments:JSON.stringify(Z.input)}},Q=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,X=J.error===void 0,W=J.output,V={success:X,llmContent:typeof W==="string"||W!==null&&typeof W==="object"?W:W===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(W),...J.error?{error:{type:"execution_error",message:J.error}}:{},...Q?{metadata:Q}:{}},U=[{kind:"tool_result",toolCall:Y,result:V}],H=rY(Y,V);if(H)U.push(H);return U})}takeStartupRecoveryEvents(){let $=this.sessionRuntime?.getTurnRecoveryAssessment(),Z=$?.state==="requires_attention"?$:this.sessionRuntime?.takeStartupTurnRecoveryAssessment(),J=Z&&Z.state!=="none"?[{kind:"turn_recovery",assessment:Z}]:[];return J.push(...this.takeStartupAdoptedToolResultEvents()),J}buildLoopDependencies(){return{chatService:this.chatService,toolExecutor:this.toolExecutor,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,s.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($),staticProjectRules:this.sessionRuntime?.getStaticProjectRules(),hydrateProjectRules:this.sessionRuntime?($)=>this.sessionRuntime.hydrateProjectRules($):void 0,resolveContextualProjectRules:this.sessionRuntime?($,Z,J,Y)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,Y):void 0}}async chatWithSystem($,Z){if(!this.isInitialized)throw Error("Agent未初始化");let J=[{role:"system",content:$},{role:"user",content:Z}];return(await this.chatService.chat(J)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.toolExecutor?this.toolExecutor.getRegistry().getAll():[]}getToolRegistry(){return this.toolExecutor.getRegistry()}applyToolWhitelist($){let Z=this.toolExecutor.getRegistry(),Y=Z.getAll().filter((Q)=>!$.includes(Q.name));for(let Q of Y)Z.unregister(Q.name);s.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let Y of Z.getAll())if(J.has(Y.name))Z.unregister(Y.name);s.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let Y=Z.get(J.kind)||0;Z.set(J.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.name)}}async destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=(async()=>{this.log("销毁Agent..."),await this.activeOperations.shutdown("agent-destroy");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}})(),this.destroyPromise}syncRuntimeState(){if(!this.sessionRuntime)return;this.chatService=this.sessionRuntime.getChatService(),this.executionEngine=this.sessionRuntime.getExecutionEngine(),this.attachmentCollector=this.sessionRuntime.getAttachmentCollector(),this.currentModelId=this.sessionRuntime.getCurrentModelId(),this.currentModelMaxContextTokens=this.sessionRuntime.getCurrentModelMaxContextTokens()}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}log($,Z){s.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){s.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await Y1({...this.sessionRuntime?.isRemoteWorkspace()?{workspaceAccess:"none"}:{projectPath:this.sessionRuntime?.workspaceRoot??C()},replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...this.sessionRuntime?.isRemoteWorkspace()?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot},...this.sessionRuntime?{environmentOptions:{...u1,workingDirectory:this.sessionRuntime.executionRoot}}:{}});if(J.prompt)this.log("系统提示配置验证成功"),s.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await v4({sessionId:"default",configDir:t(),workspaceRoot:C(),resourceRoot:C(),agentResources:this.agentResources});s.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;s.debug(`Builtin tools registered: ${Z} tools`),s.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw s.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await W4({workspaceRoot:C(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){s.debug("No MCP servers configured");return}let Z=e0.createIsolated({artifactWriter:new o2(`legacy-${XG()}`)});this.legacyMcpRegistry=Z;for(let[X,W]of Object.entries($))try{s.debug(`Connecting to MCP server: ${X}`),await Z.registerServer(X,W),s.debug(`MCP server "${X}" connected`)}catch(V){s.warn(`Warning: MCP server "${X}" connection failed:`,V)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(Y6(Z));let Q=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:Q.revision,reason:"snapshot",replace:!0,instructions:Q.instructions,removed:[]}),Z.on("catalogChanged",(X)=>{J.replaceMcpTools(X.tools,X)}),Z.on("contentCatalogChanged",(X)=>{J.queueMcpContentChange(X)}),Z.on("resourceUpdated",(X)=>{J.queueMcpResourceUpdated(X)}),Z.on("connectionLifecycleChanged",(X)=>{J.queueMcpConnectionChange(X)}),Z.on("log",(X)=>{J.queueMcpLog(X)}),Z.on("instructionsChanged",(X)=>{J.queueMcpInstructionsChange({revision:X.revision,reason:X.reason,replace:!1,instructions:X.action==="added"&&X.instruction?[{serverName:X.serverName,...X.instruction}]:[],removed:X.action==="removed"?[X.serverName]:[]})}),Y.tools.length>0)s.debug(`Registered ${Y.tools.length} MCP tools`),s.debug(`[MCP Tools] ${Y.tools.map((X)=>X.name).join(", ")}`)}catch($){s.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await c0(C());if(this.agentResources=k4($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)s.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else s.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;s.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{if(Y.name==="ReadPromptArtifact")return!0;return Z.some((Q)=>{if(Q===Y.name)return!0;let X=Q.match(/^(\w+)\(.*\)$/);if(X&&X[1]===Y.name)return!0;return!1})});return s.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)s.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let Z=[];for(let Y of $)if(Y.type==="text")Z.push(Y.text);if(Z.length===0)return $;let J=Z.join(`
864
+ `),L={id:this.generateTaskId(),type:"simple",prompt:F};return{success:!0,finalMessage:(await this.executeTask(L)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-j14160j3.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){s.debug("Processing Plan mode message...");let{prompt:Y}=await Y1({...Z.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:Z.workspaceRoot||C()},mode:"plan",includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:Z.executionRoot??Z.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...Z.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}}),Q;if(typeof $==="string")Q=t2($);else{let X=$.filter((W)=>W.type==="text");if(X.length>0){let W=X[0];Q=$.map((V)=>V===W?{type:"text",text:t2(W.text)}:V)}else Q=[{type:"text",text:t2("")},...$]}return yield*this.executeLoop(Q,Z,J,Y)}async*runLoop($,Z,J){s.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z);return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await Y1({...$.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:$.workspaceRoot||C()},replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:$.executionRoot??$.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...$.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let Q=this.buildLoopDependencies();return nY(Q,$,Z,J,Y)}takeStartupAdoptedToolResultEvents(){return(this.sessionRuntime?.takeStartupAdoptedToolResults()??[]).flatMap(({call:Z,result:J})=>{let Y={id:Z.toolCallId,type:"function",function:{name:Z.toolName,arguments:JSON.stringify(Z.input)}},Q=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,X=J.error===void 0,W=J.output,V={success:X,llmContent:typeof W==="string"||W!==null&&typeof W==="object"?W:W===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(W),...J.error?{error:{type:"execution_error",message:J.error}}:{},...Q?{metadata:Q}:{}},U=[{kind:"tool_result",toolCall:Y,result:V}],H=rY(Y,V);if(H)U.push(H);return U})}takeStartupRecoveryEvents(){let $=this.sessionRuntime?.getTurnRecoveryAssessment(),Z=$?.state==="requires_attention"?$:this.sessionRuntime?.takeStartupTurnRecoveryAssessment(),J=Z&&Z.state!=="none"?[{kind:"turn_recovery",assessment:Z}]:[];return J.push(...this.takeStartupAdoptedToolResultEvents()),J}buildLoopDependencies(){return{chatService:this.chatService,toolExecutor:this.toolExecutor,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,s.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($),staticProjectRules:this.sessionRuntime?.getStaticProjectRules(),hydrateProjectRules:this.sessionRuntime?($)=>this.sessionRuntime.hydrateProjectRules($):void 0,resolveContextualProjectRules:this.sessionRuntime?($,Z,J,Y)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,Y):void 0}}async chatWithSystem($,Z){if(!this.isInitialized)throw Error("Agent未初始化");let J=[{role:"system",content:$},{role:"user",content:Z}];return(await this.chatService.chat(J)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.toolExecutor?this.toolExecutor.getRegistry().getAll():[]}getToolRegistry(){return this.toolExecutor.getRegistry()}applyToolWhitelist($){let Z=this.toolExecutor.getRegistry(),Y=Z.getAll().filter((Q)=>!$.includes(Q.name));for(let Q of Y)Z.unregister(Q.name);s.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let Y of Z.getAll())if(J.has(Y.name))Z.unregister(Y.name);s.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let Y=Z.get(J.kind)||0;Z.set(J.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.name)}}async destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=(async()=>{this.log("销毁Agent..."),await this.activeOperations.shutdown("agent-destroy");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}})(),this.destroyPromise}syncRuntimeState(){if(!this.sessionRuntime)return;this.chatService=this.sessionRuntime.getChatService(),this.executionEngine=this.sessionRuntime.getExecutionEngine(),this.attachmentCollector=this.sessionRuntime.getAttachmentCollector(),this.currentModelId=this.sessionRuntime.getCurrentModelId(),this.currentModelMaxContextTokens=this.sessionRuntime.getCurrentModelMaxContextTokens()}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}log($,Z){s.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){s.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await Y1({...this.sessionRuntime?.isRemoteWorkspace()?{workspaceAccess:"none"}:{projectPath:this.sessionRuntime?.workspaceRoot??C()},replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...this.sessionRuntime?.isRemoteWorkspace()?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot},...this.sessionRuntime?{environmentOptions:{...u1,workingDirectory:this.sessionRuntime.executionRoot}}:{}});if(J.prompt)this.log("系统提示配置验证成功"),s.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await v4({sessionId:"default",configDir:t(),workspaceRoot:C(),resourceRoot:C(),agentResources:this.agentResources});s.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;s.debug(`Builtin tools registered: ${Z} tools`),s.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw s.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await W4({workspaceRoot:C(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){s.debug("No MCP servers configured");return}let Z=e0.createIsolated({artifactWriter:new o2(`legacy-${XG()}`)});this.legacyMcpRegistry=Z;for(let[X,W]of Object.entries($))try{s.debug(`Connecting to MCP server: ${X}`),await Z.registerServer(X,W),s.debug(`MCP server "${X}" connected`)}catch(V){s.warn(`Warning: MCP server "${X}" connection failed:`,V)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(Y6(Z));let Q=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:Q.revision,reason:"snapshot",replace:!0,instructions:Q.instructions,removed:[]}),Z.on("catalogChanged",(X)=>{J.replaceMcpTools(X.tools,X)}),Z.on("contentCatalogChanged",(X)=>{J.queueMcpContentChange(X)}),Z.on("resourceUpdated",(X)=>{J.queueMcpResourceUpdated(X)}),Z.on("connectionLifecycleChanged",(X)=>{J.queueMcpConnectionChange(X)}),Z.on("log",(X)=>{J.queueMcpLog(X)}),Z.on("instructionsChanged",(X)=>{J.queueMcpInstructionsChange({revision:X.revision,reason:X.reason,replace:!1,instructions:X.action==="added"&&X.instruction?[{serverName:X.serverName,...X.instruction}]:[],removed:X.action==="removed"?[X.serverName]:[]})}),Y.tools.length>0)s.debug(`Registered ${Y.tools.length} MCP tools`),s.debug(`[MCP Tools] ${Y.tools.map((X)=>X.name).join(", ")}`)}catch($){s.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await c0(C());if(this.agentResources=k4($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)s.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else s.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;s.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{if(Y.name==="ReadPromptArtifact")return!0;return Z.some((Q)=>{if(Q===Y.name)return!0;let X=Q.match(/^(\w+)\(.*\)$/);if(X&&X[1]===Y.name)return!0;return!1})});return s.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)s.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let Z=[];for(let Y of $)if(Y.type==="text")Z.push(Y.text);if(Z.length===0)return $;let J=Z.join(`
865
865
  `);try{let Y=await this.attachmentCollector.collect(J);if(Y.length===0)return $;s.debug(`Processed ${Y.length} @ file mentions in multimodal message`);let Q=this.buildAttachmentText(Y);if(!Q)return $;return[...$,{type:"text",text:Q}]}catch(Y){return s.error("Failed to process @ mentions in multimodal message:",Y),$}}buildAttachmentText($){let Z=[],J=[];for(let Q of $)if(Q.type==="file"){let X=Q.metadata?.lineRange?` (lines ${Q.metadata.lineRange.start}${Q.metadata.lineRange.end?`-${Q.metadata.lineRange.end}`:""})`:"";Z.push(`<file path="${Q.path}"${X?` range="${X}"`:""}>`,Q.content,"</file>")}else if(Q.type==="directory")Z.push(`<directory path="${Q.path}">`,Q.content,"</directory>");else if(Q.type==="error")J.push(`- @${Q.path}: ${Q.error}`);let Y="";if(Z.length>0)Y+=`
866
866
 
867
867
  <system-reminder>
@@ -1677,7 +1677,7 @@ ${J}
1677
1677
  `)),{success:!0,message:"Schedules listed",content:U.join(`
1678
1678
  `)}}case"create":{let V=sw(X);if("error"in V)return Y.sendMessage(`创建失败:${V.error}`),{success:!1,error:V.error};let U={prompt:V.prompt,projectPath:W,trigger:V.trigger,isolation:"worktree",permissionMode:"default",enabled:!0};try{let H=await $.create(U),z=H.nextRunAt?new Date(H.nextRunAt).toLocaleString():"(无)";return Y.sendMessage(`[OK] 已创建定时任务 \`${H.id}\`
1679
1679
  ${A9(H.trigger)} · 下次运行: ${z}`),{success:!0,message:`Schedule ${H.id} created`}}catch(H){let z=H instanceof Error?H.message:String(H);return Y.sendMessage(`创建失败:${z}`),{success:!1,error:z}}}case"remove":case"rm":{let V=X[0];if(!V)return Y.sendMessage("用法:/schedule remove <id>"),{success:!1,error:"Missing schedule id"};let U=await $.remove(V);return Y.sendMessage(U?`[OK] 已删除 \`${V}\``:`未找到 \`${V}\``),{success:U,message:U?"Removed":"Not found"}}case"enable":case"disable":{let V=X[0];if(!V)return Y.sendMessage(`用法:/schedule ${Q} <id>`),{success:!1,error:"Missing schedule id"};let U=await $.setEnabled(V,Q==="enable");return Y.sendMessage(U?`[OK] 已${Q==="enable"?"启用":"停用"} \`${V}\``:`未找到 \`${V}\``),{success:Boolean(U),message:U?"Updated":"Not found"}}case"run":{let V=X[0];if(!V)return Y.sendMessage("用法:/schedule run <id>"),{success:!1,error:"Missing schedule id"};try{return await ow(V),Y.sendMessage(`[OK] 已触发 \`${V}\``),{success:!0,message:"Schedule triggered"}}catch(U){let H=U instanceof Error?U.message:String(U);return Y.sendMessage(`运行失败:${H}`),{success:!1,error:H}}}default:return Y.sendMessage(`未知子命令: ${Q}
1680
- 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Q}`}}}}}var oW=tw();import*as f2 from"node:fs/promises";import*as P2 from"node:path";async function JV($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:Q,storagePath:X}=Z,W=X??P6(Q??C());if(!X){let G=await ew($,Q??C(),J,Y);if(G)return G}let V;try{V=(await f2.readdir(W)).filter((D)=>D.endsWith(".jsonl")&&!D.startsWith("agent_")).map((D)=>P2.join(W,D))}catch{return[]}let H=(await Promise.all(V.map(async(G)=>{try{let D=await f2.stat(G);return{path:G,mtime:D.mtimeMs}}catch{return null}}))).filter((G)=>G!==null).sort((G,D)=>D.mtime-G.mtime).map((G)=>G.path),z=[],B=Y?$:$.toLowerCase();for(let G of H){if(z.length>=J)break;let D=P2.basename(G,".jsonl"),w=await $_(G,B,Y,D);if(z.push(...w),z.length>=J){z.length=J;break}}return z}async function ew($,Z,J,Y){try{let{syncAll:Q}=await import("./chunk-d420fs8m.js"),X=await $V();if(!X)return null;let{SessionService:W}=await import("./chunk-eb93bmdq.js");await Q(X,W.projectionDeriverForSearch());let V=P2.resolve(Z),U=ZV(X,$,V,J*4),H=Y?$:$.toLowerCase(),z=[];for(let B of U){if(B.role!=="user"&&B.role!=="assistant")continue;let G=M9(B.text,H,Y,B.session_id,B.role,B.timestamp??void 0,0);if(G)z.push(G);if(z.length>=J)break}return z}catch{return null}}async function $_($,Z,J,Y){try{let Q=await f2.readFile($,"utf8"),W=Q.split(`
1680
+ 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Q}`}}}}}var oW=tw();import*as f2 from"node:fs/promises";import*as P2 from"node:path";async function JV($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:Q,storagePath:X}=Z,W=X??P6(Q??C());if(!X){let G=await ew($,Q??C(),J,Y);if(G)return G}let V;try{V=(await f2.readdir(W)).filter((D)=>D.endsWith(".jsonl")&&!D.startsWith("agent_")).map((D)=>P2.join(W,D))}catch{return[]}let H=(await Promise.all(V.map(async(G)=>{try{let D=await f2.stat(G);return{path:G,mtime:D.mtimeMs}}catch{return null}}))).filter((G)=>G!==null).sort((G,D)=>D.mtime-G.mtime).map((G)=>G.path),z=[],B=Y?$:$.toLowerCase();for(let G of H){if(z.length>=J)break;let D=P2.basename(G,".jsonl"),w=await $_(G,B,Y,D);if(z.push(...w),z.length>=J){z.length=J;break}}return z}async function ew($,Z,J,Y){try{let{syncAll:Q}=await import("./chunk-d420fs8m.js"),X=await $V();if(!X)return null;let{SessionService:W}=await import("./chunk-dszeb34b.js");await Q(X,W.projectionDeriverForSearch());let V=P2.resolve(Z),U=ZV(X,$,V,J*4),H=Y?$:$.toLowerCase(),z=[];for(let B of U){if(B.role!=="user"&&B.role!=="assistant")continue;let G=M9(B.text,H,Y,B.session_id,B.role,B.timestamp??void 0,0);if(G)z.push(G);if(z.length>=J)break}return z}catch{return null}}async function $_($,Z,J,Y){try{let Q=await f2.readFile($,"utf8"),W=Q.split(`
1681
1681
  `).flatMap((B,G)=>{if(!B.trim())return[];try{return[{event:JSON.parse(B),index:G}]}catch{return[]}});if(!W.some(({event:B})=>B.type==="session_created"))return Z_(W,Z,J,Y);let U=new Map(W.flatMap(({event:B,index:G})=>typeof B.id==="string"?[[B.id,G+1]]:[])),H=tW(eW(Q,$)),z=new Map;for(let B of H){if(B.type==="message_created"&&(B.data.role==="user"||B.data.role==="assistant"))z.set(B.data.messageId,{role:B.data.role,content:[],timestamp:B.timestamp,lineNumber:U.get(B.id)??0});if(B.type==="part_created"&&B.data.partType==="text"){let G=z.get(B.data.messageId),D=B.data.payload.text;if(G&&typeof D==="string")G.content.push(D)}}return[...z.values()].flatMap((B)=>{let G=M9(B.content.join(" "),Z,J,Y,B.role,B.timestamp,B.lineNumber);return G?[G]:[]})}catch{return[]}}function Z_($,Z,J,Y){return $.flatMap(({event:Q,index:X})=>{if(Q.type!=="message")return[];let W=Q.message;if(W?.role!=="user"&&W?.role!=="assistant"||!W.content)return[];let V=typeof W.content==="string"?W.content:Array.isArray(W.content)?W.content.filter((H)=>typeof H==="object"&&H!==null&&H.type==="text"&&typeof H.text==="string").map((H)=>H.text).join(" "):"",U=M9(V,Z,J,Y,W.role,typeof Q.timestamp==="string"?Q.timestamp:void 0,X+1);return U?[U]:[]})}function M9($,Z,J,Y,Q,X,W){if(!$)return;let V=J?$:$.toLowerCase();if(!V.includes(Z))return;let U=V.indexOf(Z),H=Math.max(0,U-80),z=Math.min($.length,U+Z.length+80);return{sessionId:Y,role:Q,content:(H>0?"...":"")+$.slice(H,z).replace(/\n/g," ")+(z<$.length?"...":""),timestamp:X,lineNumber:W}}function YV($){if($.length===0)return"没有找到匹配的历史记录";let Z=[`**找到 ${$.length} 条匹配:**
1682
1682
  `];for(let J of $){let Y=J.timestamp?new Date(J.timestamp).toLocaleString("zh-CN",{timeZone:"Asia/Shanghai"}):"?",Q=J.role==="user"?"\uD83D\uDC64":"\uD83E\uDD16";Z.push(`${Q} \`${J.sessionId.slice(0,8)}\` (${Y})`),Z.push(` ${J.content}`),Z.push("")}return Z.join(`
1683
1683
  `)}var J_={name:"search",description:"Search past session transcripts",fullDescription:"搜索历史会话记录,查找过去的对话内容",usage:"/search <keyword>",aliases:["find","history"],category:"Session",examples:['/search 断路器 - 搜索包含"断路器"的历史对话',"/search edit tool - 搜索 edit tool 相关讨论"],async handler($,Z){let J=c(Z);if($.length===0)return J.sendMessage("**用法:** `/search <关键词>`\n\n在历史会话中搜索包含指定关键词的对话"),{success:!0,message:"显示帮助"};let Y=$.join(" ");J.sendMessage(`正在搜索: "${Y}" ...`);try{let Q=await JV(Y,{maxResults:15,projectPath:Z.cwd}),X=YV(Q);return J.sendMessage(X),{success:!0,message:`found ${Q.length} results`,data:{matches:Q.length}}}catch(Q){let X=Q instanceof Error?Q.message:"未知错误";return J.sendMessage(`搜索失败: ${X}`),{success:!1,error:X}}}},QV=J_;var Y_={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,Z)=>{try{let J=Z.workspaceRoot??Z.cwd;return await f$(J,async(Y)=>{await Y.skills.refresh(),i1(J),await l1(J)}),{success:!0,message:"show_skills_manager",data:{action:"show_skills_manager"}}}catch(J){let Y=`获取 Skills 失败: ${J instanceof Error?J.message:"未知错误"}`;return d().addAssistantMessage(Y),{success:!1,error:Y}}}},XV=Y_;import Q_ from"node:path";function O8($){if($<1000)return`${$}ms`;let Z=Math.floor($/1000);if(Z<60)return`${Z}s`;let J=Math.floor(Z/60);if(J<60)return`${J}m ${Z%60}s`;return`${Math.floor(J/60)}h ${J%60}m`}function WV($){switch($){case"running":return"[RUNNING]";case"completed":case"exited":return"[OK]";case"failed":case"error":return"[FAIL]";case"killed":case"cancelled":return"[STOPPED]";default:return"[?]"}}function VV($,Z){if($.length<=Z)return $;return $.slice(0,Z-3)+"..."}async function X_($,Z){let J=c(Z),Y=$[0],Q=Y0.getInstance(),X=D0.getInstance(),W=Z.sessionId??"",V=Z.sessionId?{sessionId:Z.sessionId,projectPath:Q_.resolve(Z.workspaceRoot??Z.cwd)}:void 0;if(Y==="resume"){let D=$[1],w=$.slice(2).join(" ").trim();if(!D||!w)return{success:!1,error:"Usage: /tasks resume <agentId> <prompt>"};if(!Z.subagents)return{success:!1,error:"This surface does not own a subagent runtime"};let q=await Z.subagents.resume(D,w),F=`Resumed \`${D}\` as \`${q.session.id}\` (depth ${q.session.resumeDepth}).`;return J.sendMessage(F),{success:!0,message:F,data:{action:"subagent_resumed",sourceAgentId:D,subagent:q.session}}}if(Y==="clean"){let D=X.cleanupExpiredSessionsForParent(V??W,0);return J.sendMessage(`已清理 ${D} 个已完成的 Agent 会话`),{success:!0,message:`Cleaned ${D} agent sessions`}}let U=[`**后台任务列表**
@@ -1 +1 @@
1
- import{a,b as i,c as l,d as m}from"./chunk-7gya2kat.js";import"./chunk-wr1m9dr0.js";import"./chunk-zj1g4nbq.js";import"./chunk-y6zhrc3p.js";import"./chunk-yhxjr3xd.js";import"./chunk-va15gerc.js";import"./chunk-m2gh9f07.js";import"./chunk-g01mth5d.js";import"./chunk-1nkczacx.js";import"./chunk-30x3mcsb.js";import"./chunk-p9rx0a48.js";import"./chunk-zzvs471p.js";import"./chunk-j1xkhc0r.js";import"./chunk-53fc0yrq.js";import"./chunk-y5wngtz0.js";import"./chunk-w33zjw8m.js";import{yf as n}from"./chunk-wbbeb520.js";import"./chunk-jj4ggb04.js";import{Uf as s}from"./chunk-qw1ktyac.js";import"./chunk-v508x7cg.js";import"./chunk-t0gm0pn1.js";import"./chunk-1yq72zb7.js";import"./chunk-kqvzmnja.js";import"./chunk-0mr8nexh.js";import"./chunk-50vwafn5.js";import"./chunk-1zx3pb13.js";import"./chunk-by2txwsv.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-cbctk8hh.js";import"./chunk-3y2x6fb6.js";import"./chunk-4c8q1dbe.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-y8qs0rys.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";import v from"chalk";var C={command:"serve",describe:"Start a headless Blade server (no browser)",builder:a,handler:async(p)=>{let r=i(p);if(await s(),!process.env.BLADE_SERVER_PASSWORD)console.log(v.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let e=await m.listenAsync(r);if(console.log(`Blade server listening on http://${e.hostname}:${e.port}`),r.hostname==="0.0.0.0"){let o=l();for(let g of o)console.log(` Network: http://${g}:${e.port}`)}let t,c=new Promise((o)=>{t=o}),d=n(async()=>{await e.stop(),t()});try{await c}finally{d(),await e.stop()}}};export{C as serveCommand};
1
+ import{a,b as i,c as l,d as m}from"./chunk-hwyqk6bh.js";import"./chunk-dd5jptem.js";import"./chunk-zj1g4nbq.js";import"./chunk-0gwf5gkf.js";import"./chunk-0dsqjvg8.js";import"./chunk-1h19j4h5.js";import"./chunk-jwb09kyr.js";import"./chunk-g01mth5d.js";import"./chunk-wcrxh6rm.js";import"./chunk-30x3mcsb.js";import"./chunk-r2qv7nx5.js";import"./chunk-zzvs471p.js";import"./chunk-zacyth0b.js";import"./chunk-53fc0yrq.js";import"./chunk-y5wngtz0.js";import"./chunk-w33zjw8m.js";import{yf as n}from"./chunk-vn9x5zs8.js";import"./chunk-jj4ggb04.js";import{Uf as s}from"./chunk-a9qm5jtz.js";import"./chunk-v508x7cg.js";import"./chunk-t0gm0pn1.js";import"./chunk-1yq72zb7.js";import"./chunk-kqvzmnja.js";import"./chunk-0mr8nexh.js";import"./chunk-50vwafn5.js";import"./chunk-cbqmf0vm.js";import"./chunk-azbwg9vk.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-xjvq4ee8.js";import"./chunk-3y2x6fb6.js";import"./chunk-aazwy1r8.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-7z0ah4z0.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";import v from"chalk";var C={command:"serve",describe:"Start a headless Blade server (no browser)",builder:a,handler:async(p)=>{let r=i(p);if(await s(),!process.env.BLADE_SERVER_PASSWORD)console.log(v.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let e=await m.listenAsync(r);if(console.log(`Blade server listening on http://${e.hostname}:${e.port}`),r.hostname==="0.0.0.0"){let o=l();for(let g of o)console.log(` Network: http://${g}:${e.port}`)}let t,c=new Promise((o)=>{t=o}),d=n(async()=>{await e.stop(),t()});try{await c}finally{d(),await e.stop()}}};export{C as serveCommand};
@@ -1 +1 @@
1
- import{$g as j,Sg as a,Tg as b,Ug as c,Vg as d,Wg as e,Xg as f,Yg as g,Zg as h,_g as i,ah as k}from"./chunk-by2txwsv.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-cbctk8hh.js";import"./chunk-3y2x6fb6.js";import"./chunk-4c8q1dbe.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-y8qs0rys.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";export{g as withWorkspaceAgentResources,i as snapshotWorkspaceAgentResources,f as resolveWorkspaceAgentResources,k as resetWorkspaceAgentResources,d as refreshWorkspaceCommunicationStyles,h as getWorkspaceAgentResourceCacheStats,j as createEmptySessionAgentResources,e as configureInvocationPluginDirs,c as WorkspaceAgentResourceCapacityError,a as MAX_RESIDENT_WORKSPACE_AGENT_RESOURCES,b as MAX_ACTIVE_WORKSPACE_AGENT_RESOURCES};
1
+ import{$g as j,Sg as a,Tg as b,Ug as c,Vg as d,Wg as e,Xg as f,Yg as g,Zg as h,_g as i,ah as k}from"./chunk-azbwg9vk.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-xjvq4ee8.js";import"./chunk-3y2x6fb6.js";import"./chunk-aazwy1r8.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-7z0ah4z0.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";export{g as withWorkspaceAgentResources,i as snapshotWorkspaceAgentResources,f as resolveWorkspaceAgentResources,k as resetWorkspaceAgentResources,d as refreshWorkspaceCommunicationStyles,h as getWorkspaceAgentResourceCacheStats,j as createEmptySessionAgentResources,e as configureInvocationPluginDirs,c as WorkspaceAgentResourceCapacityError,a as MAX_RESIDENT_WORKSPACE_AGENT_RESOURCES,b as MAX_ACTIVE_WORKSPACE_AGENT_RESOURCES};