blade-code 0.10.128 → 0.10.129
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/blade.js +2 -2
- package/dist/chunk-0z9nqbd0.js +2 -0
- package/dist/{chunk-yqqeh12b.js → chunk-1c11sbk3.js} +2 -2
- package/dist/{chunk-fa0pyv9k.js → chunk-1q6sasj0.js} +2 -2
- package/dist/chunk-1y8x5q68.js +1 -0
- package/dist/chunk-2bnpn8be.js +1 -0
- package/dist/{chunk-xzfc1s6k.js → chunk-2y1qngw7.js} +1 -1
- package/dist/{chunk-p2rxrxct.js → chunk-440v1nhy.js} +3 -3
- package/dist/{chunk-ted1hyvb.js → chunk-44jtpg8y.js} +1 -1
- package/dist/{chunk-z3hpstky.js → chunk-53h87fmt.js} +1 -1
- package/dist/chunk-54yagjc7.js +2 -0
- package/dist/chunk-606343xt.js +1 -0
- package/dist/{chunk-85jv1sr7.js → chunk-651cnx1s.js} +2 -2
- package/dist/{chunk-n8w1jxsh.js → chunk-67qdrjyy.js} +1 -1
- package/dist/chunk-6czf04er.js +1 -0
- package/dist/{chunk-pq6g92cz.js → chunk-6p6ts4kv.js} +2 -2
- package/dist/{chunk-sca5q3tt.js → chunk-77efqpdc.js} +1 -1
- package/dist/{chunk-10w2pj3r.js → chunk-93x9xbew.js} +1 -1
- package/dist/chunk-9gs4eqt8.js +1 -0
- package/dist/{chunk-jy0vfp8a.js → chunk-9kt66etm.js} +1 -1
- package/dist/chunk-9pzfv6nb.js +1 -0
- package/dist/{chunk-p7349xay.js → chunk-9rj01jd1.js} +2 -2
- package/dist/chunk-9s8saznq.js +1 -0
- package/dist/{chunk-1aw643j2.js → chunk-9snmrjg8.js} +2 -2
- package/dist/{chunk-yqpej45c.js → chunk-a60cmnmz.js} +2 -2
- package/dist/{chunk-8hd4vd20.js → chunk-aaxc81jc.js} +1 -1
- package/dist/{chunk-c47db31j.js → chunk-ajsw4te2.js} +2 -2
- package/dist/{chunk-xejvs1fk.js → chunk-amc5d34g.js} +1 -1
- package/dist/{chunk-r04vwtej.js → chunk-ar5np5h5.js} +2 -2
- package/dist/{chunk-mkvvyq49.js → chunk-bamj4e6v.js} +2 -2
- package/dist/{chunk-atema2rc.js → chunk-dfjmvj3d.js} +2 -2
- package/dist/{chunk-9n90djh7.js → chunk-dg54m1y3.js} +2 -2
- package/dist/{chunk-s7axaw78.js → chunk-edtxcqxa.js} +1 -1
- package/dist/chunk-f8gb685p.js +2 -0
- package/dist/chunk-fhafrrvs.js +1 -0
- package/dist/{chunk-zfyg3888.js → chunk-g4xny949.js} +1 -1
- package/dist/chunk-gfbkrk60.js +338 -0
- package/dist/{chunk-12hdakw4.js → chunk-gmqpfm52.js} +2 -2
- package/dist/{chunk-skv2gb99.js → chunk-grhsv55v.js} +2 -2
- package/dist/{chunk-nx8xb7dm.js → chunk-jkfkyedn.js} +1 -1
- package/dist/{chunk-v4nqv1pr.js → chunk-jxh9wf3c.js} +356 -356
- package/dist/{chunk-b408cqg1.js → chunk-kbxqsf93.js} +2 -2
- package/dist/chunk-kd3k1q9z.js +1 -0
- package/dist/{chunk-a7gghhvn.js → chunk-m5vpmvrs.js} +18 -18
- package/dist/chunk-m9mw8ppy.js +1 -0
- package/dist/{chunk-y93nqyqd.js → chunk-mawx6fa5.js} +2 -2
- package/dist/{chunk-xshrj2nd.js → chunk-mdew58v9.js} +1 -1
- package/dist/{chunk-60he05xs.js → chunk-mkzze9aq.js} +2 -2
- package/dist/{chunk-n4q6fvqe.js → chunk-mvm1rzc4.js} +2 -2
- package/dist/chunk-nz8wbcf1.js +1 -0
- package/dist/{chunk-qm632an7.js → chunk-p00f53yq.js} +1 -1
- package/dist/{chunk-9hnfz9bx.js → chunk-pa636c8e.js} +1 -1
- package/dist/chunk-pd1b8jrv.js +1 -0
- package/dist/chunk-pj69j4zp.js +2 -0
- package/dist/{chunk-41byj2h8.js → chunk-q6xsfm60.js} +2 -2
- package/dist/{chunk-6m4sqwj0.js → chunk-qcvxff27.js} +2 -2
- package/dist/chunk-r1b4pnce.js +94 -0
- package/dist/{chunk-jxc67ydz.js → chunk-rnmt44jm.js} +2 -2
- package/dist/chunk-s51h6n70.js +23 -0
- package/dist/chunk-s6158tg7.js +170 -0
- package/dist/{chunk-fgbqm2jh.js → chunk-sfe4810k.js} +1 -1
- package/dist/{chunk-96w8ay2h.js → chunk-sj1dzeta.js} +1 -1
- package/dist/{chunk-ektgnqmh.js → chunk-sx77dpxw.js} +1 -1
- package/dist/chunk-t6bg5b37.js +1 -0
- package/dist/{chunk-gxwkwkhp.js → chunk-tkydv9k8.js} +1 -1
- package/dist/{chunk-q3y3s16v.js → chunk-v52wc8yg.js} +2 -2
- package/dist/chunk-wzcwxhhz.js +1 -0
- package/dist/{chunk-yysqw1cq.js → chunk-xcmadwjv.js} +2 -2
- package/dist/chunk-xdphpfrg.js +14 -0
- package/dist/chunk-xsjtjrt9.js +10 -0
- package/dist/{chunk-6v2hhgka.js → chunk-y4f99y85.js} +2 -2
- package/dist/{chunk-mvgmsjwq.js → chunk-z03dtyh6.js} +1 -1
- package/dist/{chunk-rz2wc93t.js → chunk-za8gyypy.js} +4 -4
- package/dist/{chunk-mm05y2c5.js → chunk-zkzhm39s.js} +1 -1
- package/dist/{chunk-1xg7qx35.js → chunk-zwjrensv.js} +1 -1
- package/dist/chunk-zzgxy86p.js +1 -0
- package/dist/web/assets/ChatView-Bg36FUaj.js +53 -0
- package/dist/web/assets/{CodeBlockHighlighter-0VOa5Mes.js → CodeBlockHighlighter-D5rB73Eo.js} +2 -2
- package/dist/web/assets/FilePreview-BxaBSmap.js +65 -0
- package/dist/web/assets/KanbanBoard-B4gx3JMo.js +16 -0
- package/dist/web/assets/{MarkdownRenderer-3g4TPTeI.js → MarkdownRenderer-BRH7LHhN.js} +3 -3
- package/dist/web/assets/ScrollArea-DikU3QeQ.js +1 -0
- package/dist/web/assets/SessionHistorySurface-DG80d6-F.js +6 -0
- package/dist/web/assets/{SettingsModal-3GMy6V-E.js → SettingsModal-Bxqkok81.js} +3 -3
- package/dist/web/assets/Sidebar-DGaHGcHx.js +31 -0
- package/dist/web/assets/TaskSwitcher-DOnLPurk.js +26 -0
- package/dist/web/assets/TerminalPanel-BzhCF9vw.js +6 -0
- package/dist/web/assets/archive-BiDGrqry.js +6 -0
- package/dist/web/assets/{arrow-left-03GxbYI7.js → arrow-left-BY-esOAP.js} +1 -1
- package/dist/web/assets/{calendar-clock-8W4ostX1.js → calendar-clock-BCyxvfVt.js} +1 -1
- package/dist/web/assets/chevron-right-Bg-10yuN.js +6 -0
- package/dist/web/assets/{chevrons-up-down-BboZzEAk.js → chevrons-up-down-M5SAJq7T.js} +1 -1
- package/dist/web/assets/{clock-3-aXgeptZP.js → clock-3-v-nHTA0A.js} +1 -1
- package/dist/web/assets/copy-p1zc_rjZ.js +6 -0
- package/dist/web/assets/download-D_-kbJXR.js +6 -0
- package/dist/web/assets/{external-link-UkIIC2ds.js → external-link-wSGTIqe3.js} +1 -1
- package/dist/web/assets/{folder-BOCc5dv2.js → folder-Ltm9jCS5.js} +1 -1
- package/dist/web/assets/index-B4186fIT.css +1 -0
- package/dist/web/assets/index-_xnlrekR.js +210 -0
- package/dist/web/assets/{pause-DVIT6IIr.js → pause-_LvCZkxM.js} +1 -1
- package/dist/web/assets/pencil-DB6ICr_h.js +6 -0
- package/dist/web/assets/{play-DsdF5dji.js → play-BRXP1rHJ.js} +1 -1
- package/dist/web/assets/plus-BqvjEpLw.js +6 -0
- package/dist/web/assets/session-events-AGMXvPey.js +22 -0
- package/dist/web/assets/settings-LfQbDvBA.js +6 -0
- package/dist/web/assets/teamService-B5FnUcet.js +1 -0
- package/dist/web/assets/terminal-By4sO9Gw.js +6 -0
- package/dist/web/assets/vendor-radix-D6QrtXqd.js +45 -0
- package/dist/web/index.html +3 -3
- package/package.json +1 -1
- package/dist/chunk-0ktte40x.js +0 -185
- package/dist/chunk-1acb8fwq.js +0 -120
- package/dist/chunk-3pwqqk7w.js +0 -1
- package/dist/chunk-3q7g9206.js +0 -1
- package/dist/chunk-562w5zc6.js +0 -2
- package/dist/chunk-5x56nka1.js +0 -1
- package/dist/chunk-7hajkvde.js +0 -1
- package/dist/chunk-9wptwfmg.js +0 -1
- package/dist/chunk-ap01rwg0.js +0 -169
- package/dist/chunk-cm8fy1jn.js +0 -1
- package/dist/chunk-dp4r5bay.js +0 -1
- package/dist/chunk-dtxza4zh.js +0 -1
- package/dist/chunk-hd7bxzvy.js +0 -1
- package/dist/chunk-hks48s9k.js +0 -1
- package/dist/chunk-hmncnf7p.js +0 -1
- package/dist/chunk-j6fj679p.js +0 -10
- package/dist/chunk-m8czdpyg.js +0 -1
- package/dist/chunk-p5awnndq.js +0 -8
- package/dist/chunk-s7peh6kf.js +0 -2
- package/dist/chunk-ws6gtw33.js +0 -1
- package/dist/chunk-wtmhqy5s.js +0 -1
- package/dist/chunk-xnstybjm.js +0 -2
- package/dist/chunk-xpdtg9h9.js +0 -23
- package/dist/chunk-z2jwm4s8.js +0 -1
- package/dist/web/assets/ChatView-DCHnicTP.js +0 -58
- package/dist/web/assets/FilePreview-C_3KHzzj.js +0 -65
- package/dist/web/assets/KanbanBoard-D_NTkUnD.js +0 -16
- package/dist/web/assets/TaskSwitcher-eCdxu5Eo.js +0 -26
- package/dist/web/assets/TerminalPanel-9q9Trmv9.js +0 -6
- package/dist/web/assets/index-DGf6Z2kM.css +0 -1
- package/dist/web/assets/index-DaiT-mmo.js +0 -275
- package/dist/web/assets/session-events-CWzF04l4.js +0 -22
- package/dist/web/assets/teamService-BliaDj1Z.js +0 -1
- package/dist/web/assets/vendor-radix-Bc1_Q9tz.js +0 -45
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./chunk-
|
|
1
|
+
import"./chunk-zkzhm39s.js";var d={command:"install [target]",describe:"Install Blade native build. Use [target] to specify version (stable, latest, or specific version)",builder:(b)=>{return b.positional("target",{describe:"Version to install",type:"string",default:"stable",choices:["stable","latest"]}).option("force",{type:"boolean",describe:"Force reinstall",default:!1}).example([["$0 install","Install stable version"],["$0 install latest","Install latest version"],["$0 install --force","Force reinstall stable version"]])},handler:async(b)=>{console.log(`Installing Blade ${b.target}...`);try{if(b.force)console.log("Force reinstall enabled");console.log("Downloading..."),console.log("Installing..."),console.log("Installation completed successfully")}catch(c){console.error(`Error: Installation failed: ${c instanceof Error?c.message:"未知错误"}`),process.exit(1)}}};export{d as installCommands};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{dc as C4}from"./chunk-sca5q3tt.js";import{Ed as X1,Pd as I0,Rd as H2,Sd as k1,Td as j2,_d as n$,ad as m6,cd as l6,dd as i6,ec as z$,ed as iJ,fd as rJ,gc as Y1,hc as c6,ic as W1,kc as K$,ld as r6,md as I4,nd as u4,od as pJ,pd as I1,qd as g4,rd as p4,sd as M1,wd as G6}from"./chunk-1acb8fwq.js";import{de as v4}from"./chunk-z3hpstky.js";import{fe as B0,ie as T6,je as T$}from"./chunk-0ktte40x.js";import{sf as K4}from"./chunk-xshrj2nd.js";import{Af as X2,Bf as D6,Cf as w6,Ef as q6,tf as k4,uf as m0,vf as E4,wf as U6,zf as T1}from"./chunk-c47db31j.js";import{pg as e0,qg as l0,tg as h4,xg as q4}from"./chunk-ektgnqmh.js";import{Kg as A$}from"./chunk-p2rxrxct.js";import{di as J4}from"./chunk-nx8xb7dm.js";import{si as Q0}from"./chunk-ted1hyvb.js";import{Ui as h0}from"./chunk-r04vwtej.js";import{gj as d6}from"./chunk-b408cqg1.js";import{Fj as x6,Gj as k6,Jj as a$,Lj as a2,Mj as C1,Oj as u6,Tj as g6,Uj as p6,qj as I6}from"./chunk-xnstybjm.js";import{Wj as _8}from"./chunk-mm05y2c5.js";function f$($){return $.role==="system"&&Array.isArray($.content)}function O$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class P1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,J){this.context=$;let Z=$.messages.find(f$);if(this._contextualSystemMessages=$.messages.filter(O$),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!f$(W)&&!O$(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(!O$($))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($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((J)=>J.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((J)=>!f$(J)&&!O$(J)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(O$),this._history=$.filter((J)=>!f$(J)&&!O$(J)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let J=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((Z)=>!$(Z)),this._pending=this._pending.filter((Z)=>!$(Z)),this._contextualSystemMessages=this._contextualSystemMessages.filter((Z)=>!$(Z)),this.syncContextualSystemMessages(),this._history.length!==J[0]||this._pending.length!==J[1]||this._contextualSystemMessages.length!==J[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function T2($){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 M2($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function R2($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import V$ from"node:path";var s4=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"]),t4=/^(LD_.+|DYLD_.+|PATH)$/,x2=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function m$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(x2);if(!V)break;let K=V[1];if(!s4.has(K))break;J=Y}return J}function iZ($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(x2);if(!V)break;let K=V[1];if(t4.test(K))break;J=Y}return J}var e4=[/^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 GJ($){let J=$,Z=!0;while(Z){Z=!1;for(let W of e4){let Y=J.match(W);if(Y){J=J.slice(Y[0].length),Z=!0;break}}if(J.startsWith("-- "))J=J.slice(3),Z=!0}return J}function l$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){Z+=Q,V=!0;continue}if(Q==="'"&&!Y){W=!W,Z+=Q;continue}if(Q==='"'&&!W){Y=!Y,Z+=Q;continue}if(W||Y){Z+=Q;continue}if(Q==="|"){if(K+1<$.length&&$[K+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&K+1<$.length&&$[K+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}if(Q==="&")return null;if(Q===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=Q}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function k2($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let V=$[Y];if(W){W=!1;continue}if(V==="\\"&&!J){W=!0;continue}if(V==="'"&&!Z){J=!J;continue}if(V==='"'&&!J){Z=!Z;continue}if(J)continue;if(V==="$"){let K=$[Y+1];if(K&&/[A-Za-z_@*#?!$0-9({]/.test(K))return!0}if(V==="`")return!0;if(Z)continue;if(V==="|")return!0;if(V===">"||V==="<")return!0;if(V==="{"){let K=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(K)||/^\{[^}]*\.\.[^}]*\}/.test(K))return!0}}return!1}function Y$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){if(V=!0,Y){let X=$[K+1];if(X&&'$`"\\'.includes(X))continue;Z+=Q,V=!1}continue}if(Q==="'"&&!Y){W=!W;continue}if(Q==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(Q)){if(Z)J.push(Z),Z="";continue}Z+=Q}if(Z)J.push(Z);return J}var $5=new Set(["npm","pnpm","yarn","bun"]),h2=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),J5=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),Z5=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function W5($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function v2($){return $.replace(/\s+2>&1\s*$/,"").trim()}function Y5($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=Y$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let V=Y[1];if(!V||V==="-")return;let K=V$.isAbsolute(V)?V$.resolve(V):V$.resolve(Z,V);if(!K$.isWithinWorkspace(K,Z))return;return W[2]?.trim()||void 0}function V5($){let J=[],Z=!1,W=!1,Y=!1;for(let V=0;V<$.length;V++){let K=$[V];if(Y){Y=!1;continue}if(K==="\\"&&!Z){Y=!0;continue}if(K==="'"&&!W){Z=!Z;continue}if(K==='"'&&!Z){W=!W;continue}if(K!=="|"||Z||W)continue;if($[V+1]==="|")return;J.push(V)}return J}function K5($){let J=Y$($),[Z,W,Y]=J;if(Z!=="head"&&Z!=="tail")return!1;if(J.length===1)return!0;let V=(K)=>K!==void 0&&/^[1-9]\d{0,4}$/.test(K);if(J.length===2)return W?.startsWith("--lines=")&&V(W.slice(8))||W?.startsWith("-")&&V(W.slice(1));return J.length===3&&(W==="-n"||W==="--lines")&&V(Y)}function Q5($){let J=v2($.replace(Z5,"").trim()),Z=V5(J);if(!Z)return;if(Z.length===0)return C2(J);if(Z.length!==1)return;let W=Z[0];if(W===void 0)return;let Y=v2(J.slice(0,W).trim()),V=J.slice(W+1).trim();if(!Y||!K5(V))return;return C2(Y)}function C2($){let Z=l$($)?.at(-1);if(!Z)return $;let W=Y$(Z),[Y,V]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&V==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function y$($,J){let Z=Q5($);if(!Z)return!1;let W=m$(Z),Y=l$(W);if(!Y||k2(W)||/[\r\n]/.test(W))return!1;let V=Y.length===1?Y[0]:Y5(W,Y,J);if(!V)return!1;let K=Y$(V);if(K.length===0||K.some((z)=>[...J5].some((B)=>z===B||z.startsWith(`${B}=`))))return!1;let[Q,X,H]=K;if($5.has(Q??""))return W5(X==="run"?H:X)||X==="--test";if((Q==="npx"||Q==="bunx")&&h2.has(X??""))return!0;if(h2.has(Q??""))return!0;if(Q==="node"&&X==="--test")return!0;if(Q==="go"&&["build","test","vet"].includes(X??""))return!0;return Q==="cargo"&&["build","check","clippy","test"].includes(X??"")}function sZ($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!V$.isAbsolute($);let Z=V$.isAbsolute($)?V$.resolve($):V$.resolve(J,$);return K$.isWithinWorkspace(Z,J)}var FJ=h0("Agent"),X5=3;function LJ($,J,Z){if($!=="length")return{action:"none"};if(J>=X5)return{action:"truncated"};if(T2(Z)==="stop")return FJ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var H5=[/:\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],j5=/```[\s\S]{50,}```/,I2="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",z5=2;function OJ($,J,Z=!0){if(!$||J>=z5)return{action:"none"};if(!Z&&j5.test($))return{action:"retry",prompt:I2};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(H5.some((K)=>K.test(W)))return{action:"retry",prompt:I2};return{action:"none"}}var B5=[/\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}(?:测试|单测|集成测试|检查|构建)/],u2={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},U5={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},D5="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.",w5="Required verification did not run successfully before the retry limit.",q5=3;function p2($,J,Z,W){if(!Z.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(J)){$.clear();return}if(J==="Bash"&&typeof Z.metadata?.command==="string"&&Z.metadata.exit_code===0&&y$(Z.metadata.command,W)){$.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes(J))return;let Y=Z.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let V of Y)if(typeof V==="string"&&y$(V,W))$.add(V)}function fJ($,J,Z){if(!$||!B5.some((X)=>X.test($)))return{action:"none"};let W=Object.keys(u2).filter((X)=>u2[X].test($)),Y=[...J],V=W.filter((X)=>!Y.some((H)=>U5[X].test(H)));if(W.length>0?V.length===0:Y.some((X)=>y$(X)))return{action:"none"};if(Z>=q5)return{action:"fail",message:w5};let Q=W.length>1&&V.length>0?` Missing successful verification categories: ${V.join(", ")}.`:"";return{action:"retry",prompt:`${D5}${Q}`}}var G5=[/\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|子代理|子智能体)/],d2=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function c2($){return typeof $==="string"&&d2.some((J)=>J.test($))}var F5=[/\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|子代理)/],L5=[/\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 O5($){if(typeof $!=="string")return;if(L5.some((J)=>J.test($)))return"multiple-allowed";return F5.some((J)=>J.test($))?"required":void 0}function i$($){for(let J of $){let Z=O5(J);if(Z!==void 0)return Z==="required"}return!1}var f5="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.",y5="Required delegation did not complete before the retry limit.",A5=3;function m2($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),Y=i$(W),V=!1;if(!Y)for(let K of W){if(d2.some((Q)=>Q.test(K)))break;if(G5.some((Q)=>Q.test(K))){V=!0;break}}if(W.length===0||!Y&&!V||J.has("Task"))return{action:"none"};if(Z>=A5)return{action:"fail",message:y5};return{action:"retry",prompt:f5}}var P5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],N5=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],_5=[/\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 l2($){return _5.reduce((J,Z)=>J.replace(Z," "),$)}function _1($){if(typeof $!=="string")return!1;let J=l2($);return P5.some((Z)=>Z.test(J))}var b5="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.",E5="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.",S5="Required worktree lifecycle did not complete before the retry limit.",T5=3;function i2($,J,Z){if(!$)return{action:"none"};let W=l2($);if(!_1(W))return{action:"none"};let Y=N5.some((K)=>K.test(W));if(J.has("TaskWorktree"))return{action:"none"};let V=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!V)return{action:"none"};if(Z>=T5)return{action:"fail",message:S5};return{action:"retry",tool:V,prompt:V==="EnterWorktree"?b5:E5}}var g2=30000;async function yJ($){try{let Z=A$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??Q0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((V)=>{W=setTimeout(()=>V("timeout"),g2)});try{let V=await Promise.race([Z,Y]);if(V==="timeout")return FJ.warn(`[Loop] Stop hook 超时 (${g2}ms),按 shouldStop: true 处理`),{action:"stop"};let K=V;if(!K.shouldStop)return{action:"continue",reason:K.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return FJ.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function M5($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var R5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function x5($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((J)=>{if(typeof J==="string")return J;if(J&&typeof J==="object"&&"text"in J){let Z=J.text;return typeof Z==="string"?Z:""}return""}).join(" ");return""}function k5($){let J=$;for(let X of R5)J=J.replace(X," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:Z;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let V=Y.slice(0,60),K=V.lastIndexOf(" ");return`${(K>36?V.slice(0,K):V).trimEnd()}…`}function r2($){return k5(x5($))}import{EventEmitter as h5}from"events";import n2 from"node:path";function AJ($){if(a2($.sessionId),!n2.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:n2.resolve($.projectPath)}}function o2($){let J=AJ($);return JSON.stringify([J.projectPath,J.sessionId])}function H3($,J){return o2($)===o2(J)}class P$ extends h5{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!P$.instance)P$.instance=new P$;return P$.instance}publish($,J,Z,W){let Y=AJ($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:J,...W!==void 0?{seq:W}:{},properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var r$=P$.getInstance();var a0=h0("Agent"),b1=new Set;async function v5($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(b1.has(Z))return;if(b1.size>=5000)b1.clear();b1.add(Z);try{let W=$.workspaceRoot,Y=await n$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let V=r2(J);if(!V)return;await n$.updateSessionMetadata(Z,Y.projectPath,{title:V}),r$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:V})}catch(W){a0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var PJ=`<turn_aborted>
|
|
1
|
+
import{gc as C4}from"./chunk-77efqpdc.js";import{Id as I0,Kd as H2,Ld as k1,Md as j2,Td as n$,dd as m6,fd as l6,gd as i6,hc as z$,hd as iJ,id as rJ,jc as Y1,kc as c6,lc as W1,nc as K$,od as r6,pd as I4,qd as u4,rd as pJ,sd as I1,td as g4,ud as p4,vd as M1,zd as G6}from"./chunk-r1b4pnce.js";import{Yd as v4}from"./chunk-53h87fmt.js";import{$d as B0,ce as T6,de as T$,oe as X1}from"./chunk-gfbkrk60.js";import{Of as K4}from"./chunk-mdew58v9.js";import{Pf as k4,Qf as m0,Rf as E4,Sf as U6,Vf as T1,Wf as X2,Xf as D6,Yf as w6,_f as q6}from"./chunk-ajsw4te2.js";import{Lg as e0,Mg as l0,Pg as h4,Tg as q4}from"./chunk-sx77dpxw.js";import{eh as A$}from"./chunk-440v1nhy.js";import{zi as J4}from"./chunk-jkfkyedn.js";import{Ii as Q0}from"./chunk-44jtpg8y.js";import{oj as h0}from"./chunk-ar5np5h5.js";import{Cj as d6}from"./chunk-kbxqsf93.js";import{$j as x6,Mj as I6,ak as k6,dk as a$,gk as a2,hk as C1,jk as u6,ok as g6,pk as p6}from"./chunk-pj69j4zp.js";import{rk as _8}from"./chunk-zkzhm39s.js";function f$($){return $.role==="system"&&Array.isArray($.content)}function O$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class P1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,J){this.context=$;let Z=$.messages.find(f$);if(this._contextualSystemMessages=$.messages.filter(O$),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!f$(W)&&!O$(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(!O$($))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($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((J)=>J.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((J)=>!f$(J)&&!O$(J)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(O$),this._history=$.filter((J)=>!f$(J)&&!O$(J)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let J=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((Z)=>!$(Z)),this._pending=this._pending.filter((Z)=>!$(Z)),this._contextualSystemMessages=this._contextualSystemMessages.filter((Z)=>!$(Z)),this.syncContextualSystemMessages(),this._history.length!==J[0]||this._pending.length!==J[1]||this._contextualSystemMessages.length!==J[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function T2($){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 M2($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function R2($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import V$ from"node:path";var s4=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"]),t4=/^(LD_.+|DYLD_.+|PATH)$/,x2=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function m$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(x2);if(!V)break;let K=V[1];if(!s4.has(K))break;J=Y}return J}function iZ($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(x2);if(!V)break;let K=V[1];if(t4.test(K))break;J=Y}return J}var e4=[/^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 GJ($){let J=$,Z=!0;while(Z){Z=!1;for(let W of e4){let Y=J.match(W);if(Y){J=J.slice(Y[0].length),Z=!0;break}}if(J.startsWith("-- "))J=J.slice(3),Z=!0}return J}function l$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){Z+=Q,V=!0;continue}if(Q==="'"&&!Y){W=!W,Z+=Q;continue}if(Q==='"'&&!W){Y=!Y,Z+=Q;continue}if(W||Y){Z+=Q;continue}if(Q==="|"){if(K+1<$.length&&$[K+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&K+1<$.length&&$[K+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}if(Q==="&")return null;if(Q===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=Q}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function k2($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let V=$[Y];if(W){W=!1;continue}if(V==="\\"&&!J){W=!0;continue}if(V==="'"&&!Z){J=!J;continue}if(V==='"'&&!J){Z=!Z;continue}if(J)continue;if(V==="$"){let K=$[Y+1];if(K&&/[A-Za-z_@*#?!$0-9({]/.test(K))return!0}if(V==="`")return!0;if(Z)continue;if(V==="|")return!0;if(V===">"||V==="<")return!0;if(V==="{"){let K=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(K)||/^\{[^}]*\.\.[^}]*\}/.test(K))return!0}}return!1}function Y$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){if(V=!0,Y){let X=$[K+1];if(X&&'$`"\\'.includes(X))continue;Z+=Q,V=!1}continue}if(Q==="'"&&!Y){W=!W;continue}if(Q==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(Q)){if(Z)J.push(Z),Z="";continue}Z+=Q}if(Z)J.push(Z);return J}var $5=new Set(["npm","pnpm","yarn","bun"]),h2=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),J5=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),Z5=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function W5($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function v2($){return $.replace(/\s+2>&1\s*$/,"").trim()}function Y5($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=Y$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let V=Y[1];if(!V||V==="-")return;let K=V$.isAbsolute(V)?V$.resolve(V):V$.resolve(Z,V);if(!K$.isWithinWorkspace(K,Z))return;return W[2]?.trim()||void 0}function V5($){let J=[],Z=!1,W=!1,Y=!1;for(let V=0;V<$.length;V++){let K=$[V];if(Y){Y=!1;continue}if(K==="\\"&&!Z){Y=!0;continue}if(K==="'"&&!W){Z=!Z;continue}if(K==='"'&&!Z){W=!W;continue}if(K!=="|"||Z||W)continue;if($[V+1]==="|")return;J.push(V)}return J}function K5($){let J=Y$($),[Z,W,Y]=J;if(Z!=="head"&&Z!=="tail")return!1;if(J.length===1)return!0;let V=(K)=>K!==void 0&&/^[1-9]\d{0,4}$/.test(K);if(J.length===2)return W?.startsWith("--lines=")&&V(W.slice(8))||W?.startsWith("-")&&V(W.slice(1));return J.length===3&&(W==="-n"||W==="--lines")&&V(Y)}function Q5($){let J=v2($.replace(Z5,"").trim()),Z=V5(J);if(!Z)return;if(Z.length===0)return C2(J);if(Z.length!==1)return;let W=Z[0];if(W===void 0)return;let Y=v2(J.slice(0,W).trim()),V=J.slice(W+1).trim();if(!Y||!K5(V))return;return C2(Y)}function C2($){let Z=l$($)?.at(-1);if(!Z)return $;let W=Y$(Z),[Y,V]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&V==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function y$($,J){let Z=Q5($);if(!Z)return!1;let W=m$(Z),Y=l$(W);if(!Y||k2(W)||/[\r\n]/.test(W))return!1;let V=Y.length===1?Y[0]:Y5(W,Y,J);if(!V)return!1;let K=Y$(V);if(K.length===0||K.some((z)=>[...J5].some((B)=>z===B||z.startsWith(`${B}=`))))return!1;let[Q,X,H]=K;if($5.has(Q??""))return W5(X==="run"?H:X)||X==="--test";if((Q==="npx"||Q==="bunx")&&h2.has(X??""))return!0;if(h2.has(Q??""))return!0;if(Q==="node"&&X==="--test")return!0;if(Q==="go"&&["build","test","vet"].includes(X??""))return!0;return Q==="cargo"&&["build","check","clippy","test"].includes(X??"")}function sZ($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!V$.isAbsolute($);let Z=V$.isAbsolute($)?V$.resolve($):V$.resolve(J,$);return K$.isWithinWorkspace(Z,J)}var FJ=h0("Agent"),X5=3;function LJ($,J,Z){if($!=="length")return{action:"none"};if(J>=X5)return{action:"truncated"};if(T2(Z)==="stop")return FJ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var H5=[/:\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],j5=/```[\s\S]{50,}```/,I2="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",z5=2;function OJ($,J,Z=!0){if(!$||J>=z5)return{action:"none"};if(!Z&&j5.test($))return{action:"retry",prompt:I2};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(H5.some((K)=>K.test(W)))return{action:"retry",prompt:I2};return{action:"none"}}var B5=[/\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}(?:测试|单测|集成测试|检查|构建)/],u2={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},U5={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},D5="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.",w5="Required verification did not run successfully before the retry limit.",q5=3;function p2($,J,Z,W){if(!Z.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(J)){$.clear();return}if(J==="Bash"&&typeof Z.metadata?.command==="string"&&Z.metadata.exit_code===0&&y$(Z.metadata.command,W)){$.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes(J))return;let Y=Z.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let V of Y)if(typeof V==="string"&&y$(V,W))$.add(V)}function fJ($,J,Z){if(!$||!B5.some((X)=>X.test($)))return{action:"none"};let W=Object.keys(u2).filter((X)=>u2[X].test($)),Y=[...J],V=W.filter((X)=>!Y.some((H)=>U5[X].test(H)));if(W.length>0?V.length===0:Y.some((X)=>y$(X)))return{action:"none"};if(Z>=q5)return{action:"fail",message:w5};let Q=W.length>1&&V.length>0?` Missing successful verification categories: ${V.join(", ")}.`:"";return{action:"retry",prompt:`${D5}${Q}`}}var G5=[/\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|子代理|子智能体)/],d2=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function c2($){return typeof $==="string"&&d2.some((J)=>J.test($))}var F5=[/\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|子代理)/],L5=[/\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 O5($){if(typeof $!=="string")return;if(L5.some((J)=>J.test($)))return"multiple-allowed";return F5.some((J)=>J.test($))?"required":void 0}function i$($){for(let J of $){let Z=O5(J);if(Z!==void 0)return Z==="required"}return!1}var f5="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.",y5="Required delegation did not complete before the retry limit.",A5=3;function m2($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),Y=i$(W),V=!1;if(!Y)for(let K of W){if(d2.some((Q)=>Q.test(K)))break;if(G5.some((Q)=>Q.test(K))){V=!0;break}}if(W.length===0||!Y&&!V||J.has("Task"))return{action:"none"};if(Z>=A5)return{action:"fail",message:y5};return{action:"retry",prompt:f5}}var P5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],N5=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],_5=[/\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 l2($){return _5.reduce((J,Z)=>J.replace(Z," "),$)}function _1($){if(typeof $!=="string")return!1;let J=l2($);return P5.some((Z)=>Z.test(J))}var b5="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.",E5="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.",S5="Required worktree lifecycle did not complete before the retry limit.",T5=3;function i2($,J,Z){if(!$)return{action:"none"};let W=l2($);if(!_1(W))return{action:"none"};let Y=N5.some((K)=>K.test(W));if(J.has("TaskWorktree"))return{action:"none"};let V=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!V)return{action:"none"};if(Z>=T5)return{action:"fail",message:S5};return{action:"retry",tool:V,prompt:V==="EnterWorktree"?b5:E5}}var g2=30000;async function yJ($){try{let Z=A$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??Q0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((V)=>{W=setTimeout(()=>V("timeout"),g2)});try{let V=await Promise.race([Z,Y]);if(V==="timeout")return FJ.warn(`[Loop] Stop hook 超时 (${g2}ms),按 shouldStop: true 处理`),{action:"stop"};let K=V;if(!K.shouldStop)return{action:"continue",reason:K.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return FJ.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function M5($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var R5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function x5($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((J)=>{if(typeof J==="string")return J;if(J&&typeof J==="object"&&"text"in J){let Z=J.text;return typeof Z==="string"?Z:""}return""}).join(" ");return""}function k5($){let J=$;for(let X of R5)J=J.replace(X," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:Z;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let V=Y.slice(0,60),K=V.lastIndexOf(" ");return`${(K>36?V.slice(0,K):V).trimEnd()}…`}function r2($){return k5(x5($))}import{EventEmitter as h5}from"events";import n2 from"node:path";function AJ($){if(a2($.sessionId),!n2.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:n2.resolve($.projectPath)}}function o2($){let J=AJ($);return JSON.stringify([J.projectPath,J.sessionId])}function j3($,J){return o2($)===o2(J)}class P$ extends h5{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!P$.instance)P$.instance=new P$;return P$.instance}publish($,J,Z,W){let Y=AJ($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:J,...W!==void 0?{seq:W}:{},properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var r$=P$.getInstance();var a0=h0("Agent"),b1=new Set;async function v5($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(b1.has(Z))return;if(b1.size>=5000)b1.clear();b1.add(Z);try{let W=$.workspaceRoot,Y=await n$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let V=r2(J);if(!V)return;await n$.updateSessionMetadata(Z,Y.projectPath,{title:V}),r$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:V})}catch(W){a0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var PJ=`<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>`,Q$="Tool execution was blocked because its durable call record could not be committed. No tool side effect was started.",s2="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 N$ extends Error{phase;constructor($,J){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.",J);this.phase=$;this.name="DurableConversationPersistenceError"}}function X$($){return $.executionEngine?.getContextManager()}async function c0($,J,Z,W=null,Y,V={}){let K=V.required??$.executionEngine!==void 0;try{let Q=X$($),X=typeof Z==="string"?Z.trim()!=="":Z.some((H)=>H.type==="text"?H.text.trim()!=="":!0);if(Q&&J.sessionId&&X){let H=await Q.saveMessage(J.sessionId,"user",Z,W,Y,J.subagentInfo);if(K&&!H)throw Error("Durable user-message commit returned no identity");if(Y?.clientVisible!==!1)v5(J,Z);return H}if(K&&J.sessionId&&X)throw Error("Durable user-message storage is unavailable")}catch(Q){if(a0.warn("[Loop] 保存用户消息失败:",Q),K)throw new N$("user_message",{cause:Q})}return null}async function v0($,J,Z,W,Y,V,K={}){let Q=K.required??$.executionEngine!==void 0;try{let X=X$($),H=Boolean(Z.trim()||Y?.trim());if(X&&J.sessionId&&H){let z=await X.saveMessage(J.sessionId,"assistant",Z,W,V,J.subagentInfo,Y);if(Q&&!z)throw Error("Durable assistant-message commit returned no identity");return z}if(Q&&J.sessionId&&H)throw Error("Durable assistant-message storage is unavailable")}catch(X){if(a0.warn("[Loop] 保存助手消息失败:",X),Q)throw new N$("assistant_message",{cause:X})}return null}async function t2($,J,Z){try{let W=X$($);if(W&&J.sessionId)return await W.saveMessage(J.sessionId,"system",PJ,Z,void 0,J.subagentInfo)}catch(W){a0.warn("[Loop] 保存中断边界失败:",W)}return null}async function e2($,J,Z,W,Y){try{let V=X$($);if(!V||!J.sessionId||Z.length===0)return null;return await V.saveMessage(J.sessionId,"system",`<contextual-project-instructions-ref count="${Z.length}" />`,Y,{contextualProjectRules:!0,ruleReferences:JSON.parse(JSON.stringify(Z.map((K)=>({...K})))),triggerPaths:[...W]},J.subagentInfo)}catch(V){a0.warn("[Loop] 保存 contextual project rules provenance 失败:",V)}return null}async function NJ($,J,Z,W,Y,V={}){try{let K=X$($);if(K&&J.sessionId){let Q=await K.saveToolUse(J.sessionId,Z,W,Y,J.subagentInfo,V.providerToolCallId);if(V.required&&!Q)throw Error("Durable tool-use commit returned no identity");return Q}if(V.required&&J.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(K){if(a0.warn("[Loop] 保存工具调用失败:",K),V.required)throw K}return null}async function E1($,J,Z,W,Y,V,K,Q,X,H={}){try{let z=X$($);if(z&&J.sessionId){let B=await z.saveToolResult(J.sessionId,Z,W,Y,V,K,J.subagentInfo,Q,X);if(H.required&&!B)throw Error("Durable tool-result commit returned no identity");return B}if(H.required&&J.sessionId)throw Error("Durable tool-result storage is unavailable")}catch(z){if(a0.warn("[Loop] 保存工具结果失败:",z),H.required)throw z}return null}async function o$($,J,Z,W,Y={}){try{let V=X$($);if(V&&J.sessionId){let K=await V.saveCompaction(J.sessionId,Z,W,null);if(Y.required&&!K)throw Error("Compaction checkpoint commit returned no identity");return K||null}if(Y.required&&J.sessionId)throw Error("Compaction checkpoint storage is unavailable")}catch(V){if(a0.warn("[Loop] 保存压缩数据失败:",V),Y.required)throw V}return null}async function G0($){let{deps:J,context:Z,state:W,assistantContent:Y,assistantReasoningContent:V,lastMessageUuid:K,controlPrompt:Q,controlMetadata:X}=$;W.appendAssistant({role:"assistant",content:Y,reasoningContent:V});let H=K,z=await v0(J,Z,Y,H,V);if(z)H=z;if(Q!==void 0){let B={role:"user",content:Q};if(X)B.metadata=X;W.appendControl("user",B);let j=await c0(J,Z,B.content,H,X);if(j)H=j}return H}import{createHash as z2}from"node:crypto";import{promises as t5}from"node:fs";import e5 from"node:path";import{nanoid as s0}from"nanoid";import*as Y0 from"node:fs/promises";import*as H$ from"node:path";var $6={enabled:!0,maxIndexLines:200};var C5="memory",J6="MEMORY.md";class _J{memoryDir;config;initialized=!1;constructor($,J,Z){if(Z)this.memoryDir=Z;else{let W=a$($);this.memoryDir=H$.join(W,C5)}this.config={...$6,...J}}async initialize(){if(this.initialized)return;await Y0.mkdir(this.memoryDir,{recursive:!0}),this.initialized=!0}async loadIndex(){if(!this.config.enabled)return null;await this.initialize();let $=H$.join(this.memoryDir,J6);try{let J=await Y0.readFile($,"utf-8");if(!J.trim())return null;let Z=J.split(`
|
|
4
4
|
`),Y=Z.slice(0,this.config.maxIndexLines).join(`
|
|
@@ -83,7 +83,7 @@ Full output saved to: ${Q}`}catch{return`${J}
|
|
|
83
83
|
|
|
84
84
|
${Y}`}}import C8 from"node:path";import{nanoid as I8}from"nanoid";import*as x0 from"node:fs/promises";import*as M6 from"node:path";import{Mutex as f8}from"async-mutex";import y8 from"write-file-atomic";var E6=120,uJ=128;function J1($){if(!Array.isArray($)||$.length>120||!$.every((J)=>typeof J==="string"&&J.length>0&&J.length<=128))return;return[...new Set($)]}function O8($){if(!$||typeof $!=="object"||Array.isArray($))return[];if(!("recovery"in $)||!$.recovery)return[];let J=$.recovery;if(typeof J!=="object"||Array.isArray(J))return[];if(!("version"in J)||J.version!==1&&J.version!==2&&J.version!==3||!("inputMessageIds"in J)||!("hadSuccessfulToolResult"in J)||typeof J.hadSuccessfulToolResult!=="boolean"||!("emptyFinalCorrectionSpent"in J)||typeof J.emptyFinalCorrectionSpent!=="boolean"||!("acknowledgedInputMessageIds"in $))return[];if((J.version===2||J.version===3)&&(!("interruptedToolCallCount"in J)||!Number.isSafeInteger(J.interruptedToolCallCount)||J.interruptedToolCallCount<0))return[];if(J.version===3&&(!("allSuccessfulToolResultsSafeForResume"in J)||typeof J.allSuccessfulToolResultsSafeForResume!=="boolean"))return[];let Z=J1(J.inputMessageIds),W=J1($.acknowledgedInputMessageIds);if(!Z||!W)return[];let Y=new Set(Z);return W.filter((V)=>Y.has(V))}function R1($,J){let Z=$[J];if(Z?.type!=="turn_aborted")return[];let W=O8(Z.data);if(W.length===0)return[];let Y=-1;for(let K=J-1;K>=0;K--){let Q=$[K];if(Q.type==="turn_started"){if(Q.data.turnId!==Z.data.turnId)return[];Y=K;break}if(Q.type==="turn_completed"||Q.type==="turn_aborted")return[]}if(Y<0)return[];let V=new Set;for(let K=Y+1;K<J;K++){let Q=$[K];if(Q.type!=="message_created"||Q.data.role!=="user")continue;let X=Q.data.metadata,H=Q.data.inboxMessageId!==void 0?Q.data.inboxMessageId:X!==null&&typeof X==="object"&&!Array.isArray(X)?X.inboxMessageId:void 0;if(typeof H==="string"&&H.length>0&&H.length<=128)V.add(H)}return W.filter((K)=>V.has(K))}var x1=1,Z1=8388608;function S6($,J){let Z={version:x1,sessionId:$,messages:J.map(({recovered:W,...Y})=>Y)};return`${JSON.stringify(Z)}
|
|
85
85
|
`}function gJ($,J){return $ instanceof Error&&"code"in $&&$.code===J}function A8($){if(typeof $==="string")return!0;if(!Array.isArray($))return!1;return $.every((J)=>{if(!J||typeof J!=="object"||!("type"in J))return!1;if(J.type==="text")return"text"in J&&typeof J.text==="string";return J.type==="image_url"&&"image_url"in J&&typeof J.image_url==="object"&&J.image_url!==null&&"url"in J.image_url&&typeof J.image_url.url==="string"})}function P8($,J,Z){let W;try{W=JSON.parse($)}catch(V){throw Error(`Invalid steering inbox JSON: ${J}`,{cause:V})}if(!W||typeof W!=="object"||!("version"in W)||W.version!==x1||!("sessionId"in W)||W.sessionId!==Z||!("messages"in W)||!Array.isArray(W.messages))throw Error(`Invalid steering inbox record: ${J}`);let Y=W.messages.map((V)=>{if(!V||typeof V!=="object"||!("id"in V)||typeof V.id!=="string"||!("content"in V)||!A8(V.content)||!("queuedAt"in V)||typeof V.queuedAt!=="number"||"persisted"in V&&typeof V.persisted!=="boolean"||"origin"in V&&V.origin!=="user"&&V.origin!=="background_subagent"&&V.origin!=="team_message"||"metadata"in V&&(V.metadata===null||typeof V.metadata!=="object"||Array.isArray(V.metadata))||"outputSchema"in V&&V.outputSchema!==void 0&&(!V.outputSchema||typeof V.outputSchema!=="object"||Array.isArray(V.outputSchema)))throw Error(`Invalid steering inbox message: ${J}`);let K="outputSchema"in V&&V.outputSchema!==void 0?k1(V.outputSchema).schema:void 0;return{id:V.id,content:V.content,queuedAt:V.queuedAt,..."persisted"in V&&V.persisted===!0?{persisted:!0}:{},..."origin"in V&&V.origin?{origin:V.origin}:{},..."metadata"in V&&V.metadata?{metadata:JSON.parse(JSON.stringify(V.metadata))}:{},...K?{outputSchema:K}:{}}});return{version:x1,sessionId:Z,messages:Y}}function N8($){return new Set($.flatMap((J,Z)=>{if(J.type==="inbox_acknowledged")return J.data.messageIds;if(J.type==="turn_aborted")return R1($,Z);return[]}))}class h1{sessionId;stateStorage;mutex=new f8;messages=[];constructor($,J){this.sessionId=$;this.stateStorage=J}static async open($,J,Z=z$($)){let W=new h1(J,Z);return await W.loadAndReconcile(),W}async enqueue($,J){return this.mutex.runExclusive(async()=>{if(J&&!J(this.messages))return!1;let Z=[...this.messages,{...$,recovered:!1}],W=S6(this.sessionId,Z);if(Buffer.byteLength(W)>Z1)return!1;return await this.persist(Z,W),this.messages=Z,!0})}async acknowledge($){if($.length===0)return;let J=new Set($);await this.mutex.runExclusive(async()=>{let Z=this.messages.filter((W)=>!J.has(W.id));this.messages=Z,await this.persist(Z)})}list(){return this.messages.map(($)=>({...$,content:typeof $.content==="string"?$.content:$.content.map((J)=>J.type==="text"?{...J}:{...J,image_url:{...J.image_url}}),...$.outputSchema?{outputSchema:JSON.parse(JSON.stringify($.outputSchema))}:{},...$.metadata?{metadata:JSON.parse(JSON.stringify($.metadata))}:{}}))}count(){return this.messages.length}recoveredCount(){return this.messages.filter(($)=>$.recovered).length}async loadAndReconcile(){await this.mutex.runExclusive(async()=>{await W1(this.stateStorage,this.sessionId,async($)=>{let J={version:x1,sessionId:this.sessionId,messages:[]};try{if((await x0.stat($.inboxPath)).size>Z1)throw Error(`Steering inbox exceeds ${Z1} bytes: ${$.inboxPath}`);await x0.chmod($.inboxPath,384),J=P8(await x0.readFile($.inboxPath,"utf8"),$.inboxPath,this.sessionId)}catch(Y){if(!gJ(Y,"ENOENT"))throw Y}let Z=new Set;try{Z=N8(T6(await x0.readFile($.transcriptPath,"utf8"),$.transcriptPath))}catch(Y){if(!gJ(Y,"ENOENT"))throw Y}let W=J.messages.filter((Y)=>!Z.has(Y.id)).map((Y)=>({...Y,recovered:!0}));if(this.messages=W,W.length!==J.messages.length)await this.persistAtPath(W,$)})})}async persist($,J){await W1(this.stateStorage,this.sessionId,(Z)=>this.persistAtPath($,Z,J))}async persistAtPath($,J,Z){if(await x0.mkdir(M6.dirname(J.inboxPath),{recursive:!0,mode:448}),$.length===0){await x0.unlink(J.inboxPath).catch((Y)=>{if(!gJ(Y,"ENOENT"))throw Y});return}let W=Z??S6(this.sessionId,$);if(Buffer.byteLength(W)>Z1)throw Error(`Steering inbox exceeds ${Z1} bytes: ${J.inboxPath}`);await y8(J.inboxPath,W,{encoding:"utf8",mode:384,fsync:!0})}}import*as C0 from"node:fs/promises";import*as n6 from"node:path";import{nanoid as j0}from"nanoid";var R6=256;class F0{sessionId;projectPath;storage;static instances=new Map;subscribers=new Set;highestSeq=0;constructor($,J,Z){this.sessionId=$;this.projectPath=J;this.storage=Z}static for($,J,Z=z$(J)){let W=Y1(Z,$),Y=F0.instances.get(W);if(!Y)Y=new F0($,J,Z),F0.instances.set(W,Y),F0.pruneIdleInstances(W);else F0.instances.delete(W),F0.instances.set(W,Y);return Y}static release($,J,Z=z$(J)){F0.instances.delete(Y1(Z,$))}static pruneIdleInstances($){if(F0.instances.size<=R6)return;for(let[J,Z]of F0.instances){if(J===$||Z.subscribers.size>0)continue;if(F0.instances.delete(J),F0.instances.size<=R6)return}}get lastSeq(){return this.highestSeq}async readAll(){return this.withStore(async($,J,Z)=>{let W=J?await $.readAllValidated(J):await $.readAll();return Z(W),W})}async commit($){let[J]=await this.commitEntries([$]);return this.record(J),J}async commitBatch($){if($.length===0)return[];let J=await this.commitEntries($);for(let Z of J)this.record(Z);return J}async commitValidated($){let J=await this.withStore((Z,W,Y)=>Z.appendValidated((V)=>{return Y(V),$(V)},W));return this.record(J),J}async commitValidatedBatch($){let J=await this.withStore((Z,W,Y)=>Z.appendValidatedBatch((V)=>{return Y(V),$(V)},W));for(let Z of J)this.record(Z);return J}emitDelta($){for(let J of this.subscribers)J.onDelta?.($);r$.publish({sessionId:this.sessionId,projectPath:this.projectPath},"delta",{delta:$})}subscribe($,J){if(this.subscribers.add($),J?.fromSeq!==void 0)this.replay($,J.fromSeq);return()=>{this.subscribers.delete($),F0.pruneIdleInstances()}}async replay($,J){let Z=await this.withStore(async(W,Y,V)=>{let K=Y?await W.readAllValidated(Y):await W.readAll();return V(K),K.filter((Q)=>(Q.seq??0)>=J)});for(let W of Z){if(pJ(W))continue;await $.onCommitted(W)}}record($){if(typeof $.seq==="number"&&$.seq>this.highestSeq)this.highestSeq=$.seq;if(pJ($))return;for(let J of this.subscribers){let Z=J.onCommitted($);if(Z)Promise.resolve(Z).catch(()=>{return})}r$.publish({sessionId:this.sessionId,projectPath:this.projectPath},`committed.${$.type}`,{event:$},$.seq)}commitEntries($){return this.withStore((J,Z,W)=>Z?J.appendValidatedBatch((Y)=>{return W(Y),$},Z):J.appendBatch($))}withStore($){return W1(this.storage,this.sessionId,async(J)=>{let Z=new T$(J.transcriptPath);if(!J.remoteScope)return $(Z,void 0,()=>{return});let W=J.remoteScope;return $(Z,{noFollow:!0,validateHandle:async(K)=>{await x6(W,J.transcriptPath,K)}},(K)=>{k6(K,this.sessionId,this.projectPath,this.storage.kind==="acp-remote"?this.storage.descriptor:void 0)})})}}function B$($){let J=null,Z=null;for(let W of $){if(W.type==="turn_started"){J=W.data;continue}if(W.type==="turn_completed")Z={type:"turn_completed",data:W.data};else if(W.type==="turn_aborted")Z={type:"turn_aborted",data:W.data};else continue;if(J?.turnId===Z.data.turnId)J=null}return{active:J,lastTerminal:Z}}class N0 extends Error{}var b8="Tool execution was interrupted by a process restart. The operation may have partially completed. Inspect the workspace, running processes, and external state before deciding whether to retry it.";function dJ($,J){let Z=$.findLastIndex((W)=>W.type==="turn_started"&&W.data.turnId===J);if(Z<0)return!1;return $.slice(Z+1).some((W)=>{if(W.type!=="message_created"||W.data.role!=="user")return!1;let Y=W.data.metadata;return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)&&Y.clientVisible===!1&&Y.emptyFinalCorrection===!0})}function h6($,J){let Z=$.findLastIndex((Y)=>Y.type==="turn_started"&&Y.data.turnId===J);if(Z<0)return[];let W=[];for(let Y of $.slice(Z+1)){if(Y.type==="turn_started"&&Y.data.turnId!==J||(Y.type==="turn_completed"||Y.type==="turn_aborted")&&Y.data.turnId===J)break;if(Y.type!=="message_created"||Y.data.role!=="user")continue;let V=Y.data.metadata,K=Y.data.inboxMessageId!==void 0?Y.data.inboxMessageId:V!==null&&typeof V==="object"&&!Array.isArray(V)?V.inboxMessageId:void 0;if(typeof K==="string"&&K.length>0&&K.length<=uJ)W.push(K)}return[...new Set(W)]}function o6($){if(!$||typeof $!=="object"||Array.isArray($))return;if(!("version"in $)||$.version!==1&&$.version!==2&&$.version!==3)return;let J="inputMessageIds"in $?J1($.inputMessageIds):void 0;if(!J||!("hadSuccessfulToolResult"in $)||typeof $.hadSuccessfulToolResult!=="boolean"||!("emptyFinalCorrectionSpent"in $)||typeof $.emptyFinalCorrectionSpent!=="boolean")return;let Z=$.version===1?0:("interruptedToolCallCount"in $)&&Number.isSafeInteger($.interruptedToolCallCount)&&$.interruptedToolCallCount>=0?$.interruptedToolCallCount:void 0;if(Z===void 0)return;let W=$.version===3&&"allSuccessfulToolResultsSafeForResume"in $&&typeof $.allSuccessfulToolResultsSafeForResume==="boolean"?$.allSuccessfulToolResultsSafeForResume:!1;return{version:$.version,inputMessageIds:J,hadSuccessfulToolResult:$.hadSuccessfulToolResult,interruptedToolCallCount:Z,...$.version===3?{allSuccessfulToolResultsSafeForResume:W}:{},emptyFinalCorrectionSpent:$.emptyFinalCorrectionSpent}}function E8($,J){let Z=$.findLastIndex((Q)=>Q.type==="turn_started"&&Q.data.turnId===J);if(Z<0)return 0;let W=$.findIndex((Q,X)=>X>Z&&Q.type==="turn_started"&&Q.data.turnId!==J),Y=$.slice(Z+1,W<0?void 0:W),V=new Set(Y.flatMap((Q)=>{if(Q.type!=="part_created"||Q.data.partType!=="tool_call")return[];let X=Q.data.payload;return X&&typeof X==="object"&&!Array.isArray(X)?[typeof X.toolCallId==="string"?X.toolCallId:Q.data.partId]:[Q.data.partId]})),K=new Set;for(let Q of Y){if(Q.type!=="part_created"||Q.data.partType!=="tool_result")continue;let X=Q.data.payload;if(!X||typeof X!=="object"||Array.isArray(X))continue;let H=typeof X.toolCallId==="string"?X.toolCallId:Q.data.partId,z=X.metadata;if(V.has(H)&&z&&typeof z==="object"&&!Array.isArray(z)&&z.processRestartRecovery===!0&&z.sideEffectsUncertain===!0)K.add(H)}return K.size}function a6($){return new Set($.flatMap((J,Z)=>{if(J.type==="inbox_acknowledged")return J.data.messageIds;if(J.type==="turn_aborted")return R1($,Z);return[]}))}function cJ($,J,Z=[]){let W=o6(J.data.recovery);if(!W)return;if($.some((Q)=>Q.type==="turn_recovery_acknowledged"&&Q.data.turnId===J.data.turnId))return;let Y=a6($);for(let Q of Z)Y.add(Q);let V=W.inputMessageIds.filter((Q)=>!Y.has(Q)),K=W.version===1?E8($,J.data.turnId):W.interruptedToolCallCount;if(V.length===0&&!W.hadSuccessfulToolResult&&K===0)return;return{turnId:J.data.turnId,outcome:"aborted",inputMessageIds:V,hadSuccessfulToolResult:W.hadSuccessfulToolResult,...K>0?{interruptedToolCallCount:K}:{},...W.version===3&&W.allSuccessfulToolResultsSafeForResume===!0?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:W.emptyFinalCorrectionSpent}}function V1($){for(let J=$.length-1;J>=0;J--){let Z=$[J];if(Z.type!=="turn_aborted")continue;let W=cJ($,Z);if(W)return W}return}function v1($,J){let Z=$.input,W=J?.metadata,Y=J?.subagentRef;if($.toolName!=="Task"||J?.toolCallId!==$.toolCallId||J.toolName!=="Task"||Z===null||typeof Z!=="object"||Array.isArray(Z)||W===null||typeof W!=="object"||Array.isArray(W)||!Y)return!1;let{subagent_session_id:V,subagent_type:K,description:Q}=Z,X=Y.subagentStatus==="completed"&&J.error===void 0&&typeof J.output==="string"||Y.subagentStatus==="failed"&&typeof J.error==="string"&&J.error.length>0&&J.output===null;return typeof V==="string"&&V===Y.subagentSessionId&&W.subagentSessionId===Y.subagentSessionId&&typeof Q==="string"&&Y.subagentDescription===Q&&W.description===Q&&(K===void 0||typeof K==="string"&&K===Y.subagentType)&&W.subagentType===Y.subagentType&&W.subagentStatus===Y.subagentStatus&&X&&W.processRestartRecovery===!0&&W.subagentResultAdopted===!0&&W.sideEffectsUncertain===!1}var S8=1e4,T8=1e5,M8=2592000000,v6=128,R8=1e6,x8=256;function k8($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(typeof J.goalId!=="string"||J.goalId.length===0||J.goalId.length>v6||typeof J.verificationAttempt!=="number"||!Number.isSafeInteger(J.verificationAttempt)||J.verificationAttempt<1||J.verificationAttempt>R8||typeof J.verifierSessionId!=="string"||J.verifierSessionId.length===0||J.verifierSessionId.length>v6||typeof J.evidenceSha256!=="string"||!/^[a-f0-9]{64}$/.test(J.evidenceSha256)||typeof J.goalUpdatedAt!=="string"||!Number.isFinite(Date.parse(J.goalUpdatedAt)))return;return{goalId:J.goalId,verificationAttempt:J.verificationAttempt,verifierSessionId:J.verifierSessionId,evidenceSha256:J.evidenceSha256,goalUpdatedAt:J.goalUpdatedAt}}function s6($,J){let Z=$.data.metadata;if(!Z||typeof Z!=="object"||Array.isArray(Z))return;let W=Z.turnFinalization;if(!W||typeof W!=="object"||Array.isArray(W))return;let Y=W,V=Y.turnId,K=Y.inputMessageIds,Q=Y.turnsCount,X=Y.toolCallsCount,H=Y.durationMs,z=Array.isArray(K)?K.filter((j)=>typeof j==="string"&&j.length>0&&j.length<=uJ):[];if(typeof V!=="string"||V.length===0||V.length>128||J!==void 0&&V!==J||!Array.isArray(K)||K.length>E6||z.length!==K.length||typeof Q!=="number"||!Number.isSafeInteger(Q)||Q<0||Q>S8||typeof X!=="number"||!Number.isSafeInteger(X)||X<0||X>T8||typeof H!=="number"||!Number.isSafeInteger(H)||H<0||H>M8)return;let B;if("goalFinalization"in Y){if(B=k8(Y.goalFinalization),!B)return}return{turnId:V,inputMessageIds:[...new Set(z)],turnsCount:Q,toolCallsCount:X,durationMs:H,...B?{goalFinalization:B}:{}}}function C6($,J){let Z=$.findLastIndex((W)=>W.type==="turn_started"&&W.data.turnId===J);if(Z<0)return;for(let W=$.length-1;W>Z;W--){let Y=$[W];if(Y?.type!=="message_created")continue;let V=s6(Y,J);if(V)return V}return}function h8($){for(let J=$.length-1;J>=0;J--){let Z=$[J];if(Z?.type!=="message_created")continue;let W=s6(Z);if(!W?.goalFinalization)continue;if(!$.slice(0,J).some((V)=>V.type==="turn_started"&&V.data.turnId===W.turnId))continue;return{turnId:W.turnId,finalization:W}}return}function M$($,J){let Z=J?$.findLastIndex((X)=>X.type==="turn_started"&&X.data.turnId===J):-1;if(J&&Z<0)return{all:[],orphaned:[],hadSuccessfulResult:!1};let W=new Map,Y=new Set,V=new Set,K=new Set;for(let X of $.slice(Z+1)){if(X.type==="interaction_requested"){K.add(X.data.toolCallId);continue}if(X.type!=="part_created")continue;let H=X.data.payload&&typeof X.data.payload==="object"&&!Array.isArray(X.data.payload)?X.data.payload:{},z=typeof H.toolCallId==="string"?H.toolCallId:X.data.partId;if(X.data.partType==="tool_call")W.set(z,{toolCallId:z,messageId:X.data.messageId,toolName:typeof H.toolName==="string"?H.toolName:"unknown",input:H.input??null});else if(X.data.partType==="tool_result"){if(Y.add(z),Y.add(X.data.partId),Y.add(X.data.messageId),W.has(z)&&H.error===null)V.add(z)}}let Q=[...W.values()];return{all:Q,orphaned:Q.filter((X)=>!Y.has(X.toolCallId)&&!K.has(X.toolCallId)),hadSuccessfulResult:Q.some((X)=>V.has(X.toolCallId))}}class _0{static sessionInitializationRuns=new Map;projectPath;maxSessions;version;stateStorage;initializedSessions=new Set;constructor($=Q0(),J=100,Z=d6(),W=z$($)){this.projectPath=$,this.maxSessions=J,this.version=Z,this.stateStorage=W}createEvent($,J,Z){return{id:j0(),sessionId:J,projectPath:this.projectPath,timestamp:new Date().toISOString(),type:$,cwd:this.projectPath,...this.stateStorage.kind==="local"?{gitBranch:g6(this.projectPath)}:{},version:this.version,data:Z}}log($){return F0.for($,this.projectPath,this.stateStorage)}async ensureSessionCreated($,J){let Z=Y1(this.stateStorage,$);if(this.initializedSessions.delete($)){this.initializedSessions.add($);return}let W=_0.sessionInitializationRuns.get(Z);if(!W)W=this.initializeSessionFile($,Z,J),_0.sessionInitializationRuns.set(Z,W);try{await W,this.rememberInitializedSession($)}finally{if(_0.sessionInitializationRuns.get(Z)===W)_0.sessionInitializationRuns.delete(Z)}}rememberInitializedSession($){this.initializedSessions.delete($),this.initializedSessions.add($);while(this.initializedSessions.size>x8){let J=this.initializedSessions.values().next().value;if(J===void 0)return;this.initializedSessions.delete(J)}}async initializeSessionFile($,J,Z){if((await this.log($).readAll()).length>0)return;if(this.stateStorage.kind==="acp-remote")throw Error("ACP remote session has no durable creation record");let Y=new Date().toISOString(),V={sessionId:$,rootId:Z?.parentSessionId??$,parentId:Z?.parentSessionId,relationType:Z?"subagent":void 0,resumedFrom:Z?.resumedFrom,rootAgentId:Z?.rootAgentId,resumeDepth:Z?.resumeDepth,title:void 0,status:"running",taskStatus:Z?"running":"queued",taskFailure:null,agentType:Z?.subagentType,model:void 0,permission:void 0,createdAt:Y,updatedAt:Y},K=this.createEvent("session_created",$,V);await this.log($).commit(K)}buildCompactionMetadata($){let J={trigger:$.trigger,preTokens:$.preTokens};if($.reason)J.reason=$.reason;if($.strategy)J.strategy=$.strategy;if($.preTokenSource)J.preTokenSource=$.preTokenSource;if($.estimatedPendingTokens!==void 0)J.estimatedPendingTokens=$.estimatedPendingTokens;if($.postTokens!==void 0)J.postTokens=$.postTokens;if($.sampleAttempts!==void 0)J.sampleAttempts=$.sampleAttempts;if($.inputReductions!==void 0)J.inputReductions=$.inputReductions;if($.messagesOmitted!==void 0)J.messagesOmitted=$.messagesOmitted;if($.filesOmitted!==void 0)J.filesOmitted=$.filesOmitted;if($.imagesOmitted!==void 0)J.imagesOmitted=$.imagesOmitted;if($.fallbackTargetTokens!==void 0)J.fallbackTargetTokens=$.fallbackTargetTokens;if($.fallbackMessagesOmitted!==void 0)J.fallbackMessagesOmitted=$.fallbackMessagesOmitted;if($.fallbackMessagesTruncated!==void 0)J.fallbackMessagesTruncated=$.fallbackMessagesTruncated;if($.failureReason)J.failureReason=$.failureReason;if($.filesIncluded)J.filesIncluded=$.filesIncluded;if($.replacementMessages)J.checkpointVersion=l6;return J}async initialize(){try{await c6(this.stateStorage,async($)=>{if(this.stateStorage.kind==="local")await C0.mkdir($,{recursive:!0,mode:493})})}catch($){console.warn("[PersistentStore] 无法创建持久化存储目录:",$)}}async saveMessage($,J,Z,W=null,Y,V,K){try{await this.ensureSessionCreated($,V);let Q=new Date().toISOString(),X=j0(),H={messageId:X,role:J,parentMessageId:W??void 0,inboxMessageId:Y?.inboxMessageId,createdAt:Q,model:Y?.model,usage:Y?.usage,metadata:Y?JSON.parse(JSON.stringify(Y)):void 0},z=this.createEvent("message_created",$,H),B=J==="assistant"&&K?.trim()?[this.createEvent("part_created",$,{partId:j0(),messageId:X,partType:"reasoning",payload:{text:K},createdAt:Q})]:[],j=typeof Z==="string"?[this.createEvent("part_created",$,{partId:j0(),messageId:X,partType:"text",payload:{text:Z},createdAt:Q})]:Z.map((U)=>this.createEvent("part_created",$,{partId:j0(),messageId:X,partType:U.type==="text"?"text":"image",payload:U.type==="text"?{text:U.text}:{mimeType:v8(U.image_url.url)??"image/png",dataUrl:U.image_url.url},createdAt:Q}));return await this.log($).commitBatch([z,...B,...j]),X}catch(Q){throw console.error(`[PersistentStore] 保存消息失败 (session: ${$}):`,Q),Q}}async acknowledgeInboxMessages($,J){if(J.length===0)return;await this.ensureSessionCreated($);let Z=new Date().toISOString();await this.log($).commit(this.createEvent("inbox_acknowledged",$,{messageIds:[...J],acknowledgedAt:Z}))}async acknowledgeTurnRecovery($,J){await this.ensureSessionCreated($);try{await this.log($).commitValidated((Z)=>{let W=B0(Z);if(W.some((V)=>V.type==="turn_recovery_acknowledged"&&V.data.turnId===J))throw new N0;let Y=W.findLast((V)=>V.type==="turn_aborted"&&V.data.turnId===J);if(!Y||!cJ(W,Y))throw new N0;return this.createEvent("turn_recovery_acknowledged",$,{turnId:J,acknowledgedAt:new Date().toISOString()})})}catch(Z){if(!(Z instanceof N0))throw Z}}async persistBackgroundSubagentCompletion($,J){if(J.inboxMessageId!==`background-subagent-completion:${J.childSessionId}`)return{eligible:!1,acknowledged:!1,persisted:!1};await this.ensureSessionCreated($);let Z={eligible:!1,acknowledged:!1,persisted:!1};return await this.log($).commitValidatedBatch((W)=>{let Y=B0(W),V=Y.some((j)=>j.type==="inbox_acknowledged"&&j.data.messageIds.includes(J.inboxMessageId)),K=Y.find((j)=>j.type==="message_created"&&j.data.inboxMessageId===J.inboxMessageId),Q=Y.findLast((j)=>{if(j.type!=="part_created"||j.data.partType!=="tool_call"||!j.data.payload||typeof j.data.payload!=="object"||Array.isArray(j.data.payload))return!1;let U=j.data.payload;if(U.toolName!=="Task"||!U.input||typeof U.input!=="object"||Array.isArray(U.input))return!1;let P=U.input,_=P.resume_from??P.resume;return P.run_in_background===!0&&P.subagent_session_id===J.childSessionId&&P.description===J.subagentRef.subagentDescription&&(P.subagent_type===void 0||P.subagent_type===J.subagentRef.subagentType)&&(P.resume_from===void 0||P.resume===void 0||P.resume_from===P.resume)&&(_===void 0?J.subagentRef.subagentResumedFrom===void 0:_===J.subagentRef.subagentResumedFrom)});if(!Q)return Z={eligible:!1,acknowledged:V,persisted:!1,...K?{messageId:K.data.messageId}:{}},[];if(V)return Z={eligible:!0,acknowledged:!0,persisted:!1,...K?{messageId:K.data.messageId}:{}},[];let X=Y.find((j)=>j.type==="part_created"&&j.data.partType==="subtask_ref"&&j.data.payload!==null&&typeof j.data.payload==="object"&&!Array.isArray(j.data.payload)&&j.data.payload.childSessionId===J.childSessionId&&j.data.payload.status===J.subagentRef.subagentStatus);if(K&&X)return Z={eligible:!0,acknowledged:!1,persisted:!1,messageId:K.data.messageId},[];let H=new Date().toISOString(),z=K?.data.messageId??j0(),B=[];if(!K){let j={messageId:z,role:"user",inboxMessageId:J.inboxMessageId,createdAt:H,metadata:JSON.parse(JSON.stringify(J.metadata))};B.push(this.createEvent("message_created",$,j)),B.push(this.createEvent("part_created",$,{partId:j0(),messageId:z,partType:"text",payload:{text:J.content},createdAt:H}))}if(!X){let j=Y.findLast((P)=>P.type==="part_created"&&P.data.partType==="subtask_ref"&&P.data.messageId===Q.data.messageId&&P.data.payload!==null&&typeof P.data.payload==="object"&&!Array.isArray(P.data.payload)&&P.data.payload.childSessionId===J.childSessionId),U=j?.data.payload&&typeof j.data.payload==="object"&&!Array.isArray(j.data.payload)?j.data.payload:void 0;B.push(this.createEvent("part_created",$,{partId:j0(),messageId:Q.data.messageId,partType:"subtask_ref",payload:{childSessionId:J.subagentRef.subagentSessionId,agentType:J.subagentRef.subagentType,description:J.subagentRef.subagentDescription??"",status:J.subagentRef.subagentStatus,summary:J.subagentRef.subagentSummary??"",resumedFrom:J.subagentRef.subagentResumedFrom??null,rootAgentId:J.subagentRef.subagentRootId??J.subagentRef.subagentSessionId,resumeDepth:J.subagentRef.subagentResumeDepth??0,verificationVerdict:J.subagentRef.verificationVerdict??null,startedAt:typeof U?.startedAt==="string"?U.startedAt:H,finishedAt:H},createdAt:H}))}return Z={eligible:!0,acknowledged:!1,persisted:B.length>0,messageId:z},B}),Z}async saveTurnStart($,J){await this.ensureSessionCreated($);try{await this.log($).commitValidated((Z)=>{let W=B0(Z);if(W.some((V)=>V.type==="turn_started"&&V.data.turnId===J.turnId))throw new N0;let Y=B$(W).active;if(Y)throw Error(`Session already has an active turn: ${Y.turnId}`);return this.createEvent("turn_started",$,J)})}catch(Z){if(!(Z instanceof N0))throw Z}}async saveTurnCompletion($,J,Z=[]){await this.ensureSessionCreated($);try{await this.log($).commitValidatedBatch((W)=>{let Y=B0(W),V=new Set(Y.flatMap((H)=>H.type==="inbox_acknowledged"?H.data.messageIds:[])),K=[...new Set(Z)].filter((H)=>!V.has(H)),Q=Y.findLast((H)=>(H.type==="turn_completed"||H.type==="turn_aborted")&&H.data.turnId===J.turnId);if(Q){if(Q.type==="turn_aborted"||K.length===0)throw new N0;return[this.createEvent("inbox_acknowledged",$,{messageIds:K,acknowledgedAt:J.completedAt})]}let X=B$(Y).active;if(!X||X.turnId!==J.turnId)throw Error(`Turn is not active: ${J.turnId}`);return[...K.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:K,acknowledgedAt:J.completedAt})]:[],this.createEvent("turn_completed",$,J)]})}catch(W){if(!(W instanceof N0))throw W}}async saveTurnAbort($,J,Z={}){let W=Z.acknowledgeInputMessageIds??[],Y=J1(W);if(!Y)throw Error("Invalid turn abort acknowledgement input message IDs");let V=Y;await this.ensureSessionCreated($);let K,Q=[];try{await this.log($).commitValidatedBatch((X)=>{let H=B0(X),z=a6(H),B=H.findLast((i)=>(i.type==="turn_completed"||i.type==="turn_aborted")&&i.data.turnId===J.turnId);if(B){if(B.type==="turn_completed")throw K=void 0,Q=[],new N0;let i=o6(B.data.recovery),L0=i?V.filter((y0)=>i.inputMessageIds.includes(y0)):[],S=L0.filter((y0)=>!z.has(y0));if(Q=L0,K=cJ(H,B,L0),S.length===0)throw new N0;return[this.createEvent("inbox_acknowledged",$,{messageIds:S,acknowledgedAt:J.abortedAt})]}let j=B$(H).active;if(!j||j.turnId!==J.turnId)throw Error(`Turn is not active: ${J.turnId}`);let U=M$(H,j.turnId),P=h6(H,j.turnId),_=V1(H),k=new Set(J.recovery?.inputMessageIds??[]),R=_?_.inputMessageIds.filter((i)=>k.has(i)):[],h=[...new Set([...P,...R])],d=U.hadSuccessfulResult||J.recovery?.hadSuccessfulToolResult===!0,x={version:3,inputMessageIds:h,hadSuccessfulToolResult:d,interruptedToolCallCount:U.orphaned.length+(J.recovery?.version===2||J.recovery?.version===3?J.recovery.interruptedToolCallCount:0),allSuccessfulToolResultsSafeForResume:d&&!U.hadSuccessfulResult&&J.recovery?.version===3&&J.recovery.hadSuccessfulToolResult&&J.recovery.allSuccessfulToolResultsSafeForResume,emptyFinalCorrectionSpent:dJ(H,j.turnId)||J.recovery?.emptyFinalCorrectionSpent===!0};K={turnId:J.turnId,outcome:"aborted",inputMessageIds:x.inputMessageIds,hadSuccessfulToolResult:x.hadSuccessfulToolResult,...x.interruptedToolCallCount>0?{interruptedToolCallCount:x.interruptedToolCallCount}:{},...x.allSuccessfulToolResultsSafeForResume?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:x.emptyFinalCorrectionSpent};let o=V.filter((i)=>h.includes(i)),G=o.filter((i)=>!z.has(i));Q=o;let E=new Set(z);for(let i of o)E.add(i);let l=x.inputMessageIds.filter((i)=>!E.has(i)),g=x.hadSuccessfulToolResult||x.interruptedToolCallCount>0;K=l.length>0||g?{turnId:J.turnId,outcome:"aborted",inputMessageIds:l,hadSuccessfulToolResult:x.hadSuccessfulToolResult,...x.interruptedToolCallCount>0?{interruptedToolCallCount:x.interruptedToolCallCount}:{},...x.allSuccessfulToolResultsSafeForResume?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:x.emptyFinalCorrectionSpent}:void 0;let{acknowledgedInputMessageIds:V0,...I}=J;return[this.createEvent("turn_aborted",$,{...I,...o.length>0?{acknowledgedInputMessageIds:o}:{},recovery:x}),...G.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:G,acknowledgedAt:J.abortedAt})]:[]]})}catch(X){if(!(X instanceof N0))throw X}return{...K?{recovery:K}:{},acknowledgedInputMessageIds:Q}}async loadInterruptedToolCalls($){let J=await this.loadEvents($);if(!J)return[];let Z=B0(J),W=B$(Z).active;return W?M$(Z,W.turnId).orphaned.map((Y)=>({...Y,input:structuredClone(Y.input)})):[]}async hasRecoverableTurn($){let J=await this.loadEvents($);if(!J)return!1;let Z=B0(J),W=B$(Z).active;if(W){let Y=M$(Z,W.turnId);if(Y.orphaned.length>0||Y.hadSuccessfulResult)return!0;if(C6(Z,W.turnId))return!0}return V1(Z)!==void 0}async loadBackgroundTaskChildIds($){let J=await this.loadEvents($);if(!J)return new Set;let Z=B0(J).flatMap((W)=>{if(W.type!=="part_created"||W.data.partType!=="tool_call"||!W.data.payload||typeof W.data.payload!=="object"||Array.isArray(W.data.payload))return[];let Y=W.data.payload;if(Y.toolName!=="Task"||!Y.input||typeof Y.input!=="object"||Array.isArray(Y.input))return[];let V=Y.input;return V.run_in_background===!0&&typeof V.subagent_session_id==="string"?[V.subagent_session_id]:[]});return new Set(Z)}async recoverInterruptedTurn($,J={}){await this.ensureSessionCreated($);let Z;try{await this.log($).commitValidatedBatch((W)=>{let Y=B0(W),V=B$(Y).active,K=M$(Y);if(!V&&K.orphaned.length===0){if(Z=V1(Y),Z)return[];throw new N0}let Q=V?C6(Y,V.turnId):void 0;if(V&&Q&&K.orphaned.length===0){let E=M$(Y,V.turnId);Z={turnId:V.turnId,outcome:"completed",inputMessageIds:Q.inputMessageIds,hadSuccessfulToolResult:E.hadSuccessfulResult,emptyFinalCorrectionSpent:dJ(Y,V.turnId),finalization:Q};let l=new Set(Y.flatMap((I)=>I.type==="inbox_acknowledged"?I.data.messageIds:[])),g=Q.inputMessageIds.filter((I)=>!l.has(I)),V0=new Date().toISOString();return[...g.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:g,acknowledgedAt:V0})]:[],this.createEvent("turn_completed",$,{turnId:V.turnId,completedAt:V0,turnsCount:Q.turnsCount,toolCallsCount:Q.toolCallsCount,durationMs:Q.durationMs})]}let X=V?M$(Y,V.turnId):void 0,H=X?.orphaned.some((E)=>{let l=J.adoptedToolResults?.get(E.toolCallId);return v1(E,l)&&l?.error===void 0})??!1,z=X?.orphaned.filter((E)=>{let l=J.adoptedToolResults?.get(E.toolCallId);return l?.toolCallId===E.toolCallId&&l.toolName===E.toolName&&l.error===void 0}).every((E)=>v1(E,J.adoptedToolResults?.get(E.toolCallId)))??!0,B=new Set(V?.inputMessageIds??[]),j=V?V1(Y):void 0,U=j?j.inputMessageIds.filter((E)=>B.has(E)):[],P=U.length>0,_=V?h6(Y,V.turnId):[],k=X?X.orphaned.filter((E)=>{let l=J.adoptedToolResults?.get(E.toolCallId);return!v1(E,l)}).length:0,R=P&&j?.hadSuccessfulToolResult===!0,h=(X?.hadSuccessfulResult??!1)||H||R;Z=V?{turnId:V.turnId,outcome:"aborted",inputMessageIds:[...new Set([..._,...U])],hadSuccessfulToolResult:h,...(()=>{let E=k+(P?j?.interruptedToolCallCount??0:0);return E>0?{interruptedToolCallCount:E}:{}})(),...h&&!(X?.hadSuccessfulResult??!1)&&z&&(!R||j?.allSuccessfulToolResultsSafeForResume===!0)?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:dJ(Y,V.turnId)||P&&j?.emptyFinalCorrectionSpent===!0}:V1(Y);let d=V?X?.all.length??0:0,x=new Date().toISOString(),o=V?Date.parse(V.startedAt):Number.NaN,G=K.orphaned.flatMap((E)=>{let l=J.adoptedToolResults?.get(E.toolCallId),g=v1(E,l)?l:void 0,V0=this.createEvent("part_created",$,{partId:E.toolCallId,messageId:g?E.messageId:E.toolCallId,partType:"tool_result",payload:g?{toolCallId:E.toolCallId,toolName:E.toolName,output:g.output,error:g.error??null,...g.metadata===void 0?{}:{metadata:g.metadata}}:{toolCallId:E.toolCallId,toolName:E.toolName,output:null,error:b8,metadata:{processRestartRecovery:!0,sideEffectsUncertain:!0}},createdAt:x});if(!g?.subagentRef)return[V0];let I=g.subagentRef;return[V0,this.createEvent("part_created",$,{partId:j0(),messageId:E.messageId,partType:"subtask_ref",payload:{childSessionId:I.subagentSessionId,agentType:I.subagentType,description:I.subagentDescription??"",status:I.subagentStatus,summary:I.subagentSummary??"",resumedFrom:I.subagentResumedFrom??null,rootAgentId:I.subagentRootId??I.subagentSessionId,resumeDepth:I.subagentResumeDepth??0,verificationVerdict:I.verificationVerdict??null,startedAt:x,finishedAt:x},createdAt:x})]});return V?[...G,this.createEvent("turn_aborted",$,{turnId:V.turnId,cause:"process_restart",abortedAt:x,turnsCount:0,toolCallsCount:d,durationMs:Number.isFinite(o)?Math.max(0,Date.now()-o):0,recovery:Z?{version:3,inputMessageIds:Z.inputMessageIds,hadSuccessfulToolResult:Z.hadSuccessfulToolResult,interruptedToolCallCount:Z.interruptedToolCallCount??0,allSuccessfulToolResultsSafeForResume:Z.allSuccessfulToolResultsSafeForResume===!0,emptyFinalCorrectionSpent:Z.emptyFinalCorrectionSpent}:void 0})]:G})}catch(W){if(!(W instanceof N0))throw W}return Z}async loadLatestGoalFinalization($){let J=await this.loadEvents($);return J?h8(J):void 0}async saveInteractionRequest($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(Z.some((Y)=>Y.type==="interaction_requested"&&Y.data.requestId===J.requestId))throw Error(`Interaction request already exists: ${J.requestId}`);return this.createEvent("interaction_requested",$,J)})}async saveInteractionResponse($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((V)=>V.type==="interaction_requested"&&V.data.requestId===J.requestId))throw Error(`Interaction request not found: ${J.requestId}`);if(Z.some((V)=>V.type==="interaction_responded"&&V.data.requestId===J.requestId))throw Error(`Interaction already responded: ${J.requestId}`);return this.createEvent("interaction_responded",$,J)})}async saveInteractionRecovery($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((V)=>V.type==="interaction_responded"&&V.data.requestId===J.requestId))throw Error(`Interaction response not found: ${J.requestId}`);if(Z.some((V)=>V.type==="interaction_recovered"&&V.data.requestId===J.requestId))throw Error(`Interaction already recovered: ${J.requestId}`);return this.createEvent("interaction_recovered",$,J)})}async saveReviewStart($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(Z.some((V)=>V.type==="review_started"&&V.data.reviewId===J.reviewId))throw Error(`Review already exists: ${J.reviewId}`);if(Z.some((V)=>V.type==="review_started"&&!Z.some((K)=>K.type==="review_completed"&&K.data.reviewId===V.data.reviewId)))throw Error("Session already has an active review");return this.createEvent("review_started",$,J)})}async saveReviewCompletion($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((V)=>V.type==="review_started"&&V.data.reviewId===J.reviewId))throw Error(`Review not found: ${J.reviewId}`);if(Z.some((V)=>V.type==="review_completed"&&V.data.reviewId===J.reviewId))throw Error(`Review already completed: ${J.reviewId}`);return this.createEvent("review_completed",$,J)})}async saveToolUse($,J,Z,W=null,Y,V){try{if(V!==void 0&&(V.length===0||V.length>512))throw Error("Provider tool call identity must contain 1-512 characters");await this.ensureSessionCreated($,Y);let K=new Date().toISOString(),Q=W??j0(),X=[];if(!W){let B={messageId:Q,role:"assistant",parentMessageId:void 0,createdAt:K};X.push(this.createEvent("message_created",$,B))}let H=V??j0(),z={partId:H,messageId:Q,partType:"tool_call",payload:{toolCallId:H,toolName:J,input:Z},createdAt:K};if(X.push(this.createEvent("part_created",$,z)),J==="Task"&&Z&&typeof Z==="object"){let B=Z,j=typeof B.subagent_session_id==="string"?B.subagent_session_id:void 0,U=typeof B.subagent_type==="string"?B.subagent_type:void 0;if(j&&U){let P={partId:j0(),messageId:Q,partType:"subtask_ref",payload:{childSessionId:j,agentType:U,status:"running",summary:typeof B.description==="string"?B.description:"",startedAt:K},createdAt:K};X.push(this.createEvent("part_created",$,P))}}return await this.log($).commitBatch(X),H}catch(K){throw console.error(`[PersistentStore] 保存工具调用失败 (session: ${$}):`,K),K}}async saveToolResult($,J,Z,W,Y=null,V,K,Q,X){try{await this.ensureSessionCreated($,K);let H=new Date().toISOString(),z=Y??j0();return await this.log($).commitValidatedBatch((B)=>{let j=Q?.subagentStatus==="running"?B0(B).findLast((h)=>h.type==="part_created"&&h.data.partType==="subtask_ref"&&h.data.payload!==null&&typeof h.data.payload==="object"&&!Array.isArray(h.data.payload)&&h.data.payload.childSessionId===Q.subagentSessionId&&(h.data.payload.status==="completed"||h.data.payload.status==="failed"||h.data.payload.status==="cancelled")):void 0,U=j?.data.payload,P=X&&typeof X==="object"&&!Array.isArray(X)?X:{},_=U?{...P,subagentSessionId:U.childSessionId,subagentType:U.agentType,description:U.description,subagentStatus:U.status,subagentSummary:U.summary,subagentResumedFrom:U.resumedFrom,subagentRootId:U.rootAgentId,subagentResumeDepth:U.resumeDepth,verificationVerdict:U.verificationVerdict}:X,k=[];if(!Y){let h={messageId:z,role:"assistant",parentMessageId:void 0,createdAt:H};k.push(this.createEvent("message_created",$,h))}let R={partId:J,messageId:z,partType:"tool_result",payload:{toolCallId:J,toolName:Z,output:W,error:V??null,..._===void 0?{}:{metadata:_}},createdAt:H};if(k.push(this.createEvent("part_created",$,R)),Q&&!j){let h=Q.subagentStatus==="running"?null:H,d={partId:j0(),messageId:z,partType:"subtask_ref",payload:{childSessionId:Q.subagentSessionId,agentType:Q.subagentType,description:Q.subagentDescription??"",status:Q.subagentStatus,summary:Q.subagentSummary??"",resumedFrom:Q.subagentResumedFrom??null,rootAgentId:Q.subagentRootId??Q.subagentSessionId,resumeDepth:Q.subagentResumeDepth??0,verificationVerdict:Q.verificationVerdict??null,startedAt:H,finishedAt:h},createdAt:H};k.push(this.createEvent("part_created",$,d))}return k}),J}catch(H){throw console.error(`[PersistentStore] 保存工具结果失败 (session: ${$}):`,H),H}}async saveCompaction($,J,Z,W=null){try{await this.ensureSessionCreated($);let Y=new Date().toISOString(),V=j0(),K={messageId:V,role:"system",parentMessageId:W??void 0,createdAt:Y},Q=this.buildCompactionMetadata(Z),X={partId:j0(),messageId:V,partType:"summary",payload:{text:J,metadata:Q,...Z.replacementMessages?{replacementMessages:i6(Z.replacementMessages)}:{}},createdAt:Y},H=[this.createEvent("message_created",$,K),this.createEvent("part_created",$,X)];return await this.log($).commitBatch(H),V}catch(Y){throw console.error(`[PersistentStore] 保存压缩失败 (session: ${$}):`,Y),Y}}async recordTokenBudgetHandoff($,J){await this.ensureSessionCreated($);let Z=I1([]),W=await this.log($).commitValidatedBatch((V)=>{if(Z=I1(B0(V)),Z.kind!=="none")return[];let K=new Date().toISOString();return[this.createEvent("token_budget_handoff_recorded",$,{...J,messageId:`${r6}${j0()}`,createdAt:K})]});if(Z.kind==="valid")return{outcome:"existing",event:Z.event};if(Z.kind==="suppressed")return{outcome:"suppressed",recordId:Z.recordId};if(W.length!==1)throw Error("Token budget handoff commit produced an impossible result");let Y=I1(W);if(Y.kind!=="valid")throw Error("Token budget handoff commit produced an invalid event");return{outcome:"created",event:Y.event}}async initSession($,J){await this.ensureSessionCreated($,J)}async loadEvents($){try{let J=await this.log($).readAll();return J.length>0?B0(J):null}catch{return null}}async loadSession($){try{let J=B0(await this.log($).readAll());if(J.length===0)return null;let Z=J.find((W)=>W.type==="session_created");return{sessionId:$,userId:void 0,preferences:{},configuration:{},startTime:new Date(Z?.timestamp??J[0].timestamp).getTime()}}catch{return null}}async loadConversation($){try{let J=B0(await this.log($).readAll());if(J.length===0)return null;let Z=new Map;for(let K of J){if(K.type==="message_created")Z.set(K.data.messageId,{id:K.data.messageId,role:K.data.role,content:"",timestamp:new Date(K.timestamp).getTime()});if(K.type==="part_created"&&K.data.partType==="text"){let Q=Z.get(K.data.messageId);if(Q){let X=K.data.payload;Q.content=X.text??""}}if(K.type==="part_created"&&K.data.partType==="image"){let Q=Z.get(K.data.messageId);if(Q)Q.content=Q.content?`${Q.content}
|
|
86
|
-
[Image]`:"[Image]"}}let W=Array.from(Z.values()),Y=J[J.length-1],V=new Date(Y.timestamp).getTime();return{messages:W,topics:[],lastActivity:V}}catch{return null}}async listSessions(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session enumeration requires SessionService");try{let $=a$(this.projectPath);return(await C0.readdir($)).filter((Z)=>Z.endsWith(".jsonl")).map((Z)=>Z.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session summaries require SessionService");try{let J=C1(this.projectPath,$),Z=new T$(J);if(!(await Z.getStats()).exists)return null;let Y=await Z.readAll();if(Y.length===0)return null;let V=B0(Y),K=Y[Y.length-1],Q=V.filter((X)=>X.type==="message_created"&&["user","assistant"].includes(X.data.role)).length;return{sessionId:$,lastActivity:new Date(K.timestamp).getTime(),messageCount:Q,topics:[]}}catch{return null}}async deleteSession($){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session deletion requires SessionService");this.initializedSessions.delete($);try{let J=C1(this.projectPath,$);await new T$(J).delete(),await C0.unlink(u6(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W}),await m6(this.projectPath,$,I6());try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-
|
|
86
|
+
[Image]`:"[Image]"}}let W=Array.from(Z.values()),Y=J[J.length-1],V=new Date(Y.timestamp).getTime();return{messages:W,topics:[],lastActivity:V}}catch{return null}}async listSessions(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session enumeration requires SessionService");try{let $=a$(this.projectPath);return(await C0.readdir($)).filter((Z)=>Z.endsWith(".jsonl")).map((Z)=>Z.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session summaries require SessionService");try{let J=C1(this.projectPath,$),Z=new T$(J);if(!(await Z.getStats()).exists)return null;let Y=await Z.readAll();if(Y.length===0)return null;let V=B0(Y),K=Y[Y.length-1],Q=V.filter((X)=>X.type==="message_created"&&["user","assistant"].includes(X.data.role)).length;return{sessionId:$,lastActivity:new Date(K.timestamp).getTime(),messageCount:Q,topics:[]}}catch{return null}}async deleteSession($){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session deletion requires SessionService");this.initializedSessions.delete($);try{let J=C1(this.projectPath,$);await new T$(J).delete(),await C0.unlink(u6(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W}),await m6(this.projectPath,$,I6());try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-2bnpn8be.js"),V=await W();if(V)Y(V,$,this.projectPath)}catch{}}catch(J){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,J)}finally{this.initializedSessions.delete($)}}async cleanupOldSessions(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session cleanup requires SessionService");try{let $=await this.listSessions();if($.length<=this.maxSessions)return;let W=(await Promise.all($.map((Y)=>this.getSessionSummary(Y)))).filter((Y)=>Y!==null).sort((Y,V)=>V.lastActivity-Y.lastActivity).slice(this.maxSessions).map((Y)=>Y.sessionId);await Promise.all(W.map((Y)=>this.deleteSession(Y))),console.log(`[PersistentStore] 已清理 ${W.length} 个旧会话`)}catch($){console.error("[PersistentStore] 清理旧会话失败:",$)}}async getStorageStats(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote storage statistics require SessionService");try{let $=await this.listSessions(),J=0;for(let Z of $){let W=C1(this.projectPath,Z),V=await new T$(W).getStats();J+=V.size}return{totalSessions:$.length,totalSize:J,projectPath:this.projectPath}}catch{return{totalSessions:0,totalSize:0,projectPath:this.projectPath}}}async checkStorageHealth(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote storage health checks require SessionService");try{let $=a$(this.projectPath);await C0.mkdir($,{recursive:!0,mode:493});let J=n6.join($,".health-check");return await C0.writeFile(J,"test","utf-8"),await C0.unlink(J),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return p6()}}function v8($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}var t6=131072,mJ=new J4;function lJ($,J){return`${C8.resolve($)}\x00${J}`}function nJ($,J){let Z=JSON.stringify($);if(Z===void 0)throw Error(`${J} is not JSON serializable`);if(Buffer.byteLength(Z,"utf8")>t6)throw Error(`${J} exceeds ${t6} bytes`);return JSON.parse(Z)}function e6($){if($.type==="askUserQuestion")return"question";if($.type==="mcpElicitation")return"elicitation";if($.type==="permission"||$.type==="mcpSampling")return"permission";return}function u8($,J){return JSON.stringify($)===JSON.stringify(J)}function g8($,J){if($.request.interactionType!=="elicitation")return nJ(J,"Interaction response");return nJ({approved:J.approved,...J.reason?{reason:J.reason}:{},...J.elicitation?{elicitation:{action:J.elicitation.action}}:{},...J.openExternalUrl?{openExternalUrl:!0}:{}},"Interaction response")}function $4($){let J=$.request.details;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid durable interaction details: ${$.request.requestId}`);return J}function p8($){let J=$.response?.response;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid durable interaction response: ${$.request.requestId}`);return J}function d8($){if(!$.answers||Object.keys($.answers).length===0)return"No structured answers were provided.";return Object.entries($.answers).map(([J,Z])=>{let W=Array.isArray(Z)?Z.join(", "):Z;return`${J}: ${W}`}).join(`
|
|
87
87
|
`)}function c8($,J){let{request:Z}=$;if(Z.interactionType==="question"){let K=d8(J);return{toolOutput:`User answers:
|
|
88
88
|
${K}`,inbox:`The process restarted while waiting for a structured answer. The recovered user response is:
|
|
89
89
|
${K}
|
|
@@ -98,7 +98,7 @@ ${J.map((Z)=>`- ${Z}`).join(`
|
|
|
98
98
|
`)||"- none recorded; inspect the workspace and transcript evidence"}`,"Run every relevant configured test, lint, type-check, build, or targeted","verification command that the objective requires. For non-code goals, verify","the requested observable outcome directly instead of inventing code checks.","Do not trust the parent agent summary or claimed result. Do not modify files.","Submit exactly one final structured verdict object with verdict, summary,","and findings fields according to the built-in Goal verifier contract."].join(`
|
|
99
99
|
|
|
100
100
|
`)}import qZ from"node:path";var eJ={"--all":"none","--branches":"none","--tags":"none","--remotes":"none"},$2={"--since":"string","--after":"string","--until":"string","--before":"string"},J2={"--oneline":"none","--graph":"none","--decorate":"none","--no-decorate":"none","--date":"string","--relative-date":"none"},g1={"--max-count":"number","-n":"number"},p1={"--stat":"none","--numstat":"none","--shortstat":"none","--name-only":"none","--name-status":"none"},R$={"--color":"none","--no-color":"none"},d1={"--patch":"none","-p":"none","--no-patch":"none","--no-ext-diff":"none","-s":"none"},O4={"--author":"string","--committer":"string","--grep":"string"},c1={"--format":"string","--pretty":"string"},JZ={"git diff":{safeFlags:{...p1,...R$,...d1,"--cached":"none","--staged":"none","--no-index":"none","--diff-filter":"string","--word-diff":"none","--word-diff-regex":"string","-U":"number","--unified":"number","--compact-summary":"none","--ignore-space-change":"none","-b":"none","--ignore-all-space":"none","-w":"none","--ignore-blank-lines":"none","--src-prefix":"string","--dst-prefix":"string","--no-prefix":"none","-R":"none","--relative":"none","--histogram":"none","--patience":"none","--minimal":"none","--check":"none","--ext-diff":"none","--binary":"none","--abbrev":"none","--full-index":"none","--break-rewrites":"none","-B":"none","--find-renames":"none","-M":"none","--find-copies":"none","-C":"none","--diff-algorithm":"string"}},"git log":{safeFlags:{...eJ,...$2,...J2,...g1,...p1,...R$,...d1,...O4,...c1,"--follow":"none","--first-parent":"none","--merges":"none","--no-merges":"none","--reverse":"none","--ancestry-path":"none","--simplify-by-decoration":"none","--abbrev-commit":"none","--no-abbrev-commit":"none","--abbrev":"number","--topo-order":"none","--diff-filter":"string","--skip":"number","--left-right":"none","--cherry-pick":"none","--cherry-mark":"none","--cherry":"none","--walk-reflogs":"none","-g":"none","--boundary":"none","--source":"none"}},"git show":{safeFlags:{...p1,...R$,...d1,...c1,"--abbrev-commit":"none","--no-abbrev-commit":"none","--abbrev":"number","-U":"number","--unified":"number","--diff-filter":"string","--word-diff":"none","--word-diff-regex":"string","--compact-summary":"none"}},"git shortlog":{safeFlags:{...eJ,...$2,...g1,...O4,"-s":"none","--summary":"none","-n":"number","--numbered":"none","-e":"none","--email":"none","--group":"string","--format":"string"}},"git reflog":{safeFlags:{...J2,...g1,...R$,...c1,"--date":"string"},isDangerousCallback:($,J)=>{let Z=new Set(["expire","delete","exists"]);for(let W of J)if(Z.has(W))return!0;return!1}},"git stash list":{safeFlags:{...J2,...R$,...c1}},"git stash show":{safeFlags:{...p1,...R$,...d1,"-U":"number","--unified":"number","--include-untracked":"none","-u":"none"}},"git ls-remote":{safeFlags:{"--heads":"none","--tags":"none","--refs":"none","--quiet":"none","-q":"none","--get-url":"none","--sort":"string","--symref":"none"}},"git status":{safeFlags:{"--short":"none","-s":"none","--branch":"none","-b":"none","--porcelain":"none","--long":"none","--verbose":"none","-v":"none","--untracked-files":"none","-u":"none","--ignored":"none","--ignore-submodules":"none","--column":"none","--no-column":"none","--ahead-behind":"none","--no-ahead-behind":"none","--renames":"none","--no-renames":"none","--show-stash":"none"}},"git blame":{safeFlags:{"-L":"string","--line-porcelain":"none","--porcelain":"none","-p":"none","--show-name":"none","--show-number":"none","-n":"none","--show-email":"none","-e":"none","-w":"none","-M":"none","-C":"none","--date":"string","--color-lines":"none","--color-by-age":"none","--abbrev":"number","-s":"none","--score-debug":"none","--first-parent":"none","--root":"none","--since":"string"}},"git ls-files":{safeFlags:{"--cached":"none","-c":"none","--deleted":"none","-d":"none","--modified":"none","-m":"none","--others":"none","-o":"none","--ignored":"none","-i":"none","--stage":"none","-s":"none","--unmerged":"none","-u":"none","--killed":"none","-k":"none","--exclude":"string","-x":"string","--exclude-from":"string","-X":"string","--exclude-per-directory":"string","--exclude-standard":"none","--error-unmatch":"none","--full-name":"none","--recurse-submodules":"none","-z":"none","--eol":"none","--deduplicate":"none"}},"git config --get":{safeFlags:{"--global":"none","--system":"none","--local":"none","--worktree":"none","--get-regexp":"none","--list":"none","-l":"none","--show-origin":"none","--show-scope":"none","-z":"none","--null":"none","--name-only":"none","--type":"string","--default":"string"}},"git remote show":{safeFlags:{"-n":"none"},isDangerousCallback:($,J)=>{let Z=J.filter((W)=>!W.startsWith("-"));if(Z.length!==1)return!0;return!/^[a-zA-Z0-9_.-]+$/.test(Z[0])}},"git remote":{safeFlags:{"-v":"none","--verbose":"none"},isDangerousCallback:($,J)=>{return J.filter((W)=>!W.startsWith("-")).length>0}},"git merge-base":{safeFlags:{"--all":"none","--octopus":"none","--is-ancestor":"none","--independent":"none","--fork-point":"none"}},"git rev-parse":{safeFlags:{"--verify":"none","--quiet":"none","-q":"none","--short":"none","--symbolic":"none","--symbolic-full-name":"none","--abbrev-ref":"none","--show-toplevel":"none","--show-cdup":"none","--show-prefix":"none","--show-superproject-working-tree":"none","--git-dir":"none","--git-common-dir":"none","--git-path":"string","--is-inside-git-dir":"none","--is-inside-work-tree":"none","--is-bare-repository":"none","--is-shallow-repository":"none","--absolute-git-dir":"none","--resolve-git-dir":"string","--all":"none","--branches":"none","--tags":"none","--remotes":"none","--glob":"string","--exclude":"string"}},"git rev-list":{safeFlags:{...eJ,...$2,...g1,"--count":"none","--objects":"none","--no-walk":"none","--first-parent":"none","--merges":"none","--no-merges":"none","--reverse":"none","--ancestry-path":"none","--topo-order":"none","--left-right":"none","--cherry-pick":"none","--cherry-mark":"none","--cherry":"none","--boundary":"none","--abbrev-commit":"none","--abbrev":"number","--header":"none","--skip":"number"}},"git describe":{safeFlags:{"--all":"none","--tags":"none","--contains":"none","--abbrev":"number","--long":"none","--first-parent":"none","--always":"none","--match":"string","--exclude":"string","--exact-match":"none","--dirty":"none","--broken":"none","--candidates":"number","--debug":"none"}},"git cat-file":{safeFlags:{"-t":"none","-s":"none","-e":"none","-p":"none","--batch":"none","--batch-check":"none","--batch-all-objects":"none","--textconv":"none","--filters":"none","--allow-unknown-type":"none","--buffer":"none","--unordered":"none"}},"git for-each-ref":{safeFlags:{"--format":"string","--sort":"string","--count":"number","--shell":"none","--perl":"none","--python":"none","--tcl":"none","--points-at":"string","--merged":"string","--no-merged":"string","--contains":"string","--no-contains":"string"}},"git grep":{safeFlags:{"-i":"none","--ignore-case":"none","-w":"none","--word-regexp":"none","-v":"none","--invert-match":"none","-n":"none","--line-number":"none","-l":"none","--files-with-matches":"none","--name-only":"none","-L":"none","--files-without-match":"none","-c":"none","--count":"none","--color":"none","--no-color":"none","-e":"string","-f":"string","--and":"none","--or":"none","--not":"none","--all-match":"none","-E":"none","--extended-regexp":"none","-G":"none","--basic-regexp":"none","-P":"none","--perl-regexp":"none","-F":"none","--fixed-strings":"none","--cached":"none","--untracked":"none","--no-index":"none","--recurse-submodules":"none","--max-depth":"number","-h":"none","--no-filename":"none","-H":"none","--full-name":"none","-z":"none","--break":"none","--heading":"none","-p":"none","--show-function":"none","-W":"none","--function-context":"none","--threads":"number","-O":"string","--open-files-in-pager":"none","-A":"number","-B":"number","-C":"number","--context":"number"}},"git worktree list":{safeFlags:{"--porcelain":"none","-z":"none","-v":"none","--verbose":"none","--expire":"string"}},"git tag":{safeFlags:{"-l":"none","--list":"none","-n":"number","--sort":"string","--column":"none","--no-column":"none","--contains":"string","--no-contains":"string","--merged":"string","--no-merged":"string","--points-at":"string","--format":"string","--color":"none","--no-color":"none"},isDangerousCallback:($,J)=>{if(J.some((Y)=>Y==="-l"||Y==="--list"))return!1;return J.filter((Y)=>!Y.startsWith("-")).length>0}},"git branch":{safeFlags:{"-l":"none","--list":"none","-a":"none","--all":"none","-r":"none","--remotes":"none","-v":"none","--verbose":"none","-vv":"none","--sort":"string","--format":"string","--color":"none","--no-color":"none","--column":"none","--no-column":"none","--contains":"string","--no-contains":"string","--merged":"string","--no-merged":"string","--points-at":"string","--abbrev":"number","--no-abbrev":"none","--show-current":"none"},isDangerousCallback:($,J)=>{let Z=new Set(["-l","--list","-a","--all","-r","--remotes","--show-current"]);if(J.some((K)=>Z.has(K)))return!1;let Y=new Set(["-d","-D","-m","-M","-c","--copy","--delete","--move","--set-upstream-to","--unset-upstream","--edit-description"]);if(J.some((K)=>Y.has(K.split("=")[0])))return!0;return J.filter((K)=>!K.startsWith("-")).length>0}}};function $0($,J){for(let Z of J){if(Z.includes("://")||Z.includes("@"))return!0;if((Z.match(/\//g)||[]).length>=2)return!0}return!1}var J0={"--json":"string","--jq":"string","--template":"string","-q":"none","--limit":"number","-L":"number","--web":"none","-w":"none","--comments":"none"},ZZ={"gh pr view":{safeFlags:{...J0},isDangerousCallback:$0},"gh pr list":{safeFlags:{...J0,"--state":"string","-s":"string","--author":"string","--label":"string","--base":"string","--head":"string","--search":"string","--assignee":"string","--draft":"none"},isDangerousCallback:$0},"gh pr diff":{safeFlags:{...J0,"--color":"string","--patch":"none","--name-only":"none"},isDangerousCallback:$0},"gh pr checks":{safeFlags:{...J0,"--watch":"none","--fail-fast":"none","--required":"none"},isDangerousCallback:$0},"gh pr status":{safeFlags:{...J0},isDangerousCallback:$0},"gh issue view":{safeFlags:{...J0},isDangerousCallback:$0},"gh issue list":{safeFlags:{...J0,"--state":"string","-s":"string","--author":"string","--label":"string","--search":"string","--assignee":"string","--milestone":"string"},isDangerousCallback:$0},"gh issue status":{safeFlags:{...J0},isDangerousCallback:$0},"gh repo view":{safeFlags:{...J0},isDangerousCallback:$0},"gh run list":{safeFlags:{...J0,"--workflow":"string","-w":"string","--branch":"string","-b":"string","--status":"string","-s":"string","--user":"string","-u":"string","--event":"string","-e":"string"},isDangerousCallback:$0},"gh run view":{safeFlags:{...J0,"--log":"none","--log-failed":"none","--exit-status":"none","--verbose":"none","-v":"none","--job":"string","-j":"string"},isDangerousCallback:$0},"gh auth status":{safeFlags:{"--hostname":"string","-h":"string","--active":"none"},isDangerousCallback:($,J)=>{return J.some((Z)=>Z==="--show-token"||Z==="-t")}},"gh release list":{safeFlags:{...J0,"--exclude-drafts":"none","--exclude-pre-releases":"none"},isDangerousCallback:$0},"gh release view":{safeFlags:{...J0},isDangerousCallback:$0},"gh workflow list":{safeFlags:{...J0,"--all":"none","-a":"none"},isDangerousCallback:$0},"gh workflow view":{safeFlags:{...J0,"--yaml":"none","-y":"none","--ref":"string","-r":"string"},isDangerousCallback:$0},"gh label list":{safeFlags:{...J0,"--search":"string","--sort":"string","--order":"string"},isDangerousCallback:$0},"gh search repos":{safeFlags:{...J0,"--language":"string","--topic":"string","--sort":"string","--order":"string","--match":"string","--owner":"string","--visibility":"string"},isDangerousCallback:$0},"gh search issues":{safeFlags:{...J0,"--sort":"string","--order":"string","--match":"string","--state":"string","--label":"string","--language":"string","--author":"string","--assignee":"string","--repo":"string"},isDangerousCallback:$0},"gh search prs":{safeFlags:{...J0,"--sort":"string","--order":"string","--match":"string","--state":"string","--label":"string","--language":"string","--author":"string","--assignee":"string","--repo":"string"},isDangerousCallback:$0},"gh search commits":{safeFlags:{...J0,"--sort":"string","--order":"string","--author":"string","--committer":"string","--repo":"string"},isDangerousCallback:$0},"gh search code":{safeFlags:{...J0,"--language":"string","--filename":"string","--extension":"string","--repo":"string","--match":"string"},isDangerousCallback:$0}},WZ={"docker logs":{safeFlags:{"--follow":"none","-f":"none","--tail":"number","-n":"number","--timestamps":"none","-t":"none","--since":"string","--until":"string","--details":"none"}},"docker inspect":{safeFlags:{"--format":"string","-f":"string","--type":"string","--size":"none","-s":"none"}}},YZ={rg:{safeFlags:{"-e":"string","--regexp":"string","-F":"none","--fixed-strings":"none","-i":"none","--ignore-case":"none","-S":"none","--smart-case":"none","-s":"none","--case-sensitive":"none","-v":"none","--invert-match":"none","-w":"none","--word-regexp":"none","-x":"none","--line-regexp":"none","-P":"none","--pcre2":"none","--engine":"string","-m":"number","--max-count":"number","--max-depth":"number","--maxdepth":"number","-d":"number","--max-filesize":"string","--mmap":"none","--no-mmap":"none","-U":"none","--multiline":"none","--multiline-dotall":"none","--crlf":"none","--no-crlf":"none","-c":"none","--count":"none","--count-matches":"none","-l":"none","--files-with-matches":"none","--files-without-match":"none","-o":"none","--only-matching":"none","--vimgrep":"none","-r":"string","--replace":"string","-t":"string","--type":"string","-T":"string","--type-not":"string","-g":"string","--glob":"string","--iglob":"string","--type-add":"string","--type-clear":"string","-A":"number","--after-context":"number","-B":"number","--before-context":"number","-C":"number","--context":"number","--color":"string","--colors":"string","-n":"none","--line-number":"none","-N":"none","--no-line-number":"none","-H":"none","--with-filename":"none","--no-filename":"none","-p":"none","--pretty":"none","--heading":"none","--no-heading":"none","--column":"none","--no-column":"none","--byte-offset":"none","--trim":"none","-j":"number","--threads":"number","--sort":"string","--sortr":"string","--stats":"none","--no-ignore":"none","--no-ignore-vcs":"none","--no-ignore-parent":"none","--no-ignore-global":"none","--hidden":"none","--no-hidden":"none","-L":"none","--follow":"none","--one-file-system":"none","--null":"none","-0":"none","--path-separator":"string","--no-config":"none","--no-ignore-dot":"none","--no-ignore-exclude":"none","--no-unicode":"none","--pcre2-version":"none","-q":"none","--quiet":"none","--help":"none","-h":"none","--version":"none","-V":"none","--":"none","--json":"none","--auto-hybrid-regex":"none","--binary":"none","--block-buffered":"none","--line-buffered":"none","--debug":"none","--dfa-size-limit":"string","--encoding":"string","-E":"string","--no-messages":"none","--regex-size-limit":"string","--search-zip":"none","-z":"none","--type-list":"none","--unrestricted":"none","-u":"none"}}},VZ={...JZ,...ZZ,...WZ,...YZ,file:{safeFlags:{"-b":"none","--brief":"none","-i":"none","--mime":"none","--mime-type":"none","--mime-encoding":"none","-L":"none","-h":"none","--no-dereference":"none","-z":"none"}},sort:{safeFlags:{"-r":"none","--reverse":"none","-n":"none","--numeric-sort":"none","-u":"none","--unique":"none","-k":"string","--key":"string","-t":"string","--field-separator":"string","-f":"none","--ignore-case":"none","-s":"none","--stable":"none","-h":"none","--human-numeric-sort":"none","-V":"none","--version-sort":"none","-g":"none","--general-numeric-sort":"none","-M":"none","--month-sort":"none"}},grep:{safeFlags:{"-i":"none","--ignore-case":"none","-v":"none","--invert-match":"none","-c":"none","--count":"none","-l":"none","--files-with-matches":"none","-L":"none","--files-without-match":"none","-n":"none","--line-number":"none","-H":"none","--with-filename":"none","-h":"none","--no-filename":"none","-r":"none","-R":"none","--recursive":"none","-E":"none","--extended-regexp":"none","-F":"none","--fixed-strings":"none","-P":"none","--perl-regexp":"none","-w":"none","--word-regexp":"none","-x":"none","--line-regexp":"none","-A":"number","--after-context":"number","-B":"number","--before-context":"number","-C":"number","--context":"number","-m":"number","--max-count":"number","--color":"string","--colour":"string","-e":"string","--regexp":"string","--include":"string","--exclude":"string","--exclude-dir":"string","-o":"none","--only-matching":"none","-q":"none","--quiet":"none","--silent":"none","-s":"none","--no-messages":"none","-Z":"none","--null":"none"}},tree:{safeFlags:{"-L":"number","-d":"none","-a":"none","-f":"none","-i":"none","-l":"none","-s":"none","-h":"none","-p":"none","-u":"none","-g":"none","-D":"none","-r":"none","-t":"none","--noreport":"none","--dirsfirst":"none","-C":"none","--color":"none","-n":"none","-I":"string","-P":"string","--charset":"string","-o":"string","--prune":"none","-J":"none","-X":"none","-H":"string"}},date:{safeFlags:{"-u":"none","--utc":"none","-d":"string","--date":"string","-I":"none","--iso-8601":"none","-R":"none","--rfc-2822":"none","--rfc-3339":"string"}},ps:{safeFlags:{"-e":"none","-f":"none","-l":"none","-a":"none","-u":"none","-x":"none","-o":"string","--sort":"string","-p":"string","--pid":"string","-C":"string","--forest":"none","-H":"none","--headers":"none","--no-headers":"none","-w":"none","--width":"number"}},lsof:{safeFlags:{"-i":"string","-p":"string","-n":"none","-P":"none","-t":"none","-c":"string","-u":"string","-d":"string","-a":"none"}},netstat:{safeFlags:{"-t":"none","-u":"none","-l":"none","-n":"none","-p":"none","-a":"none","-r":"none","-s":"none","-e":"none","-o":"none","-i":"none"}},man:{safeFlags:{"-k":"string","--apropos":"string","-f":"string","--whatis":"string"}},sed:{safeFlags:{"-n":"none","--quiet":"none","--silent":"none","-E":"none","-r":"none","--regexp-extended":"none","-e":"string","--expression":"string"},isDangerousCallback:($,J)=>{for(let Z of J){if(Z==="-i"||Z.startsWith("-i")||Z==="--in-place")return!0;if(/\bw\s/.test(Z)||/\bw$/.test(Z))return!0}return!1}},base64:{safeFlags:{"-d":"none","--decode":"none","-w":"number","--wrap":"number","-i":"none","--ignore-garbage":"none"}},sha256sum:{safeFlags:{"-c":"none","--check":"none","-b":"none","--binary":"none","-t":"none","--text":"none","--tag":"none","--status":"none","-w":"none","--warn":"none","--strict":"none","--quiet":"none"}},sha1sum:{safeFlags:{"-c":"none","--check":"none","-b":"none","--binary":"none","--tag":"none","--status":"none"}},md5sum:{safeFlags:{"-c":"none","--check":"none","-b":"none","--binary":"none","--tag":"none","--status":"none"}},hostname:{safeFlags:{"-s":"none","-f":"none","--fqdn":"none","-d":"none","-i":"none","-I":"none","-a":"none"}},pgrep:{safeFlags:{"-l":"none","-a":"none","-f":"none","-x":"none","-n":"none","-o":"none","-c":"none","-d":"string","-u":"string","-U":"string","-P":"string","-G":"string","-t":"string"}},ss:{safeFlags:{"-t":"none","-u":"none","-l":"none","-n":"none","-p":"none","-a":"none","-r":"none","-s":"none","-e":"none","-o":"none","-i":"none","-4":"none","-6":"none","-m":"none","-Z":"none","-K":"none"}},fd:{safeFlags:{"-t":"string","--type":"string","-e":"string","--extension":"string","-E":"string","--exclude":"string","-d":"number","--max-depth":"number","-H":"none","--hidden":"none","-I":"none","--no-ignore":"none","-s":"none","--case-sensitive":"none","-i":"none","--ignore-case":"none","-a":"none","--absolute-path":"none","-l":"none","--list-details":"none","-L":"none","--follow":"none","-p":"none","--full-path":"none","-0":"none","--print0":"none","-1":"none","--color":"string","--glob":"none","-g":"none","-F":"none","--fixed-strings":"none","--prune":"none","-u":"none","--unrestricted":"none","-S":"string","--size":"string","--changed-within":"string","--changed-before":"string","-j":"number","--threads":"number"}},fdfind:{safeFlags:{"-t":"string","--type":"string","-e":"string","--extension":"string","-E":"string","--exclude":"string","-d":"number","--max-depth":"number","-H":"none","--hidden":"none","-I":"none","--no-ignore":"none","-s":"none","--case-sensitive":"none","-i":"none","--ignore-case":"none","-a":"none","--absolute-path":"none","-l":"none","--list-details":"none","-L":"none","--follow":"none","-p":"none","--full-path":"none","-0":"none","--print0":"none","-1":"none","--color":"string","--glob":"none","-g":"none","-F":"none","--fixed-strings":"none"}},tput:{safeFlags:{"-S":"none"}},help:{safeFlags:{}},info:{safeFlags:{}}};function KZ($){let J=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^${J}(?:\\s|$)[^<>()$\`|{}&;\\n\\r]*$`)}var QZ=["docker ps","docker images","cal","uptime","cat","head","tail","wc","stat","strings","hexdump","od","nl","id","uname","free","df","du","locale","groups","nproc","basename","dirname","realpath","cut","paste","tr","column","tac","rev","fold","expand","unexpand","fmt","comm","cmp","numfmt","readlink","diff","true","false","sleep","which","type","expr","test","getconf","seq","tsort","pr"],XZ=[/^echo(?:\s+(?:'[^']*'|"[^"$<>\n\r]*"|[^|;&`$(){}><#\\!"'\s]+))*(?:\s+2>&1)?\s*$/,/^uniq(?:\s+(?:-[a-zA-Z]+|--[a-zA-Z-]+(?:=\S+)?|-[fsw]\s+\d+))*(?:\s|$)\s*$/,/^pwd$/,/^whoami$/,/^alias$/,/^node\s+(-v|--version)\s*$/,/^python\s+--version\s*$/,/^python3\s+--version\s*$/,/^bun\s+--version\s*$/,/^deno\s+--version\s*$/,/^history(?:\s+\d+)?\s*$/,/^arch(?:\s+(?:--help|-h))?\s*$/,/^ip\s+addr$/,/^ifconfig(?:\s+[a-zA-Z][a-zA-Z0-9_-]*)?\s*$/,/^ls(?:\s+[^<>()$`|{}&;\n\r]*)?\s*$/,/^cd(?:\s+(?:'[^']*'|"[^"]*"|[^\s;|&`$(){}><#\\]+))?$/,/^find(?:\s+(?:\\[()]|(?!-delete\b|-exec\b|-execdir\b|-ok\b|-okdir\b|-fprint0?\b|-fls\b|-fprintf\b)[^<>()$`|{}&;\n\r\s]|\s)+)?$/,/^jq(?!\s+.*(?:-f\b|--from-file|--rawfile|--slurpfile|--run-tests|-L\b|--library-path|\benv\b|\$ENV\b))(?:\s+(?:-[a-zA-Z]+|--[a-zA-Z-]+(?:=\S+)?))*(?:\s+'[^'`]*'|\s+"[^"`]*"|\s+[^-\s'"][^\s]*)+\s*$/],HZ=[...QZ.map(KZ),...XZ];function m1($,J){switch(J){case"none":return!1;case"number":return/^\d+$/.test($);case"string":return!0}}function jZ($,J,Z){let W=J,Y=Z.respectsDoubleDash!==!1;while(W<$.length){let V=$[W];if(V==="--"&&Y)break;if(!V.startsWith("-")){W++;continue}if(V.startsWith("--")){let H=V.indexOf("="),z=H!==-1,B=z?V.substring(0,H):V,j=Z.safeFlags[B];if(j===void 0)return!1;if(j==="none"){if(z)return!1;W++;continue}if(z){let U=V.substring(H+1);if(!m1(U,j))return!1;W++}else{if(W++,W>=$.length)return!1;let U=$[W];if(j==="string"&&U.startsWith("-")){if(B!=="--sort")return!1}if(!m1(U,j))return!1;W++}continue}let K=V;if(/^-\d+$/.test(K)){W++;continue}let Q=Z.safeFlags[K];if(Q!==void 0){if(Q==="none"){W++;continue}if(W++,W>=$.length)return!1;let H=$[W];if(!m1(H,Q))return!1;W++;continue}let X=K.indexOf("=");if(X!==-1){let H=K.substring(0,X),z=Z.safeFlags[H];if(z===void 0)return!1;let B=K.substring(X+1);if(z!=="none"&&!m1(B,z))return!1;W++;continue}if(/^-[A-Za-z]\d+$/.test(K)){let H=K.substring(0,2);if(Z.safeFlags[H]==="number"){W++;continue}}if(/^-[A-Za-z]{2,}$/.test(K)){let H=!0;for(let z=1;z<K.length;z++){let B=`-${K[z]}`;if(Z.safeFlags[B]!=="none"){H=!1;break}}if(H){W++;continue}}return!1}return!0}function zZ($){for(let J=Math.min(3,$.length);J>=1;J--){let Z=$.slice(0,J).join(" "),W=VZ[Z];if(W)return[Z,W,J]}return null}function BZ($){let J=Y$($);if(J.length===0)return!1;let Z=zZ(J);if(!Z)return!1;let[W,Y,V]=Z,K=J.slice(V);for(let Q of K)if(Q.includes("$"))return!1;for(let Q of K)if(Q.includes("{")&&(Q.includes(",")||Q.includes("..")))return!1;if(!jZ(J,V,Y))return!1;if(Y.regex&&!Y.regex.test($))return!1;if(Y.isDangerousCallback&&Y.isDangerousCallback($,K))return!1;if(W==="grep"||W==="rg"){for(let Q of K)if(Q.includes(`
|
|
101
|
-
`)||Q.includes("\r"))return!1}return!0}function UZ($){for(let J of HZ)if(J.test($))return!0;return!1}function DZ($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let V=$[Y];if(W){W=!1;continue}if(V==="\\"&&!J){W=!0;continue}if(V==="'"&&!Z){J=!J;continue}if(V==='"'&&!J){Z=!Z;continue}if(J)continue;if(V==="$"){let K=$[Y+1];if(K&&/[A-Za-z_@*#?!$0-9({-]/.test(K))return!0}if(V==="`")return!0}return!1}function wZ($){let J=$.replace(/\s+2>&1\s*$/,"").trim();if(!J)return!1;if(DZ(J))return!1;if(BZ(J))return!0;if(UZ(J)){if(/\bgit\b/.test(J)){if(/\s-c\s/.test(J)||/--exec-path/.test(J)||/--config-env/.test(J))return!1}return!0}return!1}function f4($){let J=$.trim();if(!J)return!1;let Z=l$(J);if(Z===null)return!1;if(Z.length>1){let W=!1,Y=!1;for(let V of Z){let K=m$(GJ(V.trim()));if(/^cd\b/.test(K))W=!0;if(/\bgit\b/.test(K))Y=!0}if(W&&Y)return!1}for(let W of Z){let Y=W.trim();if(!Y)continue;let V=m$(GJ(Y));if(!V)return!1;if(!wZ(V))return!1}return!0}var W2="<bash-mutation>",GZ=3,FZ=/^##\s+Verification Result:\s*(PASS|FAIL|PARTIAL)\s*$/gim,LZ=/(?:^|\/)(?:docs?|tests?|__tests__|fixtures?|examples?|snapshots?)(?:\/|$)/i,OZ=/\.(?:md|mdx|txt|snap)$/i,fZ=/(?:^|\/)(?:api|server|backend|infra|infrastructure|auth|security|migrations?|database|workflows?)(?:\/|$)/i,yZ=/(?:^|\/)(?:Dockerfile|docker-compose(?:\.[^/]+)?|wrangler\.(?:jsonc?|toml)|[^/]+\.tf)$/i;function l1($){if(typeof $!=="string")return;let J=$.trim().replaceAll("\\","/");if(!J)return;return qZ.posix.normalize(J)}function Z2($){if(!Array.isArray($))return[];return $.map(l1).filter((J)=>J!==void 0)}function y4($){if(!$)return;let J=[...$.matchAll(FZ)].map((Z)=>Z[1]?.toLowerCase());return J.length===1?J[0]:void 0}function A4($,J,Z){if(!J.success)return[];let W=J.metadata;if(!W||typeof W!=="object")return[];if($==="Edit"||$==="Write"){let Y=l1(W.file_path);return Y?[Y]:[]}if($==="ApplyPatch"){let Y=Z2(W.affected_paths);if(Y.length>0)return Y;if(!Array.isArray(W.changes))return[];return W.changes.map((V)=>V&&typeof V==="object"&&("path"in V)?l1(V.path):void 0).filter((V)=>V!==void 0)}if($==="NotebookEdit"){let Y=l1(W.notebook_path);return Y?[Y]:[]}if($==="Task"||$==="TaskOutput")return Z2(W.modifiedFiles??W.modified_files);if($==="Bash"&&typeof W.command==="string"){let Y=W.command;if(!y$(Y,Z)&&!f4(Y))return[W2]}return[]}function P4($,J,Z,W){let Y=A4(J,Z,W);for(let V of Y)$.add(V);return Y}function N4($){let J={modifiedFiles:new Set,mutationRevision:0,verificationRevision:-1};for(let Z of $){if(Z.role!=="tool"||!Z.metadata)continue;let W=Z.metadata;if(typeof W!=="object"||Array.isArray(W)||W===null)continue;let Y=W.metadata&&typeof W.metadata==="object"&&!Array.isArray(W.metadata)?W.metadata:void 0,V=W.independentVerification,K=V&&typeof V==="object"&&!Array.isArray(V)?V:Y?{modifiedFiles:A4(typeof W.toolName==="string"?W.toolName:Z.name??"",{success:typeof W.error!=="string",llmContent:Z.content,metadata:Y}),verificationAttempted:(W.toolName==="Task"||Z.name==="Task")&&Y.verificationAgentBuiltin===!0&&(Y.subagentStatus==="completed"||Y.status==="completed"),verificationAgentBuiltin:Y.verificationAgentBuiltin===!0,verificationVerdict:Y.verificationVerdict==="pass"||Y.verificationVerdict==="fail"||Y.verificationVerdict==="partial"?Y.verificationVerdict:void 0}:void 0;if(typeof K!=="object"||Array.isArray(K)||K===null)continue;let Q=Z2(K.modifiedFiles);if(Q.length>0){for(let X of Q)J.modifiedFiles.add(X);J.mutationRevision++,J.verificationRevision=-1,J.verificationVerdict=void 0}if(K.verificationAttempted===!0&&K.verificationAgentBuiltin===!0)J.verificationRevision=J.mutationRevision,J.verificationVerdict=K.verificationVerdict==="pass"||K.verificationVerdict==="fail"||K.verificationVerdict==="partial"?K.verificationVerdict:void 0}return J}function Y2($){if($.has(W2))return!0;let J=[...$].filter((Z)=>!LZ.test(Z)&&!OZ.test(Z));return J.length>=3||J.some((Z)=>fZ.test(Z)||yZ.test(Z))}function _4($){if(!$.enabled||$.isSubagent||!$.taskAvailable||$.delegationForbidden||$.singleTaskDelegationRequired||!Y2($.modifiedFiles))return{action:"none"};if($.verificationRevision===$.mutationRevision&&$.verificationVerdict==="pass")return{action:"none"};if($.retryCount>=GZ)return{action:"fail",message:"Independent verification did not produce a fresh PASS before the retry limit."};if($.verificationRevision===$.mutationRevision){if($.verificationVerdict==="fail")return{action:"retry",requireVerificationTask:!1,prompt:"The independent verification agent returned FAIL. Fix every reported failure with tool calls, then run a fresh verification agent. Do not finish or claim success before the new verdict is PASS."};if($.verificationVerdict==="partial")return{action:"retry",requireVerificationTask:!1,prompt:"The independent verification agent returned PARTIAL. Resolve the reported medium-risk findings with tool calls, then run a fresh verification agent. Do not finish before the new verdict is PASS."};return{action:"retry",requireVerificationTask:!0,prompt:'The verification agent did not return exactly one structured "## Verification Result: PASS | FAIL | PARTIAL" verdict. Run Task again with subagent_type="verification" and run_in_background=false. Require tool-backed evidence and the exact final verdict heading.'}}let J=[...$.modifiedFiles].filter((Z)=>Z!==W2).slice(0,20).join(", ");return{action:"retry",requireVerificationTask:!0,prompt:`This turn made a non-trivial implementation. Before finishing, call Task with subagent_type="verification", run_in_background=false, and isolation="none". Give it the original request, implementation approach, and changed files${J?`: ${J}`:""}. Do not give the verifier your test results or a claimed outcome. Do not ask it to skip any project check; the runtime replaces the verifier prompt with an authoritative scope. Only a fresh structured PASS verdict allows completion.`}}var
|
|
101
|
+
`)||Q.includes("\r"))return!1}return!0}function UZ($){for(let J of HZ)if(J.test($))return!0;return!1}function DZ($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let V=$[Y];if(W){W=!1;continue}if(V==="\\"&&!J){W=!0;continue}if(V==="'"&&!Z){J=!J;continue}if(V==='"'&&!J){Z=!Z;continue}if(J)continue;if(V==="$"){let K=$[Y+1];if(K&&/[A-Za-z_@*#?!$0-9({-]/.test(K))return!0}if(V==="`")return!0}return!1}function wZ($){let J=$.replace(/\s+2>&1\s*$/,"").trim();if(!J)return!1;if(DZ(J))return!1;if(BZ(J))return!0;if(UZ(J)){if(/\bgit\b/.test(J)){if(/\s-c\s/.test(J)||/--exec-path/.test(J)||/--config-env/.test(J))return!1}return!0}return!1}function f4($){let J=$.trim();if(!J)return!1;let Z=l$(J);if(Z===null)return!1;if(Z.length>1){let W=!1,Y=!1;for(let V of Z){let K=m$(GJ(V.trim()));if(/^cd\b/.test(K))W=!0;if(/\bgit\b/.test(K))Y=!0}if(W&&Y)return!1}for(let W of Z){let Y=W.trim();if(!Y)continue;let V=m$(GJ(Y));if(!V)return!1;if(!wZ(V))return!1}return!0}var W2="<bash-mutation>",GZ=3,FZ=/^##\s+Verification Result:\s*(PASS|FAIL|PARTIAL)\s*$/gim,LZ=/(?:^|\/)(?:docs?|tests?|__tests__|fixtures?|examples?|snapshots?)(?:\/|$)/i,OZ=/\.(?:md|mdx|txt|snap)$/i,fZ=/(?:^|\/)(?:api|server|backend|infra|infrastructure|auth|security|migrations?|database|workflows?)(?:\/|$)/i,yZ=/(?:^|\/)(?:Dockerfile|docker-compose(?:\.[^/]+)?|wrangler\.(?:jsonc?|toml)|[^/]+\.tf)$/i;function l1($){if(typeof $!=="string")return;let J=$.trim().replaceAll("\\","/");if(!J)return;return qZ.posix.normalize(J)}function Z2($){if(!Array.isArray($))return[];return $.map(l1).filter((J)=>J!==void 0)}function y4($){if(!$)return;let J=[...$.matchAll(FZ)].map((Z)=>Z[1]?.toLowerCase());return J.length===1?J[0]:void 0}function A4($,J,Z){if(!J.success)return[];let W=J.metadata;if(!W||typeof W!=="object")return[];if($==="Edit"||$==="Write"){let Y=l1(W.file_path);return Y?[Y]:[]}if($==="ApplyPatch"){let Y=Z2(W.affected_paths);if(Y.length>0)return Y;if(!Array.isArray(W.changes))return[];return W.changes.map((V)=>V&&typeof V==="object"&&("path"in V)?l1(V.path):void 0).filter((V)=>V!==void 0)}if($==="NotebookEdit"){let Y=l1(W.notebook_path);return Y?[Y]:[]}if($==="Task"||$==="TaskOutput")return Z2(W.modifiedFiles??W.modified_files);if($==="Bash"&&typeof W.command==="string"){let Y=W.command;if(!y$(Y,Z)&&!f4(Y))return[W2]}return[]}function P4($,J,Z,W){let Y=A4(J,Z,W);for(let V of Y)$.add(V);return Y}function N4($){let J={modifiedFiles:new Set,mutationRevision:0,verificationRevision:-1};for(let Z of $){if(Z.role!=="tool"||!Z.metadata)continue;let W=Z.metadata;if(typeof W!=="object"||Array.isArray(W)||W===null)continue;let Y=W.metadata&&typeof W.metadata==="object"&&!Array.isArray(W.metadata)?W.metadata:void 0,V=W.independentVerification,K=V&&typeof V==="object"&&!Array.isArray(V)?V:Y?{modifiedFiles:A4(typeof W.toolName==="string"?W.toolName:Z.name??"",{success:typeof W.error!=="string",llmContent:Z.content,metadata:Y}),verificationAttempted:(W.toolName==="Task"||Z.name==="Task")&&Y.verificationAgentBuiltin===!0&&(Y.subagentStatus==="completed"||Y.status==="completed"),verificationAgentBuiltin:Y.verificationAgentBuiltin===!0,verificationVerdict:Y.verificationVerdict==="pass"||Y.verificationVerdict==="fail"||Y.verificationVerdict==="partial"?Y.verificationVerdict:void 0}:void 0;if(typeof K!=="object"||Array.isArray(K)||K===null)continue;let Q=Z2(K.modifiedFiles);if(Q.length>0){for(let X of Q)J.modifiedFiles.add(X);J.mutationRevision++,J.verificationRevision=-1,J.verificationVerdict=void 0}if(K.verificationAttempted===!0&&K.verificationAgentBuiltin===!0)J.verificationRevision=J.mutationRevision,J.verificationVerdict=K.verificationVerdict==="pass"||K.verificationVerdict==="fail"||K.verificationVerdict==="partial"?K.verificationVerdict:void 0}return J}function Y2($){if($.has(W2))return!0;let J=[...$].filter((Z)=>!LZ.test(Z)&&!OZ.test(Z));return J.length>=3||J.some((Z)=>fZ.test(Z)||yZ.test(Z))}function _4($){if(!$.enabled||$.isSubagent||!$.taskAvailable||$.delegationForbidden||$.singleTaskDelegationRequired||!Y2($.modifiedFiles))return{action:"none"};if($.verificationRevision===$.mutationRevision&&$.verificationVerdict==="pass")return{action:"none"};if($.retryCount>=GZ)return{action:"fail",message:"Independent verification did not produce a fresh PASS before the retry limit."};if($.verificationRevision===$.mutationRevision){if($.verificationVerdict==="fail")return{action:"retry",requireVerificationTask:!1,prompt:"The independent verification agent returned FAIL. Fix every reported failure with tool calls, then run a fresh verification agent. Do not finish or claim success before the new verdict is PASS."};if($.verificationVerdict==="partial")return{action:"retry",requireVerificationTask:!1,prompt:"The independent verification agent returned PARTIAL. Resolve the reported medium-risk findings with tool calls, then run a fresh verification agent. Do not finish before the new verdict is PASS."};return{action:"retry",requireVerificationTask:!0,prompt:'The verification agent did not return exactly one structured "## Verification Result: PASS | FAIL | PARTIAL" verdict. Run Task again with subagent_type="verification" and run_in_background=false. Require tool-backed evidence and the exact final verdict heading.'}}let J=[...$.modifiedFiles].filter((Z)=>Z!==W2).slice(0,20).join(", ");return{action:"retry",requireVerificationTask:!0,prompt:`This turn made a non-trivial implementation. Before finishing, call Task with subagent_type="verification", run_in_background=false, and isolation="none". Give it the original request, implementation approach, and changed files${J?`: ${J}`:""}. Do not give the verifier your test results or a claimed outcome. Do not ask it to skip any project check; the runtime replaces the verifier prompt with an authoritative scope. Only a fresh structured PASS verdict allows completion.`}}var D9={includeGitSnapshot:!1,includeDirectoryListing:!1};function b4($,J){if(!$)return $;let Z=J.getDeferredToolsListing();return`${$}${Z?`
|
|
102
102
|
|
|
103
103
|
${Z}`:""}${`
|
|
104
104
|
|
|
@@ -168,4 +168,4 @@ ${A}`}if(typeof v==="object"&&v!==null)v=JSON.stringify(v,null,2);if(typeof v===
|
|
|
168
168
|
${V4(W$)}
|
|
169
169
|
</system-reminder>`,metadata:X1};G.appendControl("user",w);let D=await c0($,Z,w.content,X,X1);if(D)X=D}}if(W?.signal?.aborted)return z(K,Q.length,W.signal);if(K>=L0&&(i||g)){if(r.info(`Warning: 达到轮次上限 ${L0} 轮`),W?.onTurnLimitReached){let w=await W.onTurnLimitReached({turnsCount:K});if(w?.continue){G.writeback();let D="failed",N,y,m,b,f,p,v,A0,H0,C,A,e,s,q0;yield{kind:"compaction",phase:"start",reason:"turn_limit"};try{let O=$.chatService.getConfig(),P0=P(),f0=G$&&i$(q$)?P0.filter((qJ)=>qJ.name!=="Task"):P0,z0=u0?f0.filter((qJ)=>qJ.name===u0):f0,M=kJ(G.systemMessages,z0,O.model),M0=F$.project({history:G.getHistory(),contextRevision:G.contextRevision,modelName:O.model,requestProfile:M});m=M0.source,b=M0.estimatedPendingTokens;let u=await b$.compact(Z.messages,{trigger:"auto",modelName:O.model,modelProvider:O.provider,maxContextTokens:O.maxContextTokens??0,apiKey:O.apiKey,baseURL:O.baseUrl,actualPreTokens:M0.contextTokens,signal:W?.signal,activeTask:S0,workspaceRoot:Z.workspaceRoot||Q0(),workspaceAccess:Z.workspaceKind==="acp-remote"?"none":"full",sessionId:Z.sessionId});if(u.usage)yield{kind:"token_usage",usage:r1(u.usage,O.maxContextTokens??0)};let a4={role:"user",content:`This session is being continued from a previous conversation. The conversation is summarized above.
|
|
170
170
|
|
|
171
|
-
Please continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.`},S2=[...u.compactedMessages,a4];N=u.success?"llm":"fallback",y=u.preTokens,f=u.postTokens,p=u.sampleAttempts,v=u.inputReductions,A0=u.messagesOmitted,H0=u.filesOmitted,C=u.imagesOmitted,A=u.fallbackTargetTokens,e=u.fallbackMessagesOmitted,s=u.fallbackMessagesTruncated,q0=u.failureReason,await o$($,Z,u.summary,{trigger:"auto",reason:"turn_limit",strategy:N,preTokens:u.preTokens,preTokenSource:M0.source,...M0.estimatedPendingTokens!==void 0?{estimatedPendingTokens:M0.estimatedPendingTokens}:{},postTokens:u.postTokens,sampleAttempts:u.sampleAttempts,inputReductions:u.inputReductions,messagesOmitted:u.messagesOmitted,filesOmitted:u.filesOmitted,imagesOmitted:u.imagesOmitted,fallbackTargetTokens:u.fallbackTargetTokens,fallbackMessagesOmitted:u.fallbackMessagesOmitted,fallbackMessagesTruncated:u.fallbackMessagesTruncated,failureReason:u.failureReason,filesIncluded:u.filesIncluded,replacementMessages:S2},{required:$.executionEngine!==void 0}),Z.messages=S2,G.replaceHistory(Z.messages),F$.reset(),D=u.success?"completed":"fallback"}catch(O){throw r.error("[Loop] 轮次上限压缩失败,停止继续执行:",O),O}finally{yield{kind:"compaction",phase:"end",reason:"turn_limit",outcome:D,strategy:N,preTokens:y,preTokenSource:m,estimatedPendingTokens:b,postTokens:f,sampleAttempts:p,inputReductions:v,messagesOmitted:A0,filesOmitted:H0,imagesOmitted:C,fallbackTargetTokens:A,fallbackMessagesOmitted:e,fallbackMessagesTruncated:s,failureReason:q0}}K=0;continue}return{success:!0,finalMessage:w?.reason||"已达到对话轮次上限,用户选择停止",metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:S}}}return{success:!1,error:{type:"max_turns_exceeded",message:g?`子代理已达到轮次上限 (${L0} 轮)。`:`已达到轮次上限 (${L0} 轮)。`},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:S}}}}}catch(L){if(L instanceof N$)try{let F=Z.sessionId?await n$.loadSessionModelContext(Z.sessionId,Z.workspaceRoot):o;G.restoreDurableHistory(F)}catch(F){r.error("[Loop] Failed to reload durable context after message commit failure:",F),G.restoreDurableHistory(o)}throw L}finally{if(W?.transientInput==="goal_continuation")G.removeMessages((L)=>{let F=L.metadata;return F!==null&&typeof F==="object"&&!Array.isArray(F)&&F.transientGoalContinuation===!0});G.writeback()}}catch(B){if(m0(B))return z(K,Q.length,W?.signal);if(B instanceof N$)return{success:!1,error:{type:"message_persistence_failed",message:B.message},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V}};let j=EZ(B);return r.error(`API 调用失败: ${j}`),{success:!1,error:{type:"api_error",message:j,details:B},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V}}}finally{if(H)Z.messages.push({role:"system",content:PJ}),await t2($,Z,X)}}export{_J as
|
|
171
|
+
Please continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.`},S2=[...u.compactedMessages,a4];N=u.success?"llm":"fallback",y=u.preTokens,f=u.postTokens,p=u.sampleAttempts,v=u.inputReductions,A0=u.messagesOmitted,H0=u.filesOmitted,C=u.imagesOmitted,A=u.fallbackTargetTokens,e=u.fallbackMessagesOmitted,s=u.fallbackMessagesTruncated,q0=u.failureReason,await o$($,Z,u.summary,{trigger:"auto",reason:"turn_limit",strategy:N,preTokens:u.preTokens,preTokenSource:M0.source,...M0.estimatedPendingTokens!==void 0?{estimatedPendingTokens:M0.estimatedPendingTokens}:{},postTokens:u.postTokens,sampleAttempts:u.sampleAttempts,inputReductions:u.inputReductions,messagesOmitted:u.messagesOmitted,filesOmitted:u.filesOmitted,imagesOmitted:u.imagesOmitted,fallbackTargetTokens:u.fallbackTargetTokens,fallbackMessagesOmitted:u.fallbackMessagesOmitted,fallbackMessagesTruncated:u.fallbackMessagesTruncated,failureReason:u.failureReason,filesIncluded:u.filesIncluded,replacementMessages:S2},{required:$.executionEngine!==void 0}),Z.messages=S2,G.replaceHistory(Z.messages),F$.reset(),D=u.success?"completed":"fallback"}catch(O){throw r.error("[Loop] 轮次上限压缩失败,停止继续执行:",O),O}finally{yield{kind:"compaction",phase:"end",reason:"turn_limit",outcome:D,strategy:N,preTokens:y,preTokenSource:m,estimatedPendingTokens:b,postTokens:f,sampleAttempts:p,inputReductions:v,messagesOmitted:A0,filesOmitted:H0,imagesOmitted:C,fallbackTargetTokens:A,fallbackMessagesOmitted:e,fallbackMessagesTruncated:s,failureReason:q0}}K=0;continue}return{success:!0,finalMessage:w?.reason||"已达到对话轮次上限,用户选择停止",metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:S}}}return{success:!1,error:{type:"max_turns_exceeded",message:g?`子代理已达到轮次上限 (${L0} 轮)。`:`已达到轮次上限 (${L0} 轮)。`},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:S}}}}}catch(L){if(L instanceof N$)try{let F=Z.sessionId?await n$.loadSessionModelContext(Z.sessionId,Z.workspaceRoot):o;G.restoreDurableHistory(F)}catch(F){r.error("[Loop] Failed to reload durable context after message commit failure:",F),G.restoreDurableHistory(o)}throw L}finally{if(W?.transientInput==="goal_continuation")G.removeMessages((L)=>{let F=L.metadata;return F!==null&&typeof F==="object"&&!Array.isArray(F)&&F.transientGoalContinuation===!0});G.writeback()}}catch(B){if(m0(B))return z(K,Q.length,W?.signal);if(B instanceof N$)return{success:!1,error:{type:"message_persistence_failed",message:B.message},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V}};let j=EZ(B);return r.error(`API 调用失败: ${j}`),{success:!1,error:{type:"api_error",message:j,details:B},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V}}}finally{if(H)Z.messages.push({role:"system",content:PJ}),await t2($,Z,X)}}export{_J as lb,m$ as mb,iZ as nb,GJ as ob,l$ as pb,v2 as qb,Q5 as rb,y$ as sb,sZ as tb,B$ as ub,AJ as vb,o2 as wb,j3 as xb,r$ as yb,F0 as zb,_0 as Ab,LJ as Bb,OJ as Cb,p2 as Db,yJ as Eb,f4 as Fb,y4 as Gb,P4 as Hb,f$ as Ib,P1 as Jb,M5 as Kb,c0 as Lb,v0 as Mb,NJ as Nb,E1 as Ob,o$ as Pb,n as Qb,b$ as Rb,h1 as Sb,U0 as Tb,D9 as Ub,b4 as Vb,i1 as Wb,S4 as Xb,T4 as Yb,M4 as Zb,NZ as _b,K2 as $b,d4 as ac,pZ as bc};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{createRequire as a}from"node:module";var c=a(import.meta.url);
|
|
2
|
-
export{c as
|
|
2
|
+
export{c as rk};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{promises as B}from"node:fs";import q from"node:path";import{LRUCache as H}from"lru-cache";var K=512,Z=new H({max:K});async function L(x){let b=x;while(!0){try{return await B.lstat(q.join(b,".git")),b}catch(V){if(V.code!=="ENOENT")return}let F=q.dirname(b);if(F===b)return;b=F}}async function M(x){let b=q.join(x,".git"),F=await B.lstat(b);if(F.isDirectory())return x;if(!F.isFile())return;let V=await B.readFile(b,"utf8"),J=/^gitdir:\s*(.+)\s*$/im.exec(V);if(!J)return;let Q=await B.realpath(q.isAbsolute(J[1])?J[1]:q.resolve(x,J[1])),Y=Q;try{let z=(await B.readFile(q.join(Q,"commondir"),"utf8")).trim();if(z)Y=await B.realpath(q.resolve(Q,z))}catch(z){if(z.code!=="ENOENT")throw z}return q.basename(Y)===".git"?B.realpath(q.dirname(Y)):void 0}async function N(x){if(!q.isAbsolute(x))throw Error("Workspace path must be absolute");let b=await B.realpath(x),F=Z.get(b);if(F)return F;let V=b;try{let Q=await L(b);if(Q){let Y=await M(Q),z=q.relative(Q,b);if(Y&&(z===""||!z.startsWith(`..${q.sep}`)&&z!==".."&&!q.isAbsolute(z))){let $=q.resolve(Y,z);V=await B.realpath($).catch(()=>$)}}}catch{}let J={projectPath:b,trustRoot:V};return Z.set(b,J),J}async function S(x){if(!q.isAbsolute(x))throw Error("Workspace path must be absolute");let b=await B.realpath(x);Z.delete(b)}
|
|
2
|
-
export{N as
|
|
2
|
+
export{N as Kj,S as Lj};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{cf as a,df as b,ef as c}from"./chunk-q6xsfm60.js";import"./chunk-gmqpfm52.js";import"./chunk-rnmt44jm.js";import"./chunk-v508x7cg.js";import"./chunk-mdew58v9.js";import"./chunk-93x9xbew.js";import"./chunk-y4f99y85.js";import"./chunk-jkfkyedn.js";import"./chunk-f8gb685p.js";import"./chunk-44jtpg8y.js";import"./chunk-sj1dzeta.js";import"./chunk-2y1qngw7.js";import"./chunk-ar5np5h5.js";import"./chunk-dfjmvj3d.js";import"./chunk-tkydv9k8.js";import"./chunk-kbxqsf93.js";import"./chunk-qcvxff27.js";import"./chunk-zwjrensv.js";import"./chunk-pj69j4zp.js";import"./chunk-zkzhm39s.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
|