blade-code 0.10.186 → 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-3srr8yxv.js → chunk-0dsqjvg8.js} +1 -1
  3. package/dist/{chunk-rg2zvq82.js → chunk-0gwf5gkf.js} +1 -1
  4. package/dist/{chunk-t5d4mgsk.js → chunk-0x87kf3z.js} +1 -1
  5. package/dist/{chunk-ek41mnsh.js → chunk-17pbcdyk.js} +1 -1
  6. package/dist/{chunk-a6872238.js → chunk-1h19j4h5.js} +1 -1
  7. package/dist/{chunk-m32qp4rt.js → chunk-1s51njkf.js} +1 -1
  8. package/dist/{chunk-9xybbr14.js → chunk-2x0z6tm0.js} +1 -1
  9. package/dist/{chunk-gcx3pp40.js → chunk-5te08d1r.js} +1 -1
  10. package/dist/{chunk-xmcjrhya.js → chunk-67xepbbh.js} +1 -1
  11. package/dist/{chunk-9wajn74r.js → chunk-7z0ah4z0.js} +1 -1
  12. package/dist/chunk-a1379svb.js +1 -0
  13. package/dist/{chunk-emdrsc6w.js → chunk-a9qm5jtz.js} +17 -17
  14. package/dist/{chunk-yw3q45xx.js → chunk-aazwy1r8.js} +1 -1
  15. package/dist/{chunk-0egj5t8f.js → chunk-azbwg9vk.js} +1 -1
  16. package/dist/{chunk-m9m67nsg.js → chunk-b5s67sc5.js} +1 -1
  17. package/dist/{chunk-wmr59hhd.js → chunk-bfjp7za5.js} +1 -1
  18. package/dist/{chunk-6egjnp46.js → chunk-cbqmf0vm.js} +1 -1
  19. package/dist/{chunk-jsjyw0np.js → chunk-cprb73sh.js} +1 -1
  20. package/dist/{chunk-1xcspsc1.js → chunk-dd5jptem.js} +1 -1
  21. package/dist/{chunk-214593zs.js → chunk-dgx8b825.js} +1 -1
  22. package/dist/{chunk-sp7bt98w.js → chunk-dqfwgj7g.js} +1 -1
  23. package/dist/{chunk-bd7jxk4x.js → chunk-dszeb34b.js} +1 -1
  24. package/dist/{chunk-8wc5v2x8.js → chunk-ewaw877d.js} +1 -1
  25. package/dist/chunk-fpdb3a5z.js +1 -0
  26. package/dist/{chunk-6bpsz0rk.js → chunk-fv86z092.js} +2 -2
  27. package/dist/{chunk-kb85yt7y.js → chunk-hwyqk6bh.js} +1 -1
  28. package/dist/{chunk-nz1gj4w6.js → chunk-j14160j3.js} +1 -1
  29. package/dist/{chunk-qr8xb3x2.js → chunk-jwb09kyr.js} +3 -3
  30. package/dist/{chunk-fxega1pp.js → chunk-m6bz8fh9.js} +1 -1
  31. package/dist/{chunk-t4q8whem.js → chunk-n3z4hr06.js} +1 -1
  32. package/dist/{chunk-sq2qp12b.js → chunk-r2qv7nx5.js} +1 -1
  33. package/dist/{chunk-dyxnzsbr.js → chunk-t8xynv04.js} +1 -1
  34. package/dist/{chunk-5k55azp6.js → chunk-te08f57k.js} +1 -1
  35. package/dist/{chunk-wrc2zpyc.js → chunk-vn9x5zs8.js} +1 -1
  36. package/dist/{chunk-nf7nbhtp.js → chunk-wcrxh6rm.js} +1 -1
  37. package/dist/{chunk-fmrjpyw2.js → chunk-xjvq4ee8.js} +1 -1
  38. package/dist/{chunk-7g49r6t9.js → chunk-xk938s1h.js} +2 -2
  39. package/dist/{chunk-5ky370dq.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-05ds0e8p.js +0 -1
  73. package/dist/chunk-d9hbxw1r.js +0 -1
@@ -1,4 +1,4 @@
1
- import{e as $X,f as JX,h as S$,i as M4}from"./chunk-1xcspsc1.js";import{l as eX,m as $Z,n as JZ}from"./chunk-8wc5v2x8.js";import{A as q4,y as A9,z as b9}from"./chunk-3srr8yxv.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-qr8xb3x2.js";import"./chunk-g01mth5d.js";import{Ma as E5,Na as h5,Oa as g5,Ra as NZ}from"./chunk-nf7nbhtp.js";import{Ta as BY}from"./chunk-30x3mcsb.js";import{Mb as FY,Nb as F4,Zb as LY,hc as P6}from"./chunk-sq2qp12b.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-5ky370dq.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-wrc2zpyc.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-emdrsc6w.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-6egjnp46.js";import{Hg as H4,Jg as hX,Og as FX,Xg as OZ}from"./chunk-0egj5t8f.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-fmrjpyw2.js";import"./chunk-3y2x6fb6.js";import{Mi as zZ,Ri as HX,Si as qZ}from"./chunk-yw3q45xx.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-9wajn74r.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-1xcspsc1.js";import{j as o1}from"./chunk-zj1g4nbq.js";import{v as a0,w as y2}from"./chunk-rg2zvq82.js";import{A as m0,x as g2,y as p2,z as v2}from"./chunk-3srr8yxv.js";import{B as C2,C as U$,D as H$,E as F$,F as z0,G as N$}from"./chunk-a6872238.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-qr8xb3x2.js";import{La as q$,Ra as uO}from"./chunk-nf7nbhtp.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-sq2qp12b.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-5ky370dq.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-emdrsc6w.js";import{dg as c1}from"./chunk-t0gm0pn1.js";import{wg as J2}from"./chunk-50vwafn5.js";import{yg as B1}from"./chunk-6egjnp46.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-0egj5t8f.js";import{th as P$,uh as Y2}from"./chunk-vbjgcn49.js";import{yh as b$,zh as l0}from"./chunk-fmrjpyw2.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-yw3q45xx.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-9wajn74r.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-sq2qp12b.js";import"./chunk-zzvs471p.js";import"./chunk-5ky370dq.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-fmrjpyw2.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-9wajn74r.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-nf7nbhtp.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-sq2qp12b.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-5ky370dq.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-emdrsc6w.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-6egjnp46.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-0egj5t8f.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-fmrjpyw2.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-yw3q45xx.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-9wajn74r.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-nz1gj4w6.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-bd7jxk4x.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-kb85yt7y.js";import"./chunk-1xcspsc1.js";import"./chunk-zj1g4nbq.js";import"./chunk-rg2zvq82.js";import"./chunk-3srr8yxv.js";import"./chunk-a6872238.js";import"./chunk-qr8xb3x2.js";import"./chunk-g01mth5d.js";import"./chunk-nf7nbhtp.js";import"./chunk-30x3mcsb.js";import"./chunk-sq2qp12b.js";import"./chunk-zzvs471p.js";import"./chunk-5ky370dq.js";import"./chunk-53fc0yrq.js";import"./chunk-y5wngtz0.js";import"./chunk-w33zjw8m.js";import{yf as n}from"./chunk-wrc2zpyc.js";import"./chunk-jj4ggb04.js";import{Uf as s}from"./chunk-emdrsc6w.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-6egjnp46.js";import"./chunk-0egj5t8f.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-fmrjpyw2.js";import"./chunk-3y2x6fb6.js";import"./chunk-yw3q45xx.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-9wajn74r.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-0egj5t8f.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-fmrjpyw2.js";import"./chunk-3y2x6fb6.js";import"./chunk-yw3q45xx.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-9wajn74r.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};
@@ -1,4 +1,4 @@
1
- import{wc as q8}from"./chunk-zzvs471p.js";import{$d as a1,Ac as _2,Bc as n1,Dc as z$,Ed as f2,Fd as G8,Gd as L8,Hd as H6,Id as $Z,Jd as F8,Kd as O8,Ld as l1,Pd as iJ,Yd as p0,_d as T6,ae as R6,he as Y1,td as A2,vd as b2,wd as y2,xc as U$,xd as D6,yd as w6,zc as w$}from"./chunk-5ky370dq.js";import{me as U8}from"./chunk-53fc0yrq.js";import{Ee as y0,pe as q0,se as z2,te as g$}from"./chunk-y5wngtz0.js";import{dg as g2}from"./chunk-t0gm0pn1.js";import{eg as D8,fg as r0,gg as Q8,hg as mJ,jg as c1,kg as S6,lg as dJ,mg as cJ,pg as lJ}from"./chunk-1yq72zb7.js";import{bh as Y$,ch as n0,fh as w8}from"./chunk-3kszepm6.js";import{kh as o2,oh as W2}from"./chunk-wcps5gjm.js";import{zh as S$}from"./chunk-fmrjpyw2.js";import{Ui as M$}from"./chunk-kv458q06.js";import{bj as j0}from"./chunk-2f8d0km4.js";import{Dj as E0}from"./chunk-2mk914vk.js";import{Xj as N2}from"./chunk-9wajn74r.js";import{Bk as LJ,Ck as e1,Ek as F2,Jk as O2,Kk as P2,fk as L2,uk as D2,vk as w2,yk as X1}from"./chunk-4wx5sya5.js";import{Mk as cZ}from"./chunk-eg3ms291.js";function f$($){return $.role==="system"&&Array.isArray($.content)}function y$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class h1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,Z){this.context=$;let J=$.messages.find(f$);if(this._contextualSystemMessages=$.messages.filter(y$),J)this.systemMessages=[J,...this._contextualSystemMessages];else if(Z)this.systemMessages=[{role:"system",content:[{type:"text",text:Z,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!f$(W)&&!y$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}get contextRevision(){return this._contextRevision}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!y$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(f$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,Z){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push({...Z,metadata:{...Z.metadata&&typeof Z.metadata==="object"&&!Array.isArray(Z.metadata)?Z.metadata:{},...y0}})}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((Z)=>Z.id===$.id))return;this._history.push($)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((Z)=>!f$(Z)&&!y$(Z)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(y$),this._history=$.filter((Z)=>!f$(Z)&&!y$(Z)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let Z=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages(),this._history.length!==Z[0]||this._pending.length!==Z[1]||this._contextualSystemMessages.length!==Z[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function t6($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function e6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function $J($,Z,J){return{...$,usage:$.usage+Z,lastOutputDelta:Z,consecutiveContinuations:J?$.consecutiveContinuations+1:0}}import V$ from"node:path";var M8=new Set(["GOEXPERIMENT","GOOS","GOARCH","CGO_ENABLED","GO111MODULE","RUST_BACKTRACE","RUST_LOG","NODE_ENV","PYTHONUNBUFFERED","PYTHONDONTWRITEBYTECODE","GIT_TERMINAL_PROMPT","LANG","LANGUAGE","LC_ALL","LC_CTYPE","LC_TIME","CHARSET","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","TZ","LS_COLORS","LSCOLORS","GREP_COLOR","GREP_COLORS"]),k8=/^(LD_.+|DYLD_.+|PATH)$/,ZJ=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function e$($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],K=W.match(ZJ);if(!K)break;let X=K[1];if(!M8.has(X))break;Z=Y}return Z}function i5($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],K=W.match(ZJ);if(!K)break;let X=K[1];if(k8.test(X))break;Z=Y}return Z}var x8=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function kZ($){let Z=$,J=!0;while(J){J=!1;for(let W of x8){let Y=Z.match(W);if(Y){Z=Z.slice(Y[0].length),J=!0;break}}if(Z.startsWith("-- "))Z=Z.slice(3),J=!0}return Z}function $1($){let Z=[],J="",W=!1,Y=!1,K=!1;for(let X=0;X<$.length;X++){let Q=$[X];if(K){J+=Q,K=!1;continue}if(Q==="\\"&&!W){J+=Q,K=!0;continue}if(Q==="'"&&!Y){W=!W,J+=Q;continue}if(Q==='"'&&!W){Y=!Y,J+=Q;continue}if(W||Y){J+=Q;continue}if(Q==="|"){if(X+1<$.length&&$[X+1]==="|"){if(J.trim())Z.push(J.trim());J="",X++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&X+1<$.length&&$[X+1]==="&"){if(J.trim())Z.push(J.trim());J="",X++;continue}if(Q==="&")return null;if(Q===";"){if(J.trim())Z.push(J.trim());J="";continue}J+=Q}if(J.trim())Z.push(J.trim());return Z.length>0?Z:null}function JJ($){let Z=!1,J=!1,W=!1;for(let Y=0;Y<$.length;Y++){let K=$[Y];if(W){W=!1;continue}if(K==="\\"&&!Z){W=!0;continue}if(K==="'"&&!J){Z=!Z;continue}if(K==='"'&&!Z){J=!J;continue}if(Z)continue;if(K==="$"){let X=$[Y+1];if(X&&/[A-Za-z_@*#?!$0-9({]/.test(X))return!0}if(K==="`")return!0;if(J)continue;if(K==="|")return!0;if(K===">"||K==="<")return!0;if(K==="{"){let X=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(X)||/^\{[^}]*\.\.[^}]*\}/.test(X))return!0}}return!1}function H$($){let Z=[],J="",W=!1,Y=!1,K=!1;for(let X=0;X<$.length;X++){let Q=$[X];if(K){J+=Q,K=!1;continue}if(Q==="\\"&&!W){if(K=!0,Y){let H=$[X+1];if(H&&'$`"\\'.includes(H))continue;J+=Q,K=!1}continue}if(Q==="'"&&!Y){W=!W;continue}if(Q==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(Q)){if(J)Z.push(J),J="";continue}J+=Q}if(J)Z.push(J);return Z}var I8=new Set(["npm","pnpm","yarn","bun"]),WJ=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),h8=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),v8=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function C8($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function YJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function g8($,Z,J){if(!J||Z.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=H$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let K=Y[1];if(!K||K==="-")return;let X=V$.isAbsolute(K)?V$.resolve(K):V$.resolve(J,K);if(!z$.isWithinWorkspace(X,J))return;return W[2]?.trim()||void 0}function p8($){let Z=[],J=!1,W=!1,Y=!1;for(let K=0;K<$.length;K++){let X=$[K];if(Y){Y=!1;continue}if(X==="\\"&&!J){Y=!0;continue}if(X==="'"&&!W){J=!J;continue}if(X==='"'&&!J){W=!W;continue}if(X!=="|"||J||W)continue;if($[K+1]==="|")return;Z.push(K)}return Z}function u8($){let Z=H$($),[J,W,Y]=Z;if(J!=="head"&&J!=="tail")return!1;if(Z.length===1)return!0;let K=(X)=>X!==void 0&&/^[1-9]\d{0,4}$/.test(X);if(Z.length===2)return W?.startsWith("--lines=")&&K(W.slice(8))||W?.startsWith("-")&&K(W.slice(1));return Z.length===3&&(W==="-n"||W==="--lines")&&K(Y)}function m8($){let Z=YJ($.replace(v8,"").trim()),J=p8(Z);if(!J)return;if(J.length===0)return KJ(Z);if(J.length!==1)return;let W=J[0];if(W===void 0)return;let Y=YJ(Z.slice(0,W).trim()),K=Z.slice(W+1).trim();if(!Y||!u8(K))return;return KJ(Y)}function KJ($){let J=$1($)?.at(-1);if(!J)return $;let W=H$(J),[Y,K]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&K==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function E$($,Z){let J=m8($);if(!J)return!1;let W=e$(J),Y=$1(W);if(!Y||JJ(W)||/[\r\n]/.test(W))return!1;let K=Y.length===1?Y[0]:g8(W,Y,Z);if(!K)return!1;let X=H$(K);if(X.length===0||X.some((z)=>[...h8].some((w)=>z===w||z.startsWith(`${w}=`))))return!1;let[Q,H,V]=X;if(I8.has(Q??""))return C8(H==="run"?V:H)||H==="--test";if((Q==="npx"||Q==="bunx")&&WJ.has(H??""))return!0;if(WJ.has(Q??""))return!0;if(Q==="node"&&H==="--test")return!0;if(Q==="go"&&["build","test","vet"].includes(H??""))return!0;return Q==="cargo"&&["build","check","clippy","test"].includes(H??"")}function s5($,Z){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!Z)return!V$.isAbsolute($);let J=V$.isAbsolute($)?V$.resolve($):V$.resolve(Z,$);return z$.isWithinWorkspace(J,Z)}var xZ=E0("Agent"),d8=3;function IZ($,Z,J){if($!=="length")return{action:"none"};if(Z>=d8)return{action:"truncated"};if(t6(J)==="stop")return xZ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var c8=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/,/\d+\.\s+(First|Next|Then|Finally)/i],l8=/```[\s\S]{50,}```/,XJ="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",i8=2;function hZ($,Z,J=!0){if(!$||Z>=i8)return{action:"none"};if(!J&&l8.test($))return{action:"retry",prompt:XJ};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(c8.some((X)=>X.test(W)))return{action:"retry",prompt:XJ};return{action:"none"}}var v1=2,r8="The model returned tool-call JSON as text instead of completing the requested tool workflow.",n8="The previous response contained tool-call JSON as ordinary text. It did not execute a tool. If the requested operation is still needed, use the native tool-call interface with an available tool. If it already succeeded, use the recorded result to answer instead of repeating the operation. Do not return another tool-call JSON envelope as your final answer.";function vZ($,Z,J,W){if(!$||$.length>65536||J.length===0)return{action:"none"};let Y=Z.replace(/```[\s\S]*?(?:```|$)/g,"").replace(/^\s*>.*$/gm,"");if(/\b(?:example|schema|serialize|serialization|quote|print|illustrate|verbatim)\b|示例|样例|序列化|引用原文/i.test(Y)||/\b(?:explain|show|return|output)\b[^.!?\n]{0,80}\b(?:json|tool.calls?)\b|(?:解释|展示|输出|返回)[^。!?\n]{0,40}(?:JSON|工具调用格式)/i.test(Y)||/\b(?:do not|don't|never)\s+(?:use|call|invoke|execute)\s+(?:any\s+)?tools?\b|不要(?:使用|调用|执行)(?:任何)?工具/i.test(Y))return{action:"none"};let K;try{K=JSON.parse($)}catch{return{action:"none"}}if(!K||typeof K!=="object"||Array.isArray(K)||Object.keys(K).length!==1||!("tool_calls"in K)||!Array.isArray(K.tool_calls)||K.tool_calls.length===0||K.tool_calls.length>32)return{action:"none"};let X=new Set;for(let Q of K.tool_calls){if(!Q||typeof Q!=="object"||Array.isArray(Q))return{action:"none"};let H="function"in Q;if(Object.keys(Q).some((G)=>!["id","type",...H?["function"]:["name","arguments"]].includes(G)))return{action:"none"};if("type"in Q&&Q.type!=="function")return{action:"none"};let V=H?Q.function:Q;if(!V||typeof V!=="object"||Array.isArray(V)||!("name"in V)||typeof V.name!=="string"||!("arguments"in V))return{action:"none"};if(H&&Object.keys(V).some((G)=>G!=="name"&&G!=="arguments"))return{action:"none"};if(!J.includes(V.name))return{action:"none"};let z=V.arguments;if(typeof z!=="string"&&(!z||typeof z!=="object"||Array.isArray(z)))return{action:"none"};let w=V.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),B=new RegExp(`(?:^|[.!?。!?;;\\n])\\s*(?:please\\s+)?(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${w}(?![\\w:-])|(?:^|[。!?;\\n])\\s*(?:请)?(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${w}(?![\\w:-])`,"i"),j=new RegExp(`(?:do not|don't|never)\\s+(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${w}(?![\\w:-])|(?:不要|禁止)(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${w}(?![\\w:-])`,"i");if(!B.test(Y)||j.test(Y))return{action:"none"};X.add(V.name)}return W<v1?{action:"retry",prompt:n8,...X.size===1?{toolName:[...X][0]}:{}}:{action:"fail",message:r8}}var o8=[/\b(?:run|execute|rerun|re-run)\b[\s\S]{0,60}\b(?:tests?|test suite|lint|type-?check|build)\b/i,/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b/i,/(?:运行|执行|跑|重新运行).{0,30}(?:测试|单测|集成测试|检查|构建)/],QJ={test:/\b(?:tests?|test suite)\b|(?:测试|单测|集成测试)/i,lint:/\blint(?:ing)?\b/i,"type-check":/\btype[\s-]?check(?:ing)?\b|\btsc\b|类型检查/i,build:/\bbuild\b|构建/i},a8={test:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|(?:^|\s)(?:node|bun)\s+--test\b|(?:^|\s)(?:vitest|jest|pytest|go\s+test|cargo\s+test)\b/i,lint:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?lint\b/i,"type-check":/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?type-?check\b|(?:^|\s)tsc\b/i,build:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?build\b/i},s8="The user explicitly required verification, but it has not run successfully. Do not finish or explain. Your next action must be a Bash tool call that runs the requested test, lint, type-check, or build command. Inspect the command result and fix any failure before finishing.",t8="Required verification did not run successfully before the retry limit.",e8=3;function VJ($,Z,J,W){if(!J.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(Z)){$.clear();return}if(Z==="Bash"&&typeof J.metadata?.command==="string"&&J.metadata.exit_code===0&&E$(J.metadata.command,W)){$.add(J.metadata.command);return}if(!["Task","TaskOutput"].includes(Z))return;let Y=J.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let K of Y)if(typeof K==="string"&&E$(K,W))$.add(K)}function CZ($,Z,J){if(!$||!o8.some((H)=>H.test($)))return{action:"none"};let W=Object.keys(QJ).filter((H)=>QJ[H].test($)),Y=[...Z],K=W.filter((H)=>!Y.some((V)=>a8[H].test(V)));if(W.length>0?K.length===0:Y.some((H)=>E$(H)))return{action:"none"};if(J>=e8)return{action:"fail",message:t8};let Q=W.length>1&&K.length>0?` Missing successful verification categories: ${K.join(", ")}.`:"";return{action:"retry",prompt:`${s8}${Q}`}}var $9=[/\bdelegate\b[\s\S]{0,120}\b(?:Task tool|subagent|agent)\b/i,/\b(?:call|use|invoke)\b[\s\S]{0,80}\bTask tool\b/i,/(?:委派|交给|调用|使用).{0,60}(?:Task|子代理|子智能体)/],zJ=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function jJ($){return typeof $==="string"&&zJ.some((Z)=>Z.test($))}var Z9=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],J9=[/\b(?:do not|don't|never)\s+(?:call|use|invoke)\s+(?:the\s+)?Task\b[\s\S]{0,30}\bexactly once\b/i,/\bTask\b[\s\S]{0,30}\b(?:does not|doesn't|need not)\b[\s\S]{0,30}\bexactly once\b/i,/\bmultiple\s+Task(?: tool)?\s+calls?\s+(?:are\s+)?allowed\b/i,/(?:不要|禁止).{0,12}(?:Task|子代理).{0,12}(?:恰好|仅|只)(?:调用|使用)?一次/];function W9($){if(typeof $!=="string")return;if(J9.some((Z)=>Z.test($)))return"multiple-allowed";return Z9.some((Z)=>Z.test($))?"required":void 0}function J1($){for(let Z of $){let J=W9(Z);if(J!==void 0)return J==="required"}return!1}var Y9="The user explicitly required delegation, but no Task tool call completed successfully. Do not solve the task directly or explain. Your next action must be a Task tool call using the requested subagent.",K9="Required delegation did not complete before the retry limit.",X9=3;function BJ($,Z,J){let W=(typeof $==="string"?[$]:$??[]).map((X)=>X.trim()).filter(Boolean),Y=J1(W),K=!1;if(!Y)for(let X of W){if(zJ.some((Q)=>Q.test(X)))break;if($9.some((Q)=>Q.test(X))){K=!0;break}}if(W.length===0||!Y&&!K||Z.has("Task"))return{action:"none"};if(J>=X9)return{action:"fail",message:K9};return{action:"retry",prompt:Y9}}var Q9=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],H9=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],V9=[/\b(?:do not|don't|never|must not|should not)\b[^.!?;\n]{0,80}\b(?:git\s+)?worktree\b/gi,/\bwithout\b[^.!?;\n]{0,60}\b(?:git\s+)?worktree\b/gi,/(?:不要|禁止|不得|无需)[^。!?;\n]{0,50}(?:worktree|工作树)/gi];function DJ($){return V9.reduce((Z,J)=>Z.replace(J," "),$)}function C1($){if(typeof $!=="string")return!1;let Z=DJ($);return Q9.some((J)=>J.test(Z))}var z9="The user explicitly required git worktree isolation, but EnterWorktree has not completed successfully. Do not continue in the original workspace. Your next action must be an EnterWorktree tool call. Wait for its result before using file or Bash tools.",j9="The user explicitly required leaving the managed worktree, but ExitWorktree has not completed successfully. Do not finish or explain. Your next action must be an ExitWorktree tool call using the action requested by the user.",B9="Required worktree lifecycle did not complete before the retry limit.",D9=3;function wJ($,Z,J){if(!$)return{action:"none"};let W=DJ($);if(!C1(W))return{action:"none"};let Y=H9.some((X)=>X.test(W));if(Z.has("TaskWorktree"))return{action:"none"};let K=!Z.has("EnterWorktree")?"EnterWorktree":Y&&!Z.has("ExitWorktree")?"ExitWorktree":void 0;if(!K)return{action:"none"};if(J>=D9)return{action:"fail",message:B9};return{action:"retry",tool:K,prompt:K==="EnterWorktree"?z9:j9}}var HJ=30000;async function gZ($){try{let J=S$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??j0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((K)=>{W=setTimeout(()=>K("timeout"),HJ)});try{let K=await Promise.race([J,Y]);if(K==="timeout")return xZ.warn(`[Loop] Stop hook 超时 (${HJ}ms),按 shouldStop: true 处理`),{action:"stop"};let X=K;if(!X.shouldStop)return{action:"continue",reason:X.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(Z){return xZ.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}async function w9($,Z){let J;while(!(J=await $.next()).done)if(Z)await Z(J.value);return J.value}var U9=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function q9($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((Z)=>{if(typeof Z==="string")return Z;if(Z&&typeof Z==="object"&&"text"in Z){let J=Z.text;return typeof J==="string"?J:""}return""}).join(" ");return""}function G9($){let Z=$;for(let H of U9)Z=Z.replace(H," ");Z=Z.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let J=Z.replace(/\s+/g," ").trim();if(!J)return"";let W=J.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:J;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let K=Y.slice(0,60),X=K.lastIndexOf(" ");return`${(X>36?K.slice(0,X):K).trimEnd()}…`}function UJ($){return G9(q9($))}import{EventEmitter as L9}from"events";import qJ from"node:path";function pZ($){if(LJ($.sessionId),!qJ.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:qJ.resolve($.projectPath)}}function GJ($){let Z=pZ($);return JSON.stringify([Z.projectPath,Z.sessionId])}function z3($,Z){return GJ($)===GJ(Z)}class T$ extends L9{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!T$.instance)T$.instance=new T$;return T$.instance}publish($,Z,J,W){let Y=pZ($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:Z,...W!==void 0?{seq:W}:{},properties:J})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var W1=T$.getInstance();var $$=E0("Agent"),g1=new Set;async function F9($,Z){let J=$.sessionId;if(!J||$.subagentInfo)return;if(g1.has(J))return;if(g1.size>=5000)g1.clear();g1.add(J);try{let W=$.workspaceRoot,Y=await Y1.findSessionMetadata(J,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let K=UJ(Z);if(!K)return;await Y1.updateSessionMetadata(J,Y.projectPath,{title:K}),W1.publish({sessionId:J,projectPath:Y.projectPath},"session.updated",{title:K})}catch(W){$$.debug?.("[Loop] 自动生成会话标题失败:",W)}}var uZ=`<turn_aborted>
1
+ import{wc as q8}from"./chunk-zzvs471p.js";import{$d as a1,Ac as _2,Bc as n1,Dc as z$,Ed as f2,Fd as G8,Gd as L8,Hd as H6,Id as $Z,Jd as F8,Kd as O8,Ld as l1,Pd as iJ,Yd as p0,_d as T6,ae as R6,he as Y1,td as A2,vd as b2,wd as y2,xc as U$,xd as D6,yd as w6,zc as w$}from"./chunk-zacyth0b.js";import{me as U8}from"./chunk-53fc0yrq.js";import{Ee as y0,pe as q0,se as z2,te as g$}from"./chunk-y5wngtz0.js";import{dg as g2}from"./chunk-t0gm0pn1.js";import{eg as D8,fg as r0,gg as Q8,hg as mJ,jg as c1,kg as S6,lg as dJ,mg as cJ,pg as lJ}from"./chunk-1yq72zb7.js";import{bh as Y$,ch as n0,fh as w8}from"./chunk-3kszepm6.js";import{kh as o2,oh as W2}from"./chunk-wcps5gjm.js";import{zh as S$}from"./chunk-xjvq4ee8.js";import{Ui as M$}from"./chunk-kv458q06.js";import{bj as j0}from"./chunk-2f8d0km4.js";import{Dj as E0}from"./chunk-2mk914vk.js";import{Xj as N2}from"./chunk-7z0ah4z0.js";import{Bk as LJ,Ck as e1,Ek as F2,Jk as O2,Kk as P2,fk as L2,uk as D2,vk as w2,yk as X1}from"./chunk-4wx5sya5.js";import{Mk as cZ}from"./chunk-eg3ms291.js";function f$($){return $.role==="system"&&Array.isArray($.content)}function y$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class h1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,Z){this.context=$;let J=$.messages.find(f$);if(this._contextualSystemMessages=$.messages.filter(y$),J)this.systemMessages=[J,...this._contextualSystemMessages];else if(Z)this.systemMessages=[{role:"system",content:[{type:"text",text:Z,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!f$(W)&&!y$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}get contextRevision(){return this._contextRevision}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!y$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(f$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,Z){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push({...Z,metadata:{...Z.metadata&&typeof Z.metadata==="object"&&!Array.isArray(Z.metadata)?Z.metadata:{},...y0}})}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((Z)=>Z.id===$.id))return;this._history.push($)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((Z)=>!f$(Z)&&!y$(Z)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(y$),this._history=$.filter((Z)=>!f$(Z)&&!y$(Z)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let Z=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages(),this._history.length!==Z[0]||this._pending.length!==Z[1]||this._contextualSystemMessages.length!==Z[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function t6($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function e6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function $J($,Z,J){return{...$,usage:$.usage+Z,lastOutputDelta:Z,consecutiveContinuations:J?$.consecutiveContinuations+1:0}}import V$ from"node:path";var M8=new Set(["GOEXPERIMENT","GOOS","GOARCH","CGO_ENABLED","GO111MODULE","RUST_BACKTRACE","RUST_LOG","NODE_ENV","PYTHONUNBUFFERED","PYTHONDONTWRITEBYTECODE","GIT_TERMINAL_PROMPT","LANG","LANGUAGE","LC_ALL","LC_CTYPE","LC_TIME","CHARSET","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","TZ","LS_COLORS","LSCOLORS","GREP_COLOR","GREP_COLORS"]),k8=/^(LD_.+|DYLD_.+|PATH)$/,ZJ=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function e$($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],K=W.match(ZJ);if(!K)break;let X=K[1];if(!M8.has(X))break;Z=Y}return Z}function i5($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],K=W.match(ZJ);if(!K)break;let X=K[1];if(k8.test(X))break;Z=Y}return Z}var x8=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function kZ($){let Z=$,J=!0;while(J){J=!1;for(let W of x8){let Y=Z.match(W);if(Y){Z=Z.slice(Y[0].length),J=!0;break}}if(Z.startsWith("-- "))Z=Z.slice(3),J=!0}return Z}function $1($){let Z=[],J="",W=!1,Y=!1,K=!1;for(let X=0;X<$.length;X++){let Q=$[X];if(K){J+=Q,K=!1;continue}if(Q==="\\"&&!W){J+=Q,K=!0;continue}if(Q==="'"&&!Y){W=!W,J+=Q;continue}if(Q==='"'&&!W){Y=!Y,J+=Q;continue}if(W||Y){J+=Q;continue}if(Q==="|"){if(X+1<$.length&&$[X+1]==="|"){if(J.trim())Z.push(J.trim());J="",X++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&X+1<$.length&&$[X+1]==="&"){if(J.trim())Z.push(J.trim());J="",X++;continue}if(Q==="&")return null;if(Q===";"){if(J.trim())Z.push(J.trim());J="";continue}J+=Q}if(J.trim())Z.push(J.trim());return Z.length>0?Z:null}function JJ($){let Z=!1,J=!1,W=!1;for(let Y=0;Y<$.length;Y++){let K=$[Y];if(W){W=!1;continue}if(K==="\\"&&!Z){W=!0;continue}if(K==="'"&&!J){Z=!Z;continue}if(K==='"'&&!Z){J=!J;continue}if(Z)continue;if(K==="$"){let X=$[Y+1];if(X&&/[A-Za-z_@*#?!$0-9({]/.test(X))return!0}if(K==="`")return!0;if(J)continue;if(K==="|")return!0;if(K===">"||K==="<")return!0;if(K==="{"){let X=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(X)||/^\{[^}]*\.\.[^}]*\}/.test(X))return!0}}return!1}function H$($){let Z=[],J="",W=!1,Y=!1,K=!1;for(let X=0;X<$.length;X++){let Q=$[X];if(K){J+=Q,K=!1;continue}if(Q==="\\"&&!W){if(K=!0,Y){let H=$[X+1];if(H&&'$`"\\'.includes(H))continue;J+=Q,K=!1}continue}if(Q==="'"&&!Y){W=!W;continue}if(Q==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(Q)){if(J)Z.push(J),J="";continue}J+=Q}if(J)Z.push(J);return Z}var I8=new Set(["npm","pnpm","yarn","bun"]),WJ=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),h8=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),v8=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function C8($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function YJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function g8($,Z,J){if(!J||Z.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=H$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let K=Y[1];if(!K||K==="-")return;let X=V$.isAbsolute(K)?V$.resolve(K):V$.resolve(J,K);if(!z$.isWithinWorkspace(X,J))return;return W[2]?.trim()||void 0}function p8($){let Z=[],J=!1,W=!1,Y=!1;for(let K=0;K<$.length;K++){let X=$[K];if(Y){Y=!1;continue}if(X==="\\"&&!J){Y=!0;continue}if(X==="'"&&!W){J=!J;continue}if(X==='"'&&!J){W=!W;continue}if(X!=="|"||J||W)continue;if($[K+1]==="|")return;Z.push(K)}return Z}function u8($){let Z=H$($),[J,W,Y]=Z;if(J!=="head"&&J!=="tail")return!1;if(Z.length===1)return!0;let K=(X)=>X!==void 0&&/^[1-9]\d{0,4}$/.test(X);if(Z.length===2)return W?.startsWith("--lines=")&&K(W.slice(8))||W?.startsWith("-")&&K(W.slice(1));return Z.length===3&&(W==="-n"||W==="--lines")&&K(Y)}function m8($){let Z=YJ($.replace(v8,"").trim()),J=p8(Z);if(!J)return;if(J.length===0)return KJ(Z);if(J.length!==1)return;let W=J[0];if(W===void 0)return;let Y=YJ(Z.slice(0,W).trim()),K=Z.slice(W+1).trim();if(!Y||!u8(K))return;return KJ(Y)}function KJ($){let J=$1($)?.at(-1);if(!J)return $;let W=H$(J),[Y,K]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&K==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function E$($,Z){let J=m8($);if(!J)return!1;let W=e$(J),Y=$1(W);if(!Y||JJ(W)||/[\r\n]/.test(W))return!1;let K=Y.length===1?Y[0]:g8(W,Y,Z);if(!K)return!1;let X=H$(K);if(X.length===0||X.some((z)=>[...h8].some((w)=>z===w||z.startsWith(`${w}=`))))return!1;let[Q,H,V]=X;if(I8.has(Q??""))return C8(H==="run"?V:H)||H==="--test";if((Q==="npx"||Q==="bunx")&&WJ.has(H??""))return!0;if(WJ.has(Q??""))return!0;if(Q==="node"&&H==="--test")return!0;if(Q==="go"&&["build","test","vet"].includes(H??""))return!0;return Q==="cargo"&&["build","check","clippy","test"].includes(H??"")}function s5($,Z){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!Z)return!V$.isAbsolute($);let J=V$.isAbsolute($)?V$.resolve($):V$.resolve(Z,$);return z$.isWithinWorkspace(J,Z)}var xZ=E0("Agent"),d8=3;function IZ($,Z,J){if($!=="length")return{action:"none"};if(Z>=d8)return{action:"truncated"};if(t6(J)==="stop")return xZ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var c8=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/,/\d+\.\s+(First|Next|Then|Finally)/i],l8=/```[\s\S]{50,}```/,XJ="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",i8=2;function hZ($,Z,J=!0){if(!$||Z>=i8)return{action:"none"};if(!J&&l8.test($))return{action:"retry",prompt:XJ};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(c8.some((X)=>X.test(W)))return{action:"retry",prompt:XJ};return{action:"none"}}var v1=2,r8="The model returned tool-call JSON as text instead of completing the requested tool workflow.",n8="The previous response contained tool-call JSON as ordinary text. It did not execute a tool. If the requested operation is still needed, use the native tool-call interface with an available tool. If it already succeeded, use the recorded result to answer instead of repeating the operation. Do not return another tool-call JSON envelope as your final answer.";function vZ($,Z,J,W){if(!$||$.length>65536||J.length===0)return{action:"none"};let Y=Z.replace(/```[\s\S]*?(?:```|$)/g,"").replace(/^\s*>.*$/gm,"");if(/\b(?:example|schema|serialize|serialization|quote|print|illustrate|verbatim)\b|示例|样例|序列化|引用原文/i.test(Y)||/\b(?:explain|show|return|output)\b[^.!?\n]{0,80}\b(?:json|tool.calls?)\b|(?:解释|展示|输出|返回)[^。!?\n]{0,40}(?:JSON|工具调用格式)/i.test(Y)||/\b(?:do not|don't|never)\s+(?:use|call|invoke|execute)\s+(?:any\s+)?tools?\b|不要(?:使用|调用|执行)(?:任何)?工具/i.test(Y))return{action:"none"};let K;try{K=JSON.parse($)}catch{return{action:"none"}}if(!K||typeof K!=="object"||Array.isArray(K)||Object.keys(K).length!==1||!("tool_calls"in K)||!Array.isArray(K.tool_calls)||K.tool_calls.length===0||K.tool_calls.length>32)return{action:"none"};let X=new Set;for(let Q of K.tool_calls){if(!Q||typeof Q!=="object"||Array.isArray(Q))return{action:"none"};let H="function"in Q;if(Object.keys(Q).some((G)=>!["id","type",...H?["function"]:["name","arguments"]].includes(G)))return{action:"none"};if("type"in Q&&Q.type!=="function")return{action:"none"};let V=H?Q.function:Q;if(!V||typeof V!=="object"||Array.isArray(V)||!("name"in V)||typeof V.name!=="string"||!("arguments"in V))return{action:"none"};if(H&&Object.keys(V).some((G)=>G!=="name"&&G!=="arguments"))return{action:"none"};if(!J.includes(V.name))return{action:"none"};let z=V.arguments;if(typeof z!=="string"&&(!z||typeof z!=="object"||Array.isArray(z)))return{action:"none"};let w=V.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),B=new RegExp(`(?:^|[.!?。!?;;\\n])\\s*(?:please\\s+)?(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${w}(?![\\w:-])|(?:^|[。!?;\\n])\\s*(?:请)?(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${w}(?![\\w:-])`,"i"),j=new RegExp(`(?:do not|don't|never)\\s+(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${w}(?![\\w:-])|(?:不要|禁止)(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${w}(?![\\w:-])`,"i");if(!B.test(Y)||j.test(Y))return{action:"none"};X.add(V.name)}return W<v1?{action:"retry",prompt:n8,...X.size===1?{toolName:[...X][0]}:{}}:{action:"fail",message:r8}}var o8=[/\b(?:run|execute|rerun|re-run)\b[\s\S]{0,60}\b(?:tests?|test suite|lint|type-?check|build)\b/i,/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b/i,/(?:运行|执行|跑|重新运行).{0,30}(?:测试|单测|集成测试|检查|构建)/],QJ={test:/\b(?:tests?|test suite)\b|(?:测试|单测|集成测试)/i,lint:/\blint(?:ing)?\b/i,"type-check":/\btype[\s-]?check(?:ing)?\b|\btsc\b|类型检查/i,build:/\bbuild\b|构建/i},a8={test:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|(?:^|\s)(?:node|bun)\s+--test\b|(?:^|\s)(?:vitest|jest|pytest|go\s+test|cargo\s+test)\b/i,lint:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?lint\b/i,"type-check":/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?type-?check\b|(?:^|\s)tsc\b/i,build:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?build\b/i},s8="The user explicitly required verification, but it has not run successfully. Do not finish or explain. Your next action must be a Bash tool call that runs the requested test, lint, type-check, or build command. Inspect the command result and fix any failure before finishing.",t8="Required verification did not run successfully before the retry limit.",e8=3;function VJ($,Z,J,W){if(!J.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(Z)){$.clear();return}if(Z==="Bash"&&typeof J.metadata?.command==="string"&&J.metadata.exit_code===0&&E$(J.metadata.command,W)){$.add(J.metadata.command);return}if(!["Task","TaskOutput"].includes(Z))return;let Y=J.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let K of Y)if(typeof K==="string"&&E$(K,W))$.add(K)}function CZ($,Z,J){if(!$||!o8.some((H)=>H.test($)))return{action:"none"};let W=Object.keys(QJ).filter((H)=>QJ[H].test($)),Y=[...Z],K=W.filter((H)=>!Y.some((V)=>a8[H].test(V)));if(W.length>0?K.length===0:Y.some((H)=>E$(H)))return{action:"none"};if(J>=e8)return{action:"fail",message:t8};let Q=W.length>1&&K.length>0?` Missing successful verification categories: ${K.join(", ")}.`:"";return{action:"retry",prompt:`${s8}${Q}`}}var $9=[/\bdelegate\b[\s\S]{0,120}\b(?:Task tool|subagent|agent)\b/i,/\b(?:call|use|invoke)\b[\s\S]{0,80}\bTask tool\b/i,/(?:委派|交给|调用|使用).{0,60}(?:Task|子代理|子智能体)/],zJ=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function jJ($){return typeof $==="string"&&zJ.some((Z)=>Z.test($))}var Z9=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],J9=[/\b(?:do not|don't|never)\s+(?:call|use|invoke)\s+(?:the\s+)?Task\b[\s\S]{0,30}\bexactly once\b/i,/\bTask\b[\s\S]{0,30}\b(?:does not|doesn't|need not)\b[\s\S]{0,30}\bexactly once\b/i,/\bmultiple\s+Task(?: tool)?\s+calls?\s+(?:are\s+)?allowed\b/i,/(?:不要|禁止).{0,12}(?:Task|子代理).{0,12}(?:恰好|仅|只)(?:调用|使用)?一次/];function W9($){if(typeof $!=="string")return;if(J9.some((Z)=>Z.test($)))return"multiple-allowed";return Z9.some((Z)=>Z.test($))?"required":void 0}function J1($){for(let Z of $){let J=W9(Z);if(J!==void 0)return J==="required"}return!1}var Y9="The user explicitly required delegation, but no Task tool call completed successfully. Do not solve the task directly or explain. Your next action must be a Task tool call using the requested subagent.",K9="Required delegation did not complete before the retry limit.",X9=3;function BJ($,Z,J){let W=(typeof $==="string"?[$]:$??[]).map((X)=>X.trim()).filter(Boolean),Y=J1(W),K=!1;if(!Y)for(let X of W){if(zJ.some((Q)=>Q.test(X)))break;if($9.some((Q)=>Q.test(X))){K=!0;break}}if(W.length===0||!Y&&!K||Z.has("Task"))return{action:"none"};if(J>=X9)return{action:"fail",message:K9};return{action:"retry",prompt:Y9}}var Q9=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],H9=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],V9=[/\b(?:do not|don't|never|must not|should not)\b[^.!?;\n]{0,80}\b(?:git\s+)?worktree\b/gi,/\bwithout\b[^.!?;\n]{0,60}\b(?:git\s+)?worktree\b/gi,/(?:不要|禁止|不得|无需)[^。!?;\n]{0,50}(?:worktree|工作树)/gi];function DJ($){return V9.reduce((Z,J)=>Z.replace(J," "),$)}function C1($){if(typeof $!=="string")return!1;let Z=DJ($);return Q9.some((J)=>J.test(Z))}var z9="The user explicitly required git worktree isolation, but EnterWorktree has not completed successfully. Do not continue in the original workspace. Your next action must be an EnterWorktree tool call. Wait for its result before using file or Bash tools.",j9="The user explicitly required leaving the managed worktree, but ExitWorktree has not completed successfully. Do not finish or explain. Your next action must be an ExitWorktree tool call using the action requested by the user.",B9="Required worktree lifecycle did not complete before the retry limit.",D9=3;function wJ($,Z,J){if(!$)return{action:"none"};let W=DJ($);if(!C1(W))return{action:"none"};let Y=H9.some((X)=>X.test(W));if(Z.has("TaskWorktree"))return{action:"none"};let K=!Z.has("EnterWorktree")?"EnterWorktree":Y&&!Z.has("ExitWorktree")?"ExitWorktree":void 0;if(!K)return{action:"none"};if(J>=D9)return{action:"fail",message:B9};return{action:"retry",tool:K,prompt:K==="EnterWorktree"?z9:j9}}var HJ=30000;async function gZ($){try{let J=S$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??j0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((K)=>{W=setTimeout(()=>K("timeout"),HJ)});try{let K=await Promise.race([J,Y]);if(K==="timeout")return xZ.warn(`[Loop] Stop hook 超时 (${HJ}ms),按 shouldStop: true 处理`),{action:"stop"};let X=K;if(!X.shouldStop)return{action:"continue",reason:X.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(Z){return xZ.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}async function w9($,Z){let J;while(!(J=await $.next()).done)if(Z)await Z(J.value);return J.value}var U9=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function q9($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((Z)=>{if(typeof Z==="string")return Z;if(Z&&typeof Z==="object"&&"text"in Z){let J=Z.text;return typeof J==="string"?J:""}return""}).join(" ");return""}function G9($){let Z=$;for(let H of U9)Z=Z.replace(H," ");Z=Z.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let J=Z.replace(/\s+/g," ").trim();if(!J)return"";let W=J.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:J;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let K=Y.slice(0,60),X=K.lastIndexOf(" ");return`${(X>36?K.slice(0,X):K).trimEnd()}…`}function UJ($){return G9(q9($))}import{EventEmitter as L9}from"events";import qJ from"node:path";function pZ($){if(LJ($.sessionId),!qJ.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:qJ.resolve($.projectPath)}}function GJ($){let Z=pZ($);return JSON.stringify([Z.projectPath,Z.sessionId])}function z3($,Z){return GJ($)===GJ(Z)}class T$ extends L9{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!T$.instance)T$.instance=new T$;return T$.instance}publish($,Z,J,W){let Y=pZ($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:Z,...W!==void 0?{seq:W}:{},properties:J})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var W1=T$.getInstance();var $$=E0("Agent"),g1=new Set;async function F9($,Z){let J=$.sessionId;if(!J||$.subagentInfo)return;if(g1.has(J))return;if(g1.size>=5000)g1.clear();g1.add(J);try{let W=$.workspaceRoot,Y=await Y1.findSessionMetadata(J,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let K=UJ(Z);if(!K)return;await Y1.updateSessionMetadata(J,Y.projectPath,{title:K}),W1.publish({sessionId:J,projectPath:Y.projectPath},"session.updated",{title:K})}catch(W){$$.debug?.("[Loop] 自动生成会话标题失败:",W)}}var uZ=`<turn_aborted>
2
2
  The previous turn was interrupted. Commands or tool calls may have partially completed; inspect the workspace and running processes before retrying.
3
3
  </turn_aborted>`,j$="Tool execution was blocked because its durable call record could not be committed. No tool side effect was started.",FJ="Tool execution completed, but its durable result record could not be committed. Further model and tool execution was stopped. The operation may have completed; inspect external state before retrying.";class R$ extends Error{phase;constructor($,Z){super($==="user_message"?"Conversation input could not be committed. No further model request was started.":"Model output could not be committed. The run was stopped before any further model request or successful completion.",Z);this.phase=$;this.name="DurableConversationPersistenceError"}}function B$($){return $.executionEngine?.getContextManager()}async function i0($,Z,J,W=null,Y,K={}){let X=K.required??$.executionEngine!==void 0;try{let Q=B$($),H=typeof J==="string"?J.trim()!=="":J.some((V)=>V.type==="text"?V.text.trim()!=="":!0);if(Q&&Z.sessionId&&H){let V=await Q.saveMessage(Z.sessionId,"user",J,W,Y,Z.subagentInfo);if(X&&!V)throw Error("Durable user-message commit returned no identity");if(Y?.clientVisible!==!1)F9(Z,J);return V}if(X&&Z.sessionId&&H)throw Error("Durable user-message storage is unavailable")}catch(Q){if($$.warn("[Loop] 保存用户消息失败:",Q),X)throw new R$("user_message",{cause:Q})}return null}async function v0($,Z,J,W,Y,K,X={}){let Q=X.required??$.executionEngine!==void 0;try{let H=B$($),V=Boolean(J.trim()||Y?.trim());if(H&&Z.sessionId&&V){let z=await H.saveMessage(Z.sessionId,"assistant",J,W,K,Z.subagentInfo,Y);if(Q&&!z)throw Error("Durable assistant-message commit returned no identity");return z}if(Q&&Z.sessionId&&V)throw Error("Durable assistant-message storage is unavailable")}catch(H){if($$.warn("[Loop] 保存助手消息失败:",H),Q)throw new R$("assistant_message",{cause:H})}return null}async function OJ($,Z,J){try{let W=B$($);if(W&&Z.sessionId)return await W.saveMessage(Z.sessionId,"system",uZ,J,void 0,Z.subagentInfo)}catch(W){$$.warn("[Loop] 保存中断边界失败:",W)}return null}async function PJ($,Z,J,W,Y){try{let K=B$($);if(!K||!Z.sessionId||J.length===0)return null;return await K.saveMessage(Z.sessionId,"system",`<contextual-project-instructions-ref count="${J.length}" />`,Y,{contextualProjectRules:!0,ruleReferences:JSON.parse(JSON.stringify(J.map((X)=>({...X})))),triggerPaths:[...W]},Z.subagentInfo)}catch(K){$$.warn("[Loop] 保存 contextual project rules provenance 失败:",K)}return null}async function mZ($,Z,J,W,Y,K={}){try{let X=B$($);if(X&&Z.sessionId){let Q=await X.saveToolUse(Z.sessionId,J,W,Y,Z.subagentInfo,K.providerToolCallId);if(K.required&&!Q)throw Error("Durable tool-use commit returned no identity");return Q}if(K.required&&Z.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(X){if($$.warn("[Loop] 保存工具调用失败:",X),K.required)throw X}return null}async function p1($,Z,J,W,Y,K,X,Q,H,V={}){try{let z=B$($);if(z&&Z.sessionId){let w=await z.saveToolResult(Z.sessionId,J,W,Y,K,X,Z.subagentInfo,Q,H);if(V.required&&!w)throw Error("Durable tool-result commit returned no identity");return w}if(V.required&&Z.sessionId)throw Error("Durable tool-result storage is unavailable")}catch(z){if($$.warn("[Loop] 保存工具结果失败:",z),V.required)throw z}return null}async function K1($,Z,J,W,Y={}){try{let K=B$($);if(K&&Z.sessionId){let X=await K.saveCompaction(Z.sessionId,J,W,null);if(Y.required&&!X)throw Error("Compaction checkpoint commit returned no identity");return X||null}if(Y.required&&Z.sessionId)throw Error("Compaction checkpoint storage is unavailable")}catch(K){if($$.warn("[Loop] 保存压缩数据失败:",K),Y.required)throw K}return null}async function V0($){let{deps:Z,context:J,state:W,assistantContent:Y,assistantReasoningContent:K,lastMessageUuid:X,controlPrompt:Q}=$;W.appendAssistant({role:"assistant",content:Y,reasoningContent:K});let H=X,V=await v0(Z,J,Y,H,K);if(V)H=V;if(Q!==void 0){let z={role:"user",content:Q,metadata:y0};W.appendControl("user",z);let w=await i0(Z,J,Q,H,y0);if(w)H=w}return H}import{createHash as M6}from"node:crypto";import{promises as r9}from"node:fs";import n9 from"node:path";import{nanoid as J$}from"nanoid";import*as $0 from"node:fs/promises";import*as Z$ from"node:path";import _J from"write-file-atomic";var NJ={enabled:!0,maxIndexLines:200};var O9="memory",dZ="MEMORY.md",lZ="<!-- blade:auto-memory-topics:start -->",u1="<!-- blade:auto-memory-topics:end -->",P9={realpath:!1,retries:{retries:5,factor:1.2,minTimeout:20,maxTimeout:100,randomize:!0}},N9=new M$,AJ;function yJ($){return $.trim().replace(/\s+/g," ")}function _9($){return yJ($.replace(/^- \[\d{4}-\d{2}-\d{2}\] /,""))}function A9($){return[lZ,"## Auto-consolidated topics",...$.map((Z)=>`- [${Z}](${Z}.md)`),u1].join(`
4
4
  `)}function b9($,Z){let J=A9(Z),W=$.indexOf(lZ),Y=$.indexOf(u1,Math.max(0,W));if(W>=0&&Y>=W)return $.slice(0,W)+J+$.slice(Y+u1.length);if(!$)return`${J}