blade-code 0.10.136 → 0.10.137
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-r51afpkk.js → chunk-0c82q1sz.js} +1 -1
- package/dist/chunk-0ccm29qy.js +2 -0
- package/dist/{chunk-na3nregt.js → chunk-0k2x2ae6.js} +1 -1
- package/dist/{chunk-v2qxszks.js → chunk-1evc05gr.js} +1 -1
- package/dist/chunk-35668hyn.js +1 -0
- package/dist/{chunk-13sdjfks.js → chunk-39de5k03.js} +1 -1
- package/dist/chunk-3gmcvd0c.js +1 -0
- package/dist/{chunk-vvawhvea.js → chunk-4jqw75ce.js} +1 -1
- package/dist/chunk-5774a669.js +1 -0
- package/dist/{chunk-qjydadex.js → chunk-5btfnf2r.js} +5 -5
- package/dist/{chunk-91pb41e7.js → chunk-5dwmhsrx.js} +1 -1
- package/dist/{chunk-c5rfnzhf.js → chunk-5sf2rc1z.js} +3 -3
- package/dist/{chunk-sv5z5sna.js → chunk-69nwa6bn.js} +1 -1
- package/dist/{chunk-wj16pvvn.js → chunk-69rjav47.js} +1 -1
- package/dist/{chunk-ntd69c0k.js → chunk-6e3mh79j.js} +1 -1
- package/dist/{chunk-gdnyt8a7.js → chunk-6xvrrypm.js} +1 -1
- package/dist/{chunk-tev70rzj.js → chunk-74bswv4z.js} +2 -2
- package/dist/{chunk-g45camrd.js → chunk-75yy9yre.js} +1 -1
- package/dist/chunk-7n035mhg.js +1 -0
- package/dist/{chunk-hx10bph0.js → chunk-7ykqvsph.js} +1 -1
- package/dist/chunk-9a7bppj7.js +2 -0
- package/dist/{chunk-kbnxbb23.js → chunk-9frd4fpk.js} +1 -1
- package/dist/chunk-a26vtcv5.js +5 -0
- package/dist/{chunk-c85xvthj.js → chunk-affzv7f1.js} +1 -1
- package/dist/chunk-b08thknq.js +1 -0
- package/dist/{chunk-sy0vxdc3.js → chunk-bx75fd0d.js} +311 -311
- package/dist/chunk-bzqbmz6t.js +171 -0
- package/dist/{chunk-77x1rrz9.js → chunk-c2mx5zg0.js} +1 -1
- package/dist/chunk-chspy9f8.js +23 -0
- package/dist/chunk-d6tbr25k.js +1 -0
- package/dist/chunk-dt9n4f4e.js +1 -0
- package/dist/{chunk-82x77b2p.js → chunk-e76gej4y.js} +2 -2
- package/dist/{chunk-g4vgnxh4.js → chunk-e8pfbb6c.js} +1 -1
- package/dist/chunk-ermypm1x.js +2 -0
- package/dist/chunk-esp69w6w.js +1 -0
- package/dist/{chunk-5sknjz9b.js → chunk-etf3e9kt.js} +1 -1
- package/dist/{chunk-1cbaqh71.js → chunk-f2b9cyj5.js} +2 -2
- package/dist/chunk-g1y60ey9.js +1 -0
- package/dist/{chunk-jc28ddt0.js → chunk-g799czsy.js} +1 -1
- package/dist/{chunk-w2n1vwzg.js → chunk-g9vdmvk2.js} +2 -2
- package/dist/chunk-gf5v8aff.js +1 -0
- package/dist/chunk-gpj7k3er.js +6 -0
- package/dist/{chunk-hqwpnb0x.js → chunk-h05qhgrb.js} +1 -1
- package/dist/{chunk-24rsvr6e.js → chunk-h74p51hg.js} +1 -1
- package/dist/{chunk-f7hsagj6.js → chunk-karq4wfd.js} +1 -1
- package/dist/{chunk-9z9v8v4j.js → chunk-ky9br0z8.js} +1 -1
- package/dist/chunk-m9kh7djg.js +6 -0
- package/dist/{chunk-qm96k94k.js → chunk-mavranwn.js} +3 -3
- package/dist/{chunk-6rvrx275.js → chunk-mthf5akx.js} +2 -2
- package/dist/{chunk-jb8stg10.js → chunk-mzye1ah2.js} +1 -1
- package/dist/chunk-na4wzne8.js +1 -0
- package/dist/chunk-ntmkzrs8.js +1 -0
- package/dist/{chunk-1p9sjb8d.js → chunk-nxnmqk4s.js} +1 -1
- package/dist/{chunk-mq1mk3v5.js → chunk-p0gbxaqz.js} +1 -1
- package/dist/chunk-pj15kt5b.js +10 -0
- package/dist/chunk-pv1vwasz.js +1 -0
- package/dist/{chunk-mm1atkae.js → chunk-ramana2t.js} +2 -2
- package/dist/{chunk-1pmvyqed.js → chunk-rgjr7jsd.js} +1 -1
- package/dist/{chunk-0qq64xqm.js → chunk-v5503t2t.js} +3 -3
- package/dist/chunk-vda03kxj.js +1 -0
- package/dist/{chunk-cgkbdh2m.js → chunk-vg3zwv4g.js} +1 -1
- package/dist/chunk-vp6d1fqp.js +3 -0
- package/dist/{chunk-xtngc0th.js → chunk-w9z34f27.js} +1 -1
- package/dist/{chunk-nzwh9v6t.js → chunk-wa71vstt.js} +1 -1
- package/dist/{chunk-ffh4c30x.js → chunk-wc9wsyrc.js} +1 -1
- package/dist/{chunk-bdtpq7j9.js → chunk-wxtj6gqb.js} +1 -1
- package/dist/{chunk-zy2etr3v.js → chunk-wxypv01z.js} +2 -2
- package/dist/{chunk-s3a017q7.js → chunk-xg9fyvw0.js} +2 -2
- package/dist/{chunk-fnc97xg7.js → chunk-xt0ktytp.js} +1 -1
- package/dist/{chunk-46jmq302.js → chunk-y6jee9w7.js} +1 -1
- package/dist/{chunk-yacv7f7h.js → chunk-ybc5myz7.js} +1 -1
- package/dist/{chunk-mxe4pr8t.js → chunk-zk9rf1d7.js} +1 -1
- package/dist/web/assets/ChatView-DpvPjAh7.js +63 -0
- package/dist/web/assets/{CodeBlockHighlighter-41xRPXs2.js → CodeBlockHighlighter-Czp4VZIg.js} +1 -1
- package/dist/web/assets/{FilePreview-lcc_hL7J.js → FilePreview-BJWuYfyF.js} +7 -7
- package/dist/web/assets/{KanbanBoard-BHgM338V.js → KanbanBoard-DrYzt5Kh.js} +2 -2
- package/dist/web/assets/{MarkdownRenderer-BMAuTkc6.js → MarkdownRenderer-DxkR5r7t.js} +3 -3
- package/dist/web/assets/{ScrollArea-DJq2Kdpi.js → ScrollArea-D71pJjgW.js} +1 -1
- package/dist/web/assets/{SessionHistorySurface-DSe8ePBJ.js → SessionHistorySurface-2y9bnndm.js} +1 -1
- package/dist/web/assets/{SettingsModal-Cih4bWul.js → SettingsModal-BbaTL5Rk.js} +1 -1
- package/dist/web/assets/{Sidebar-DnWlUKmO.js → Sidebar-COZltpL9.js} +2 -2
- package/dist/web/assets/{TaskSwitcher-D3mrXv_i.js → TaskSwitcher-3giB7l1P.js} +1 -1
- package/dist/web/assets/{TerminalPanel-BNKHhBVM.js → TerminalPanel-gvTTiTgX.js} +1 -1
- package/dist/web/assets/{archive-Dof4YpyT.js → archive-DndqAA2q.js} +1 -1
- package/dist/web/assets/{arrow-left-DGFXaGox.js → arrow-left-XNYfpUAb.js} +1 -1
- package/dist/web/assets/{calendar-clock-BoxUNOvH.js → calendar-clock-BQOfNcCK.js} +1 -1
- package/dist/web/assets/{chevron-right-Brb1rhaA.js → chevron-right-Cvq3LzHK.js} +1 -1
- package/dist/web/assets/{chevrons-up-down-N-VshXV_.js → chevrons-up-down-Dia1U9Sz.js} +1 -1
- package/dist/web/assets/{clock-3-gdZEKe2U.js → clock-3-CnxLS8cv.js} +1 -1
- package/dist/web/assets/{copy-d9M8JUfQ.js → copy-CWCS3Lql.js} +1 -1
- package/dist/web/assets/{download-CQ-Pwfq0.js → download-DXdsM18t.js} +1 -1
- package/dist/web/assets/{external-link-GRAtjoO2.js → external-link-1IN2ZfaO.js} +1 -1
- package/dist/web/assets/{folder-CqLD0IBh.js → folder-Bpq602dI.js} +1 -1
- package/dist/web/assets/index-57UZsfTt.css +1 -0
- package/dist/web/assets/index-DEOQizD2.js +203 -0
- package/dist/web/assets/{pause-BqsFgQi0.js → pause-BYhoGDZq.js} +1 -1
- package/dist/web/assets/{pencil-Ca9289F-.js → pencil-pRZQVHFU.js} +1 -1
- package/dist/web/assets/{play-DmEPnYDS.js → play-DGZdCyPk.js} +1 -1
- package/dist/web/assets/{plus-kIBLgk0p.js → plus-CAQ3qlUJ.js} +1 -1
- package/dist/web/assets/session-events-C5_Q0kZV.js +29 -0
- package/dist/web/assets/{settings-BuSrJl6s.js → settings-BPfzj_Vf.js} +1 -1
- package/dist/web/assets/{teamService-B7Fp8Oyg.js → teamService-BScT9o9A.js} +1 -1
- package/dist/web/assets/{terminal-Qkr_gcNu.js → terminal-CldJbdMr.js} +1 -1
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/chunk-1dscf8xj.js +0 -23
- package/dist/chunk-1n5d6b5k.js +0 -1
- package/dist/chunk-1qdemrkr.js +0 -1
- package/dist/chunk-83nxcfz3.js +0 -1
- package/dist/chunk-9y7j565j.js +0 -6
- package/dist/chunk-acsfh1cw.js +0 -5
- package/dist/chunk-as8stb2j.js +0 -10
- package/dist/chunk-azaqc1b6.js +0 -1
- package/dist/chunk-e1warjkn.js +0 -171
- package/dist/chunk-g13jmewd.js +0 -1
- package/dist/chunk-g7h0peka.js +0 -3
- package/dist/chunk-gq7fdc8c.js +0 -2
- package/dist/chunk-gwjah260.js +0 -1
- package/dist/chunk-n238rdz8.js +0 -1
- package/dist/chunk-nfzad4te.js +0 -2
- package/dist/chunk-pnanbvn3.js +0 -1
- package/dist/chunk-pz91qga3.js +0 -1
- package/dist/chunk-s4b1r3my.js +0 -1
- package/dist/chunk-t6cajkaj.js +0 -6
- package/dist/chunk-tah2002b.js +0 -1
- package/dist/chunk-tzfd2fza.js +0 -1
- package/dist/chunk-v3veeja5.js +0 -1
- package/dist/chunk-vptn8fhx.js +0 -2
- package/dist/chunk-wj813rcc.js +0 -1
- package/dist/web/assets/ChatView-Bc9twpWM.js +0 -63
- package/dist/web/assets/index-CPpIFWLG.css +0 -1
- package/dist/web/assets/index-DiRs2_w4.js +0 -203
- package/dist/web/assets/session-events-BqQQkbAN.js +0 -29
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Mj as S}from"./chunk-g9vdmvk2.js";import{Bk as f}from"./chunk-6e3mh79j.js";import*as $ from"fs/promises";import*as K from"path";import j from"semver";import{ProxyAgent as H,fetch as I}from"undici";function R(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function N(){let q=R();if(q)try{return new H(q)}catch(z){console.warn(`[proxyFetch] Invalid proxy URL: ${q}`)}return}async function M(q,z={}){let{timeout:W=30000,signal:Q,...B}=z;if(Q?.aborted)throw new DOMException("The operation was aborted.","AbortError");let J=N(),X=new AbortController,Y=!1,F=setTimeout(()=>{Y=!0,X.abort()},W),b=()=>X.abort();Q?.addEventListener("abort",b);try{let Z={method:B.method,headers:B.headers,body:B.body,signal:X.signal,dispatcher:J};return await I(q.toString(),Z)}catch(Z){if(Z instanceof Error&&Z.name==="AbortError"){if(Y)throw Error(`Request timeout after ${W}ms`);throw Z}throw Z}finally{clearTimeout(F),Q?.removeEventListener("abort",b)}}var w="blade-code",y="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",G=K.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),O=K.join(G,"version-cache.json"),P=3600000,k=`https://registry.npmjs.org/${w}/latest`;async function L(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;return S()}catch{return"unknown"}}async function T(){try{let q=await $.readFile(O,"utf-8"),z=JSON.parse(q);if(Date.now()-z.checkedAt<P)return z;return{...z,checkedAt:0}}catch{return null}}async function D(q){try{await $.mkdir(G,{recursive:!0,mode:493}),await $.writeFile(O,JSON.stringify(q,null,2))}catch{}}async function x(){try{let q=await M(k,{timeout:5000,headers:{Accept:"application/json"}});if(!q.ok)return null;return(await q.json()).version||null}catch{return null}}async function _(q=!1){let z=await L(),W=y;if(z==="unknown")return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to determine current version"};let Q=await T(),B=Q?.skipUntilVersion,J=null;if(!q&&Q?.latestVersion&&Q.checkedAt>0)J=Q.latestVersion;else if(J=await x(),J)await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});else if(Q?.latestVersion)await D({checkedAt:0,skipUntilVersion:B});if(!J||!j.valid(J))return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to check for updates"};if(j.lt(J,z))J=z,await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});let X=j.gt(J,z),Y=X;if(X&&B)Y=j.gt(J,B);return{currentVersion:z,latestVersion:J,hasUpdate:X,shouldPrompt:Y,releaseNotesUrl:W}}async function u(q){let z=await T();await D({latestVersion:z?.latestVersion??q,checkedAt:z?.checkedAt||Date.now(),skipUntilVersion:q})}function g(){return`npm install -g ${w}@latest --registry https://registry.npmjs.org`}async function C(){let{spawn:q}=await import("child_process");return new Promise((z)=>{let W=g(),Q=q(W,{stdio:"inherit",shell:!0});Q.on("close",(B)=>{if(B===0)z({success:!0,message:"Upgrade successful! Please restart blade."});else z({success:!1,message:`Upgrade failed (exit code: ${B})`})}),Q.on("error",(B)=>{z({success:!1,message:`Upgrade failed: ${B.message}`})})})}async function V(){try{let q=await _();return q.shouldPrompt?q:null}catch{return null}}
|
|
2
2
|
export{_ as k,u as l,g as m,C as n,V as o};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{nc as m4}from"./chunk-wzkh3e6a.js";import{Ad as r4,Bd as n4,Cd as x1,Gd as A6,Pd as I0,Rd as w2,Sd as I1,Td as q2,_d as t$,kd as t6,md as e6,nd as $4,oc as U$,od as tJ,pd as eJ,qc as B$,rc as s6,sc as v1,uc as K$,vd as J4,wd as l4,xd as i4,yd as rJ,zd as d1}from"./chunk-mxe4pr8t.js";import{de as c4}from"./chunk-z3hpstky.js";import{ge as B0,je as I6,ke as k$,ve as j1}from"./chunk-mq1mk3v5.js";import{Wf as U4}from"./chunk-q0s3gcjm.js";import{Xf as p4,Yf as m0,Zf as h4,_f as L6,bg as R1,cg as D2,dg as O6,eg as f6,gg as y6}from"./chunk-acsfh1cw.js";import{$g as A4,Tg as $$,Ug as l0,Xg as d4}from"./chunk-5sknjz9b.js";import{mh as N$}from"./chunk-qm96k94k.js";import{Hi as h1}from"./chunk-gdnyt8a7.js";import{Qi as K0}from"./chunk-jc28ddt0.js";import{wj as k0}from"./chunk-g7h0peka.js";import{Kj as a6}from"./chunk-w2n1vwzg.js";import{Uj as i6,hk as p6,ik as d6,lk as $1,ok as Z6,pk as p1,rk as r6,wk as n6,xk as o6}from"./chunk-na3nregt.js";import{zk as v6}from"./chunk-ntd69c0k.js";function A$($){return $.role==="system"&&Array.isArray($.content)}function y$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class _1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,J){this.context=$;let Z=$.messages.find(A$);if(this._contextualSystemMessages=$.messages.filter(y$),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)=>!A$(W)&&!y$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}get contextRevision(){return this._contextRevision}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!y$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(A$);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)=>!A$(J)&&!y$(J)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(y$),this._history=$.filter((J)=>!A$(J)&&!y$(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 v2($){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 C2($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function I2($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import Q$ from"node:path";var Y5=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"]),V5=/^(LD_.+|DYLD_.+|PATH)$/,u2=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function n$($){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(u2);if(!V)break;let Q=V[1];if(!Y5.has(Q))break;J=Y}return J}function W3($){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(u2);if(!V)break;let Q=V[1];if(V5.test(Q))break;J=Y}return J}var Q5=[/^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 fJ($){let J=$,Z=!0;while(Z){Z=!1;for(let W of Q5){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 o$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let Q=0;Q<$.length;Q++){let K=$[Q];if(V){Z+=K,V=!1;continue}if(K==="\\"&&!W){Z+=K,V=!0;continue}if(K==="'"&&!Y){W=!W,Z+=K;continue}if(K==='"'&&!W){Y=!Y,Z+=K;continue}if(W||Y){Z+=K;continue}if(K==="|"){if(Q+1<$.length&&$[Q+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",Q++;continue}return null}if(K===">"||K==="<")return null;if(K==="&"&&Q+1<$.length&&$[Q+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",Q++;continue}if(K==="&")return null;if(K===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=K}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function g2($){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 Q=$[Y+1];if(Q&&/[A-Za-z_@*#?!$0-9({]/.test(Q))return!0}if(V==="`")return!0;if(Z)continue;if(V==="|")return!0;if(V===">"||V==="<")return!0;if(V==="{"){let Q=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(Q)||/^\{[^}]*\.\.[^}]*\}/.test(Q))return!0}}return!1}function V$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let Q=0;Q<$.length;Q++){let K=$[Q];if(V){Z+=K,V=!1;continue}if(K==="\\"&&!W){if(V=!0,Y){let X=$[Q+1];if(X&&'$`"\\'.includes(X))continue;Z+=K,V=!1}continue}if(K==="'"&&!Y){W=!W;continue}if(K==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(K)){if(Z)J.push(Z),Z="";continue}Z+=K}if(Z)J.push(Z);return J}var K5=new Set(["npm","pnpm","yarn","bun"]),p2=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),X5=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),H5=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function j5($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function d2($){return $.replace(/\s+2>&1\s*$/,"").trim()}function z5($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=V$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let V=Y[1];if(!V||V==="-")return;let Q=Q$.isAbsolute(V)?Q$.resolve(V):Q$.resolve(Z,V);if(!K$.isWithinWorkspace(Q,Z))return;return W[2]?.trim()||void 0}function B5($){let J=[],Z=!1,W=!1,Y=!1;for(let V=0;V<$.length;V++){let Q=$[V];if(Y){Y=!1;continue}if(Q==="\\"&&!Z){Y=!0;continue}if(Q==="'"&&!W){Z=!Z;continue}if(Q==='"'&&!Z){W=!W;continue}if(Q!=="|"||Z||W)continue;if($[V+1]==="|")return;J.push(V)}return J}function U5($){let J=V$($),[Z,W,Y]=J;if(Z!=="head"&&Z!=="tail")return!1;if(J.length===1)return!0;let V=(Q)=>Q!==void 0&&/^[1-9]\d{0,4}$/.test(Q);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 D5($){let J=d2($.replace(H5,"").trim()),Z=B5(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=d2(J.slice(0,W).trim()),V=J.slice(W+1).trim();if(!Y||!U5(V))return;return c2(Y)}function c2($){let Z=o$($)?.at(-1);if(!Z)return $;let W=V$(Z),[Y,V]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&V==="vitest")||W.some((K)=>K==="--configLoader"||K.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function P$($,J){let Z=D5($);if(!Z)return!1;let W=n$(Z),Y=o$(W);if(!Y||g2(W)||/[\r\n]/.test(W))return!1;let V=Y.length===1?Y[0]:z5(W,Y,J);if(!V)return!1;let Q=V$(V);if(Q.length===0||Q.some((z)=>[...X5].some((B)=>z===B||z.startsWith(`${B}=`))))return!1;let[K,X,H]=Q;if(K5.has(K??""))return j5(X==="run"?H:X)||X==="--test";if((K==="npx"||K==="bunx")&&p2.has(X??""))return!0;if(p2.has(K??""))return!0;if(K==="node"&&X==="--test")return!0;if(K==="go"&&["build","test","vet"].includes(X??""))return!0;return K==="cargo"&&["build","check","clippy","test"].includes(X??"")}function X3($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!Q$.isAbsolute($);let Z=Q$.isAbsolute($)?Q$.resolve($):Q$.resolve(J,$);return K$.isWithinWorkspace(Z,J)}var yJ=k0("Agent"),w5=3;function AJ($,J,Z){if($!=="length")return{action:"none"};if(J>=w5)return{action:"truncated"};if(v2(Z)==="stop")return yJ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var q5=[/:\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],G5=/```[\s\S]{50,}```/,m2="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",F5=2;function PJ($,J,Z=!0){if(!$||J>=F5)return{action:"none"};if(!Z&&G5.test($))return{action:"retry",prompt:m2};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(q5.some((Q)=>Q.test(W)))return{action:"retry",prompt:m2};return{action:"none"}}var L5=[/\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}(?:测试|单测|集成测试|检查|构建)/],l2={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},O5={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},f5="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.",y5="Required verification did not run successfully before the retry limit.",A5=3;function r2($,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&&P$(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"&&P$(V,W))$.add(V)}function NJ($,J,Z){if(!$||!L5.some((X)=>X.test($)))return{action:"none"};let W=Object.keys(l2).filter((X)=>l2[X].test($)),Y=[...J],V=W.filter((X)=>!Y.some((H)=>O5[X].test(H)));if(W.length>0?V.length===0:Y.some((X)=>P$(X)))return{action:"none"};if(Z>=A5)return{action:"fail",message:y5};let K=W.length>1&&V.length>0?` Missing successful verification categories: ${V.join(", ")}.`:"";return{action:"retry",prompt:`${f5}${K}`}}var P5=[/\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|子代理|子智能体)/],n2=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function o2($){return typeof $==="string"&&n2.some((J)=>J.test($))}var N5=[/\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|子代理)/],_5=[/\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 b5($){if(typeof $!=="string")return;if(_5.some((J)=>J.test($)))return"multiple-allowed";return N5.some((J)=>J.test($))?"required":void 0}function a$($){for(let J of $){let Z=b5(J);if(Z!==void 0)return Z==="required"}return!1}var E5="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.",S5="Required delegation did not complete before the retry limit.",T5=3;function a2($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((Q)=>Q.trim()).filter(Boolean),Y=a$(W),V=!1;if(!Y)for(let Q of W){if(n2.some((K)=>K.test(Q)))break;if(P5.some((K)=>K.test(Q))){V=!0;break}}if(W.length===0||!Y&&!V||J.has("Task"))return{action:"none"};if(Z>=T5)return{action:"fail",message:S5};return{action:"retry",prompt:E5}}var M5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],R5=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],x5=[/\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 s2($){return x5.reduce((J,Z)=>J.replace(Z," "),$)}function E1($){if(typeof $!=="string")return!1;let J=s2($);return M5.some((Z)=>Z.test(J))}var k5="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.",h5="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.",v5="Required worktree lifecycle did not complete before the retry limit.",C5=3;function t2($,J,Z){if(!$)return{action:"none"};let W=s2($);if(!E1(W))return{action:"none"};let Y=R5.some((Q)=>Q.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>=C5)return{action:"fail",message:v5};return{action:"retry",tool:V,prompt:V==="EnterWorktree"?k5:h5}}var i2=30000;async function _J($){try{let Z=N$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??K0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((V)=>{W=setTimeout(()=>V("timeout"),i2)});try{let V=await Promise.race([Z,Y]);if(V==="timeout")return yJ.warn(`[Loop] Stop hook 超时 (${i2}ms),按 shouldStop: true 处理`),{action:"stop"};let Q=V;if(!Q.shouldStop)return{action:"continue",reason:Q.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return yJ.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function I5($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var u5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function g5($){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 p5($){let J=$;for(let X of u5)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),Q=V.lastIndexOf(" ");return`${(Q>36?V.slice(0,Q):V).trimEnd()}…`}function e2($){return p5(g5($))}import{EventEmitter as d5}from"events";import $6 from"node:path";function bJ($){if(Z6($.sessionId),!$6.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:$6.resolve($.projectPath)}}function J6($){let J=bJ($);return JSON.stringify([J.projectPath,J.sessionId])}function f3($,J){return J6($)===J6(J)}class _$ extends d5{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!_$.instance)_$.instance=new _$;return _$.instance}publish($,J,Z,W){let Y=bJ($);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 s$=_$.getInstance();var s0=k0("Agent"),S1=new Set;async function c5($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(S1.has(Z))return;if(S1.size>=5000)S1.clear();S1.add(Z);try{let W=$.workspaceRoot,Y=await t$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let V=e2(J);if(!V)return;await t$.updateSessionMetadata(Z,Y.projectPath,{title:V}),s$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:V})}catch(W){s0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var EJ=`<turn_aborted>
|
|
1
|
+
import{nc as m4}from"./chunk-wzkh3e6a.js";import{Ad as r4,Bd as n4,Cd as x1,Gd as A6,Pd as I0,Rd as w2,Sd as I1,Td as q2,_d as t$,kd as t6,md as e6,nd as $4,oc as U$,od as tJ,pd as eJ,qc as B$,rc as s6,sc as v1,uc as K$,vd as J4,wd as l4,xd as i4,yd as rJ,zd as d1}from"./chunk-zk9rf1d7.js";import{de as c4}from"./chunk-z3hpstky.js";import{ge as B0,je as I6,ke as k$,ve as j1}from"./chunk-p0gbxaqz.js";import{Wf as U4}from"./chunk-q0s3gcjm.js";import{Xf as p4,Yf as m0,Zf as h4,_f as L6,ag as R1,bg as D2,cg as O6,dg as f6,gg as y6}from"./chunk-a26vtcv5.js";import{Vg as $$,Wg as l0,Zg as d4,bh as A4}from"./chunk-etf3e9kt.js";import{oh as N$}from"./chunk-mavranwn.js";import{Ji as h1}from"./chunk-6xvrrypm.js";import{Si as K0}from"./chunk-g799czsy.js";import{sj as k0}from"./chunk-vp6d1fqp.js";import{Mj as a6}from"./chunk-g9vdmvk2.js";import{Wj as i6,jk as p6,kk as d6,nk as $1,qk as Z6,rk as p1,tk as r6,yk as n6,zk as o6}from"./chunk-0k2x2ae6.js";import{Bk as v6}from"./chunk-6e3mh79j.js";function A$($){return $.role==="system"&&Array.isArray($.content)}function y$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class _1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,J){this.context=$;let Z=$.messages.find(A$);if(this._contextualSystemMessages=$.messages.filter(y$),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)=>!A$(W)&&!y$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}get contextRevision(){return this._contextRevision}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!y$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(A$);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)=>!A$(J)&&!y$(J)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(y$),this._history=$.filter((J)=>!A$(J)&&!y$(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 v2($){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 C2($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function I2($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import Q$ from"node:path";var Y5=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"]),V5=/^(LD_.+|DYLD_.+|PATH)$/,u2=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function n$($){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(u2);if(!V)break;let Q=V[1];if(!Y5.has(Q))break;J=Y}return J}function W3($){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(u2);if(!V)break;let Q=V[1];if(V5.test(Q))break;J=Y}return J}var Q5=[/^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 fJ($){let J=$,Z=!0;while(Z){Z=!1;for(let W of Q5){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 o$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let Q=0;Q<$.length;Q++){let K=$[Q];if(V){Z+=K,V=!1;continue}if(K==="\\"&&!W){Z+=K,V=!0;continue}if(K==="'"&&!Y){W=!W,Z+=K;continue}if(K==='"'&&!W){Y=!Y,Z+=K;continue}if(W||Y){Z+=K;continue}if(K==="|"){if(Q+1<$.length&&$[Q+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",Q++;continue}return null}if(K===">"||K==="<")return null;if(K==="&"&&Q+1<$.length&&$[Q+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",Q++;continue}if(K==="&")return null;if(K===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=K}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function g2($){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 Q=$[Y+1];if(Q&&/[A-Za-z_@*#?!$0-9({]/.test(Q))return!0}if(V==="`")return!0;if(Z)continue;if(V==="|")return!0;if(V===">"||V==="<")return!0;if(V==="{"){let Q=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(Q)||/^\{[^}]*\.\.[^}]*\}/.test(Q))return!0}}return!1}function V$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let Q=0;Q<$.length;Q++){let K=$[Q];if(V){Z+=K,V=!1;continue}if(K==="\\"&&!W){if(V=!0,Y){let X=$[Q+1];if(X&&'$`"\\'.includes(X))continue;Z+=K,V=!1}continue}if(K==="'"&&!Y){W=!W;continue}if(K==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(K)){if(Z)J.push(Z),Z="";continue}Z+=K}if(Z)J.push(Z);return J}var K5=new Set(["npm","pnpm","yarn","bun"]),p2=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),X5=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),H5=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function j5($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function d2($){return $.replace(/\s+2>&1\s*$/,"").trim()}function z5($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=V$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let V=Y[1];if(!V||V==="-")return;let Q=Q$.isAbsolute(V)?Q$.resolve(V):Q$.resolve(Z,V);if(!K$.isWithinWorkspace(Q,Z))return;return W[2]?.trim()||void 0}function B5($){let J=[],Z=!1,W=!1,Y=!1;for(let V=0;V<$.length;V++){let Q=$[V];if(Y){Y=!1;continue}if(Q==="\\"&&!Z){Y=!0;continue}if(Q==="'"&&!W){Z=!Z;continue}if(Q==='"'&&!Z){W=!W;continue}if(Q!=="|"||Z||W)continue;if($[V+1]==="|")return;J.push(V)}return J}function U5($){let J=V$($),[Z,W,Y]=J;if(Z!=="head"&&Z!=="tail")return!1;if(J.length===1)return!0;let V=(Q)=>Q!==void 0&&/^[1-9]\d{0,4}$/.test(Q);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 D5($){let J=d2($.replace(H5,"").trim()),Z=B5(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=d2(J.slice(0,W).trim()),V=J.slice(W+1).trim();if(!Y||!U5(V))return;return c2(Y)}function c2($){let Z=o$($)?.at(-1);if(!Z)return $;let W=V$(Z),[Y,V]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&V==="vitest")||W.some((K)=>K==="--configLoader"||K.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function P$($,J){let Z=D5($);if(!Z)return!1;let W=n$(Z),Y=o$(W);if(!Y||g2(W)||/[\r\n]/.test(W))return!1;let V=Y.length===1?Y[0]:z5(W,Y,J);if(!V)return!1;let Q=V$(V);if(Q.length===0||Q.some((z)=>[...X5].some((B)=>z===B||z.startsWith(`${B}=`))))return!1;let[K,X,H]=Q;if(K5.has(K??""))return j5(X==="run"?H:X)||X==="--test";if((K==="npx"||K==="bunx")&&p2.has(X??""))return!0;if(p2.has(K??""))return!0;if(K==="node"&&X==="--test")return!0;if(K==="go"&&["build","test","vet"].includes(X??""))return!0;return K==="cargo"&&["build","check","clippy","test"].includes(X??"")}function X3($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!Q$.isAbsolute($);let Z=Q$.isAbsolute($)?Q$.resolve($):Q$.resolve(J,$);return K$.isWithinWorkspace(Z,J)}var yJ=k0("Agent"),w5=3;function AJ($,J,Z){if($!=="length")return{action:"none"};if(J>=w5)return{action:"truncated"};if(v2(Z)==="stop")return yJ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var q5=[/:\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],G5=/```[\s\S]{50,}```/,m2="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",F5=2;function PJ($,J,Z=!0){if(!$||J>=F5)return{action:"none"};if(!Z&&G5.test($))return{action:"retry",prompt:m2};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(q5.some((Q)=>Q.test(W)))return{action:"retry",prompt:m2};return{action:"none"}}var L5=[/\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}(?:测试|单测|集成测试|检查|构建)/],l2={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},O5={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},f5="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.",y5="Required verification did not run successfully before the retry limit.",A5=3;function r2($,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&&P$(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"&&P$(V,W))$.add(V)}function NJ($,J,Z){if(!$||!L5.some((X)=>X.test($)))return{action:"none"};let W=Object.keys(l2).filter((X)=>l2[X].test($)),Y=[...J],V=W.filter((X)=>!Y.some((H)=>O5[X].test(H)));if(W.length>0?V.length===0:Y.some((X)=>P$(X)))return{action:"none"};if(Z>=A5)return{action:"fail",message:y5};let K=W.length>1&&V.length>0?` Missing successful verification categories: ${V.join(", ")}.`:"";return{action:"retry",prompt:`${f5}${K}`}}var P5=[/\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|子代理|子智能体)/],n2=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function o2($){return typeof $==="string"&&n2.some((J)=>J.test($))}var N5=[/\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|子代理)/],_5=[/\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 b5($){if(typeof $!=="string")return;if(_5.some((J)=>J.test($)))return"multiple-allowed";return N5.some((J)=>J.test($))?"required":void 0}function a$($){for(let J of $){let Z=b5(J);if(Z!==void 0)return Z==="required"}return!1}var E5="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.",S5="Required delegation did not complete before the retry limit.",T5=3;function a2($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((Q)=>Q.trim()).filter(Boolean),Y=a$(W),V=!1;if(!Y)for(let Q of W){if(n2.some((K)=>K.test(Q)))break;if(P5.some((K)=>K.test(Q))){V=!0;break}}if(W.length===0||!Y&&!V||J.has("Task"))return{action:"none"};if(Z>=T5)return{action:"fail",message:S5};return{action:"retry",prompt:E5}}var M5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],R5=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],x5=[/\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 s2($){return x5.reduce((J,Z)=>J.replace(Z," "),$)}function E1($){if(typeof $!=="string")return!1;let J=s2($);return M5.some((Z)=>Z.test(J))}var k5="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.",h5="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.",v5="Required worktree lifecycle did not complete before the retry limit.",C5=3;function t2($,J,Z){if(!$)return{action:"none"};let W=s2($);if(!E1(W))return{action:"none"};let Y=R5.some((Q)=>Q.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>=C5)return{action:"fail",message:v5};return{action:"retry",tool:V,prompt:V==="EnterWorktree"?k5:h5}}var i2=30000;async function _J($){try{let Z=N$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??K0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((V)=>{W=setTimeout(()=>V("timeout"),i2)});try{let V=await Promise.race([Z,Y]);if(V==="timeout")return yJ.warn(`[Loop] Stop hook 超时 (${i2}ms),按 shouldStop: true 处理`),{action:"stop"};let Q=V;if(!Q.shouldStop)return{action:"continue",reason:Q.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return yJ.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function I5($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var u5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function g5($){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 p5($){let J=$;for(let X of u5)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),Q=V.lastIndexOf(" ");return`${(Q>36?V.slice(0,Q):V).trimEnd()}…`}function e2($){return p5(g5($))}import{EventEmitter as d5}from"events";import $6 from"node:path";function bJ($){if(Z6($.sessionId),!$6.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:$6.resolve($.projectPath)}}function J6($){let J=bJ($);return JSON.stringify([J.projectPath,J.sessionId])}function f3($,J){return J6($)===J6(J)}class _$ extends d5{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!_$.instance)_$.instance=new _$;return _$.instance}publish($,J,Z,W){let Y=bJ($);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 s$=_$.getInstance();var s0=k0("Agent"),S1=new Set;async function c5($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(S1.has(Z))return;if(S1.size>=5000)S1.clear();S1.add(Z);try{let W=$.workspaceRoot,Y=await t$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let V=e2(J);if(!V)return;await t$.updateSessionMetadata(Z,Y.projectPath,{title:V}),s$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:V})}catch(W){s0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var EJ=`<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>`,X$="Tool execution was blocked because its durable call record could not be committed. No tool side effect was started.",W6="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 b$ 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 H$($){return $.executionEngine?.getContextManager()}async function c0($,J,Z,W=null,Y,V={}){let Q=V.required??$.executionEngine!==void 0;try{let K=H$($),X=typeof Z==="string"?Z.trim()!=="":Z.some((H)=>H.type==="text"?H.text.trim()!=="":!0);if(K&&J.sessionId&&X){let H=await K.saveMessage(J.sessionId,"user",Z,W,Y,J.subagentInfo);if(Q&&!H)throw Error("Durable user-message commit returned no identity");if(Y?.clientVisible!==!1)c5(J,Z);return H}if(Q&&J.sessionId&&X)throw Error("Durable user-message storage is unavailable")}catch(K){if(s0.warn("[Loop] 保存用户消息失败:",K),Q)throw new b$("user_message",{cause:K})}return null}async function h0($,J,Z,W,Y,V,Q={}){let K=Q.required??$.executionEngine!==void 0;try{let X=H$($),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(K&&!z)throw Error("Durable assistant-message commit returned no identity");return z}if(K&&J.sessionId&&H)throw Error("Durable assistant-message storage is unavailable")}catch(X){if(s0.warn("[Loop] 保存助手消息失败:",X),K)throw new b$("assistant_message",{cause:X})}return null}async function Y6($,J,Z){try{let W=H$($);if(W&&J.sessionId)return await W.saveMessage(J.sessionId,"system",EJ,Z,void 0,J.subagentInfo)}catch(W){s0.warn("[Loop] 保存中断边界失败:",W)}return null}async function V6($,J,Z,W,Y){try{let V=H$($);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((Q)=>({...Q})))),triggerPaths:[...W]},J.subagentInfo)}catch(V){s0.warn("[Loop] 保存 contextual project rules provenance 失败:",V)}return null}async function SJ($,J,Z,W,Y,V={}){try{let Q=H$($);if(Q&&J.sessionId){let K=await Q.saveToolUse(J.sessionId,Z,W,Y,J.subagentInfo,V.providerToolCallId);if(V.required&&!K)throw Error("Durable tool-use commit returned no identity");return K}if(V.required&&J.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(Q){if(s0.warn("[Loop] 保存工具调用失败:",Q),V.required)throw Q}return null}async function T1($,J,Z,W,Y,V,Q,K,X,H={}){try{let z=H$($);if(z&&J.sessionId){let B=await z.saveToolResult(J.sessionId,Z,W,Y,V,Q,J.subagentInfo,K,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(s0.warn("[Loop] 保存工具结果失败:",z),H.required)throw z}return null}async function e$($,J,Z,W,Y={}){try{let V=H$($);if(V&&J.sessionId){let Q=await V.saveCompaction(J.sessionId,Z,W,null);if(Y.required&&!Q)throw Error("Compaction checkpoint commit returned no identity");return Q||null}if(Y.required&&J.sessionId)throw Error("Compaction checkpoint storage is unavailable")}catch(V){if(s0.warn("[Loop] 保存压缩数据失败:",V),Y.required)throw V}return null}async function G0($){let{deps:J,context:Z,state:W,assistantContent:Y,assistantReasoningContent:V,lastMessageUuid:Q,controlPrompt:K,controlMetadata:X}=$;W.appendAssistant({role:"assistant",content:Y,reasoningContent:V});let H=Q,z=await h0(J,Z,Y,H,V);if(z)H=z;if(K!==void 0){let B={role:"user",content:K};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 G2}from"node:crypto";import{promises as V8}from"node:fs";import Q8 from"node:path";import{nanoid as t0}from"nanoid";import*as Y0 from"node:fs/promises";import*as j$ from"node:path";var Q6={enabled:!0,maxIndexLines:200};var m5="memory",K6="MEMORY.md";class TJ{memoryDir;config;initialized=!1;constructor($,J,Z){if(Z)this.memoryDir=Z;else{let W=$1($);this.memoryDir=j$.join(W,m5)}this.config={...Q6,...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 $=j$.join(this.memoryDir,K6);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: ${K}`}catch{return`${J}
|
|
|
83
83
|
|
|
84
84
|
${Y}`}}import n8 from"node:path";import{nanoid as o8}from"nanoid";import{randomUUID as Q1}from"node:crypto";import*as v0 from"node:fs/promises";import*as u6 from"node:path";import{Mutex as R8}from"async-mutex";import x8 from"write-file-atomic";var k6=120,cJ=128;function V1($){if(!Array.isArray($)||$.length>120||!$.every((J)=>typeof J==="string"&&J.length>0&&J.length<=128))return;return[...new Set($)]}function b8($){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=V1(J.inputMessageIds),W=V1($.acknowledgedInputMessageIds);if(!Z||!W)return[];let Y=new Set(Z);return W.filter((V)=>Y.has(V))}function k1($,J){let Z=$[J];if(Z?.type!=="turn_aborted")return[];let W=b8(Z.data);if(W.length===0)return[];let Y=-1;for(let Q=J-1;Q>=0;Q--){let K=$[Q];if(K.type==="turn_started"){if(K.data.turnId!==Z.data.turnId)return[];Y=Q;break}if(K.type==="turn_completed"||K.type==="turn_aborted")return[]}if(Y<0)return[];let V=new Set;for(let Q=Y+1;Q<J;Q++){let K=$[Q];if(K.type!=="message_created"||K.data.role!=="user")continue;let X=K.data.metadata,H=K.data.inboxMessageId!==void 0?K.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((Q)=>V.has(Q))}import*as C1 from"node:fs/promises";import*as C6 from"node:path";var E8={realpath:!1,retries:{retries:150,factor:1.2,minTimeout:10,maxTimeout:100,randomize:!0}},S8=new h1,h6;async function R$($,J,Z,W=M8){let Y=B$($,J);return S8.runExclusive(Y,()=>v1($,J,async(V)=>{let Q=C6.dirname(V.inboxPath);await C1.mkdir(Q,{recursive:!0,mode:448}),await C1.chmod(Q,448);let K,X=await W(V.inboxPath,{...E8,onCompromised:(H)=>{K=H}});try{if(K)throw K;let H=await Z(V);if(K)throw K;return H}finally{await X()}}))}async function T8(){return h6??=await import("proper-lockfile"),h6}async function M8($,J){return(await T8()).lock($,J)}var iJ=2,x$=8388608;function mJ($,J,Z){let W={version:iJ,sessionId:$,generation:J,messages:Z.map(({recovered:Y,...V})=>V)};return`${JSON.stringify(W)}
|
|
85
85
|
`}function lJ($,J){return $ instanceof Error&&"code"in $&&$.code===J}function k8($){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 h8($,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!==1&&W.version!==iJ||!("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)||!k8(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"&&V.origin!=="interaction_recovery"&&V.origin!=="user_shell"||"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 Q="outputSchema"in V&&V.outputSchema!==void 0?I1(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))}:{},...Q?{outputSchema:Q}:{}}});if(new Set(Y.map((V)=>V.id)).size!==Y.length)throw Error(`Duplicate steering inbox message: ${J}`);if(W.version===1)return{version:1,sessionId:Z,messages:Y};if(!("generation"in W)||typeof W.generation!=="string"||!/^[a-f0-9-]{36}$/.test(W.generation))throw Error(`Invalid steering inbox generation: ${J}`);return{version:iJ,sessionId:Z,generation:W.generation,messages:Y}}function v8($){return new Set($.flatMap((J,Z)=>{if(J.type==="inbox_acknowledged")return J.data.messageIds;if(J.type==="turn_aborted")return k1($,Z);return[]}))}function C8($){return new Set($.flatMap((J)=>{if(J.type!=="message_created"||J.data.role!=="user")return[];let Z=J.data.metadata,W=J.data.inboxMessageId!==void 0?J.data.inboxMessageId:Z!==null&&typeof Z==="object"&&!Array.isArray(Z)?Z.inboxMessageId:void 0;return typeof W==="string"?[W]:[]}))}class u1{sessionId;stateStorage;writeFile;lockFile;mutex=new R8;generation=Q1();messages=[];constructor($,J,Z,W){this.sessionId=$;this.stateStorage=J;this.writeFile=Z;this.lockFile=W}static async open($,J,Z=U$($),W={}){let Y=new u1(J,Z,W.writeFile??x8,W.lockFile);return await Y.loadAndReconcile(),Y}async enqueue($,J){return this.mutex.runExclusive(async()=>{let Z=await R$(this.stateStorage,this.sessionId,async(W)=>{let Y=await this.readAndReconcileAtPath(W);if(Y.messages.some((X)=>X.id===$.id))return{accepted:!0,snapshot:Y};if(J&&!J(Y.messages))return{accepted:!1,snapshot:Y};let V=[...Y.messages,{...$,recovered:!1}],Q=Q1(),K=mJ(this.sessionId,Q,V);if(Buffer.byteLength(K)>x$)return{accepted:!1,snapshot:Y};return await this.persistAtPath(V,Q,W,K),{accepted:!0,snapshot:{generation:Q,messages:V}}},this.lockFile);return this.install(Z.snapshot),Z.accepted})}async acknowledge($){if($.length===0)return;let J=new Set($);await this.mutex.runExclusive(async()=>{let Z=await R$(this.stateStorage,this.sessionId,async(W)=>{let Y=await this.readAndReconcileAtPath(W),V=Y.messages.filter((K)=>!J.has(K.id));if(V.length===Y.messages.length&&!Y.acknowledgedRemoved)return Y;let Q=Q1();return await this.persistAtPath(V,Q,W),{generation:Q,messages:V}},this.lockFile);this.install(Z)})}snapshot(){return{generation:this.generation,messages:this.list()}}async refresh(){return this.mutex.runExclusive(async()=>{let $=await R$(this.stateStorage,this.sessionId,(J)=>this.readAndReconcileAtPath(J),this.lockFile);return this.install($),this.snapshot()})}async replace($,J){return this.mutex.runExclusive(async()=>{let Z=await R$(this.stateStorage,this.sessionId,async(W)=>{let Y=await this.readAndReconcileAtPath(W);if(Y.generation!==$)return{replaced:!1,snapshot:Y};let V=Q1(),Q=J.map((X)=>({...X})),K=mJ(this.sessionId,V,Q);if(Buffer.byteLength(K)>x$)return{replaced:!1,snapshot:Y};return await this.persistAtPath(Q,V,W,K),{replaced:!0,snapshot:{generation:V,messages:Q}}},this.lockFile);return this.install(Z.snapshot),{replaced:Z.replaced,snapshot:this.snapshot()}})}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()=>{let $=await R$(this.stateStorage,this.sessionId,async(J)=>{let Z=await this.readAndReconcileAtPath(J);if(Z.migrationRequired||Z.acknowledgedRemoved){let W=Q1();return await this.persistAtPath(Z.messages,W,J),{generation:W,messages:Z.messages}}return Z},this.lockFile);this.install($)})}install($){this.generation=$.generation,this.messages=$.messages}async readAndReconcileAtPath($){let J;try{let Q=await v0.open($.inboxPath,"r");try{if((await Q.stat()).size>x$)throw Error(`Steering inbox exceeds ${x$} bytes: ${$.inboxPath}`);J=h8(await Q.readFile("utf8"),$.inboxPath,this.sessionId)}finally{await Q.close()}await v0.chmod($.inboxPath,384)}catch(Q){if(!lJ(Q,"ENOENT"))throw Q}let Z=new Set,W=new Set;try{let Q=I6(await v0.readFile($.transcriptPath,"utf8"),$.transcriptPath);Z=v8(Q),W=C8(Q)}catch(Q){if(!lJ(Q,"ENOENT"))throw Q}let Y=new Map(this.messages.map((Q)=>[Q.id,Q.recovered])),V=(J?.messages??[]).filter((Q)=>!Z.has(Q.id)).map((Q)=>({...Q,recovered:Y.get(Q.id)??!0,...Q.persisted===!0||W.has(Q.id)?{persisted:!0}:{}}));return{generation:J?.version===2?J.generation:this.generation,messages:V,...J?.version===1&&V.length>0?{migrationRequired:!0}:{},...J&&V.length!==J.messages.length?{acknowledgedRemoved:!0}:{}}}async persistAtPath($,J,Z,W){if(await v0.mkdir(u6.dirname(Z.inboxPath),{recursive:!0,mode:448}),$.length===0){await v0.unlink(Z.inboxPath).catch((V)=>{if(!lJ(V,"ENOENT"))throw V});return}let Y=W??mJ(this.sessionId,J,$);if(Buffer.byteLength(Y)>x$)throw Error(`Steering inbox exceeds ${x$} bytes: ${Z.inboxPath}`);await this.writeFile(Z.inboxPath,Y,{encoding:"utf8",mode:384,fsync:!0})}}import*as C0 from"node:fs/promises";import*as Z4 from"node:path";import{nanoid as j0}from"nanoid";var g6=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=U$(J)){let W=B$(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=U$(J)){F0.instances.delete(B$(Z,$))}static pruneIdleInstances($){if(F0.instances.size<=g6)return;for(let[J,Z]of F0.instances){if(J===$||Z.subscribers.size>0)continue;if(F0.instances.delete(J),F0.instances.size<=g6)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?.($);s$.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 Q=Y?await W.readAllValidated(Y):await W.readAll();return V(Q),Q.filter((K)=>(K.seq??0)>=J)});for(let W of Z){if(rJ(W))continue;await $.onCommitted(W)}}record($){if(typeof $.seq==="number"&&$.seq>this.highestSeq)this.highestSeq=$.seq;if(rJ($))return;for(let J of this.subscribers){let Z=J.onCommitted($);if(Z)Promise.resolve(Z).catch(()=>{return})}s$.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 v1(this.storage,this.sessionId,async(J)=>{let Z=new k$(J.transcriptPath);if(!J.remoteScope)return $(Z,void 0,()=>{return});let W=J.remoteScope;return $(Z,{noFollow:!0,validateHandle:async(Q)=>{await p6(W,J.transcriptPath,Q)}},(Q)=>{d6(Q,this.sessionId,this.projectPath,this.storage.kind==="acp-remote"?this.storage.descriptor:void 0)})})}}function D$($){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 I8="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 nJ($,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 c6($,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,Q=Y.data.inboxMessageId!==void 0?Y.data.inboxMessageId:V!==null&&typeof V==="object"&&!Array.isArray(V)?V.inboxMessageId:void 0;if(typeof Q==="string"&&Q.length>0&&Q.length<=cJ)W.push(Q)}return[...new Set(W)]}function W4($){if(!$||typeof $!=="object"||Array.isArray($))return;if(!("version"in $)||$.version!==1&&$.version!==2&&$.version!==3)return;let J="inputMessageIds"in $?V1($.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 u8($,J){let Z=$.findLastIndex((K)=>K.type==="turn_started"&&K.data.turnId===J);if(Z<0)return 0;let W=$.findIndex((K,X)=>X>Z&&K.type==="turn_started"&&K.data.turnId!==J),Y=$.slice(Z+1,W<0?void 0:W),V=new Set(Y.flatMap((K)=>{if(K.type!=="part_created"||K.data.partType!=="tool_call")return[];let X=K.data.payload;return X&&typeof X==="object"&&!Array.isArray(X)?[typeof X.toolCallId==="string"?X.toolCallId:K.data.partId]:[K.data.partId]})),Q=new Set;for(let K of Y){if(K.type!=="part_created"||K.data.partType!=="tool_result")continue;let X=K.data.payload;if(!X||typeof X!=="object"||Array.isArray(X))continue;let H=typeof X.toolCallId==="string"?X.toolCallId:K.data.partId,z=X.metadata;if(V.has(H)&&z&&typeof z==="object"&&!Array.isArray(z)&&z.processRestartRecovery===!0&&z.sideEffectsUncertain===!0)Q.add(H)}return Q.size}function Y4($){return new Set($.flatMap((J,Z)=>{if(J.type==="inbox_acknowledged")return J.data.messageIds;if(J.type==="turn_aborted")return k1($,Z);return[]}))}function oJ($,J,Z=[]){let W=W4(J.data.recovery);if(!W)return;if($.some((K)=>K.type==="turn_recovery_acknowledged"&&K.data.turnId===J.data.turnId))return;let Y=Y4($);for(let K of Z)Y.add(K);let V=W.inputMessageIds.filter((K)=>!Y.has(K)),Q=W.version===1?u8($,J.data.turnId):W.interruptedToolCallCount;if(V.length===0&&!W.hadSuccessfulToolResult&&Q===0)return;return{turnId:J.data.turnId,outcome:"aborted",inputMessageIds:V,hadSuccessfulToolResult:W.hadSuccessfulToolResult,...Q>0?{interruptedToolCallCount:Q}:{},...W.version===3&&W.allSuccessfulToolResultsSafeForResume===!0?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:W.emptyFinalCorrectionSpent}}function K1($){for(let J=$.length-1;J>=0;J--){let Z=$[J];if(Z.type!=="turn_aborted")continue;let W=oJ($,Z);if(W)return W}return}function g1($,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:Q,description:K}=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 K==="string"&&Y.subagentDescription===K&&W.description===K&&(Q===void 0||typeof Q==="string"&&Q===Y.subagentType)&&W.subagentType===Y.subagentType&&W.subagentStatus===Y.subagentStatus&&X&&W.processRestartRecovery===!0&&W.subagentResultAdopted===!0&&W.sideEffectsUncertain===!1}var g8=1e4,p8=1e5,d8=2592000000,m6=128,c8=1e6,m8=256;function l8($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(typeof J.goalId!=="string"||J.goalId.length===0||J.goalId.length>m6||typeof J.verificationAttempt!=="number"||!Number.isSafeInteger(J.verificationAttempt)||J.verificationAttempt<1||J.verificationAttempt>c8||typeof J.verifierSessionId!=="string"||J.verifierSessionId.length===0||J.verifierSessionId.length>m6||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 V4($,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,Q=Y.inputMessageIds,K=Y.turnsCount,X=Y.toolCallsCount,H=Y.durationMs,z=Array.isArray(Q)?Q.filter((j)=>typeof j==="string"&&j.length>0&&j.length<=cJ):[];if(typeof V!=="string"||V.length===0||V.length>128||J!==void 0&&V!==J||!Array.isArray(Q)||Q.length>k6||z.length!==Q.length||typeof K!=="number"||!Number.isSafeInteger(K)||K<0||K>g8||typeof X!=="number"||!Number.isSafeInteger(X)||X<0||X>p8||typeof H!=="number"||!Number.isSafeInteger(H)||H<0||H>d8)return;let B;if("goalFinalization"in Y){if(B=l8(Y.goalFinalization),!B)return}return{turnId:V,inputMessageIds:[...new Set(z)],turnsCount:K,toolCallsCount:X,durationMs:H,...B?{goalFinalization:B}:{}}}function l6($,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=V4(Y,J);if(V)return V}return}function i8($){for(let J=$.length-1;J>=0;J--){let Z=$[J];if(Z?.type!=="message_created")continue;let W=V4(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 h$($,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,Q=new Set;for(let X of $.slice(Z+1)){if(X.type==="interaction_requested"){Q.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 K=[...W.values()];return{all:K,orphaned:K.filter((X)=>!Y.has(X.toolCallId)&&!Q.has(X.toolCallId)),hadSuccessfulResult:K.some((X)=>V.has(X.toolCallId))}}class _0{static sessionInitializationRuns=new Map;projectPath;maxSessions;version;stateStorage;initializedSessions=new Set;constructor($=K0(),J=100,Z=a6(),W=U$($)){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:n6(this.projectPath)}:{},version:this.version,data:Z}}log($){return F0.for($,this.projectPath,this.stateStorage)}async ensureSessionCreated($,J){let Z=B$(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>m8){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},Q=this.createEvent("session_created",$,V);await this.log($).commit(Q)}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=e6;return J}async initialize(){try{await s6(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,Q){try{await this.ensureSessionCreated($,V);let K=new Date().toISOString(),X=j0(),H={messageId:X,role:J,parentMessageId:W??void 0,inboxMessageId:Y?.inboxMessageId,createdAt:K,model:Y?.model,usage:Y?.usage,metadata:Y?JSON.parse(JSON.stringify(Y)):void 0},z=this.createEvent("message_created",$,H),B=J==="assistant"&&Q?.trim()?[this.createEvent("part_created",$,{partId:j0(),messageId:X,partType:"reasoning",payload:{text:Q},createdAt:K})]:[],j=typeof Z==="string"?[this.createEvent("part_created",$,{partId:j0(),messageId:X,partType:"text",payload:{text:Z},createdAt:K})]: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:r8(U.image_url.url)??"image/png",dataUrl:U.image_url.url},createdAt:K}));return await this.log($).commitBatch([z,...B,...j]),X}catch(K){throw console.error(`[PersistentStore] 保存消息失败 (session: ${$}):`,K),K}}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||!oJ(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)),Q=Y.find((j)=>j.type==="message_created"&&j.data.inboxMessageId===J.inboxMessageId),K=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(!K)return Z={eligible:!1,acknowledged:V,persisted:!1,...Q?{messageId:Q.data.messageId}:{}},[];if(V)return Z={eligible:!0,acknowledged:!0,persisted:!1,...Q?{messageId:Q.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(Q&&X)return Z={eligible:!0,acknowledged:!1,persisted:!1,messageId:Q.data.messageId},[];let H=new Date().toISOString(),z=Q?.data.messageId??j0(),B=[];if(!Q){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===K.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:K.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=D$(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:[])),Q=[...new Set(Z)].filter((H)=>!V.has(H)),K=Y.findLast((H)=>(H.type==="turn_completed"||H.type==="turn_aborted")&&H.data.turnId===J.turnId);if(K){if(K.type==="turn_aborted"||Q.length===0)throw new N0;return[this.createEvent("inbox_acknowledged",$,{messageIds:Q,acknowledgedAt:J.completedAt})]}let X=D$(Y).active;if(!X||X.turnId!==J.turnId)throw Error(`Turn is not active: ${J.turnId}`);return[...Q.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:Q,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=V1(W);if(!Y)throw Error("Invalid turn abort acknowledgement input message IDs");let V=Y;await this.ensureSessionCreated($);let Q,K=[];try{await this.log($).commitValidatedBatch((X)=>{let H=B0(X),z=Y4(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 Q=void 0,K=[],new N0;let i=W4(B.data.recovery),L0=i?V.filter((y0)=>i.inputMessageIds.includes(y0)):[],S=L0.filter((y0)=>!z.has(y0));if(K=L0,Q=oJ(H,B,L0),S.length===0)throw new N0;return[this.createEvent("inbox_acknowledged",$,{messageIds:S,acknowledgedAt:J.abortedAt})]}let j=D$(H).active;if(!j||j.turnId!==J.turnId)throw Error(`Turn is not active: ${J.turnId}`);let U=h$(H,j.turnId),P=c6(H,j.turnId),_=K1(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:nJ(H,j.turnId)||J.recovery?.emptyFinalCorrectionSpent===!0};Q={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));K=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;Q=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{...Q?{recovery:Q}:{},acknowledgedInputMessageIds:K}}async loadInterruptedToolCalls($){let J=await this.loadEvents($);if(!J)return[];let Z=B0(J),W=D$(Z).active;return W?h$(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=D$(Z).active;if(W){let Y=h$(Z,W.turnId);if(Y.orphaned.length>0||Y.hadSuccessfulResult)return!0;if(l6(Z,W.turnId))return!0}return K1(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=D$(Y).active,Q=h$(Y);if(!V&&Q.orphaned.length===0){if(Z=K1(Y),Z)return[];throw new N0}let K=V?l6(Y,V.turnId):void 0;if(V&&K&&Q.orphaned.length===0){let E=h$(Y,V.turnId);Z={turnId:V.turnId,outcome:"completed",inputMessageIds:K.inputMessageIds,hadSuccessfulToolResult:E.hadSuccessfulResult,emptyFinalCorrectionSpent:nJ(Y,V.turnId),finalization:K};let l=new Set(Y.flatMap((I)=>I.type==="inbox_acknowledged"?I.data.messageIds:[])),g=K.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:K.turnsCount,toolCallsCount:K.toolCallsCount,durationMs:K.durationMs})]}let X=V?h$(Y,V.turnId):void 0,H=X?.orphaned.some((E)=>{let l=J.adoptedToolResults?.get(E.toolCallId);return g1(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)=>g1(E,J.adoptedToolResults?.get(E.toolCallId)))??!0,B=new Set(V?.inputMessageIds??[]),j=V?K1(Y):void 0,U=j?j.inputMessageIds.filter((E)=>B.has(E)):[],P=U.length>0,_=V?c6(Y,V.turnId):[],k=X?X.orphaned.filter((E)=>{let l=J.adoptedToolResults?.get(E.toolCallId);return!g1(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:nJ(Y,V.turnId)||P&&j?.emptyFinalCorrectionSpent===!0}:K1(Y);let d=V?X?.all.length??0:0,x=new Date().toISOString(),o=V?Date.parse(V.startedAt):Number.NaN,G=Q.orphaned.flatMap((E)=>{let l=J.adoptedToolResults?.get(E.toolCallId),g=g1(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:I8,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?i8(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((Q)=>Q.type==="review_completed"&&Q.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 Q=new Date().toISOString(),K=W??j0(),X=[];if(!W){let B={messageId:K,role:"assistant",parentMessageId:void 0,createdAt:Q};X.push(this.createEvent("message_created",$,B))}let H=V??j0(),z={partId:H,messageId:K,partType:"tool_call",payload:{toolCallId:H,toolName:J,input:Z},createdAt:Q};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:K,partType:"subtask_ref",payload:{childSessionId:j,agentType:U,status:"running",summary:typeof B.description==="string"?B.description:"",startedAt:Q},createdAt:Q};X.push(this.createEvent("part_created",$,P))}}return await this.log($).commitBatch(X),H}catch(Q){throw console.error(`[PersistentStore] 保存工具调用失败 (session: ${$}):`,Q),Q}}async saveToolResult($,J,Z,W,Y=null,V,Q,K,X){try{await this.ensureSessionCreated($,Q);let H=new Date().toISOString(),z=Y??j0();return await this.log($).commitValidatedBatch((B)=>{let j=K?.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===K.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)),K&&!j){let h=K.subagentStatus==="running"?null:H,d={partId:j0(),messageId:z,partType:"subtask_ref",payload:{childSessionId:K.subagentSessionId,agentType:K.subagentType,description:K.subagentDescription??"",status:K.subagentStatus,summary:K.subagentSummary??"",resumedFrom:K.subagentResumedFrom??null,rootAgentId:K.subagentRootId??K.subagentSessionId,resumeDepth:K.subagentResumeDepth??0,verificationVerdict:K.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(),Q={messageId:V,role:"system",parentMessageId:W??void 0,createdAt:Y},K=this.buildCompactionMetadata(Z),X={partId:j0(),messageId:V,partType:"summary",payload:{text:J,metadata:K,...Z.replacementMessages?{replacementMessages:$4(Z.replacementMessages)}:{}},createdAt:Y},H=[this.createEvent("message_created",$,Q),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=d1([]),W=await this.log($).commitValidatedBatch((V)=>{if(Z=d1(B0(V)),Z.kind!=="none")return[];let Q=new Date().toISOString();return[this.createEvent("token_budget_handoff_recorded",$,{...J,messageId:`${J4}${j0()}`,createdAt:Q})]});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=d1(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 Q of J){if(Q.type==="message_created")Z.set(Q.data.messageId,{id:Q.data.messageId,role:Q.data.role,content:"",timestamp:new Date(Q.timestamp).getTime()});if(Q.type==="part_created"&&Q.data.partType==="text"){let K=Z.get(Q.data.messageId);if(K){let X=Q.data.payload;K.content=X.text??""}}if(Q.type==="part_created"&&Q.data.partType==="image"){let K=Z.get(Q.data.messageId);if(K)K.content=K.content?`${K.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 $=$1(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=p1(this.projectPath,$),Z=new k$(J);if(!(await Z.getStats()).exists)return null;let Y=await Z.readAll();if(Y.length===0)return null;let V=B0(Y),Q=Y[Y.length-1],K=V.filter((X)=>X.type==="message_created"&&["user","assistant"].includes(X.data.role)).length;return{sessionId:$,lastActivity:new Date(Q.timestamp).getTime(),messageCount:K,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=p1(this.projectPath,$);await new k$(J).delete(),await C0.unlink(r6(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W}),await t6(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 $=$1(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=p1(this.projectPath,$),Z=new k$(J);if(!(await Z.getStats()).exists)return null;let Y=await Z.readAll();if(Y.length===0)return null;let V=B0(Y),Q=Y[Y.length-1],K=V.filter((X)=>X.type==="message_created"&&["user","assistant"].includes(X.data.role)).length;return{sessionId:$,lastActivity:new Date(Q.timestamp).getTime(),messageCount:K,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=p1(this.projectPath,$);await new k$(J).delete(),await C0.unlink(r6(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W}),await t6(this.projectPath,$,i6());try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-na4wzne8.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=p1(this.projectPath,Z),V=await new k$(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 $=$1(this.projectPath);await C0.mkdir($,{recursive:!0,mode:493});let J=Z4.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 o6()}}function r8($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}var Q4=131072,aJ=new h1;function sJ($,J){return`${n8.resolve($)}\x00${J}`}function $2($,J){let Z=JSON.stringify($);if(Z===void 0)throw Error(`${J} is not JSON serializable`);if(Buffer.byteLength(Z,"utf8")>Q4)throw Error(`${J} exceeds ${Q4} bytes`);return JSON.parse(Z)}function K4($){if($.type==="askUserQuestion")return"question";if($.type==="mcpElicitation")return"elicitation";if($.type==="permission"||$.type==="mcpSampling")return"permission";return}function a8($,J){return JSON.stringify($)===JSON.stringify(J)}function s8($,J){if($.request.interactionType!=="elicitation")return $2(J,"Interaction response");return $2({approved:J.approved,...J.reason?{reason:J.reason}:{},...J.elicitation?{elicitation:{action:J.elicitation.action}}:{},...J.openExternalUrl?{openExternalUrl:!0}:{}},"Interaction response")}function X4($){let J=$.request.details;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid durable interaction details: ${$.request.requestId}`);return J}function t8($){let J=$.response?.response;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid durable interaction response: ${$.request.requestId}`);return J}function e8($){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 $Z($,J){let{request:Z}=$;if(Z.interactionType==="question"){let Q=e8(J);return{toolOutput:`User answers:
|
|
88
88
|
${Q}`,inbox:`The process restarted while waiting for a structured answer. The recovered user response is:
|
|
89
89
|
${Q}
|
|
@@ -109,7 +109,7 @@ When facing complex multi-step tasks:
|
|
|
109
109
|
3. If a step fails, diagnose the root cause rather than repeating the same approach.
|
|
110
110
|
4. When uncertain about file paths or project structure, use Grep/Glob/Read to gather facts first.
|
|
111
111
|
5. Prefer the smallest change that achieves the goal — avoid unnecessary refactoring.`}`}var w$=k0("Agent"),kZ=new Set(["Read","Glob","Grep","WebFetch","WebSearch","MemoryRead","ReadPromptArtifact","GetSpecContext","ValidateSpec","TaskOutput"]);class a1{pipeline;execContext;registry;contextMgr;sessionId;lastMessageUuid;subagentInfo;progressSink;requireDurableToolUse;pending=new Map;completed=new Map;queued=[];order=[];dispatched=new Set;abortController=new AbortController;hasExclusiveBarrier=!1;epoch=0;activeAborts=new Map;executeTool;admitTool;rollbackAdmission;turnAdmission=new X1;toolUsePersistenceTail=Promise.resolve();constructor($,J,Z,W,Y,V,Q,K,X=!1){this.pipeline=$;this.execContext=J;this.registry=Z;this.contextMgr=W;this.sessionId=Y;this.lastMessageUuid=V;this.subagentInfo=Q;this.progressSink=K;this.requireDurableToolUse=X}setExecutionPolicy($){this.executeTool=$}setAdmissionPolicy($){this.admitTool=$}setAdmissionRollback($){this.rollbackAdmission=$}addTool($,J){if(this.dispatched.has($.id))return w$.debug(`[StreamingToolExecutor] 跳过已分发工具: ${$.function.name} (${$.id})`),"rejected";this.dispatched.add($.id),this.order.push($.id);let Z=this.turnAdmission.admit();if(Z)return this.completed.set($.id,{toolCall:$,result:Z,toolUseUuid:null}),"rejected";H1($.function.name,J),$.function.arguments=JSON.stringify(J);let W=this.admitTool?.($.function.name,J);if(W)return this.completed.set($.id,{toolCall:$,result:W,toolUseUuid:null}),"rejected";let Y=this.registry.get($.function.name),V=Y?.isConcurrencySafe===!0,Q=Y?.parallelism==="shared"||Y?.parallelism===void 0&&V;if(kZ.has($.function.name)&&V&&!this.hasExclusiveBarrier){w$.debug(`[StreamingToolExecutor] 立即执行预启动工具: ${$.function.name}`);let X=this.executeOne($,J);return this.pending.set($.id,X),"prelaunched"}else{if(w$.debug(`[StreamingToolExecutor] 排队非预启动工具: ${$.function.name}`),this.queued.push({toolCall:$,params:J}),!Q)this.hasExclusiveBarrier=!0;return"queued"}}getQueuedToolCalls(){return this.queued.map(($)=>$.toolCall)}async*getRemainingResults(){this.dispatchQueuedTools();for(let $ of this.order){if(this.completed.has($)){yield this.completed.get($),this.completed.delete($);continue}if(this.pending.has($)){let J=await this.pending.get($);this.pending.delete($),yield J;continue}}}getCompletedResults(){let $=Array.from(this.completed.values());return this.completed.clear(),$}discard(){for(let $ of this.queued)this.rollbackAdmission?.($.toolCall.function.name);this.epoch++,this.abortController.abort(),this.abortController=new AbortController;for(let[,$]of this.activeAborts)$.abort();this.activeAborts.clear(),this.queued=[],this.order=[],this.dispatched.clear(),this.completed.clear(),this.pending.clear(),this.hasExclusiveBarrier=!1,this.turnAdmission.reset(),this.toolUsePersistenceTail=Promise.resolve(),w$.debug(`[StreamingToolExecutor] 已丢弃所有挂起工作并重置状态 (epoch=${this.epoch})`)}hasTools(){return this.order.length>0}getEpoch(){return this.epoch}makeAbortResult($,J,Z=null){return{toolCall:$,result:{success:!1,llmContent:"",error:{type:"execution_error",message:J},metadata:{abortedBeforeLaunch:!0}},toolUseUuid:Z}}dispatchQueuedTools(){let $=this.queued;this.queued=[],this.hasExclusiveBarrier=!1;let J=this.epoch;for(let{toolCall:Z,params:W}of $){if(this.execContext.signal?.aborted){this.completed.set(Z.id,this.makeAbortResult(Z,"Tool execution skipped: task aborted before launch"));continue}let Y=this.executeQueued(Z,W,J);this.pending.set(Z.id,Y)}}async executeQueued($,J,Z){if(Z!==this.epoch)return this.makeAbortResult($,"Tool execution aborted due to epoch mismatch (discard)");if(this.execContext.signal?.aborted)return this.makeAbortResult($,"Tool execution skipped: task aborted before launch");return this.executeOne($,J)}async executeOne($,J){let Z=this.epoch,W=new AbortController;this.activeAborts.set($.id,W);let Y=null,V=this.abortController.signal;try{if(V.aborted||W.signal.aborted)return this.makeAbortResult($,"Tool execution aborted due to discard");try{if(this.contextMgr&&this.sessionId)Y=await this.persistToolUseInOrder($,J);else if(this.requireDurableToolUse&&this.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(j){if(w$.warn("[StreamingToolExecutor] 保存工具调用失败:",j),!this.requireDurableToolUse)Y=null;else return{toolCall:$,result:{success:!1,llmContent:X$,error:{type:"execution_error",message:X$},metadata:{durableToolUseFailed:!0,summary:"Blocked tool before execution"}},toolUseUuid:null,error:j instanceof Error?j:Error(String(j))}}let Q=[V,W.signal],K=this.execContext.signal;if(K)Q.push(K);let X=h4(...Q),H={...this.execContext,messageId:Y??$.id,signal:X,confirmationHandler:this.execContext.sessionId&&this.execContext.workspaceRoot&&this.execContext.workspaceKind!=="acp-remote"?U0.createConfirmationHandler(this.execContext.confirmationHandler,{sessionId:this.execContext.sessionId,projectPath:this.execContext.workspaceRoot,toolCallId:Y??$.id,toolName:$.function.name}):this.execContext.confirmationHandler,onProgress:(j)=>{this.execContext.onProgress?.(j),this.progressSink?.($,{message:j.slice(0,1000)})},onProgressUpdate:(j)=>{this.execContext.onProgressUpdate?.(j),this.progressSink?.($,j)}},z=this.executeTool?await this.executeTool($.function.name,J,H):await this.pipeline.execute($.function.name,J,H);if(Z!==this.epoch)return w$.debug(`[StreamingToolExecutor] 丢弃旧世代工具结果: ${$.function.name} (startEpoch=${Z}, currentEpoch=${this.epoch})`),this.makeAbortResult($,"Tool execution aborted due to epoch mismatch (discard)",Y);let B={toolCall:$,result:z,toolUseUuid:Y};if(this.pending.has($.id))this.pending.delete($.id),this.completed.set($.id,B);return B}catch(Q){if(Z!==this.epoch)return this.makeAbortResult($,"Tool execution aborted due to epoch mismatch (discard)",Y);w$.error(`[StreamingToolExecutor] 工具执行失败: ${$.function.name}`,Q);let K={success:!1,llmContent:"",error:{type:"execution_error",message:Q instanceof Error?Q.message:"Unknown error"},metadata:void 0},X={toolCall:$,result:K,toolUseUuid:Y,error:Q instanceof Error?Q:Error("Unknown error")};if(this.pending.has($.id))this.pending.delete($.id),this.completed.set($.id,X);return X}finally{this.activeAborts.delete($.id)}}persistToolUseInOrder($,J){let Z=this.contextMgr,W=this.sessionId;if(!Z||!W)return Promise.resolve(null);let Y=this.toolUsePersistenceTail.then(()=>Z.saveToolUse(W,$.function.name,J,this.lastMessageUuid??null,this.subagentInfo,$.id));return this.toolUsePersistenceTail=Y.then(()=>{return},()=>{return}),Y}}class z2{pending=[];waiters=[];closed=!1;push($){if(this.closed)return;let J=this.waiters.shift();if(J){J($);return}if(this.pending.length>=256)this.pending.shift();this.pending.push($)}shift(){return this.pending.shift()}next(){let $=this.shift();if($)return Promise.resolve($);if(this.closed)return Promise.resolve(void 0);return new Promise((J)=>{this.waiters.push(J)})}get hasPending(){return this.pending.length>0}close(){if(this.closed)return;this.closed=!0;for(let $ of this.waiters.splice(0))$(void 0)}}function v4($,J){if(!["TaskCreate","TaskUpdate","TaskList"].includes($.function.name)||!J.success||!J.llmContent&&!J.metadata)return null;let Z=typeof J.llmContent==="object"?J.llmContent:{};return{kind:"task_update",tasks:J.metadata?.tasks||Z.tasks||[]}}function C4($,J,Z){if($.function.name!=="Skill"||!J.success||!J.metadata)return;let W=J.metadata;if(W.skillName)Z.onSkillActivated?.({skillName:W.skillName,allowedTools:W.allowedTools,basePath:W.basePath||""})}function I4($){let J=$.metadata;if(!J)return;return J.modelId?.toString().trim()||J.model?.toString().trim()||void 0||void 0}function hZ($,J,Z){if(!["EnterWorktree","ExitWorktree"].includes($.function.name)||!J.success)return;let W=J.metadata,Y=W?.workspaceRoot;if(!["enter","exit"].includes(String(W?.workspaceTransition))||typeof Y!=="string"||Y.trim()==="")return;return N$.getInstance().inheritProjectConfig(Z.workspaceRoot,Y,Z.sessionId),Z.workspaceRoot=Y,Z.worktreeActive=W?.workspaceTransition==="enter",Y}function vZ($,J){if($.function.name!=="Task")return null;let Z=J.metadata;if(!Z?.subagentSessionId)return null;let W=Z.subagentSessionId,Y=Z.subagentType||"Task",V=Z.subagentStatus,Q=typeof Z.subagentResumedFrom==="string"?Z.subagentResumedFrom:void 0,K=typeof Z.subagentRootId==="string"?Z.subagentRootId:void 0,X=typeof Z.subagentResumeDepth==="number"?Z.subagentResumeDepth:void 0;if(V==="completed"||V==="failed"||V==="cancelled")return{kind:"subagent_completed",sessionId:W,type:Y,success:V==="completed",summary:Z.subagentSummary,...Z.verificationVerdict==="pass"||Z.verificationVerdict==="fail"||Z.verificationVerdict==="partial"?{verificationVerdict:Z.verificationVerdict}:{},...Q?{resumedFrom:Q}:{},...K?{rootAgentId:K}:{},...X!==void 0?{resumeDepth:X}:{}};if(V==="running"){let H="";try{H=JSON.parse($.function.arguments).prompt||""}catch{}return{kind:"subagent_spawned",sessionId:W,type:Y,prompt:H,resumedFrom:Q,rootAgentId:K,resumeDepth:X}}return null}async function B2($,J,Z,W){let Y=v4($,J),V=vZ($,J);C4($,J,Z);let Q=I4(J);if(Q)await Z.onModelSwitch?.(Q);if(W)hZ($,J,W);return V||Y}var r=k0("Agent");function s1($,J){return{inputTokens:$.promptTokens??0,outputTokens:$.completionTokens??0,totalTokens:CJ($)??0,maxContextTokens:J,cacheReadTokens:$.cacheReadInputTokens??0,cacheWriteTokens:$.cacheCreationInputTokens??0,...$.promptCacheBreak?{cacheBreak:$.promptCacheBreak}:{},costUsd:$.costUsd}}function J$($){return JSON.stringify($).replaceAll("<","\\u003c").replaceAll(">","\\u003e")}function u4($){let J=$.trim();if(J=J.replace(/,\s*([}\]])/g,"$1"),J.startsWith("{")&&!J.endsWith("}"))J+="}";J=J.replace(/,\s*([}\]])/g,"$1");try{let Z=JSON.parse(J);if(typeof Z==="object"&&Z!==null&&!Array.isArray(Z))return Z;return null}catch{return null}}function z1($){let J=u4($);if(J)return J;try{let Z=JSON.parse($);return typeof Z==="string"?u4(Z):null}catch{return null}}function CZ($){let J=$.metadata&&typeof $.metadata==="object"&&!Array.isArray($.metadata)?$.metadata:void 0;if(J?.contextualProjectRules!==!0)return[];if(!Array.isArray(J.ruleReferences))throw Error("Invalid contextual project rule provenance");return J.ruleReferences.map((Z)=>{if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error("Invalid contextual project rule reference");let W=Z;if(typeof W.id!=="string"||typeof W.relativePath!=="string"||!["project","local"].includes(String(W.source))||typeof W.contentSha256!=="string"||!/^[a-f0-9]{64}$/u.test(W.contentSha256))throw Error("Invalid contextual project rule reference");return{id:W.id,relativePath:W.relativePath,source:W.source,contentSha256:W.contentSha256}})}function C$($){if(typeof $==="string")return $;try{return JSON.parse(JSON.stringify($))}catch{return String($)}}function IZ($){let J=new Set,Z=!1;for(let W of $){if(W.role==="assistant"){if(W.tool_calls&&W.tool_calls.length>0){for(let V of W.tool_calls)if("function"in V&&V.function.name==="Task")J.add(V.id)}else if(Z)Z=!1;continue}if(W.role!=="tool"||W.name!=="Task"||!W.tool_call_id||!J.has(W.tool_call_id)||typeof W.metadata!=="object"||W.metadata===null||Array.isArray(W.metadata))continue;let Y=W.metadata;if(Y.toolCallId===W.tool_call_id&&Y.toolName==="Task"&&Y.error===null)Z=!0}return Z}function uZ($){if(!($ instanceof Error))return"未知错误";let W=$.lastError??$;if(W.responseBody)try{let K=JSON.parse(W.responseBody)?.error?.message;if(K){let X=W.statusCode?` (HTTP ${W.statusCode})`:"";return`${K}${X}`}}catch{}let Y=$.message,V=Y.match(/Last error:\s*(.+)$/);if(V)return V[1];return Y}function gZ($){if(!($ instanceof Error))return!1;return["stream not supported","streaming is not available","sse not supported","does not support streaming"].some((Z)=>$.message.toLowerCase().includes(Z.toLowerCase()))}function pZ($,J){if(!J)return"Tool execution failed (no details).";let Z=[`Error: ${J.message||"Unknown error"}`];if(J.type==="validation_error")Z.push("Hint: Check the tool parameters — a required field may be missing or have the wrong type.");else if(J.type==="permission_denied")Z.push("Hint: This operation requires user approval. Try a different approach or ask the user.");else if(J.type==="timeout_error")Z.push("Hint: The operation timed out. Consider breaking it into smaller steps or increasing timeout.");else if(J.type==="execution_error"){let W=J.message??"";if(W.includes("ENOENT")||W.includes("no such file"))Z.push("Hint: File or directory not found. Use Glob or Grep to find the correct path first.");else if(W.includes("EACCES")||W.includes("permission"))Z.push("Hint: Permission denied. The file may be read-only or owned by another user.");else if(W.includes("not found in file")||W.includes("old_string"))Z.push(`Hint: The target text was not found. Use Read to view the current file content, then retry ${$} with the exact text.`);else if(W.includes("ENOTDIR"))Z.push("Hint: A path component is not a directory. Verify the full path with Glob.")}return Z.join(`
|
|
112
|
-
`)}function U2($){if(!($ instanceof Error))return!1;return R1($)||$.status===413}function dZ($,J){let Z=J,W=Z.index??0;if(!$.has(W))$.set(W,{id:Z.id||"",name:Z.function?.name||"",arguments:""});let Y=$.get(W);if(Z.id&&!Y.id)Y.id=Z.id;if(Z.function?.name&&!Y.name)Y.name=Z.function.name;if(Z.function?.arguments)Y.arguments+=Z.function.arguments}function cZ($){if($.size===0)return;return Array.from($.values()).filter((J)=>J.id&&J.name).map((J)=>({id:J.id,type:"function",function:{name:J.name,arguments:J.arguments}}))}async function*mZ($,J,Z,W,Y,V){let Q="",K="",X,H,z=new Map;try{let B=$.chatService.streamChat(J,Z,W,Y),j=0;for await(let U of B){if(W?.aborted)break;if(U.providerAdmission){yield{kind:"provider_admission",...U.providerAdmission};continue}if(U.providerCircuit){yield{kind:"provider_circuit",...U.providerCircuit};continue}if(U.providerRetry){yield{kind:"provider_retry",...U.providerRetry};continue}if(U.providerStall){yield{kind:"provider_stall",...U.providerStall};continue}if(j++,U.modelFallback){V?.discard(),Q="",K="",X=void 0,H=void 0,z.clear(),j=0,yield{kind:"model_fallback"};continue}if(U.content)Q+=U.content,yield{kind:"content_delta",delta:U.content};if(U.reasoningContent)K+=U.reasoningContent,yield{kind:"thinking_delta",delta:U.reasoningContent};if(U.usage)X=U.usage;if(U.toolCalls){for(let P of U.toolCalls)if(dZ(z,P),V){let k=P.index??0,R=z.get(k);if(R&&R.id&&R.name)try{let h=z1(R.arguments);if(h===null)continue;let d={id:R.id,type:"function",function:{name:R.name,arguments:R.arguments}},o=$.toolExecutor.getRegistry().get(R.name)?.kind,G=V.addTool(d,h);if(R.arguments=d.function.arguments,G==="prelaunched")yield{kind:"tool_start",toolCall:d,toolKind:o}}catch{}}}if(U.finishReason){H=U.finishReason;break}}if(j===0&&!W?.aborted&&Q.length===0&&z.size===0)return r.warn("[Loop] 流式响应返回0个chunk,回退到非流式模式"),V?.discard(),{...await $.chatService.chat(J,Z,W,Y),_nonStreamingFallback:!0};return{content:Q,reasoningContent:K||void 0,toolCalls:cZ(z),usage:X,finishReason:H}}catch(B){if(gZ(B))return r.warn("[Loop] 流式请求失败,降级到非流式模式"),V?.discard(),{...await $.chatService.chat(J,Z,W,Y),_nonStreamingFallback:!0};throw B}}function lZ($){return G2("sha256").update($).digest("hex").slice(0,16)}var iZ=new Set(["AbortError","Error","RangeError","TypeError"]),rZ=new Set(["EACCES","EEXIST","EIO","EMFILE","ENFILE","ENOENT","ENOSPC","EPERM","EROFS"]);function nZ($){if($ instanceof Error){let J=$,Z=iZ.has($.name)?$.name:"Error",W=typeof J.code==="string"&&rZ.has(J.code)?J.code:"unknown";return`${Z}:${W}`}return"UnknownError:unknown"}async function oZ($){let{deps:J,context:Z,state:W,snapshot:Y,attemptSpent:V}=$;if(Y.phase!=="handoff_band")return{kind:"failed"};if(W.getHistory().find((X)=>typeof X.id==="string"&&n4(X)))return{kind:"already_present"};if(V)return{kind:"failed"};let K=J.executionEngine?.getContextManager();if(!K)return{kind:"failed"};try{let X=await K.recordTokenBudgetHandoff(Z.sessionId,{version:1,observedPromptTokens:Y.contextTokens??0,availableForInput:Y.availableForInput??0,handoffThreshold:Y.handoffThreshold??0,compactionThreshold:Y.compactionThreshold??0});if(X.outcome==="suppressed")return{kind:"suppressed"};let H=r4(X.event);if(!H)return{kind:"failed"};return W.appendDurableControl(H),{kind:"appended",message:H}}catch(X){let H=`token_budget_handoff_persist_failed session=${lZ(Z.sessionId)} error=${nZ(X)}`;return r.warn(H),{kind:"failed"}}}async function*o4($,J,Z,W,Y,V,Q,K){let X=W.contextTokens,H=S6(J.messages,V),z=H!==null;if(H)J.messages=H.messages,r.debug(`[Loop] [轮次 ${Z}] MicroCompact: 清理 ${H.snippedCount} 轮旧工具结果(缓存已过期)`);let B=W1(J.messages),j=!1;if(B.snippedCount>0)j=!0,r.debug(`[Loop] [轮次 ${Z}] Snip 压缩: 移除 ${B.snippedCount} 轮旧工具调用,释放约 ${B.estimatedTokensFreed} tokens`);if(W.phase==="unknown"){if(j)J.messages=B.messages;return r.debug(`[Loop] [轮次 ${Z}] 压缩检查: 跳过(无历史 usage 数据)`),z||j?{kind:"snipped"}:{kind:"none"}}let U=$.chatService.getConfig(),P=U.model,_=W.maxContextTokens??0,k=W.maxOutputTokens??0,R=W.availableForInput??0;if(_<=0||R<=0){if(j)J.messages=B.messages;return r.debug(`[Loop] [轮次 ${Z}] 压缩检查: 跳过(模型上下文窗口未知)`),z||j?{kind:"snipped"}:{kind:"none"}}if(r.debug(`[Loop] [轮次 ${Z}] 压缩检查:`,{contextTokens:X,tokenSource:W.tokenSource,estimatedPendingTokens:W.estimatedPendingTokens,maxContextTokens:_,maxOutputTokens:k,availableForInput:R,threshold:W.compactionThreshold,shouldCompact:W.phase==="compaction_due"}),W.phase!=="compaction_due"){if(j)J.messages=B.messages;return z||j?{kind:"snipped"}:{kind:"none"}}r.debug(Z===0?"[Loop] 触发自动压缩":`[Loop] [轮次 ${Z}] 触发循环内自动压缩`);let h="failed",d,x,o,G,E,l,g,V0,I,D0,i,L0,S="compaction";yield{kind:"compaction",phase:"start",reason:"threshold"};try{let y0=j?B.messages:J.messages,T=await S$.compact(y0,{trigger:"auto",modelName:P,modelProvider:U.provider,maxContextTokens:_,apiKey:U.apiKey,baseURL:U.baseUrl,actualPreTokens:X,signal:Y,activeTask:Q,workspaceRoot:J.workspaceRoot||K0(),workspaceAccess:J.workspaceKind==="acp-remote"?"none":"full",sessionId:J.sessionId});if(T.usage)yield{kind:"token_usage",usage:s1(T.usage,_)};if(d=T.success?"llm":"fallback",x=T.preTokens,o=T.postTokens,G=T.sampleAttempts,E=T.inputReductions,l=T.messagesOmitted,g=T.filesOmitted,V0=T.imagesOmitted,I=T.fallbackTargetTokens,D0=T.fallbackMessagesOmitted,i=T.fallbackMessagesTruncated,L0=T.failureReason,T.success)r.debug(`[Loop] [轮次 ${Z}] 压缩完成: ${T.preTokens} -> ${T.postTokens} tokens`);else r.warn(`[Loop] [轮次 ${Z}] 压缩使用降级策略: ${T.preTokens} -> ${T.postTokens} tokens`);if(S="checkpoint",await e$($,J,T.summary,{trigger:"auto",reason:"threshold",strategy:d,preTokens:T.preTokens,...W.tokenSource?{preTokenSource:W.tokenSource}:{},...W.estimatedPendingTokens!==void 0?{estimatedPendingTokens:W.estimatedPendingTokens}:{},postTokens:T.postTokens,sampleAttempts:T.sampleAttempts,inputReductions:T.inputReductions,messagesOmitted:T.messagesOmitted,filesOmitted:T.filesOmitted,imagesOmitted:T.imagesOmitted,fallbackTargetTokens:T.fallbackTargetTokens,fallbackMessagesOmitted:T.fallbackMessagesOmitted,fallbackMessagesTruncated:T.fallbackMessagesTruncated,failureReason:T.failureReason,filesIncluded:T.filesIncluded,replacementMessages:T.compactedMessages},{required:$.executionEngine!==void 0}),J.messages=T.compactedMessages,K)K.lastCompactionTurn=Z;return h=T.success?"completed":"fallback",{kind:"compacted",postTokens:T.postTokens}}catch(y0){if(m0(y0))return r.debug(`[Loop] [轮次 ${Z}] 压缩被中止`),{kind:"none"};return r.error(`[Loop] [轮次 ${Z}] 压缩失败,停止执行`,y0),{kind:"failed",phase:S}}finally{yield{kind:"compaction",phase:"end",reason:"threshold",outcome:h,strategy:d,preTokens:x,...W.tokenSource?{preTokenSource:W.tokenSource}:{},...W.estimatedPendingTokens!==void 0?{estimatedPendingTokens:W.estimatedPendingTokens}:{},postTokens:o,sampleAttempts:G,inputReductions:E,messagesOmitted:l,filesOmitted:g,imagesOmitted:V0,fallbackTargetTokens:I,fallbackMessagesOmitted:D0,fallbackMessagesTruncated:i,failureReason:L0}}}function aZ($,J,Z,W){let Y=W?p4(W):"user-cancel";return{success:!1,error:{type:"aborted",message:(Y==="interrupt"?void 0:"任务已被用户中止")??"任务已中断"},metadata:{turnsCount:$,toolCallsCount:J,duration:Date.now()-Z,abortReason:Y}}}function g4($,J,Z){return{success:!1,error:{type:"tool_persistence_failed",message:W6},metadata:{turnsCount:$,toolCallsCount:J,duration:Date.now()-Z}}}function sZ($,J,Z,W){return{success:!1,error:{type:"context_compaction_failed",message:"Context compaction could not cross the hard budget boundary.",details:{phase:W}},metadata:{turnsCount:$,toolCallsCount:J,duration:Date.now()-Z}}}async function*tZ($,J,Z,W,Y){let V=Date.now(),Q=0,K=[],X=null,H=!1,z=(B,j,U)=>{return H=!0,aZ(B,j,V,U)};try{let B=$.toolExecutor.getRegistry(),j=Z.permissionMode,U=W?.outputSchema?I1(W.outputSchema):void 0,P=()=>{let L=$.applySkillToolRestrictions(B.getFunctionDeclarationsByMode(j));if(!U)return L;return[...L.filter((F)=>F.name!==I0),U.declaration]},_=D4(),k=O4(),R=z4(),h=k4(Y,B);if(U)h=`${h??""}
|
|
112
|
+
`)}function U2($){if(!($ instanceof Error))return!1;return R1($)||$.status===413}function dZ($,J){let Z=J,W=Z.index??0;if(!$.has(W))$.set(W,{id:Z.id||"",name:Z.function?.name||"",arguments:""});let Y=$.get(W);if(Z.id&&!Y.id)Y.id=Z.id;if(Z.function?.name&&!Y.name)Y.name=Z.function.name;if(Z.function?.arguments)Y.arguments+=Z.function.arguments}function cZ($){if($.size===0)return;return Array.from($.values()).filter((J)=>J.id&&J.name).map((J)=>({id:J.id,type:"function",function:{name:J.name,arguments:J.arguments}}))}async function*mZ($,J,Z,W,Y,V){let Q="",K="",X,H,z=new Map;try{let B=$.chatService.streamChat(J,Z,W,Y),j=0;for await(let U of B){if(W?.aborted)break;if(U.providerAdmission){yield{kind:"provider_admission",...U.providerAdmission};continue}if(U.providerCircuit){yield{kind:"provider_circuit",...U.providerCircuit};continue}if(U.providerRetry){yield{kind:"provider_retry",...U.providerRetry};continue}if(U.providerStall){yield{kind:"provider_stall",...U.providerStall};continue}if(j++,U.modelFallback){V?.discard(),Q="",K="",X=void 0,H=void 0,z.clear(),j=0,yield{kind:"model_fallback",...U.modelFallback};continue}if(U.content)Q+=U.content,yield{kind:"content_delta",delta:U.content};if(U.reasoningContent)K+=U.reasoningContent,yield{kind:"thinking_delta",delta:U.reasoningContent};if(U.usage)X=U.usage;if(U.toolCalls){for(let P of U.toolCalls)if(dZ(z,P),V){let k=P.index??0,R=z.get(k);if(R&&R.id&&R.name)try{let h=z1(R.arguments);if(h===null)continue;let d={id:R.id,type:"function",function:{name:R.name,arguments:R.arguments}},o=$.toolExecutor.getRegistry().get(R.name)?.kind,G=V.addTool(d,h);if(R.arguments=d.function.arguments,G==="prelaunched")yield{kind:"tool_start",toolCall:d,toolKind:o}}catch{}}}if(U.finishReason){H=U.finishReason;break}}if(j===0&&!W?.aborted&&Q.length===0&&z.size===0)return r.warn("[Loop] 流式响应返回0个chunk,回退到非流式模式"),V?.discard(),{...await $.chatService.chat(J,Z,W,Y),_nonStreamingFallback:!0};return{content:Q,reasoningContent:K||void 0,toolCalls:cZ(z),usage:X,finishReason:H}}catch(B){if(gZ(B))return r.warn("[Loop] 流式请求失败,降级到非流式模式"),V?.discard(),{...await $.chatService.chat(J,Z,W,Y),_nonStreamingFallback:!0};throw B}}function lZ($){return G2("sha256").update($).digest("hex").slice(0,16)}var iZ=new Set(["AbortError","Error","RangeError","TypeError"]),rZ=new Set(["EACCES","EEXIST","EIO","EMFILE","ENFILE","ENOENT","ENOSPC","EPERM","EROFS"]);function nZ($){if($ instanceof Error){let J=$,Z=iZ.has($.name)?$.name:"Error",W=typeof J.code==="string"&&rZ.has(J.code)?J.code:"unknown";return`${Z}:${W}`}return"UnknownError:unknown"}async function oZ($){let{deps:J,context:Z,state:W,snapshot:Y,attemptSpent:V}=$;if(Y.phase!=="handoff_band")return{kind:"failed"};if(W.getHistory().find((X)=>typeof X.id==="string"&&n4(X)))return{kind:"already_present"};if(V)return{kind:"failed"};let K=J.executionEngine?.getContextManager();if(!K)return{kind:"failed"};try{let X=await K.recordTokenBudgetHandoff(Z.sessionId,{version:1,observedPromptTokens:Y.contextTokens??0,availableForInput:Y.availableForInput??0,handoffThreshold:Y.handoffThreshold??0,compactionThreshold:Y.compactionThreshold??0});if(X.outcome==="suppressed")return{kind:"suppressed"};let H=r4(X.event);if(!H)return{kind:"failed"};return W.appendDurableControl(H),{kind:"appended",message:H}}catch(X){let H=`token_budget_handoff_persist_failed session=${lZ(Z.sessionId)} error=${nZ(X)}`;return r.warn(H),{kind:"failed"}}}async function*o4($,J,Z,W,Y,V,Q,K){let X=W.contextTokens,H=S6(J.messages,V),z=H!==null;if(H)J.messages=H.messages,r.debug(`[Loop] [轮次 ${Z}] MicroCompact: 清理 ${H.snippedCount} 轮旧工具结果(缓存已过期)`);let B=W1(J.messages),j=!1;if(B.snippedCount>0)j=!0,r.debug(`[Loop] [轮次 ${Z}] Snip 压缩: 移除 ${B.snippedCount} 轮旧工具调用,释放约 ${B.estimatedTokensFreed} tokens`);if(W.phase==="unknown"){if(j)J.messages=B.messages;return r.debug(`[Loop] [轮次 ${Z}] 压缩检查: 跳过(无历史 usage 数据)`),z||j?{kind:"snipped"}:{kind:"none"}}let U=$.chatService.getConfig(),P=U.model,_=W.maxContextTokens??0,k=W.maxOutputTokens??0,R=W.availableForInput??0;if(_<=0||R<=0){if(j)J.messages=B.messages;return r.debug(`[Loop] [轮次 ${Z}] 压缩检查: 跳过(模型上下文窗口未知)`),z||j?{kind:"snipped"}:{kind:"none"}}if(r.debug(`[Loop] [轮次 ${Z}] 压缩检查:`,{contextTokens:X,tokenSource:W.tokenSource,estimatedPendingTokens:W.estimatedPendingTokens,maxContextTokens:_,maxOutputTokens:k,availableForInput:R,threshold:W.compactionThreshold,shouldCompact:W.phase==="compaction_due"}),W.phase!=="compaction_due"){if(j)J.messages=B.messages;return z||j?{kind:"snipped"}:{kind:"none"}}r.debug(Z===0?"[Loop] 触发自动压缩":`[Loop] [轮次 ${Z}] 触发循环内自动压缩`);let h="failed",d,x,o,G,E,l,g,V0,I,D0,i,L0,S="compaction";yield{kind:"compaction",phase:"start",reason:"threshold"};try{let y0=j?B.messages:J.messages,T=await S$.compact(y0,{trigger:"auto",modelName:P,modelProvider:U.provider,maxContextTokens:_,apiKey:U.apiKey,baseURL:U.baseUrl,actualPreTokens:X,signal:Y,activeTask:Q,workspaceRoot:J.workspaceRoot||K0(),workspaceAccess:J.workspaceKind==="acp-remote"?"none":"full",sessionId:J.sessionId});if(T.usage)yield{kind:"token_usage",usage:s1(T.usage,_)};if(d=T.success?"llm":"fallback",x=T.preTokens,o=T.postTokens,G=T.sampleAttempts,E=T.inputReductions,l=T.messagesOmitted,g=T.filesOmitted,V0=T.imagesOmitted,I=T.fallbackTargetTokens,D0=T.fallbackMessagesOmitted,i=T.fallbackMessagesTruncated,L0=T.failureReason,T.success)r.debug(`[Loop] [轮次 ${Z}] 压缩完成: ${T.preTokens} -> ${T.postTokens} tokens`);else r.warn(`[Loop] [轮次 ${Z}] 压缩使用降级策略: ${T.preTokens} -> ${T.postTokens} tokens`);if(S="checkpoint",await e$($,J,T.summary,{trigger:"auto",reason:"threshold",strategy:d,preTokens:T.preTokens,...W.tokenSource?{preTokenSource:W.tokenSource}:{},...W.estimatedPendingTokens!==void 0?{estimatedPendingTokens:W.estimatedPendingTokens}:{},postTokens:T.postTokens,sampleAttempts:T.sampleAttempts,inputReductions:T.inputReductions,messagesOmitted:T.messagesOmitted,filesOmitted:T.filesOmitted,imagesOmitted:T.imagesOmitted,fallbackTargetTokens:T.fallbackTargetTokens,fallbackMessagesOmitted:T.fallbackMessagesOmitted,fallbackMessagesTruncated:T.fallbackMessagesTruncated,failureReason:T.failureReason,filesIncluded:T.filesIncluded,replacementMessages:T.compactedMessages},{required:$.executionEngine!==void 0}),J.messages=T.compactedMessages,K)K.lastCompactionTurn=Z;return h=T.success?"completed":"fallback",{kind:"compacted",postTokens:T.postTokens}}catch(y0){if(m0(y0))return r.debug(`[Loop] [轮次 ${Z}] 压缩被中止`),{kind:"none"};return r.error(`[Loop] [轮次 ${Z}] 压缩失败,停止执行`,y0),{kind:"failed",phase:S}}finally{yield{kind:"compaction",phase:"end",reason:"threshold",outcome:h,strategy:d,preTokens:x,...W.tokenSource?{preTokenSource:W.tokenSource}:{},...W.estimatedPendingTokens!==void 0?{estimatedPendingTokens:W.estimatedPendingTokens}:{},postTokens:o,sampleAttempts:G,inputReductions:E,messagesOmitted:l,filesOmitted:g,imagesOmitted:V0,fallbackTargetTokens:I,fallbackMessagesOmitted:D0,fallbackMessagesTruncated:i,failureReason:L0}}}function aZ($,J,Z,W){let Y=W?p4(W):"user-cancel";return{success:!1,error:{type:"aborted",message:(Y==="interrupt"?void 0:"任务已被用户中止")??"任务已中断"},metadata:{turnsCount:$,toolCallsCount:J,duration:Date.now()-Z,abortReason:Y}}}function g4($,J,Z){return{success:!1,error:{type:"tool_persistence_failed",message:W6},metadata:{turnsCount:$,toolCallsCount:J,duration:Date.now()-Z}}}function sZ($,J,Z,W){return{success:!1,error:{type:"context_compaction_failed",message:"Context compaction could not cross the hard budget boundary.",details:{phase:W}},metadata:{turnsCount:$,toolCallsCount:J,duration:Date.now()-Z}}}async function*tZ($,J,Z,W,Y){let V=Date.now(),Q=0,K=[],X=null,H=!1,z=(B,j,U)=>{return H=!0,aZ(B,j,V,U)};try{let B=$.toolExecutor.getRegistry(),j=Z.permissionMode,U=W?.outputSchema?I1(W.outputSchema):void 0,P=()=>{let L=$.applySkillToolRestrictions(B.getFunctionDeclarationsByMode(j));if(!U)return L;return[...L.filter((F)=>F.name!==I0),U.declaration]},_=D4(),k=O4(),R=z4(),h=k4(Y,B);if(U)h=`${h??""}
|
|
113
113
|
|
|
114
114
|
# Structured Final Output
|
|
115
115
|
This turn has a required JSON Schema final-output contract. Complete the user's
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
function v(b){switch(b){case"default":case"ignore":case void 0:return"default";case"acceptEdits":return"autoEdit";case"dontAsk":case"bypassPermissions":return"yolo";case"plan":return"plan";default:return"default"}}
|
|
2
|
-
export{v as
|
|
2
|
+
export{v as lh};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Ea as h,Ga as f,Ha as k}from"./chunk-
|
|
1
|
+
import{Ea as h,Ga as f,Ha as k}from"./chunk-h74p51hg.js";import"./chunk-6e3mh79j.js";var p={command:"status",describe:"Check the pinned Playwright Chromium installation",handler:async()=>{let c=await f();if(console.log(`Playwright: ${c.playwrightVersion}`),console.log(`Chromium executable: ${c.executablePath}`),!c.installed){console.error(`Chromium: unavailable (${c.error??"unknown error"})`),console.error(`Install with: ${h}`),process.exitCode=1;return}console.log(`Chromium: ${c.browserVersion}`),console.log("Status: ready")}},q={command:"install",describe:"Install Chromium for the pinned Playwright runtime",handler:async()=>{try{await k();let c=await f();if(!c.installed)throw Error(c.error??"Chromium is not runnable after installation");console.log(`Chromium installed: Playwright ${c.playwrightVersion}, ${c.browserVersion}`)}catch(c){console.error(`Browser installation failed: ${c instanceof Error?c.message:String(c)}`),process.exitCode=1}}},x={command:"browser",describe:"Manage the native Browser Tool runtime",builder:(c)=>c.command(p).command(q).demandCommand(1).strict(),handler:()=>{return}};export{p as browserStatusCommand,q as browserInstallCommand,x as browserCommands};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{createRequire as a}from"node:module";var c=a(import.meta.url);
|
|
2
|
-
export{c as
|
|
2
|
+
export{c as Bk};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var F;((D)=>{D.DEFAULT="default";D.AUTO_EDIT="autoEdit";D.YOLO="yolo";D.PLAN="plan"})(F||={});import{Mutex as G}from"async-mutex";class H{entries=new Map;async runExclusive(C,E){let B=this.entries.get(C);if(!B)B={mutex:new G,operations:0},this.entries.set(C,B);B.operations++;try{return await B.mutex.runExclusive(E)}finally{if(B.operations--,B.operations===0&&this.entries.get(C)===B)this.entries.delete(C)}}getStats(){let C=0;for(let E of this.entries.values())C+=E.operations;return{keys:this.entries.size,operations:C}}}
|
|
2
|
-
export{F as
|
|
2
|
+
export{F as Ii,H as Ji};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{D as
|
|
1
|
+
import{ng as B}from"./chunk-4jqw75ce.js";import{Ej as Y}from"./chunk-xg9fyvw0.js";import{Hj as Z,Kj as $}from"./chunk-wxtj6gqb.js";import{createHash as H}from"node:crypto";var N="fast-mode-2026-02-01";function R(q,x,z){if(x.api!=="anthropic-messages"||z.providerValue!=="fast")return q;let J={...q},w=Object.keys(J).find((G)=>G.toLowerCase()==="anthropic-beta")??"anthropic-beta",Q=new Set((J[w]??"").split(",").map((G)=>G.trim()).filter(Boolean));return Q.add(N),J[w]=[...Q].join(","),J}function D(q){return`BLADE_MODEL_API_KEY_${H("sha256").update(q).digest("hex").slice(0,32).toUpperCase()}`}function F(q,x){if(!q.fallbackModels?.length)return;return q.fallbackModels.map((z)=>{let J=(x.models??[]).filter((G)=>G.provider===z.provider&&G.model===z.model),w=z.configId?(x.models??[]).find((G)=>G.id===z.configId):J.length===1?J[0]:void 0;if(z.configId&&!w)throw Error(`Unknown fallback model config ID: ${z.configId}`);if(w&&(w.provider!==z.provider||w.model!==z.model))throw Error(`Fallback model config ${w.id} does not match ${z.provider}/${z.model}`);if(!z.configId&&J.length>1)throw Error(`Fallback model ${z.provider}/${z.model} is ambiguous; set configId`);if(!w)return z;let Q=w.provider===q.provider;return{...z,configId:w.id,channel:{apiKey:process.env[D(w.id)]??(Q?process.env.BLADE_API_KEY:void 0),baseUrl:w.overrides?.baseUrl??(Q?process.env.BLADE_BASE_URL:void 0),temperature:w.overrides?.temperature??x.temperature,maxOutputTokens:w.overrides?.maxOutputTokens,timeout:w.overrides?.timeout??x.timeout,streamIdleTimeout:w.overrides?.streamIdleTimeout,apiVersion:w.overrides?.apiVersion,customHeaders:w.overrides?.customHeaders,enablePromptCaching:w.overrides?.enablePromptCaching}}})}function h(q,x,z,J=Y(),w="auto",Q="auto"){let G=J.resolveConfig(q),U=B(G,z),W=$(G,w),X=Z(G,Q),L=q.overrides;return{config:q,model:G,displayName:q.displayName??G.name,chat:{provider:q.provider,model:q.model,apiKey:process.env[D(q.id)]??process.env.BLADE_API_KEY,baseUrl:process.env.BLADE_BASE_URL??L?.baseUrl,temperature:L?.temperature??x.temperature,maxContextTokens:G.contextWindow,maxOutputTokens:L?.maxOutputTokens,timeout:L?.timeout??x.timeout,streamIdleTimeout:L?.streamIdleTimeout,reasoningEnabled:U.effective!=="off",...U.effective==="off"?{}:{reasoningEffort:U.effective},...W.providerValue?{serviceTier:W.providerValue}:{},...X.providerValue?{responseVerbosity:X.providerValue}:{},fallbackModels:F(q,x),enablePromptCaching:L?.enablePromptCaching,customHeaders:R(L?.customHeaders,G,W),apiVersion:L?.apiVersion,maxRetries:L?.maxRetries,providerCircuitBreakerOpenMs:x.providerCircuitBreakerOpenMs,providerRequestConcurrency:x.providerRequestConcurrency,providerGlobalConcurrency:x.providerGlobalConcurrency,providerOwnerConcurrency:x.providerOwnerConcurrency,providerRequestAdmissionMs:x.providerRequestAdmissionMs,providerRequestPendingBytes:x.providerRequestPendingBytes,modelCatalog:J},reasoning:U,serviceTier:W,responseVerbosity:X}}function j(q,x=Y()){try{return q.displayName??x.getModel(q.provider,q.model).name}catch{return q.displayName??q.model}}
|
|
2
|
+
export{D as jg,h as kg,j as lg};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$a as O,Ya as V,_a as W,rb as J}from"./chunk-
|
|
1
|
+
import{$a as O,Ya as V,_a as W,rb as J}from"./chunk-ermypm1x.js";import"./chunk-xt0ktytp.js";import"./chunk-0ccm29qy.js";import"./chunk-9a7bppj7.js";import{Si as Q}from"./chunk-g799czsy.js";import"./chunk-vp6d1fqp.js";import"./chunk-0k2x2ae6.js";import"./chunk-6e3mh79j.js";import F from"chalk";var K=(f)=>typeof f==="string"&&f.length>0?f:void 0;function X(f){let z=K(f.cron),G=K(f.every),H=K(f.at);if([z,G,H].filter(Boolean).length!==1)throw Error("Provide exactly one of --cron, --every, or --at");if(z)return{kind:"cron",cron:z};if(G){let P=V(G);if(!P)throw Error(`Invalid --every value "${G}" (use e.g. 30m, 2h, 1d)`);return{kind:"interval",intervalMs:P}}let N=new Date(H);if(Number.isNaN(N.getTime()))throw Error(`Invalid --at value "${H}" (use an ISO timestamp)`);return{kind:"once",runAt:N.toISOString()}}var Y={command:"create <prompt>",describe:"创建定时任务",builder:(f)=>f.positional("prompt",{type:"string",describe:"定时任务运行时发送给 Agent 的提示词",demandOption:!0}).option("cron",{type:"string",describe:"5 段 cron 表达式(本地时区)"}).option("every",{type:"string",describe:"间隔(如 30m、2h、1d)"}).option("at",{type:"string",describe:"一次性运行的 ISO 时间点"}).option("project-path",{alias:["projectPath","project"],type:"string",describe:"目标项目路径(默认当前目录)"}).option("title",{type:"string",describe:"定时任务标题"}).option("model",{alias:"m",type:"string",describe:"模型 ID"}).option("permission-mode",{type:"string",choices:["default","autoEdit","yolo","plan"],default:"default",describe:"权限模式"}).option("isolation",{type:"string",choices:["local","worktree"],default:"worktree",describe:"执行隔离方式"}).example([['$0 schedule create "跑测试并汇报失败" --every 1h',"每小时运行一次"],['$0 schedule create "生成每日站会摘要" --cron "0 9 * * 1-5"',"工作日 9 点运行"]]),handler:async(f)=>{try{let z=X(f),G=W(z);if(G)throw Error(G);let H={prompt:f.prompt,projectPath:K(f.projectPath)??Q(),title:K(f.title),trigger:z,modelId:K(f.model),isolation:K(f.isolation)??"worktree",permissionMode:K(f.permissionMode)??"default",enabled:!0},B=await J.create(H);console.log(F.green(`✓ 已创建定时任务 ${B.id}`)),console.log(` ${O(B.trigger)}`),console.log(` 项目: ${B.projectPath}`),console.log(` 下次运行: ${B.nextRunAt?new Date(B.nextRunAt).toLocaleString():"(无)"}`),process.exit(0)}catch(z){console.error(F.red(`创建定时任务失败: ${z instanceof Error?z.message:z}`)),process.exit(1)}}},Z={command:"list",aliases:["ls"],describe:"列出所有定时任务",handler:async()=>{let f=await J.list();if(f.length===0)console.log(F.dim("尚无定时任务。使用 `blade schedule create` 创建。")),process.exit(0);for(let z of f){let G=z.enabled?F.green("启用"):F.dim("停用"),H=z.nextRunAt?new Date(z.nextRunAt).toLocaleString():"—",B=z.lastRunAt?`${new Date(z.lastRunAt).toLocaleString()} (${z.lastStatus??"?"})`:"从未";console.log(`${F.cyan(z.id)} [${G}] ${z.title??z.prompt.slice(0,40)}`),console.log(` ${O(z.trigger)} · 下次: ${H} · 上次: ${B} · 运行 ${z.runCount} 次`),console.log(F.dim(` 项目: ${z.projectPath}`))}process.exit(0)}},_={command:"show <id>",describe:"查看定时任务详情",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{let z=await J.get(f.id);if(!z)console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(JSON.stringify(z,null,2)),process.exit(0)}},$={command:"remove <id>",aliases:["rm"],describe:"删除定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.remove(f.id))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已删除定时任务 ${f.id}`)),process.exit(0)}},q={command:"enable <id>",describe:"启用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!0))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已启用定时任务 ${f.id}`)),process.exit(0)}},x={command:"disable <id>",describe:"停用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!1))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已停用定时任务 ${f.id}`)),process.exit(0)}},D={command:"run <id>",describe:"立即运行定时任务(需要 blade serve)",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}).option("server",{type:"string",default:process.env.BLADE_SERVER_URL??"http://127.0.0.1:4097",describe:"Blade server 地址"}),handler:async(f)=>{let z=f.id,G=(K(f.server)??"http://127.0.0.1:4097").replace(/\/$/,""),H={};if(process.env.BLADE_SERVER_PASSWORD){let B=process.env.BLADE_SERVER_USERNAME??"blade";H.Authorization=`Basic ${Buffer.from(`${B}:${process.env.BLADE_SERVER_PASSWORD}`).toString("base64")}`}try{let B=await fetch(`${G}/schedules/${encodeURIComponent(z)}/run`,{method:"POST",headers:H});if(!B.ok){let N=await B.json().catch(()=>{return});throw Error(N?.error?.message??`Schedule run failed (${B.status})`)}console.log(F.green(`✓ 已触发定时任务 ${z}`)),process.exit(0)}catch(B){console.error(F.red(`运行定时任务失败: ${B instanceof Error?B.message:B}`)),process.exit(1)}}},R={command:"schedule",describe:"管理定时任务",builder:(f)=>f.command(Y).command(Z).command(_).command($).command(q).command(x).command(D).demandCommand(1,"请提供子命令:create | list | show | remove | enable | disable | run"),handler:()=>{}};export{R as scheduleCommands};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{kf as a,lf as b,mf as c}from"./chunk-gpj7k3er.js";import"./chunk-39de5k03.js";import"./chunk-v5503t2t.js";import"./chunk-v508x7cg.js";import"./chunk-q0s3gcjm.js";import"./chunk-69nwa6bn.js";import"./chunk-ramana2t.js";import"./chunk-6xvrrypm.js";import"./chunk-9a7bppj7.js";import"./chunk-g799czsy.js";import"./chunk-mzye1ah2.js";import"./chunk-vp6d1fqp.js";import"./chunk-xg9fyvw0.js";import"./chunk-wxtj6gqb.js";import"./chunk-g9vdmvk2.js";import"./chunk-wxypv01z.js";import"./chunk-nxnmqk4s.js";import"./chunk-0k2x2ae6.js";import"./chunk-6e3mh79j.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{jc as Xt,kc as En,lc as yn,mc as bn}from"./chunk-wzkh3e6a.js";import{
|
|
1
|
+
import{jc as Xt,kc as En,lc as yn,mc as bn}from"./chunk-wzkh3e6a.js";import{oh as Bt}from"./chunk-mavranwn.js";import{Ah as mt,Ch as rn,Dh as Tn,Eh as B,Fh as dn,Gh as on,Hh as pn,Ih as lt,Jh as un,Kh as cn,Lh as Mn,Nh as S,Qh as wn,Rh as Gt,Sh as Ut,Th as h,Uh as Ht,th as xt,uh as vi,vh as sn,wh as zt,xh as U,yh as en,zh as gt}from"./chunk-ramana2t.js";import{Si as It}from"./chunk-g799czsy.js";import{uj as X,wj as x}from"./chunk-vp6d1fqp.js";import{Mj as tn,Nj as nn}from"./chunk-g9vdmvk2.js";import{Bk as ns}from"./chunk-6e3mh79j.js";import{EventEmitter as fs}from"events";import Un from"node:path";function hn(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function An(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${hn(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:An(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
|
|
2
2
|
${s.map((r)=>` - ${r.field}: ${r.message}`).join(`
|
|
3
3
|
`)}`;throw new Jt(e,s)}function st(t){if(!t||typeof t!=="object")return;let i=t;if(i.type==="object"&&i.properties)i.required??=[],i.additionalProperties??=!1;for(let n of Object.values(i))if(Array.isArray(n))for(let s of n)st(s);else st(n)}function et(t){let i=JSON.parse(JSON.stringify(t,(n,s)=>n.startsWith("~")?void 0:s));return st(i),i}class rt{toolName;params;executeFn;descriptionFn;affectedPathsFn;isRetrySafe;constructor(t,i,n,s,e,r=!1){this.toolName=t;this.params=i;this.executeFn=n;this.descriptionFn=s;this.affectedPathsFn=e;this.isRetrySafe=r}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute(t,i,n){let s={signal:t,updateOutput:i,...n};return this.executeFn(this.params,s)}}function jt(t){return{name:t.name,displayName:t.displayName,kind:t.kind,isConcurrencySafe:t.isConcurrencySafe??!1,isRetrySafe:t.isRetrySafe??!1,parallelism:t.parallelism??(t.isConcurrencySafe?"shared":"exclusive"),strict:t.strict??!1,description:t.description,version:t.version||"1.0.0",category:t.category,tags:t.tags||[],getFunctionDeclaration(){let i=et(t.schema),n=t.description.short;if(t.description.long)n+=`
|
|
4
4
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Pi as L,Si as _}from"./chunk-g799czsy.js";import{execSync as F}from"child_process";import{existsSync as Q,readFileSync as O,realpathSync as b}from"fs";import*as V from"os";import*as H from"path";import{basename as J,isAbsolute as j,resolve as R}from"path";function G(z=_()){let q=z,M=f(q);return{workingDirectory:q,projectRoot:M,platform:`${V.platform()} (${V.arch()})`,nodeVersion:process.version,currentDate:new Date().toISOString().split("T")[0],homeDirectory:V.homedir()}}function Y(z,q){try{return F(q,{cwd:z,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch{return null}}function v(z={}){let{includeGitSnapshot:q=!0,includeDirectoryListing:M=!0,workingDirectory:W}=z,B=G(W),$=Q(H.join(B.projectRoot,".git")),T=J(process.env.SHELL||"unknown"),A=["package.json","tsconfig.json","BLADE.md",".env.example"].filter((K)=>Q(H.join(B.projectRoot,K))).map((K)=>`- \`${H.join(B.projectRoot,K)}\``),N=`# Environment
|
|
2
2
|
You have been invoked in the following environment:
|
|
3
3
|
- Primary working directory: ${B.workingDirectory}
|
|
4
4
|
- Is a git repository: ${$?"true":"false"}
|