blade-code 0.10.196 → 0.10.197
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-7vc0j8m6.js → chunk-0w6ege8m.js} +6 -6
- package/dist/{chunk-m4zazwzr.js → chunk-1a72xcm5.js} +1 -1
- package/dist/{chunk-zyvxts23.js → chunk-1d3p29ck.js} +1 -1
- package/dist/{chunk-4k8d018f.js → chunk-1wvkccyq.js} +1 -1
- package/dist/{chunk-fck48bw1.js → chunk-2rjbmx95.js} +1 -1
- package/dist/{chunk-zvyh95x9.js → chunk-2tgpn3df.js} +1 -1
- package/dist/{chunk-c54t12bm.js → chunk-4esj56h2.js} +1 -1
- package/dist/{chunk-w50pdxnm.js → chunk-4szhq9af.js} +1 -1
- package/dist/{chunk-dtnd5zkh.js → chunk-4vdy0r4e.js} +1 -1
- package/dist/chunk-6hd7dhah.js +1 -0
- package/dist/{chunk-ywfa7fhr.js → chunk-7mhwhv06.js} +2 -2
- package/dist/{chunk-f04jgx3j.js → chunk-8jcw1zff.js} +1 -1
- package/dist/{chunk-9sn36cs0.js → chunk-8phhjmp2.js} +1 -1
- package/dist/{chunk-mcpkk1ce.js → chunk-8qd4t1zk.js} +1 -1
- package/dist/chunk-8r1p9etf.js +1 -0
- package/dist/{chunk-2nzmdf86.js → chunk-99975pj2.js} +1 -1
- package/dist/{chunk-byat3xec.js → chunk-9m8gjjnr.js} +1 -1
- package/dist/{chunk-tcgb56tp.js → chunk-b88ff25j.js} +1 -1
- package/dist/{chunk-b6qsc6jm.js → chunk-be3q7hz5.js} +1 -1
- package/dist/{chunk-kvst0ysv.js → chunk-bvjy2j7g.js} +1 -1
- package/dist/{chunk-bfv4rp3j.js → chunk-c0g819d8.js} +1 -1
- package/dist/{chunk-3036tv7v.js → chunk-cdrnfqqx.js} +2 -2
- package/dist/{chunk-8yvtknsk.js → chunk-ctrr7v68.js} +1 -1
- package/dist/{chunk-827nqwm8.js → chunk-er3xs5w5.js} +1 -1
- package/dist/{chunk-9dwdhka9.js → chunk-frvx7etd.js} +1 -1
- package/dist/{chunk-nh67db73.js → chunk-j8jyb6z8.js} +1 -1
- package/dist/{chunk-zme6ydm6.js → chunk-jxe9cq1m.js} +1 -1
- package/dist/{chunk-8y61xj8b.js → chunk-kn7k2hg5.js} +1 -1
- package/dist/{chunk-bc3nsr8k.js → chunk-nxe8rf1x.js} +1 -1
- package/dist/{chunk-hypy2t78.js → chunk-qbgnb5f4.js} +1 -1
- package/dist/{chunk-267tf0ts.js → chunk-qzkxhkke.js} +1 -1
- package/dist/{chunk-hkz1z544.js → chunk-rjkf30qt.js} +3 -3
- package/dist/{chunk-k40zgmnb.js → chunk-s0n3aqm0.js} +1 -1
- package/dist/chunk-w13pftn7.js +6 -0
- package/dist/{chunk-nj35kwht.js → chunk-xddrcby1.js} +1 -1
- package/dist/{chunk-ajv12d9b.js → chunk-ympp7syy.js} +1 -1
- package/dist/{chunk-xv8h6611.js → chunk-zsx0qb55.js} +1 -1
- package/dist/{chunk-af78d1nn.js → chunk-zwaa1312.js} +1 -1
- package/dist/web/assets/{ChatView-DYA3np_l.js → ChatView-BF6HUrBw.js} +4 -4
- package/dist/web/assets/{CodeBlockHighlighter-B9sgXWAy.js → CodeBlockHighlighter-C4CgCiRf.js} +1 -1
- package/dist/web/assets/{FilePreview-PKalr8bi.js → FilePreview-BS4PgFKb.js} +1 -1
- package/dist/web/assets/{KanbanBoard-GjH7MyZk.js → KanbanBoard-DDXB-yq1.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-C03DrI8Q.js → MarkdownRenderer-DS7RznBE.js} +3 -3
- package/dist/web/assets/{ScrollArea-CbOr9e7X.js → ScrollArea-BM9NzGZM.js} +1 -1
- package/dist/web/assets/{SessionHistorySurface-BZEOUN2M.js → SessionHistorySurface-DnRySeLE.js} +1 -1
- package/dist/web/assets/{SettingsModal-DAMGwO-E.js → SettingsModal-D5YLUtIo.js} +1 -1
- package/dist/web/assets/{Sidebar-CiCsK7EK.js → Sidebar-BZC6OkDJ.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-BLdgv--U.js → TaskSwitcher-WewOkw5m.js} +1 -1
- package/dist/web/assets/{TerminalPanel-uctuzvle.js → TerminalPanel-C5SGdRNr.js} +1 -1
- package/dist/web/assets/{archive-BHntc9gt.js → archive-DkczUU08.js} +1 -1
- package/dist/web/assets/{arrow-left-DkXe02NZ.js → arrow-left-9pBiQwu7.js} +1 -1
- package/dist/web/assets/{calendar-clock-_-EyQ_16.js → calendar-clock-BFnUlxrU.js} +1 -1
- package/dist/web/assets/{chevron-right-DXuaFbE2.js → chevron-right-yCVkAEcj.js} +1 -1
- package/dist/web/assets/{clock-3-DHOWUt-Y.js → clock-3-CcoWoRQs.js} +1 -1
- package/dist/web/assets/{copy-wCV3sjrM.js → copy-HJF0oQBS.js} +1 -1
- package/dist/web/assets/{download-CEXHgQhj.js → download-DSBCIqk3.js} +1 -1
- package/dist/web/assets/{external-link-D5pUXtvQ.js → external-link-zIgEO0KB.js} +1 -1
- package/dist/web/assets/{folder-Bm-uBrFM.js → folder-BdRo64o3.js} +1 -1
- package/dist/web/assets/{index-E1WG_htm.js → index-BVDkKudh.js} +4 -4
- package/dist/web/assets/{message-square-plus-ChP8ZEgZ.js → message-square-plus-3klTXO0S.js} +1 -1
- package/dist/web/assets/{pause-D8MeccMe.js → pause-B9Q5JWvH.js} +1 -1
- package/dist/web/assets/{pencil-DNEy8lVY.js → pencil-CbYIz1b1.js} +1 -1
- package/dist/web/assets/{play-DhdTbY0j.js → play-CZMTj43e.js} +1 -1
- package/dist/web/assets/{plus-B2PxWoNi.js → plus-Cc7I8fhb.js} +1 -1
- package/dist/web/assets/{session-events-aq2qdB3u.js → session-events-NEjosinC.js} +2 -2
- package/dist/web/assets/{settings-D9Kkb31b.js → settings-DSF3exX2.js} +1 -1
- package/dist/web/assets/{team-ktBP7cND.js → team-qfeJHL9s.js} +1 -1
- package/dist/web/assets/{teamService-CxPZcCrA.js → teamService-Bs9qBKI8.js} +1 -1
- package/dist/web/assets/{terminal-DcSGZkEA.js → terminal-DQLqe-Ed.js} +1 -1
- package/dist/web/index.html +1 -1
- package/package.json +1 -1
- package/dist/chunk-2wq1zztd.js +0 -1
- package/dist/chunk-akbsgbww.js +0 -6
- package/dist/chunk-xvx0t011.js +0 -1
package/dist/blade.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Af as W}from"./chunk-
|
|
2
|
+
import{Af as W}from"./chunk-ympp7syy.js";import{Df as F,Ef as M}from"./chunk-p0wyhp5a.js";import"./chunk-1wvkccyq.js";import"./chunk-v508x7cg.js";import"./chunk-5yyp6njq.js";import"./chunk-4szhq9af.js";import"./chunk-ys8gysg8.js";import"./chunk-qbgnb5f4.js";import"./chunk-qpmvp4q2.js";import"./chunk-tm3789m3.js";import{bj as N,cj as B}from"./chunk-qdbbke8f.js";import"./chunk-wezr6wfq.js";import{Dj as T}from"./chunk-rmfzym94.js";import"./chunk-j89qk7bp.js";import"./chunk-0eajnhrj.js";import"./chunk-ctrr7v68.js";import"./chunk-ggdgk3gy.js";import"./chunk-ky592ay9.js";import"./chunk-n52n2w5v.js";import{Nk as J}from"./chunk-cjfb4kjp.js";import p from"node:path";var E=process.argv.slice(2),I=c(E),u=I!==null;if(I!==null)T.setGlobalDebug(I);function c(Q){for(let Y=0;Y<Q.length;Y+=1){let U=Q[Y];if(U==="--debug"||U==="-d"){let X=Q[Y+1];return X&&!X.startsWith("-")?X:!0}if(U.startsWith("--debug="))return U.slice(8)||!0}return null}function m(Q){return Q.length===1&&(Q[0]==="--version"||Q[0]==="-V")}function q(Q,...Y){return Q.some((U)=>Y.some((X)=>U===X||U.startsWith(`${X}=`)))}function t(Q,...Y){let U=[];for(let X=0;X<Q.length;X+=1){let G=Q[X],z=Y.find(($)=>G.startsWith(`${$}=`));if(z){let $=G.slice(z.length+1);if($)U.push($);continue}if(Y.includes(G)){let $=Q[X+1];if($&&!$.startsWith("-"))U.push($),X+=1}}return U}async function l(){if(m(E)){let{getVersion:K}=await import("./chunk-8qd4t1zk.js");console.log(K());return}let Q=process.cwd(),Y=F(Q);M(Y),N(B());let U=t(E,"--plugin-dir","--pluginDir");if(U.length>0){let{configureInvocationPluginDirs:K}=await import("./chunk-qzkxhkke.js");K(U.map((Z)=>p.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:K}=await import("./chunk-6ax5dpd3.js");await K.getInstance().trust(B())}if(process.getuid&&process.getuid()===0){let K=!!process.env.SUDO_USER,Z=!!process.env.BLADE_ALLOW_ROOT;if(K&&!Z)console.error(""),console.error("Error: 请不要使用 sudo 运行 blade"),console.error(""),console.error("原因:"),console.error(" 使用 sudo 会创建属于 root 的配置文件,"),console.error(" 导致普通用户无法访问。"),console.error(""),console.error("正确用法:"),console.error(" blade # 直接运行,不要加 sudo"),console.error(""),console.error("如果遇到权限错误,请运行:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("如果你确实需要以 root 运行(容器/CI),设置环境变量:"),console.error(" BLADE_ALLOW_ROOT=1 blade"),console.error(""),process.exit(1)}if(q(E,"--headless")){let{handleHeadlessMode:K}=await import("./chunk-w13pftn7.js");if(await K())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-2tgpn3df.js");if(await K())return}if(E.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-2rjbmx95.js");await K();return}let[{default:X},{hideBin:G},{cliConfig:z,globalOptions:$},{loadConfiguration:_,validateOutput:D,validatePermissions:R},{browserCommands:S},{doctorCommands:k},{installCommands:O},{mcpCommands:y},{projectsCommands:V},{scheduleCommands:b},{serveCommand:P},{updateCommands:x},{webCommand:A}]=await Promise.all([import("yargs"),import("yargs/helpers"),import("./chunk-8r1p9etf.js"),import("./chunk-j8jyb6z8.js"),import("./chunk-wk869s65.js"),import("./chunk-7mhwhv06.js"),import("./chunk-0xf70s5c.js"),import("./chunk-s0n3aqm0.js"),import("./chunk-x49bw41v.js"),import("./chunk-g383afnv.js"),import("./chunk-c0g819d8.js"),import("./chunk-jxe9cq1m.js"),import("./chunk-9m8gjjnr.js")]),h=X(G(process.argv)).scriptName(z.scriptName).usage(z.usage).version(z.version).locale(z.locale).showHelpOnFail(z.showHelpOnFail).demandCommand(0,"").recommendCommands().strict(z.strict).parserConfiguration({"populate--":!0}).options($).middleware([_,R,D]).command(S).command(y).command(V).command(b).command(k).command(x).command(O).command(A).command(P).completion("completion",!1).help("help","Show help").alias("help","h").alias("version","V").fail((K,Z,L)=>{if(Z){if(console.error("An error occurred:"),console.error(Z.message),u&&Z.stack)console.error(`
|
|
3
3
|
Stack trace:`),console.error(Z.stack);else console.error(`
|
|
4
4
|
Run with --debug to show the stack trace.`);process.exit(1)}if(K)console.error("Error: Invalid arguments:"),console.error(K),console.error(`
|
|
5
|
-
Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let Z=K._.slice(1),L=Z.length>0?Z.join(" "):void 0,f=import("./chunk-
|
|
5
|
+
Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let Z=K._.slice(1),L=Z.length>0?Z.join(" "):void 0,f=import("./chunk-6hd7dhah.js").then(({checkVersionOnStartup:v})=>v()),[{render:w},{createElement:j},{AppWrapper:C}]=await Promise.all([import("ink"),import("react"),import("./chunk-cdrnfqqx.js")]),H={...K,initialMessage:L,debug:K.debug,print:Boolean(K.print),versionCheckPromise:f};delete H._,delete H.$0,delete H.message,w(j(C,H),{patchConsole:!0,exitOnCtrlC:!1,alternateBuffer:!1})});try{await h.parse()}catch(K){console.error("Error: Parse error:",K),process.exit(1)}}if(J.main==J.module)l().catch(console.error);export{l as main};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{xc as G8}from"./chunk-fdr4fcrf.js";import{$d as R6,Ac as U$,Bc as A2,Cc as a1,Ec as j$,Fd as E2,Gd as L8,Hd as F8,Id as V6,Jd as JZ,Kd as O8,Ld as P8,Md as r1,Qd as rJ,Zd as u0,ae as t1,be as M6,ie as X1,ud as b2,wd as y2,xd as f2,yc as q$,yd as w6,zd as U6}from"./chunk-tcgb56tp.js";import{ne as q8}from"./chunk-egss0m1x.js";import{Fe as f0,qe as q0,te as j2,ue as u$}from"./chunk-ztreczac.js";import{eg as p2}from"./chunk-5yyp6njq.js";import{fg as w8,gg as C0,hg as H8,ig as dJ,kg as i1,lg as T6,mg as cJ,ng as lJ,qg as iJ}from"./chunk-myvt7yjm.js";import{ch as K$,dh as n0,gh as U8}from"./chunk-kehgewqh.js";import{lh as a2,ph as Y2}from"./chunk-kkzznz4w.js";import{Ah as R$}from"./chunk-w50pdxnm.js";import{Vi as x$}from"./chunk-qpmvp4q2.js";import{cj as j0}from"./chunk-qdbbke8f.js";import{Ej as S0}from"./chunk-rmfzym94.js";import{Yj as _2}from"./chunk-8yvtknsk.js";import{Ck as FJ,Dk as ZZ,Fk as O2,Kk as P2,Lk as N2,gk as F2,vk as w2,wk as U2,zk as H1}from"./chunk-n52n2w5v.js";import{Nk as lZ}from"./chunk-cjfb4kjp.js";function S$($){return $.role==="system"&&Array.isArray($.content)}function E$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class C1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,Z){this.context=$;let J=$.messages.find(S$);if(this._contextualSystemMessages=$.messages.filter(E$),J)this.systemMessages=[J,...this._contextualSystemMessages];else if(Z)this.systemMessages=[{role:"system",content:[{type:"text",text:Z,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!S$(W)&&!E$(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(!E$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(S$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,Z){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push({...Z,metadata:{...Z.metadata&&typeof Z.metadata==="object"&&!Array.isArray(Z.metadata)?Z.metadata:{},...f0}})}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((Z)=>Z.id===$.id))return;this._history.push($)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((Z)=>!S$(Z)&&!E$(Z)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(E$),this._history=$.filter((Z)=>!S$(Z)&&!E$(Z)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let Z=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages(),this._history.length!==Z[0]||this._pending.length!==Z[1]||this._contextualSystemMessages.length!==Z[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function e6($){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 $J($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function ZJ($,Z,J){return{...$,usage:$.usage+Z,lastOutputDelta:Z,consecutiveContinuations:J?$.consecutiveContinuations+1:0}}import z$ from"node:path";var k8=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"]),x8=/^(LD_.+|DYLD_.+|PATH)$/,JJ=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function Z1($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],K=W.match(JJ);if(!K)break;let X=K[1];if(!k8.has(X))break;Z=Y}return Z}function r5($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],K=W.match(JJ);if(!K)break;let X=K[1];if(x8.test(X))break;Z=Y}return Z}var I8=[/^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 xZ($){let Z=$,J=!0;while(J){J=!1;for(let W of I8){let Y=Z.match(W);if(Y){Z=Z.slice(Y[0].length),J=!0;break}}if(Z.startsWith("-- "))Z=Z.slice(3),J=!0}return Z}function J1($){let Z=[],J="",W=!1,Y=!1,K=!1;for(let X=0;X<$.length;X++){let Q=$[X];if(K){J+=Q,K=!1;continue}if(Q==="\\"&&!W){J+=Q,K=!0;continue}if(Q==="'"&&!Y){W=!W,J+=Q;continue}if(Q==='"'&&!W){Y=!Y,J+=Q;continue}if(W||Y){J+=Q;continue}if(Q==="|"){if(X+1<$.length&&$[X+1]==="|"){if(J.trim())Z.push(J.trim());J="",X++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&X+1<$.length&&$[X+1]==="&"){if(J.trim())Z.push(J.trim());J="",X++;continue}if(Q==="&")return null;if(Q===";"){if(J.trim())Z.push(J.trim());J="";continue}J+=Q}if(J.trim())Z.push(J.trim());return Z.length>0?Z:null}function WJ($){let Z=!1,J=!1,W=!1;for(let Y=0;Y<$.length;Y++){let K=$[Y];if(W){W=!1;continue}if(K==="\\"&&!Z){W=!0;continue}if(K==="'"&&!J){Z=!Z;continue}if(K==='"'&&!Z){J=!J;continue}if(Z)continue;if(K==="$"){let X=$[Y+1];if(X&&/[A-Za-z_@*#?!$0-9({]/.test(X))return!0}if(K==="`")return!0;if(J)continue;if(K==="|")return!0;if(K===">"||K==="<")return!0;if(K==="{"){let X=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(X)||/^\{[^}]*\.\.[^}]*\}/.test(X))return!0}}return!1}function V$($){let Z=[],J="",W=!1,Y=!1,K=!1;for(let X=0;X<$.length;X++){let Q=$[X];if(K){J+=Q,K=!1;continue}if(Q==="\\"&&!W){if(K=!0,Y){let H=$[X+1];if(H&&'$`"\\'.includes(H))continue;J+=Q,K=!1}continue}if(Q==="'"&&!Y){W=!W;continue}if(Q==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(Q)){if(J)Z.push(J),J="";continue}J+=Q}if(J)Z.push(J);return Z}var h8=new Set(["npm","pnpm","yarn","bun"]),YJ=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),v8=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),C8=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function g8($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function KJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function p8($,Z,J){if(!J||Z.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 K=Y[1];if(!K||K==="-")return;let X=z$.isAbsolute(K)?z$.resolve(K):z$.resolve(J,K);if(!j$.isWithinWorkspace(X,J))return;return W[2]?.trim()||void 0}function u8($){let Z=[],J=!1,W=!1,Y=!1;for(let K=0;K<$.length;K++){let X=$[K];if(Y){Y=!1;continue}if(X==="\\"&&!J){Y=!0;continue}if(X==="'"&&!W){J=!J;continue}if(X==='"'&&!J){W=!W;continue}if(X!=="|"||J||W)continue;if($[K+1]==="|")return;Z.push(K)}return Z}function m8($){let Z=V$($),[J,W,Y]=Z;if(J!=="head"&&J!=="tail")return!1;if(Z.length===1)return!0;let K=(X)=>X!==void 0&&/^[1-9]\d{0,4}$/.test(X);if(Z.length===2)return W?.startsWith("--lines=")&&K(W.slice(8))||W?.startsWith("-")&&K(W.slice(1));return Z.length===3&&(W==="-n"||W==="--lines")&&K(Y)}function d8($){let Z=KJ($.replace(C8,"").trim()),J=u8(Z);if(!J)return;if(J.length===0)return XJ(Z);if(J.length!==1)return;let W=J[0];if(W===void 0)return;let Y=KJ(Z.slice(0,W).trim()),K=Z.slice(W+1).trim();if(!Y||!m8(K))return;return XJ(Y)}function XJ($){let J=J1($)?.at(-1);if(!J)return $;let W=V$(J),[Y,K]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&K==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function T$($,Z){let J=d8($);if(!J)return!1;let W=Z1(J),Y=J1(W);if(!Y||WJ(W)||/[\r\n]/.test(W))return!1;let K=Y.length===1?Y[0]:p8(W,Y,Z);if(!K)return!1;let X=V$(K);if(X.length===0||X.some((z)=>[...v8].some((w)=>z===w||z.startsWith(`${w}=`))))return!1;let[Q,H,V]=X;if(h8.has(Q??""))return g8(H==="run"?V:H)||H==="--test";if((Q==="npx"||Q==="bunx")&&YJ.has(H??""))return!0;if(YJ.has(Q??""))return!0;if(Q==="node"&&H==="--test")return!0;if(Q==="go"&&["build","test","vet"].includes(H??""))return!0;return Q==="cargo"&&["build","check","clippy","test"].includes(H??"")}function t5($,Z){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!Z)return!z$.isAbsolute($);let J=z$.isAbsolute($)?z$.resolve($):z$.resolve(Z,$);return j$.isWithinWorkspace(J,Z)}var IZ=S0("Agent"),c8=3;function hZ($,Z,J){if($!=="length")return{action:"none"};if(Z>=c8)return{action:"truncated"};if(e6(J)==="stop")return IZ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var l8=[/:\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],i8=/```[\s\S]{50,}```/,QJ="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",r8=2;function vZ($,Z,J=!0){if(!$||Z>=r8)return{action:"none"};if(!J&&i8.test($))return{action:"retry",prompt:QJ};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(l8.some((X)=>X.test(W)))return{action:"retry",prompt:QJ};return{action:"none"}}var g1=2,n8="The model returned tool-call JSON as text instead of completing the requested tool workflow.",o8="The previous response contained tool-call JSON as ordinary text. It did not execute a tool. If the requested operation is still needed, use the native tool-call interface with an available tool. If it already succeeded, use the recorded result to answer instead of repeating the operation. Do not return another tool-call JSON envelope as your final answer.";function CZ($,Z,J,W){if(!$||$.length>65536||J.length===0)return{action:"none"};let Y=Z.replace(/```[\s\S]*?(?:```|$)/g,"").replace(/^\s*>.*$/gm,"");if(/\b(?:example|schema|serialize|serialization|quote|print|illustrate|verbatim)\b|示例|样例|序列化|引用原文/i.test(Y)||/\b(?:explain|show|return|output)\b[^.!?\n]{0,80}\b(?:json|tool.calls?)\b|(?:解释|展示|输出|返回)[^。!?\n]{0,40}(?:JSON|工具调用格式)/i.test(Y)||/\b(?:do not|don't|never)\s+(?:use|call|invoke|execute)\s+(?:any\s+)?tools?\b|不要(?:使用|调用|执行)(?:任何)?工具/i.test(Y))return{action:"none"};let K;try{K=JSON.parse($)}catch{return{action:"none"}}if(!K||typeof K!=="object"||Array.isArray(K)||Object.keys(K).length!==1||!("tool_calls"in K)||!Array.isArray(K.tool_calls)||K.tool_calls.length===0||K.tool_calls.length>32)return{action:"none"};let X=new Set;for(let Q of K.tool_calls){if(!Q||typeof Q!=="object"||Array.isArray(Q))return{action:"none"};let H="function"in Q;if(Object.keys(Q).some((G)=>!["id","type",...H?["function"]:["name","arguments"]].includes(G)))return{action:"none"};if("type"in Q&&Q.type!=="function")return{action:"none"};let V=H?Q.function:Q;if(!V||typeof V!=="object"||Array.isArray(V)||!("name"in V)||typeof V.name!=="string"||!("arguments"in V))return{action:"none"};if(H&&Object.keys(V).some((G)=>G!=="name"&&G!=="arguments"))return{action:"none"};if(!J.includes(V.name))return{action:"none"};let z=V.arguments;if(typeof z!=="string"&&(!z||typeof z!=="object"||Array.isArray(z)))return{action:"none"};let w=V.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),B=new RegExp(`(?:^|[.!?。!?;;\\n])\\s*(?:please\\s+)?(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${w}(?![\\w:-])|(?:^|[。!?;\\n])\\s*(?:请)?(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${w}(?![\\w:-])`,"i"),j=new RegExp(`(?:do not|don't|never)\\s+(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${w}(?![\\w:-])|(?:不要|禁止)(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${w}(?![\\w:-])`,"i");if(!B.test(Y)||j.test(Y))return{action:"none"};X.add(V.name)}return W<g1?{action:"retry",prompt:o8,...X.size===1?{toolName:[...X][0]}:{}}:{action:"fail",message:n8}}var a8=[/\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}(?:测试|单测|集成测试|检查|构建)/],HJ={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},s8={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},t8="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.",e8="Required verification did not run successfully before the retry limit.",$9=3;function zJ($,Z,J,W){if(!J.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(Z)){$.clear();return}if(Z==="Bash"&&typeof J.metadata?.command==="string"&&J.metadata.exit_code===0&&T$(J.metadata.command,W)){$.add(J.metadata.command);return}if(!["Task","TaskOutput"].includes(Z))return;let Y=J.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let K of Y)if(typeof K==="string"&&T$(K,W))$.add(K)}function gZ($,Z,J){if(!$||!a8.some((H)=>H.test($)))return{action:"none"};let W=Object.keys(HJ).filter((H)=>HJ[H].test($)),Y=[...Z],K=W.filter((H)=>!Y.some((V)=>s8[H].test(V)));if(W.length>0?K.length===0:Y.some((H)=>T$(H)))return{action:"none"};if(J>=$9)return{action:"fail",message:e8};let Q=W.length>1&&K.length>0?` Missing successful verification categories: ${K.join(", ")}.`:"";return{action:"retry",prompt:`${t8}${Q}`}}var Z9=[/\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|子代理|子智能体)/],jJ=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function BJ($){return typeof $==="string"&&jJ.some((Z)=>Z.test($))}var J9=[/\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|子代理)/],W9=[/\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 Y9($){if(typeof $!=="string")return;if(W9.some((Z)=>Z.test($)))return"multiple-allowed";return J9.some((Z)=>Z.test($))?"required":void 0}function Y1($){for(let Z of $){let J=Y9(Z);if(J!==void 0)return J==="required"}return!1}var K9="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.",X9="Required delegation did not complete before the retry limit.",Q9=3;function DJ($,Z,J){let W=(typeof $==="string"?[$]:$??[]).map((X)=>X.trim()).filter(Boolean),Y=Y1(W),K=!1;if(!Y)for(let X of W){if(jJ.some((Q)=>Q.test(X)))break;if(Z9.some((Q)=>Q.test(X))){K=!0;break}}if(W.length===0||!Y&&!K||Z.has("Task"))return{action:"none"};if(J>=Q9)return{action:"fail",message:X9};return{action:"retry",prompt:K9}}var H9=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],V9=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],z9=[/\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 wJ($){return z9.reduce((Z,J)=>Z.replace(J," "),$)}function p1($){if(typeof $!=="string")return!1;let Z=wJ($);return H9.some((J)=>J.test(Z))}var j9="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.",B9="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.",D9="Required worktree lifecycle did not complete before the retry limit.",w9=3;function UJ($,Z,J){if(!$)return{action:"none"};let W=wJ($);if(!p1(W))return{action:"none"};let Y=V9.some((X)=>X.test(W));if(Z.has("TaskWorktree"))return{action:"none"};let K=!Z.has("EnterWorktree")?"EnterWorktree":Y&&!Z.has("ExitWorktree")?"ExitWorktree":void 0;if(!K)return{action:"none"};if(J>=w9)return{action:"fail",message:D9};return{action:"retry",tool:K,prompt:K==="EnterWorktree"?j9:B9}}var VJ=30000;async function pZ($){try{let J=R$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??j0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((K)=>{W=setTimeout(()=>K("timeout"),VJ)});try{let K=await Promise.race([J,Y]);if(K==="timeout")return IZ.warn(`[Loop] Stop hook 超时 (${VJ}ms),按 shouldStop: true 处理`),{action:"stop"};let X=K;if(!X.shouldStop)return{action:"continue",reason:X.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(Z){return IZ.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}async function U9($,Z){let J;while(!(J=await $.next()).done)if(Z)await Z(J.value);return J.value}var q9=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function G9($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((Z)=>{if(typeof Z==="string")return Z;if(Z&&typeof Z==="object"&&"text"in Z){let J=Z.text;return typeof J==="string"?J:""}return""}).join(" ");return""}function L9($){let Z=$;for(let H of q9)Z=Z.replace(H," ");Z=Z.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let J=Z.replace(/\s+/g," ").trim();if(!J)return"";let W=J.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:J;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let K=Y.slice(0,60),X=K.lastIndexOf(" ");return`${(X>36?K.slice(0,X):K).trimEnd()}…`}function qJ($){return L9(G9($))}import{EventEmitter as F9}from"events";import GJ from"node:path";function uZ($){if(FJ($.sessionId),!GJ.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:GJ.resolve($.projectPath)}}function LJ($){let Z=uZ($);return JSON.stringify([Z.projectPath,Z.sessionId])}function j3($,Z){return LJ($)===LJ(Z)}class M$ extends F9{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!M$.instance)M$.instance=new M$;return M$.instance}publish($,Z,J,W){let Y=uZ($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:Z,...W!==void 0?{seq:W}:{},properties:J})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var K1=M$.getInstance();var $$=S0("Agent"),u1=new Set;async function O9($,Z){let J=$.sessionId;if(!J||$.subagentInfo)return;if(u1.has(J))return;if(u1.size>=5000)u1.clear();u1.add(J);try{let W=$.workspaceRoot,Y=await X1.findSessionMetadata(J,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let K=qJ(Z);if(!K)return;await X1.updateSessionMetadata(J,Y.projectPath,{title:K}),K1.publish({sessionId:J,projectPath:Y.projectPath},"session.updated",{title:K})}catch(W){$$.debug?.("[Loop] 自动生成会话标题失败:",W)}}var mZ=`<turn_aborted>
|
|
1
|
+
import{xc as G8}from"./chunk-fdr4fcrf.js";import{$d as R6,Ac as U$,Bc as A2,Cc as a1,Ec as j$,Fd as E2,Gd as L8,Hd as F8,Id as V6,Jd as JZ,Kd as O8,Ld as P8,Md as r1,Qd as rJ,Zd as u0,ae as t1,be as M6,ie as X1,ud as b2,wd as y2,xd as f2,yc as q$,yd as w6,zd as U6}from"./chunk-b88ff25j.js";import{ne as q8}from"./chunk-egss0m1x.js";import{Fe as f0,qe as q0,te as j2,ue as u$}from"./chunk-ztreczac.js";import{eg as p2}from"./chunk-5yyp6njq.js";import{fg as w8,gg as C0,hg as H8,ig as dJ,kg as i1,lg as T6,mg as cJ,ng as lJ,qg as iJ}from"./chunk-myvt7yjm.js";import{ch as K$,dh as n0,gh as U8}from"./chunk-kehgewqh.js";import{lh as a2,ph as Y2}from"./chunk-kkzznz4w.js";import{Ah as R$}from"./chunk-4szhq9af.js";import{Vi as x$}from"./chunk-qpmvp4q2.js";import{cj as j0}from"./chunk-qdbbke8f.js";import{Ej as S0}from"./chunk-rmfzym94.js";import{Yj as _2}from"./chunk-ctrr7v68.js";import{Ck as FJ,Dk as ZZ,Fk as O2,Kk as P2,Lk as N2,gk as F2,vk as w2,wk as U2,zk as H1}from"./chunk-n52n2w5v.js";import{Nk as lZ}from"./chunk-cjfb4kjp.js";function S$($){return $.role==="system"&&Array.isArray($.content)}function E$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class C1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,Z){this.context=$;let J=$.messages.find(S$);if(this._contextualSystemMessages=$.messages.filter(E$),J)this.systemMessages=[J,...this._contextualSystemMessages];else if(Z)this.systemMessages=[{role:"system",content:[{type:"text",text:Z,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!S$(W)&&!E$(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(!E$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(S$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,Z){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push({...Z,metadata:{...Z.metadata&&typeof Z.metadata==="object"&&!Array.isArray(Z.metadata)?Z.metadata:{},...f0}})}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((Z)=>Z.id===$.id))return;this._history.push($)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((Z)=>!S$(Z)&&!E$(Z)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(E$),this._history=$.filter((Z)=>!S$(Z)&&!E$(Z)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let Z=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages(),this._history.length!==Z[0]||this._pending.length!==Z[1]||this._contextualSystemMessages.length!==Z[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function e6($){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 $J($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function ZJ($,Z,J){return{...$,usage:$.usage+Z,lastOutputDelta:Z,consecutiveContinuations:J?$.consecutiveContinuations+1:0}}import z$ from"node:path";var k8=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"]),x8=/^(LD_.+|DYLD_.+|PATH)$/,JJ=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function Z1($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],K=W.match(JJ);if(!K)break;let X=K[1];if(!k8.has(X))break;Z=Y}return Z}function r5($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],K=W.match(JJ);if(!K)break;let X=K[1];if(x8.test(X))break;Z=Y}return Z}var I8=[/^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 xZ($){let Z=$,J=!0;while(J){J=!1;for(let W of I8){let Y=Z.match(W);if(Y){Z=Z.slice(Y[0].length),J=!0;break}}if(Z.startsWith("-- "))Z=Z.slice(3),J=!0}return Z}function J1($){let Z=[],J="",W=!1,Y=!1,K=!1;for(let X=0;X<$.length;X++){let Q=$[X];if(K){J+=Q,K=!1;continue}if(Q==="\\"&&!W){J+=Q,K=!0;continue}if(Q==="'"&&!Y){W=!W,J+=Q;continue}if(Q==='"'&&!W){Y=!Y,J+=Q;continue}if(W||Y){J+=Q;continue}if(Q==="|"){if(X+1<$.length&&$[X+1]==="|"){if(J.trim())Z.push(J.trim());J="",X++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&X+1<$.length&&$[X+1]==="&"){if(J.trim())Z.push(J.trim());J="",X++;continue}if(Q==="&")return null;if(Q===";"){if(J.trim())Z.push(J.trim());J="";continue}J+=Q}if(J.trim())Z.push(J.trim());return Z.length>0?Z:null}function WJ($){let Z=!1,J=!1,W=!1;for(let Y=0;Y<$.length;Y++){let K=$[Y];if(W){W=!1;continue}if(K==="\\"&&!Z){W=!0;continue}if(K==="'"&&!J){Z=!Z;continue}if(K==='"'&&!Z){J=!J;continue}if(Z)continue;if(K==="$"){let X=$[Y+1];if(X&&/[A-Za-z_@*#?!$0-9({]/.test(X))return!0}if(K==="`")return!0;if(J)continue;if(K==="|")return!0;if(K===">"||K==="<")return!0;if(K==="{"){let X=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(X)||/^\{[^}]*\.\.[^}]*\}/.test(X))return!0}}return!1}function V$($){let Z=[],J="",W=!1,Y=!1,K=!1;for(let X=0;X<$.length;X++){let Q=$[X];if(K){J+=Q,K=!1;continue}if(Q==="\\"&&!W){if(K=!0,Y){let H=$[X+1];if(H&&'$`"\\'.includes(H))continue;J+=Q,K=!1}continue}if(Q==="'"&&!Y){W=!W;continue}if(Q==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(Q)){if(J)Z.push(J),J="";continue}J+=Q}if(J)Z.push(J);return Z}var h8=new Set(["npm","pnpm","yarn","bun"]),YJ=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),v8=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),C8=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function g8($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function KJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function p8($,Z,J){if(!J||Z.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 K=Y[1];if(!K||K==="-")return;let X=z$.isAbsolute(K)?z$.resolve(K):z$.resolve(J,K);if(!j$.isWithinWorkspace(X,J))return;return W[2]?.trim()||void 0}function u8($){let Z=[],J=!1,W=!1,Y=!1;for(let K=0;K<$.length;K++){let X=$[K];if(Y){Y=!1;continue}if(X==="\\"&&!J){Y=!0;continue}if(X==="'"&&!W){J=!J;continue}if(X==='"'&&!J){W=!W;continue}if(X!=="|"||J||W)continue;if($[K+1]==="|")return;Z.push(K)}return Z}function m8($){let Z=V$($),[J,W,Y]=Z;if(J!=="head"&&J!=="tail")return!1;if(Z.length===1)return!0;let K=(X)=>X!==void 0&&/^[1-9]\d{0,4}$/.test(X);if(Z.length===2)return W?.startsWith("--lines=")&&K(W.slice(8))||W?.startsWith("-")&&K(W.slice(1));return Z.length===3&&(W==="-n"||W==="--lines")&&K(Y)}function d8($){let Z=KJ($.replace(C8,"").trim()),J=u8(Z);if(!J)return;if(J.length===0)return XJ(Z);if(J.length!==1)return;let W=J[0];if(W===void 0)return;let Y=KJ(Z.slice(0,W).trim()),K=Z.slice(W+1).trim();if(!Y||!m8(K))return;return XJ(Y)}function XJ($){let J=J1($)?.at(-1);if(!J)return $;let W=V$(J),[Y,K]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&K==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function T$($,Z){let J=d8($);if(!J)return!1;let W=Z1(J),Y=J1(W);if(!Y||WJ(W)||/[\r\n]/.test(W))return!1;let K=Y.length===1?Y[0]:p8(W,Y,Z);if(!K)return!1;let X=V$(K);if(X.length===0||X.some((z)=>[...v8].some((w)=>z===w||z.startsWith(`${w}=`))))return!1;let[Q,H,V]=X;if(h8.has(Q??""))return g8(H==="run"?V:H)||H==="--test";if((Q==="npx"||Q==="bunx")&&YJ.has(H??""))return!0;if(YJ.has(Q??""))return!0;if(Q==="node"&&H==="--test")return!0;if(Q==="go"&&["build","test","vet"].includes(H??""))return!0;return Q==="cargo"&&["build","check","clippy","test"].includes(H??"")}function t5($,Z){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!Z)return!z$.isAbsolute($);let J=z$.isAbsolute($)?z$.resolve($):z$.resolve(Z,$);return j$.isWithinWorkspace(J,Z)}var IZ=S0("Agent"),c8=3;function hZ($,Z,J){if($!=="length")return{action:"none"};if(Z>=c8)return{action:"truncated"};if(e6(J)==="stop")return IZ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var l8=[/:\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],i8=/```[\s\S]{50,}```/,QJ="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",r8=2;function vZ($,Z,J=!0){if(!$||Z>=r8)return{action:"none"};if(!J&&i8.test($))return{action:"retry",prompt:QJ};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(l8.some((X)=>X.test(W)))return{action:"retry",prompt:QJ};return{action:"none"}}var g1=2,n8="The model returned tool-call JSON as text instead of completing the requested tool workflow.",o8="The previous response contained tool-call JSON as ordinary text. It did not execute a tool. If the requested operation is still needed, use the native tool-call interface with an available tool. If it already succeeded, use the recorded result to answer instead of repeating the operation. Do not return another tool-call JSON envelope as your final answer.";function CZ($,Z,J,W){if(!$||$.length>65536||J.length===0)return{action:"none"};let Y=Z.replace(/```[\s\S]*?(?:```|$)/g,"").replace(/^\s*>.*$/gm,"");if(/\b(?:example|schema|serialize|serialization|quote|print|illustrate|verbatim)\b|示例|样例|序列化|引用原文/i.test(Y)||/\b(?:explain|show|return|output)\b[^.!?\n]{0,80}\b(?:json|tool.calls?)\b|(?:解释|展示|输出|返回)[^。!?\n]{0,40}(?:JSON|工具调用格式)/i.test(Y)||/\b(?:do not|don't|never)\s+(?:use|call|invoke|execute)\s+(?:any\s+)?tools?\b|不要(?:使用|调用|执行)(?:任何)?工具/i.test(Y))return{action:"none"};let K;try{K=JSON.parse($)}catch{return{action:"none"}}if(!K||typeof K!=="object"||Array.isArray(K)||Object.keys(K).length!==1||!("tool_calls"in K)||!Array.isArray(K.tool_calls)||K.tool_calls.length===0||K.tool_calls.length>32)return{action:"none"};let X=new Set;for(let Q of K.tool_calls){if(!Q||typeof Q!=="object"||Array.isArray(Q))return{action:"none"};let H="function"in Q;if(Object.keys(Q).some((G)=>!["id","type",...H?["function"]:["name","arguments"]].includes(G)))return{action:"none"};if("type"in Q&&Q.type!=="function")return{action:"none"};let V=H?Q.function:Q;if(!V||typeof V!=="object"||Array.isArray(V)||!("name"in V)||typeof V.name!=="string"||!("arguments"in V))return{action:"none"};if(H&&Object.keys(V).some((G)=>G!=="name"&&G!=="arguments"))return{action:"none"};if(!J.includes(V.name))return{action:"none"};let z=V.arguments;if(typeof z!=="string"&&(!z||typeof z!=="object"||Array.isArray(z)))return{action:"none"};let w=V.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),B=new RegExp(`(?:^|[.!?。!?;;\\n])\\s*(?:please\\s+)?(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${w}(?![\\w:-])|(?:^|[。!?;\\n])\\s*(?:请)?(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${w}(?![\\w:-])`,"i"),j=new RegExp(`(?:do not|don't|never)\\s+(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${w}(?![\\w:-])|(?:不要|禁止)(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${w}(?![\\w:-])`,"i");if(!B.test(Y)||j.test(Y))return{action:"none"};X.add(V.name)}return W<g1?{action:"retry",prompt:o8,...X.size===1?{toolName:[...X][0]}:{}}:{action:"fail",message:n8}}var a8=[/\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}(?:测试|单测|集成测试|检查|构建)/],HJ={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},s8={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},t8="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.",e8="Required verification did not run successfully before the retry limit.",$9=3;function zJ($,Z,J,W){if(!J.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(Z)){$.clear();return}if(Z==="Bash"&&typeof J.metadata?.command==="string"&&J.metadata.exit_code===0&&T$(J.metadata.command,W)){$.add(J.metadata.command);return}if(!["Task","TaskOutput"].includes(Z))return;let Y=J.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let K of Y)if(typeof K==="string"&&T$(K,W))$.add(K)}function gZ($,Z,J){if(!$||!a8.some((H)=>H.test($)))return{action:"none"};let W=Object.keys(HJ).filter((H)=>HJ[H].test($)),Y=[...Z],K=W.filter((H)=>!Y.some((V)=>s8[H].test(V)));if(W.length>0?K.length===0:Y.some((H)=>T$(H)))return{action:"none"};if(J>=$9)return{action:"fail",message:e8};let Q=W.length>1&&K.length>0?` Missing successful verification categories: ${K.join(", ")}.`:"";return{action:"retry",prompt:`${t8}${Q}`}}var Z9=[/\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|子代理|子智能体)/],jJ=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function BJ($){return typeof $==="string"&&jJ.some((Z)=>Z.test($))}var J9=[/\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|子代理)/],W9=[/\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 Y9($){if(typeof $!=="string")return;if(W9.some((Z)=>Z.test($)))return"multiple-allowed";return J9.some((Z)=>Z.test($))?"required":void 0}function Y1($){for(let Z of $){let J=Y9(Z);if(J!==void 0)return J==="required"}return!1}var K9="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.",X9="Required delegation did not complete before the retry limit.",Q9=3;function DJ($,Z,J){let W=(typeof $==="string"?[$]:$??[]).map((X)=>X.trim()).filter(Boolean),Y=Y1(W),K=!1;if(!Y)for(let X of W){if(jJ.some((Q)=>Q.test(X)))break;if(Z9.some((Q)=>Q.test(X))){K=!0;break}}if(W.length===0||!Y&&!K||Z.has("Task"))return{action:"none"};if(J>=Q9)return{action:"fail",message:X9};return{action:"retry",prompt:K9}}var H9=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],V9=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],z9=[/\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 wJ($){return z9.reduce((Z,J)=>Z.replace(J," "),$)}function p1($){if(typeof $!=="string")return!1;let Z=wJ($);return H9.some((J)=>J.test(Z))}var j9="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.",B9="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.",D9="Required worktree lifecycle did not complete before the retry limit.",w9=3;function UJ($,Z,J){if(!$)return{action:"none"};let W=wJ($);if(!p1(W))return{action:"none"};let Y=V9.some((X)=>X.test(W));if(Z.has("TaskWorktree"))return{action:"none"};let K=!Z.has("EnterWorktree")?"EnterWorktree":Y&&!Z.has("ExitWorktree")?"ExitWorktree":void 0;if(!K)return{action:"none"};if(J>=w9)return{action:"fail",message:D9};return{action:"retry",tool:K,prompt:K==="EnterWorktree"?j9:B9}}var VJ=30000;async function pZ($){try{let J=R$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??j0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((K)=>{W=setTimeout(()=>K("timeout"),VJ)});try{let K=await Promise.race([J,Y]);if(K==="timeout")return IZ.warn(`[Loop] Stop hook 超时 (${VJ}ms),按 shouldStop: true 处理`),{action:"stop"};let X=K;if(!X.shouldStop)return{action:"continue",reason:X.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(Z){return IZ.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}async function U9($,Z){let J;while(!(J=await $.next()).done)if(Z)await Z(J.value);return J.value}var q9=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function G9($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((Z)=>{if(typeof Z==="string")return Z;if(Z&&typeof Z==="object"&&"text"in Z){let J=Z.text;return typeof J==="string"?J:""}return""}).join(" ");return""}function L9($){let Z=$;for(let H of q9)Z=Z.replace(H," ");Z=Z.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let J=Z.replace(/\s+/g," ").trim();if(!J)return"";let W=J.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:J;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let K=Y.slice(0,60),X=K.lastIndexOf(" ");return`${(X>36?K.slice(0,X):K).trimEnd()}…`}function qJ($){return L9(G9($))}import{EventEmitter as F9}from"events";import GJ from"node:path";function uZ($){if(FJ($.sessionId),!GJ.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:GJ.resolve($.projectPath)}}function LJ($){let Z=uZ($);return JSON.stringify([Z.projectPath,Z.sessionId])}function j3($,Z){return LJ($)===LJ(Z)}class M$ extends F9{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!M$.instance)M$.instance=new M$;return M$.instance}publish($,Z,J,W){let Y=uZ($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:Z,...W!==void 0?{seq:W}:{},properties:J})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var K1=M$.getInstance();var $$=S0("Agent"),u1=new Set;async function O9($,Z){let J=$.sessionId;if(!J||$.subagentInfo)return;if(u1.has(J))return;if(u1.size>=5000)u1.clear();u1.add(J);try{let W=$.workspaceRoot,Y=await X1.findSessionMetadata(J,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let K=qJ(Z);if(!K)return;await X1.updateSessionMetadata(J,Y.projectPath,{title:K}),K1.publish({sessionId:J,projectPath:Y.projectPath},"session.updated",{title:K})}catch(W){$$.debug?.("[Loop] 自动生成会话标题失败:",W)}}var mZ=`<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>`,B$="Tool execution was blocked because its durable call record could not be committed. No tool side effect was started.",OJ="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 k$ extends Error{phase;constructor($,Z){super($==="user_message"?"Conversation input could not be committed. No further model request was started.":"Model output could not be committed. The run was stopped before any further model request or successful completion.",Z);this.phase=$;this.name="DurableConversationPersistenceError"}}function D$($){return $.executionEngine?.getContextManager()}async function r0($,Z,J,W=null,Y,K={}){let X=K.required??$.executionEngine!==void 0;try{let Q=D$($),H=typeof J==="string"?J.trim()!=="":J.some((V)=>V.type==="text"?V.text.trim()!=="":!0);if(Q&&Z.sessionId&&H){let V=await Q.saveMessage(Z.sessionId,"user",J,W,Y,Z.subagentInfo);if(X&&!V)throw Error("Durable user-message commit returned no identity");if(Y?.clientVisible!==!1)O9(Z,J);return V}if(X&&Z.sessionId&&H)throw Error("Durable user-message storage is unavailable")}catch(Q){if($$.warn("[Loop] 保存用户消息失败:",Q),X)throw new k$("user_message",{cause:Q})}return null}async function v0($,Z,J,W,Y,K,X={}){let Q=X.required??$.executionEngine!==void 0;try{let H=D$($),V=Boolean(J.trim()||Y?.trim());if(H&&Z.sessionId&&V){let z=await H.saveMessage(Z.sessionId,"assistant",J,W,K,Z.subagentInfo,Y);if(Q&&!z)throw Error("Durable assistant-message commit returned no identity");return z}if(Q&&Z.sessionId&&V)throw Error("Durable assistant-message storage is unavailable")}catch(H){if($$.warn("[Loop] 保存助手消息失败:",H),Q)throw new k$("assistant_message",{cause:H})}return null}async function PJ($,Z,J){try{let W=D$($);if(W&&Z.sessionId)return await W.saveMessage(Z.sessionId,"system",mZ,J,void 0,Z.subagentInfo)}catch(W){$$.warn("[Loop] 保存中断边界失败:",W)}return null}async function NJ($,Z,J,W,Y){try{let K=D$($);if(!K||!Z.sessionId||J.length===0)return null;return await K.saveMessage(Z.sessionId,"system",`<contextual-project-instructions-ref count="${J.length}" />`,Y,{contextualProjectRules:!0,ruleReferences:JSON.parse(JSON.stringify(J.map((X)=>({...X})))),triggerPaths:[...W]},Z.subagentInfo)}catch(K){$$.warn("[Loop] 保存 contextual project rules provenance 失败:",K)}return null}async function dZ($,Z,J,W,Y,K={}){try{let X=D$($);if(X&&Z.sessionId){let Q=await X.saveToolUse(Z.sessionId,J,W,Y,Z.subagentInfo,K.providerToolCallId);if(K.required&&!Q)throw Error("Durable tool-use commit returned no identity");return Q}if(K.required&&Z.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(X){if($$.warn("[Loop] 保存工具调用失败:",X),K.required)throw X}return null}async function m1($,Z,J,W,Y,K,X,Q,H,V={}){try{let z=D$($);if(z&&Z.sessionId){let w=await z.saveToolResult(Z.sessionId,J,W,Y,K,X,Z.subagentInfo,Q,H);if(V.required&&!w)throw Error("Durable tool-result commit returned no identity");return w}if(V.required&&Z.sessionId)throw Error("Durable tool-result storage is unavailable")}catch(z){if($$.warn("[Loop] 保存工具结果失败:",z),V.required)throw z}return null}async function Q1($,Z,J,W,Y={}){try{let K=D$($);if(K&&Z.sessionId){let X=await K.saveCompaction(Z.sessionId,J,W,null);if(Y.required&&!X)throw Error("Compaction checkpoint commit returned no identity");return X||null}if(Y.required&&Z.sessionId)throw Error("Compaction checkpoint storage is unavailable")}catch(K){if($$.warn("[Loop] 保存压缩数据失败:",K),Y.required)throw K}return null}async function V0($){let{deps:Z,context:J,state:W,assistantContent:Y,assistantReasoningContent:K,lastMessageUuid:X,controlPrompt:Q}=$;W.appendAssistant({role:"assistant",content:Y,reasoningContent:K});let H=X,V=await v0(Z,J,Y,H,K);if(V)H=V;if(Q!==void 0){let z={role:"user",content:Q,metadata:f0};W.appendControl("user",z);let w=await r0(Z,J,Q,H,f0);if(w)H=w}return H}import{createHash as k6}from"node:crypto";import{promises as n9}from"node:fs";import o9 from"node:path";import{nanoid as J$}from"nanoid";import*as $0 from"node:fs/promises";import*as Z$ from"node:path";import AJ from"write-file-atomic";var _J={enabled:!0,maxIndexLines:200};var P9="memory",cZ="MEMORY.md",iZ="<!-- blade:auto-memory-topics:start -->",d1="<!-- blade:auto-memory-topics:end -->",N9={realpath:!1,retries:{retries:5,factor:1.2,minTimeout:20,maxTimeout:100,randomize:!0}},_9=new x$,bJ;function fJ($){return $.trim().replace(/\s+/g," ")}function A9($){return fJ($.replace(/^- \[\d{4}-\d{2}-\d{2}\] /,""))}function b9($){return[iZ,"## Auto-consolidated topics",...$.map((Z)=>`- [${Z}](${Z}.md)`),d1].join(`
|
|
4
4
|
`)}function y9($,Z){let J=b9(Z),W=$.indexOf(iZ),Y=$.indexOf(d1,Math.max(0,W));if(W>=0&&Y>=W)return $.slice(0,W)+J+$.slice(Y+d1.length);if(!$)return`${J}
|
|
@@ -118,8 +118,8 @@ When facing complex multi-step tasks:
|
|
|
118
118
|
2. Execute one step at a time — verify each step succeeded before moving to the next.
|
|
119
119
|
3. If a step fails, diagnose the root cause rather than repeating the same approach.
|
|
120
120
|
4. When uncertain about file paths or project structure, use Grep/Glob/Read to gather facts first.
|
|
121
|
-
5. Prefer the smallest change that achieves the goal — avoid unnecessary refactoring.`}`}var L$=S0("Agent"),A5=new Set(["Read","Glob","Grep","WebFetch","WebSearch","MemoryRead","ReadPromptArtifact","GetSpecContext","ValidateSpec","TaskOutput"]);class zZ{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 q1;toolUsePersistenceTail=Promise.resolve();constructor($,Z,J,W,Y,K,X,Q,H=!1){this.pipeline=$;this.execContext=Z;this.registry=J;this.contextMgr=W;this.sessionId=Y;this.lastMessageUuid=K;this.subagentInfo=X;this.progressSink=Q;this.requireDurableToolUse=H}setExecutionPolicy($){this.executeTool=$}setAdmissionPolicy($){this.admitTool=$}setAdmissionRollback($){this.rollbackAdmission=$}addTool($,Z){if(this.dispatched.has($.id))return L$.debug(`[StreamingToolExecutor] 跳过已分发工具: ${$.function.name} (${$.id})`),"rejected";this.dispatched.add($.id),this.order.push($.id);let J=this.turnAdmission.admit();if(J)return this.completed.set($.id,{toolCall:$,result:J,toolUseUuid:null}),"rejected";G1($.function.name,Z),$.function.arguments=JSON.stringify(Z);let W=this.admitTool?.($.function.name,Z);if(W)return this.completed.set($.id,{toolCall:$,result:W,toolUseUuid:null}),"rejected";let Y=this.registry.get($.function.name),K=Y?.isConcurrencySafe===!0,X=Y?.parallelism==="shared"||Y?.parallelism===void 0&&K;if(A5.has($.function.name)&&K&&!this.hasExclusiveBarrier){L$.debug(`[StreamingToolExecutor] 立即执行预启动工具: ${$.function.name}`);let H=this.executeOne($,Z);return this.pending.set($.id,H),"prelaunched"}else{if(L$.debug(`[StreamingToolExecutor] 排队非预启动工具: ${$.function.name}`),this.queued.push({toolCall:$,params:Z}),!X)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 Z=await this.pending.get($);this.pending.delete($),yield Z;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(),L$.debug(`[StreamingToolExecutor] 已丢弃所有挂起工作并重置状态 (epoch=${this.epoch})`)}hasTools(){return this.order.length>0}getEpoch(){return this.epoch}makeAbortResult($,Z,J=null){return{toolCall:$,result:{success:!1,llmContent:"",error:{type:"execution_error",message:Z},metadata:{abortedBeforeLaunch:!0}},toolUseUuid:J}}dispatchQueuedTools(){let $=this.queued;this.queued=[],this.hasExclusiveBarrier=!1;let Z=this.epoch;for(let{toolCall:J,params:W}of $){if(this.execContext.signal?.aborted){this.completed.set(J.id,this.makeAbortResult(J,"Tool execution skipped: task aborted before launch"));continue}let Y=this.executeQueued(J,W,Z);this.pending.set(J.id,Y)}}async executeQueued($,Z,J){if(J!==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($,Z)}async executeOne($,Z){let J=this.epoch,W=new AbortController;this.activeAborts.set($.id,W);let Y=null,K=this.abortController.signal;try{if(K.aborted||W.signal.aborted)return this.makeAbortResult($,"Tool execution aborted due to discard");try{if(this.contextMgr&&this.sessionId)Y=await this.persistToolUseInOrder($,Z);else if(this.requireDurableToolUse&&this.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(B){if(L$.warn("[StreamingToolExecutor] 保存工具调用失败:",B),!this.requireDurableToolUse)Y=null;else return{toolCall:$,result:{success:!1,llmContent:B$,error:{type:"execution_error",message:B$},metadata:{durableToolUseFailed:!0,summary:"Blocked tool before execution"}},toolUseUuid:null,error:B instanceof Error?B:Error(String(B))}}let X=[K,W.signal],Q=this.execContext.signal;if(Q)X.push(Q);let H=H8(...X),V={...this.execContext,messageId:Y??$.id,signal:H,confirmationHandler:this.execContext.sessionId&&this.execContext.workspaceRoot&&this.execContext.workspaceKind!=="acp-remote"?G0.createConfirmationHandler(this.execContext.confirmationHandler,{sessionId:this.execContext.sessionId,projectPath:this.execContext.workspaceRoot,toolCallId:Y??$.id,toolName:$.function.name}):this.execContext.confirmationHandler,onProgress:(B)=>{this.execContext.onProgress?.(B),this.progressSink?.($,{message:B.slice(0,1000)})},onProgressUpdate:(B)=>{this.execContext.onProgressUpdate?.(B),this.progressSink?.($,B)}},z=this.executeTool?await this.executeTool($.function.name,Z,V):await this.pipeline.execute($.function.name,Z,V);if(J!==this.epoch)return L$.debug(`[StreamingToolExecutor] 丢弃旧世代工具结果: ${$.function.name} (startEpoch=${J}, currentEpoch=${this.epoch})`),this.makeAbortResult($,"Tool execution aborted due to epoch mismatch (discard)",Y);let w={toolCall:$,result:z,toolUseUuid:Y};if(this.pending.has($.id))this.pending.delete($.id),this.completed.set($.id,w);return w}catch(X){if(J!==this.epoch)return this.makeAbortResult($,"Tool execution aborted due to epoch mismatch (discard)",Y);L$.error(`[StreamingToolExecutor] 工具执行失败: ${$.function.name}`,X);let Q={success:!1,llmContent:"",error:{type:"execution_error",message:X instanceof Error?X.message:"Unknown error"},metadata:void 0},H={toolCall:$,result:Q,toolUseUuid:Y,error:X instanceof Error?X:Error("Unknown error")};if(this.pending.has($.id))this.pending.delete($.id),this.completed.set($.id,H);return H}finally{this.activeAborts.delete($.id)}}persistToolUseInOrder($,Z){let J=this.contextMgr,W=this.sessionId;if(!J||!W)return Promise.resolve(null);let Y=this.toolUsePersistenceTail.then(()=>J.saveToolUse(W,$.function.name,Z,this.lastMessageUuid??null,this.subagentInfo,$.id));return this.toolUsePersistenceTail=Y.then(()=>{return},()=>{return}),Y}}class f6{pending=[];waiters=[];closed=!1;push($){if(this.closed)return;let Z=this.waiters.shift();if(Z){Z($);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((Z)=>{this.waiters.push(Z)})}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 V8($,Z){if(!["TaskCreate","TaskUpdate","TaskList"].includes($.function.name)||!Z.success||!Z.llmContent&&!Z.metadata)return null;let J=typeof Z.llmContent==="object"?Z.llmContent:{};return{kind:"task_update",tasks:Z.metadata?.tasks||J.tasks||[]}}function z8($,Z,J){if($.function.name!=="Skill"||!Z.success||!Z.metadata)return;let W=Z.metadata;if(W.skillName)J.onSkillActivated?.({skillName:W.skillName,allowedTools:W.allowedTools,basePath:W.basePath||""})}function j8($){let Z=$.metadata;if(!Z)return;return Z.modelId?.toString().trim()||Z.model?.toString().trim()||void 0||void 0}function b5($,Z,J){if(!["EnterWorktree","ExitWorktree"].includes($.function.name)||!Z.success)return;let W=Z.metadata,Y=W?.workspaceRoot;if(!["enter","exit"].includes(String(W?.workspaceTransition))||typeof Y!=="string"||Y.trim()==="")return;return R$.getInstance().inheritProjectConfig(J.workspaceRoot,Y,J.sessionId),J.workspaceRoot=Y,J.worktreeActive=W?.workspaceTransition==="enter",Y}function y5($,Z){if($.function.name!=="Task")return null;let J=Z.metadata;if(!J?.subagentSessionId)return null;let W=J.subagentSessionId,Y=J.subagentType||"Task",K=J.subagentStatus,X=typeof J.subagentResumedFrom==="string"?J.subagentResumedFrom:void 0,Q=typeof J.subagentRootId==="string"?J.subagentRootId:void 0,H=typeof J.subagentResumeDepth==="number"?J.subagentResumeDepth:void 0;if(K==="completed"||K==="failed"||K==="cancelled")return{kind:"subagent_completed",sessionId:W,type:Y,success:K==="completed",summary:J.subagentSummary,...J.verificationVerdict==="pass"||J.verificationVerdict==="fail"||J.verificationVerdict==="partial"?{verificationVerdict:J.verificationVerdict}:{},...X?{resumedFrom:X}:{},...Q?{rootAgentId:Q}:{},...H!==void 0?{resumeDepth:H}:{}};if(K==="running"){let V="";try{V=JSON.parse($.function.arguments).prompt||""}catch{}return{kind:"subagent_spawned",sessionId:W,type:Y,prompt:V,resumedFrom:X,rootAgentId:Q,resumeDepth:H}}return null}async function E6($,Z,J,W){let Y=V8($,Z),K=y5($,Z);z8($,Z,J);let X=j8(Z);if(X)await J.onModelSwitch?.(X);if(W)b5($,Z,W);return K||Y}var r=S0("Agent");function F$($,Z){return{inputTokens:$.promptTokens??0,outputTokens:$.completionTokens??0,totalTokens:n1($)??0,maxContextTokens:Z,cacheReadTokens:$.cacheReadInputTokens??0,cacheWriteTokens:$.cacheCreationInputTokens??0,...$.promptCacheBreak?{cacheBreak:$.promptCacheBreak}:{},costUsd:$.costUsd}}function X$($){return JSON.stringify($).replaceAll("<","\\u003c").replaceAll(">","\\u003e")}function B8($){let Z=$.trim();if(Z=Z.replace(/,\s*([}\]])/g,"$1"),Z.startsWith("{")&&!Z.endsWith("}"))Z+="}";Z=Z.replace(/,\s*([}\]])/g,"$1");try{let J=JSON.parse(Z);if(typeof J==="object"&&J!==null&&!Array.isArray(J))return J;return null}catch{return null}}function L1($){let Z=B8($);if(Z)return Z;try{let J=JSON.parse($);return typeof J==="string"?B8(J):null}catch{return null}}function f5($){let Z=$.metadata&&typeof $.metadata==="object"&&!Array.isArray($.metadata)?$.metadata:void 0;if(Z?.contextualProjectRules!==!0)return[];if(!Array.isArray(Z.ruleReferences))throw Error("Invalid contextual project rule provenance");return Z.ruleReferences.map((J)=>{if(!J||typeof J!=="object"||Array.isArray(J))throw Error("Invalid contextual project rule reference");let W=J;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 E5($){let Z=new Set,J=!1;for(let W of $){if(W.role==="assistant"){if(W.tool_calls&&W.tool_calls.length>0){for(let K of W.tool_calls)if("function"in K&&K.function.name==="Task")Z.add(K.id)}else if(J)J=!1;continue}if(W.role!=="tool"||W.name!=="Task"||!W.tool_call_id||!Z.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)J=!0}return J}function S5($){if(!($ instanceof Error))return"未知错误";let W=$.lastError??$;if(W.responseBody)try{let Q=JSON.parse(W.responseBody)?.error?.message;if(Q){let H=W.statusCode?` (HTTP ${W.statusCode})`:"";return`${Q}${H}`}}catch{}let Y=$.message,K=Y.match(/Last error:\s*(.+)$/);if(K)return K[1];return Y}function T5($){if(!($ instanceof Error))return!1;return["stream not supported","streaming is not available","sse not supported","does not support streaming"].some((J)=>$.message.toLowerCase().includes(J.toLowerCase()))}function R5($,Z){if(!Z)return"Tool execution failed (no details).";let J=[`Error: ${Z.message||"Unknown error"}`];if(Z.type==="validation_error")J.push("Hint: Check the tool parameters — a required field may be missing or have the wrong type.");else if(Z.type==="permission_denied")J.push("Hint: This operation requires user approval. Try a different approach or ask the user.");else if(Z.type==="timeout_error")J.push("Hint: The operation timed out. Consider breaking it into smaller steps or increasing timeout.");else if(Z.type==="execution_error"){let W=Z.message??"";if(W.includes("ENOENT")||W.includes("no such file"))J.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"))J.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"))J.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"))J.push("Hint: A path component is not a directory. Verify the full path with Glob.")}return J.join(`
|
|
122
|
-
`)}function S6($){if(!($ instanceof Error))return!1;return i1($)||$.status===413}function M5($,Z){let J=Z,W=J.index??0;if(!$.has(W))$.set(W,{id:J.id||"",name:J.function?.name||"",arguments:""});let Y=$.get(W);if(J.id&&!Y.id)Y.id=J.id;if(J.function?.name&&!Y.name)Y.name=J.function.name;if(J.function?.arguments)Y.arguments+=J.function.arguments}function k5($){if($.size===0)return;return Array.from($.values()).filter((Z)=>Z.id&&Z.name).map((Z)=>({id:Z.id,type:"function",function:{name:Z.name,arguments:Z.arguments}}))}async function*x5($,Z,J,W,Y,K){let X="",Q="",H,V,z=new Map;try{let w=$.chatService.streamChat(Z,J,W,Y),B=0;for await(let j of w){if(W?.aborted)break;if(j.providerAdmission){yield{kind:"provider_admission",...j.providerAdmission};continue}if(j.providerCircuit){yield{kind:"provider_circuit",...j.providerCircuit};continue}if(j.providerRetry){yield{kind:"provider_retry",...j.providerRetry};continue}if(j.providerStall){yield{kind:"provider_stall",...j.providerStall};continue}if(B++,j.modelFallback){K?.discard(),X="",Q="",H=void 0,V=void 0,z.clear(),B=0,yield{kind:"model_fallback",...j.modelFallback};continue}if(j.content)X+=j.content,yield{kind:"content_delta",delta:j.content};if(j.reasoningContent)Q+=j.reasoningContent,yield{kind:"thinking_delta",delta:j.reasoningContent};if(j.usage)H=j.usage;if(j.toolCalls){for(let G of j.toolCalls)if(M5(z,G),K){let A=G.index??0,S=z.get(A);if(S&&S.id&&S.name)try{let T=L1(S.arguments);if(T===null)continue;let p={id:S.id,type:"function",function:{name:S.name,arguments:S.arguments}},o=$.toolExecutor.getRegistry().get(S.name)?.kind,s=K.addTool(p,T);if(S.arguments=p.function.arguments,s==="prelaunched")yield{kind:"tool_start",toolCall:p,toolKind:o}}catch{}}}if(j.finishReason){V=j.finishReason;break}}if(B===0&&!W?.aborted&&X.length===0&&z.size===0)return r.warn("[Loop] 流式响应返回0个chunk,回退到非流式模式"),K?.discard(),{...await $.chatService.chat(Z,J,W,Y),_nonStreamingFallback:!0};return{content:X,reasoningContent:Q||void 0,toolCalls:k5(z),usage:H,finishReason:V}}catch(w){if(T5(w))return r.warn("[Loop] 流式请求失败,降级到非流式模式"),K?.discard(),{...await $.chatService.chat(Z,J,W,Y),_nonStreamingFallback:!0};throw w}}async function x6($,Z,J){if(!$)return;if(!J)return{outcome:"disabled",entries:0,topics:[]};try{return await RJ($,{workspaceRoot:Z.workspaceRoot||j0(),workspaceAccess:Z.workspaceKind==="acp-remote"?"none":"full"})}catch{return{outcome:"failed",entries:0,topics:[]}}}function I5($){return k6("sha256").update($).digest("hex").slice(0,16)}var h5=new Set(["AbortError","Error","RangeError","TypeError"]),v5=new Set(["EACCES","EEXIST","EIO","EMFILE","ENFILE","ENOENT","ENOSPC","EPERM","EROFS"]);function C5($){if($ instanceof Error){let Z=$,J=h5.has($.name)?$.name:"Error",W=typeof Z.code==="string"&&v5.has(Z.code)?Z.code:"unknown";return`${J}:${W}`}return"UnknownError:unknown"}async function g5($){let{deps:Z,context:J,state:W,snapshot:Y,attemptSpent:K}=$;if(Y.phase!=="handoff_band")return{kind:"failed"};if(W.getHistory().find((H)=>typeof H.id==="string"&&P8(H)))return{kind:"already_present"};if(K)return{kind:"failed"};let Q=Z.executionEngine?.getContextManager();if(!Q)return{kind:"failed"};try{let H=await Q.recordTokenBudgetHandoff(J.sessionId,{version:1,observedPromptTokens:Y.contextTokens??0,availableForInput:Y.availableForInput??0,handoffThreshold:Y.handoffThreshold??0,compactionThreshold:Y.compactionThreshold??0});if(H.outcome==="suppressed")return{kind:"suppressed"};let V=O8(H.event);if(!V)return{kind:"failed"};return W.appendDurableControl(V),{kind:"appended",message:V}}catch(H){let V=`token_budget_handoff_persist_failed session=${I5(J.sessionId)} error=${C5(H)}`;return r.warn(V),{kind:"failed"}}}async function*N8($,Z,J,W,Y,K,X,Q,H){let V=W.contextTokens,z=eJ(Z.messages,K),w=z!==null;if(z)Z.messages=z.messages,r.debug(`[Loop] [轮次 ${J}] MicroCompact: 清理 ${z.snippedCount} 轮旧工具结果(缓存已过期)`);let B=j1(Z.messages),j=!1;if(B.snippedCount>0)j=!0,r.debug(`[Loop] [轮次 ${J}] Snip 压缩: 移除 ${B.snippedCount} 轮旧工具调用,释放约 ${B.estimatedTokensFreed} tokens`);if(W.phase==="unknown"){if(j)Z.messages=B.messages;return r.debug(`[Loop] [轮次 ${J}] 压缩检查: 跳过(无历史 usage 数据)`),w||j?{kind:"snipped"}:{kind:"none"}}let G=$.chatService.getConfig(),N=G.model,A=W.maxContextTokens??0,S=W.maxOutputTokens??0,T=W.availableForInput??0;if(A<=0||T<=0){if(j)Z.messages=B.messages;return r.debug(`[Loop] [轮次 ${J}] 压缩检查: 跳过(模型上下文窗口未知)`),w||j?{kind:"snipped"}:{kind:"none"}}if(r.debug(`[Loop] [轮次 ${J}] 压缩检查:`,{contextTokens:V,tokenSource:W.tokenSource,estimatedPendingTokens:W.estimatedPendingTokens,maxContextTokens:A,maxOutputTokens:S,availableForInput:T,threshold:W.compactionThreshold,shouldCompact:W.phase==="compaction_due"}),W.phase!=="compaction_due"){if(j)Z.messages=B.messages;return w||j?{kind:"snipped"}:{kind:"none"}}r.debug(J===0?"[Loop] 触发自动压缩":`[Loop] [轮次 ${J}] 触发循环内自动压缩`);let p="failed",x,o,s,M,d,t,L,u,m0,h,D0,_0,c,O$="compaction";yield{kind:"compaction",phase:"start",reason:"threshold"};try{let P0=j?B.messages:Z.messages,R=await h$.compact(P0,{trigger:"auto",modelName:N,modelProvider:G.provider,maxContextTokens:A,apiKey:G.apiKey,baseURL:G.baseUrl,chatConfig:G,actualPreTokens:V,signal:Y,activeTask:X,workspaceRoot:Z.workspaceRoot||j0(),workspaceAccess:Z.workspaceKind==="acp-remote"?"none":"full",sessionId:Z.sessionId});if(R.usage)H?.(R.usage),yield{kind:"token_usage",usage:F$(R.usage,A)};if(x=R.success?"llm":"fallback",o=R.preTokens,s=R.postTokens,M=R.sampleAttempts,d=R.inputReductions,t=R.messagesOmitted,L=R.filesOmitted,u=R.imagesOmitted,m0=R.fallbackTargetTokens,h=R.fallbackMessagesOmitted,D0=R.fallbackMessagesTruncated,_0=R.failureReason,R.success)r.debug(`[Loop] [轮次 ${J}] 压缩完成: ${R.preTokens} -> ${R.postTokens} tokens`);else r.warn(`[Loop] [轮次 ${J}] 压缩使用降级策略: ${R.preTokens} -> ${R.postTokens} tokens`);O$="checkpoint";let F1=await Q1($,Z,R.summary,{trigger:"auto",reason:"threshold",strategy:x,preTokens:R.preTokens,...W.tokenSource?{preTokenSource:W.tokenSource}:{},...W.estimatedPendingTokens!==void 0?{estimatedPendingTokens:W.estimatedPendingTokens}:{},postTokens:R.postTokens,sampleAttempts:R.sampleAttempts,inputReductions:R.inputReductions,messagesOmitted:R.messagesOmitted,filesOmitted:R.filesOmitted,imagesOmitted:R.imagesOmitted,fallbackTargetTokens:R.fallbackTargetTokens,fallbackMessagesOmitted:R.fallbackMessagesOmitted,fallbackMessagesTruncated:R.fallbackMessagesTruncated,failureReason:R.failureReason,filesIncluded:R.filesIncluded,replacementMessages:R.compactedMessages},{required:$.executionEngine!==void 0});if(c=await x6(R.memoryPlan,Z,F1),Z.messages=R.compactedMessages,Q)Q.lastCompactionTurn=J;return p=R.success?"completed":"fallback",{kind:"compacted",postTokens:R.postTokens}}catch(P0){if(C0(P0)){if(P0 instanceof Y$)H?.(P0.usage),yield{kind:"token_usage",usage:F$(P0.usage,A)};return r.debug(`[Loop] [轮次 ${J}] 压缩被中止`),{kind:"none"}}return r.error(`[Loop] [轮次 ${J}] 压缩失败,停止执行`,P0),{kind:"failed",phase:O$}}finally{yield{kind:"compaction",phase:"end",reason:"threshold",outcome:p,strategy:x,preTokens:o,...W.tokenSource?{preTokenSource:W.tokenSource}:{},...W.estimatedPendingTokens!==void 0?{estimatedPendingTokens:W.estimatedPendingTokens}:{},postTokens:s,sampleAttempts:M,inputReductions:d,messagesOmitted:t,filesOmitted:L,imagesOmitted:u,fallbackTargetTokens:m0,fallbackMessagesOmitted:h,fallbackMessagesTruncated:D0,failureReason:_0,memory:c}}}function p5($,Z,J,W,Y){let K=Y?w8(Y):"user-cancel";return{success:!1,error:{type:"aborted",message:(K==="interrupt"?void 0:"任务已被用户中止")??"任务已中断"},metadata:{turnsCount:$,toolCallsCount:Z,duration:Date.now()-J,tokensUsed:W,abortReason:K}}}function D8($,Z,J,W){return{success:!1,error:{type:"tool_persistence_failed",message:OJ},metadata:{turnsCount:$,toolCallsCount:Z,duration:Date.now()-J,tokensUsed:W}}}function u5($,Z,J,W,Y){return{success:!1,error:{type:"context_compaction_failed",message:"Context compaction could not cross the hard budget boundary.",details:{phase:W}},metadata:{turnsCount:$,toolCallsCount:Z,duration:Date.now()-J,tokensUsed:Y}}}async function*m5($,Z,J,W,Y){let K=Date.now(),X=0,Q=(j)=>{X=Math.min(Number.MAX_SAFE_INTEGER,X+(n1(j)??0))},H=0,V=[],z=null,w=!1,B=(j,G,N)=>{return w=!0,p5(j,G,K,X,N)};try{let j=$.toolExecutor.getRegistry(),G=J.permissionMode,N=W?.outputSchema?t1(W.outputSchema):void 0,A=()=>{let F=$.applySkillToolRestrictions(j.getFunctionDeclarationsByMode(G));if(!N)return F;return[...F.filter((O)=>O.name!==u0),N.declaration]},S=u2(),T=K2(),p=()=>{let F=Q2(T);return F?{executionHostFailureCategory:F}:{}},x=r2(),o=C2(),s=Q8(Y,j);if(N)s=`${s??""}
|
|
121
|
+
5. Prefer the smallest change that achieves the goal — avoid unnecessary refactoring.`}`}var L$=S0("Agent"),A5=new Set(["Read","Glob","Grep","WebFetch","WebSearch","MemoryRead","ReadPromptArtifact","GetSpecContext","ValidateSpec","TaskOutput"]);class zZ{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 q1;toolUsePersistenceTail=Promise.resolve();constructor($,Z,J,W,Y,K,X,Q,H=!1){this.pipeline=$;this.execContext=Z;this.registry=J;this.contextMgr=W;this.sessionId=Y;this.lastMessageUuid=K;this.subagentInfo=X;this.progressSink=Q;this.requireDurableToolUse=H}setExecutionPolicy($){this.executeTool=$}setAdmissionPolicy($){this.admitTool=$}setAdmissionRollback($){this.rollbackAdmission=$}addTool($,Z){if(this.dispatched.has($.id))return L$.debug(`[StreamingToolExecutor] 跳过已分发工具: ${$.function.name} (${$.id})`),"rejected";this.dispatched.add($.id),this.order.push($.id);let J=this.turnAdmission.admit();if(J)return this.completed.set($.id,{toolCall:$,result:J,toolUseUuid:null}),"rejected";G1($.function.name,Z),$.function.arguments=JSON.stringify(Z);let W=this.admitTool?.($.function.name,Z);if(W)return this.completed.set($.id,{toolCall:$,result:W,toolUseUuid:null}),"rejected";let Y=this.registry.get($.function.name),K=Y?.isConcurrencySafe===!0,X=Y?.parallelism==="shared"||Y?.parallelism===void 0&&K;if(A5.has($.function.name)&&K&&!this.hasExclusiveBarrier){L$.debug(`[StreamingToolExecutor] 立即执行预启动工具: ${$.function.name}`);let H=this.executeOne($,Z);return this.pending.set($.id,H),"prelaunched"}else{if(L$.debug(`[StreamingToolExecutor] 排队非预启动工具: ${$.function.name}`),this.queued.push({toolCall:$,params:Z}),!X)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 Z=await this.pending.get($);this.pending.delete($),yield Z;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(),L$.debug(`[StreamingToolExecutor] 已丢弃所有挂起工作并重置状态 (epoch=${this.epoch})`)}hasTools(){return this.order.length>0}getEpoch(){return this.epoch}makeAbortResult($,Z,J=null){return{toolCall:$,result:{success:!1,llmContent:"",error:{type:"execution_error",message:Z},metadata:{abortedBeforeLaunch:!0}},toolUseUuid:J}}dispatchQueuedTools(){let $=this.queued;this.queued=[],this.hasExclusiveBarrier=!1;let Z=this.epoch;for(let{toolCall:J,params:W}of $){if(this.execContext.signal?.aborted){this.completed.set(J.id,this.makeAbortResult(J,"Tool execution skipped: task aborted before launch"));continue}let Y=this.executeQueued(J,W,Z);this.pending.set(J.id,Y)}}async executeQueued($,Z,J){if(J!==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($,Z)}async executeOne($,Z){let J=this.epoch,W=new AbortController;this.activeAborts.set($.id,W);let Y=null,K=this.abortController.signal;try{if(K.aborted||W.signal.aborted)return this.makeAbortResult($,"Tool execution aborted due to discard");try{if(this.contextMgr&&this.sessionId)Y=await this.persistToolUseInOrder($,Z);else if(this.requireDurableToolUse&&this.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(B){if(L$.warn("[StreamingToolExecutor] 保存工具调用失败:",B),!this.requireDurableToolUse)Y=null;else return{toolCall:$,result:{success:!1,llmContent:B$,error:{type:"execution_error",message:B$},metadata:{durableToolUseFailed:!0,summary:"Blocked tool before execution"}},toolUseUuid:null,error:B instanceof Error?B:Error(String(B))}}let X=[K,W.signal],Q=this.execContext.signal;if(Q)X.push(Q);let H=H8(...X),V={...this.execContext,messageId:Y??$.id,signal:H,confirmationHandler:this.execContext.sessionId&&this.execContext.workspaceRoot&&this.execContext.workspaceKind!=="acp-remote"?G0.createConfirmationHandler(this.execContext.confirmationHandler,{sessionId:this.execContext.sessionId,projectPath:this.execContext.workspaceRoot,toolCallId:Y??$.id,toolName:$.function.name}):this.execContext.confirmationHandler,onProgress:(B)=>{this.execContext.onProgress?.(B),this.progressSink?.($,{message:B.slice(0,1000)})},onProgressUpdate:(B)=>{this.execContext.onProgressUpdate?.(B),this.progressSink?.($,B)}},z=this.executeTool?await this.executeTool($.function.name,Z,V):await this.pipeline.execute($.function.name,Z,V);if(J!==this.epoch)return L$.debug(`[StreamingToolExecutor] 丢弃旧世代工具结果: ${$.function.name} (startEpoch=${J}, currentEpoch=${this.epoch})`),this.makeAbortResult($,"Tool execution aborted due to epoch mismatch (discard)",Y);let w={toolCall:$,result:z,toolUseUuid:Y};if(this.pending.has($.id))this.pending.delete($.id),this.completed.set($.id,w);return w}catch(X){if(J!==this.epoch)return this.makeAbortResult($,"Tool execution aborted due to epoch mismatch (discard)",Y);L$.error(`[StreamingToolExecutor] 工具执行失败: ${$.function.name}`,X);let Q={success:!1,llmContent:"",error:{type:"execution_error",message:X instanceof Error?X.message:"Unknown error"},metadata:void 0},H={toolCall:$,result:Q,toolUseUuid:Y,error:X instanceof Error?X:Error("Unknown error")};if(this.pending.has($.id))this.pending.delete($.id),this.completed.set($.id,H);return H}finally{this.activeAborts.delete($.id)}}persistToolUseInOrder($,Z){let J=this.contextMgr,W=this.sessionId;if(!J||!W)return Promise.resolve(null);let Y=this.toolUsePersistenceTail.then(()=>J.saveToolUse(W,$.function.name,Z,this.lastMessageUuid??null,this.subagentInfo,$.id));return this.toolUsePersistenceTail=Y.then(()=>{return},()=>{return}),Y}}class f6{pending=[];waiters=[];closed=!1;push($){if(this.closed)return;let Z=this.waiters.shift();if(Z){Z($);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((Z)=>{this.waiters.push(Z)})}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 V8($,Z){if(!["TaskCreate","TaskUpdate","TaskList"].includes($.function.name)||!Z.success||!Z.llmContent&&!Z.metadata)return null;let J=typeof Z.llmContent==="object"?Z.llmContent:{};return{kind:"task_update",tasks:Z.metadata?.tasks||J.tasks||[]}}function z8($,Z,J){if($.function.name!=="Skill"||!Z.success||!Z.metadata)return;let W=Z.metadata;if(W.skillName)J.onSkillActivated?.({skillName:W.skillName,allowedTools:W.allowedTools,basePath:W.basePath||""})}function j8($){let Z=$.metadata;if(!Z)return;return Z.modelId?.toString().trim()||Z.model?.toString().trim()||void 0||void 0}function b5($,Z,J){if(!["EnterWorktree","ExitWorktree"].includes($.function.name)||!Z.success)return;let W=Z.metadata,Y=W?.workspaceRoot;if(!["enter","exit"].includes(String(W?.workspaceTransition))||typeof Y!=="string"||Y.trim()==="")return;return R$.getInstance().inheritProjectConfig(J.workspaceRoot,Y,J.sessionId),J.workspaceRoot=Y,J.worktreeActive=W?.workspaceTransition==="enter",Y}function y5($,Z){if($.function.name!=="Task")return null;let J=Z.metadata;if(!J?.subagentSessionId)return null;let W=J.subagentSessionId,Y=J.subagentType||"Task",K=J.subagentStatus,X=typeof J.subagentResumedFrom==="string"?J.subagentResumedFrom:void 0,Q=typeof J.subagentRootId==="string"?J.subagentRootId:void 0,H=typeof J.subagentResumeDepth==="number"?J.subagentResumeDepth:void 0;if(K==="completed"||K==="failed"||K==="cancelled")return{kind:"subagent_completed",sessionId:W,type:Y,success:K==="completed",summary:J.subagentSummary,...J.verificationVerdict==="pass"||J.verificationVerdict==="fail"||J.verificationVerdict==="partial"?{verificationVerdict:J.verificationVerdict}:{},...X?{resumedFrom:X}:{},...Q?{rootAgentId:Q}:{},...H!==void 0?{resumeDepth:H}:{}};if(K==="running"){let V="";try{V=JSON.parse($.function.arguments).prompt||""}catch{}return{kind:"subagent_spawned",sessionId:W,type:Y,prompt:V,resumedFrom:X,rootAgentId:Q,resumeDepth:H}}return null}async function E6($,Z,J,W){let Y=V8($,Z),K=y5($,Z);z8($,Z,J);let X=j8(Z);if(X)await J.onModelSwitch?.(X);if(W)b5($,Z,W);return K||Y}var r=S0("Agent");function F$($,Z,J){return{...J?{scope:J}:{},inputTokens:$.promptTokens??0,outputTokens:$.completionTokens??0,totalTokens:n1($)??0,maxContextTokens:Z,cacheReadTokens:$.cacheReadInputTokens??0,cacheWriteTokens:$.cacheCreationInputTokens??0,...$.promptCacheBreak?{cacheBreak:$.promptCacheBreak}:{},costUsd:$.costUsd}}function X$($){return JSON.stringify($).replaceAll("<","\\u003c").replaceAll(">","\\u003e")}function B8($){let Z=$.trim();if(Z=Z.replace(/,\s*([}\]])/g,"$1"),Z.startsWith("{")&&!Z.endsWith("}"))Z+="}";Z=Z.replace(/,\s*([}\]])/g,"$1");try{let J=JSON.parse(Z);if(typeof J==="object"&&J!==null&&!Array.isArray(J))return J;return null}catch{return null}}function L1($){let Z=B8($);if(Z)return Z;try{let J=JSON.parse($);return typeof J==="string"?B8(J):null}catch{return null}}function f5($){let Z=$.metadata&&typeof $.metadata==="object"&&!Array.isArray($.metadata)?$.metadata:void 0;if(Z?.contextualProjectRules!==!0)return[];if(!Array.isArray(Z.ruleReferences))throw Error("Invalid contextual project rule provenance");return Z.ruleReferences.map((J)=>{if(!J||typeof J!=="object"||Array.isArray(J))throw Error("Invalid contextual project rule reference");let W=J;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 E5($){let Z=new Set,J=!1;for(let W of $){if(W.role==="assistant"){if(W.tool_calls&&W.tool_calls.length>0){for(let K of W.tool_calls)if("function"in K&&K.function.name==="Task")Z.add(K.id)}else if(J)J=!1;continue}if(W.role!=="tool"||W.name!=="Task"||!W.tool_call_id||!Z.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)J=!0}return J}function S5($){if(!($ instanceof Error))return"未知错误";let W=$.lastError??$;if(W.responseBody)try{let Q=JSON.parse(W.responseBody)?.error?.message;if(Q){let H=W.statusCode?` (HTTP ${W.statusCode})`:"";return`${Q}${H}`}}catch{}let Y=$.message,K=Y.match(/Last error:\s*(.+)$/);if(K)return K[1];return Y}function T5($){if(!($ instanceof Error))return!1;return["stream not supported","streaming is not available","sse not supported","does not support streaming"].some((J)=>$.message.toLowerCase().includes(J.toLowerCase()))}function R5($,Z){if(!Z)return"Tool execution failed (no details).";let J=[`Error: ${Z.message||"Unknown error"}`];if(Z.type==="validation_error")J.push("Hint: Check the tool parameters — a required field may be missing or have the wrong type.");else if(Z.type==="permission_denied")J.push("Hint: This operation requires user approval. Try a different approach or ask the user.");else if(Z.type==="timeout_error")J.push("Hint: The operation timed out. Consider breaking it into smaller steps or increasing timeout.");else if(Z.type==="execution_error"){let W=Z.message??"";if(W.includes("ENOENT")||W.includes("no such file"))J.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"))J.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"))J.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"))J.push("Hint: A path component is not a directory. Verify the full path with Glob.")}return J.join(`
|
|
122
|
+
`)}function S6($){if(!($ instanceof Error))return!1;return i1($)||$.status===413}function M5($,Z){let J=Z,W=J.index??0;if(!$.has(W))$.set(W,{id:J.id||"",name:J.function?.name||"",arguments:""});let Y=$.get(W);if(J.id&&!Y.id)Y.id=J.id;if(J.function?.name&&!Y.name)Y.name=J.function.name;if(J.function?.arguments)Y.arguments+=J.function.arguments}function k5($){if($.size===0)return;return Array.from($.values()).filter((Z)=>Z.id&&Z.name).map((Z)=>({id:Z.id,type:"function",function:{name:Z.name,arguments:Z.arguments}}))}async function*x5($,Z,J,W,Y,K){let X="",Q="",H,V,z=new Map;try{let w=$.chatService.streamChat(Z,J,W,Y),B=0;for await(let j of w){if(W?.aborted)break;if(j.providerAdmission){yield{kind:"provider_admission",...j.providerAdmission};continue}if(j.providerCircuit){yield{kind:"provider_circuit",...j.providerCircuit};continue}if(j.providerRetry){yield{kind:"provider_retry",...j.providerRetry};continue}if(j.providerStall){yield{kind:"provider_stall",...j.providerStall};continue}if(B++,j.modelFallback){K?.discard(),X="",Q="",H=void 0,V=void 0,z.clear(),B=0,yield{kind:"model_fallback",...j.modelFallback};continue}if(j.content)X+=j.content,yield{kind:"content_delta",delta:j.content};if(j.reasoningContent)Q+=j.reasoningContent,yield{kind:"thinking_delta",delta:j.reasoningContent};if(j.usage)H=j.usage;if(j.toolCalls){for(let G of j.toolCalls)if(M5(z,G),K){let A=G.index??0,S=z.get(A);if(S&&S.id&&S.name)try{let T=L1(S.arguments);if(T===null)continue;let p={id:S.id,type:"function",function:{name:S.name,arguments:S.arguments}},o=$.toolExecutor.getRegistry().get(S.name)?.kind,s=K.addTool(p,T);if(S.arguments=p.function.arguments,s==="prelaunched")yield{kind:"tool_start",toolCall:p,toolKind:o}}catch{}}}if(j.finishReason){V=j.finishReason;break}}if(B===0&&!W?.aborted&&X.length===0&&z.size===0)return r.warn("[Loop] 流式响应返回0个chunk,回退到非流式模式"),K?.discard(),{...await $.chatService.chat(Z,J,W,Y),_nonStreamingFallback:!0};return{content:X,reasoningContent:Q||void 0,toolCalls:k5(z),usage:H,finishReason:V}}catch(w){if(T5(w))return r.warn("[Loop] 流式请求失败,降级到非流式模式"),K?.discard(),{...await $.chatService.chat(Z,J,W,Y),_nonStreamingFallback:!0};throw w}}async function x6($,Z,J){if(!$)return;if(!J)return{outcome:"disabled",entries:0,topics:[]};try{return await RJ($,{workspaceRoot:Z.workspaceRoot||j0(),workspaceAccess:Z.workspaceKind==="acp-remote"?"none":"full"})}catch{return{outcome:"failed",entries:0,topics:[]}}}function I5($){return k6("sha256").update($).digest("hex").slice(0,16)}var h5=new Set(["AbortError","Error","RangeError","TypeError"]),v5=new Set(["EACCES","EEXIST","EIO","EMFILE","ENFILE","ENOENT","ENOSPC","EPERM","EROFS"]);function C5($){if($ instanceof Error){let Z=$,J=h5.has($.name)?$.name:"Error",W=typeof Z.code==="string"&&v5.has(Z.code)?Z.code:"unknown";return`${J}:${W}`}return"UnknownError:unknown"}async function g5($){let{deps:Z,context:J,state:W,snapshot:Y,attemptSpent:K}=$;if(Y.phase!=="handoff_band")return{kind:"failed"};if(W.getHistory().find((H)=>typeof H.id==="string"&&P8(H)))return{kind:"already_present"};if(K)return{kind:"failed"};let Q=Z.executionEngine?.getContextManager();if(!Q)return{kind:"failed"};try{let H=await Q.recordTokenBudgetHandoff(J.sessionId,{version:1,observedPromptTokens:Y.contextTokens??0,availableForInput:Y.availableForInput??0,handoffThreshold:Y.handoffThreshold??0,compactionThreshold:Y.compactionThreshold??0});if(H.outcome==="suppressed")return{kind:"suppressed"};let V=O8(H.event);if(!V)return{kind:"failed"};return W.appendDurableControl(V),{kind:"appended",message:V}}catch(H){let V=`token_budget_handoff_persist_failed session=${I5(J.sessionId)} error=${C5(H)}`;return r.warn(V),{kind:"failed"}}}async function*N8($,Z,J,W,Y,K,X,Q,H){let V=W.contextTokens,z=eJ(Z.messages,K),w=z!==null;if(z)Z.messages=z.messages,r.debug(`[Loop] [轮次 ${J}] MicroCompact: 清理 ${z.snippedCount} 轮旧工具结果(缓存已过期)`);let B=j1(Z.messages),j=!1;if(B.snippedCount>0)j=!0,r.debug(`[Loop] [轮次 ${J}] Snip 压缩: 移除 ${B.snippedCount} 轮旧工具调用,释放约 ${B.estimatedTokensFreed} tokens`);if(W.phase==="unknown"){if(j)Z.messages=B.messages;return r.debug(`[Loop] [轮次 ${J}] 压缩检查: 跳过(无历史 usage 数据)`),w||j?{kind:"snipped"}:{kind:"none"}}let G=$.chatService.getConfig(),N=G.model,A=W.maxContextTokens??0,S=W.maxOutputTokens??0,T=W.availableForInput??0;if(A<=0||T<=0){if(j)Z.messages=B.messages;return r.debug(`[Loop] [轮次 ${J}] 压缩检查: 跳过(模型上下文窗口未知)`),w||j?{kind:"snipped"}:{kind:"none"}}if(r.debug(`[Loop] [轮次 ${J}] 压缩检查:`,{contextTokens:V,tokenSource:W.tokenSource,estimatedPendingTokens:W.estimatedPendingTokens,maxContextTokens:A,maxOutputTokens:S,availableForInput:T,threshold:W.compactionThreshold,shouldCompact:W.phase==="compaction_due"}),W.phase!=="compaction_due"){if(j)Z.messages=B.messages;return w||j?{kind:"snipped"}:{kind:"none"}}r.debug(J===0?"[Loop] 触发自动压缩":`[Loop] [轮次 ${J}] 触发循环内自动压缩`);let p="failed",x,o,s,M,d,t,L,u,m0,h,D0,_0,c,O$="compaction";yield{kind:"compaction",phase:"start",reason:"threshold"};try{let P0=j?B.messages:Z.messages,R=await h$.compact(P0,{trigger:"auto",modelName:N,modelProvider:G.provider,maxContextTokens:A,apiKey:G.apiKey,baseURL:G.baseUrl,chatConfig:G,actualPreTokens:V,signal:Y,activeTask:X,workspaceRoot:Z.workspaceRoot||j0(),workspaceAccess:Z.workspaceKind==="acp-remote"?"none":"full",sessionId:Z.sessionId});if(R.usage)H?.(R.usage),yield{kind:"token_usage",usage:F$(R.usage,A,"auxiliary")};if(x=R.success?"llm":"fallback",o=R.preTokens,s=R.postTokens,M=R.sampleAttempts,d=R.inputReductions,t=R.messagesOmitted,L=R.filesOmitted,u=R.imagesOmitted,m0=R.fallbackTargetTokens,h=R.fallbackMessagesOmitted,D0=R.fallbackMessagesTruncated,_0=R.failureReason,R.success)r.debug(`[Loop] [轮次 ${J}] 压缩完成: ${R.preTokens} -> ${R.postTokens} tokens`);else r.warn(`[Loop] [轮次 ${J}] 压缩使用降级策略: ${R.preTokens} -> ${R.postTokens} tokens`);O$="checkpoint";let F1=await Q1($,Z,R.summary,{trigger:"auto",reason:"threshold",strategy:x,preTokens:R.preTokens,...W.tokenSource?{preTokenSource:W.tokenSource}:{},...W.estimatedPendingTokens!==void 0?{estimatedPendingTokens:W.estimatedPendingTokens}:{},postTokens:R.postTokens,sampleAttempts:R.sampleAttempts,inputReductions:R.inputReductions,messagesOmitted:R.messagesOmitted,filesOmitted:R.filesOmitted,imagesOmitted:R.imagesOmitted,fallbackTargetTokens:R.fallbackTargetTokens,fallbackMessagesOmitted:R.fallbackMessagesOmitted,fallbackMessagesTruncated:R.fallbackMessagesTruncated,failureReason:R.failureReason,filesIncluded:R.filesIncluded,replacementMessages:R.compactedMessages},{required:$.executionEngine!==void 0});if(c=await x6(R.memoryPlan,Z,F1),Z.messages=R.compactedMessages,Q)Q.lastCompactionTurn=J;return p=R.success?"completed":"fallback",{kind:"compacted",postTokens:R.postTokens}}catch(P0){if(C0(P0)){if(P0 instanceof Y$)H?.(P0.usage),yield{kind:"token_usage",usage:F$(P0.usage,A,"auxiliary")};return r.debug(`[Loop] [轮次 ${J}] 压缩被中止`),{kind:"none"}}return r.error(`[Loop] [轮次 ${J}] 压缩失败,停止执行`,P0),{kind:"failed",phase:O$}}finally{yield{kind:"compaction",phase:"end",reason:"threshold",outcome:p,strategy:x,preTokens:o,...W.tokenSource?{preTokenSource:W.tokenSource}:{},...W.estimatedPendingTokens!==void 0?{estimatedPendingTokens:W.estimatedPendingTokens}:{},postTokens:s,sampleAttempts:M,inputReductions:d,messagesOmitted:t,filesOmitted:L,imagesOmitted:u,fallbackTargetTokens:m0,fallbackMessagesOmitted:h,fallbackMessagesTruncated:D0,failureReason:_0,memory:c}}}function p5($,Z,J,W,Y){let K=Y?w8(Y):"user-cancel";return{success:!1,error:{type:"aborted",message:(K==="interrupt"?void 0:"任务已被用户中止")??"任务已中断"},metadata:{turnsCount:$,toolCallsCount:Z,duration:Date.now()-J,tokensUsed:W,abortReason:K}}}function D8($,Z,J,W){return{success:!1,error:{type:"tool_persistence_failed",message:OJ},metadata:{turnsCount:$,toolCallsCount:Z,duration:Date.now()-J,tokensUsed:W}}}function u5($,Z,J,W,Y){return{success:!1,error:{type:"context_compaction_failed",message:"Context compaction could not cross the hard budget boundary.",details:{phase:W}},metadata:{turnsCount:$,toolCallsCount:Z,duration:Date.now()-J,tokensUsed:Y}}}async function*m5($,Z,J,W,Y){let K=Date.now(),X=0,Q=(j)=>{X=Math.min(Number.MAX_SAFE_INTEGER,X+(n1(j)??0))},H=0,V=[],z=null,w=!1,B=(j,G,N)=>{return w=!0,p5(j,G,K,X,N)};try{let j=$.toolExecutor.getRegistry(),G=J.permissionMode,N=W?.outputSchema?t1(W.outputSchema):void 0,A=()=>{let F=$.applySkillToolRestrictions(j.getFunctionDeclarationsByMode(G));if(!N)return F;return[...F.filter((O)=>O.name!==u0),N.declaration]},S=u2(),T=K2(),p=()=>{let F=Q2(T);return F?{executionHostFailureCategory:F}:{}},x=r2(),o=C2(),s=Q8(Y,j);if(N)s=`${s??""}
|
|
123
123
|
|
|
124
124
|
# Structured Final Output
|
|
125
125
|
This turn has a required JSON Schema final-output contract. Complete the user's
|
|
@@ -136,9 +136,9 @@ ${m.map((e)=>`- ${e}`).join(`
|
|
|
136
136
|
`),qZ=!1}let J0=d6(F,O);if(J0&&J0.files.length>0&&j.get(F)?.kind==="write"){let m="Applicable project instructions were loaded before this write. Review the newly supplied rules, then retry the write.";return{success:!1,llmContent:m,error:{type:"validation_error",message:m},metadata:{contextualProjectRulesRequired:!0,projectRuleReferences:J0.references,summary:"Blocked write until contextual project rules are applied"}}}return $.toolExecutor.execute(F,O,K0)},AZ=$J({budget:$.currentModelMaxContextTokens,isSubagent:h}),bZ=new J6,y$=new Z6,b8={},t0=W?.turnSteering,E1=async(F)=>{for(let O of F){let K0={...O.metadata,inboxMessageId:O.id},z0=JSON.parse(JSON.stringify(K0));if(!(O.persisted===!0||L.getHistory().some((m)=>{let e=m.metadata;return e!==null&&typeof e==="object"&&!Array.isArray(e)&&e.inboxMessageId===O.id}))){let m=await r0($,J,O.content,z,K0);if(!m)throw Error(`Failed to persist steering message before applying it: ${O.id}`);z=m,L.appendUser({role:"user",content:O.content,metadata:z0})}else if(!L.getHistory().some((m)=>{let e=m.metadata;return e!==null&&typeof e==="object"&&!Array.isArray(e)&&e.inboxMessageId===O.id}))L.appendUser({role:"user",content:O.content,metadata:z0});let J0=O.policyText??(typeof O.content==="string"?O.content:O.content.filter((m)=>m.type==="text").map((m)=>m.text).join(`
|
|
137
137
|
`));if(O.origin!=="background_subagent"&&J0.trim())P$=void 0,A0=[A0,J0].join(`
|
|
138
138
|
`),PZ.push(J0),OZ=[A0,J.completionRequirements?.trim()].filter(Boolean).join(`
|
|
139
|
-
`),A$=[$.runtimeOptions.appendSystemPrompt?.trim(),J.completionRequirements?.trim(),...PZ].filter((m)=>Boolean(m)),f1=f1||p1(J0)}return{messageIds:F.map((O)=>O.id),count:F.length,recovered:F.filter((O)=>O.recovered).length,messages:F}};try{if(M0&&W?.goalLifecycle?.snapshot?.completionVerification?.status!=="pending"){await e$("A fresh host run requires new independent completion evidence");let F=await W?.goalLifecycle?.getSnapshot();if(F)yield{kind:"goal_updated",goal:F}}while(!0){if(W?.signal?.aborted)return B(H,V.length,W.signal);if(H>=P0&&(O$||h)){if(r.info(`Warning: 达到轮次上限 ${P0} 轮`),W?.onTurnLimitReached){let U=await W.onTurnLimitReached({turnsCount:H});if(W.signal?.aborted)return B(H,V.length,W.signal);if(U?.continue){L.writeback();let D="failed",f,b,l,E,_,g,k,b0,L0,v,y,X0,n,F0,i;yield{kind:"compaction",phase:"start",reason:"turn_limit"};try{let P=$.chatService.getConfig(),U0=A(),H0=b$&&Y1(A$)?U0.filter((kZ)=>kZ.name!=="Task"):U0,y0=I0?H0.filter((kZ)=>kZ.name===I0):H0,I=$6(L.systemMessages,y0,P.model),i0=y$.project({history:L.getHistory(),contextRevision:L.contextRevision,modelName:P.model,requestProfile:I});l=i0.source,E=i0.estimatedPendingTokens;let C=await h$.compact(J.messages,{trigger:"auto",modelName:P.model,modelProvider:P.provider,maxContextTokens:P.maxContextTokens??0,apiKey:P.apiKey,baseURL:P.baseUrl,chatConfig:P,actualPreTokens:i0.contextTokens,signal:W?.signal,activeTask:A0,workspaceRoot:J.workspaceRoot||j0(),workspaceAccess:J.workspaceKind==="acp-remote"?"none":"full",sessionId:J.sessionId});if(C.usage)Q(C.usage),yield{kind:"token_usage",usage:F$(C.usage,P.maxContextTokens??0)};let R8={role:"user",metadata:f0,content:`This session is being continued from a previous conversation. The conversation is summarized above.
|
|
139
|
+
`),A$=[$.runtimeOptions.appendSystemPrompt?.trim(),J.completionRequirements?.trim(),...PZ].filter((m)=>Boolean(m)),f1=f1||p1(J0)}return{messageIds:F.map((O)=>O.id),count:F.length,recovered:F.filter((O)=>O.recovered).length,messages:F}};try{if(M0&&W?.goalLifecycle?.snapshot?.completionVerification?.status!=="pending"){await e$("A fresh host run requires new independent completion evidence");let F=await W?.goalLifecycle?.getSnapshot();if(F)yield{kind:"goal_updated",goal:F}}while(!0){if(W?.signal?.aborted)return B(H,V.length,W.signal);if(H>=P0&&(O$||h)){if(r.info(`Warning: 达到轮次上限 ${P0} 轮`),W?.onTurnLimitReached){let U=await W.onTurnLimitReached({turnsCount:H});if(W.signal?.aborted)return B(H,V.length,W.signal);if(U?.continue){L.writeback();let D="failed",f,b,l,E,_,g,k,b0,L0,v,y,X0,n,F0,i;yield{kind:"compaction",phase:"start",reason:"turn_limit"};try{let P=$.chatService.getConfig(),U0=A(),H0=b$&&Y1(A$)?U0.filter((kZ)=>kZ.name!=="Task"):U0,y0=I0?H0.filter((kZ)=>kZ.name===I0):H0,I=$6(L.systemMessages,y0,P.model),i0=y$.project({history:L.getHistory(),contextRevision:L.contextRevision,modelName:P.model,requestProfile:I});l=i0.source,E=i0.estimatedPendingTokens;let C=await h$.compact(J.messages,{trigger:"auto",modelName:P.model,modelProvider:P.provider,maxContextTokens:P.maxContextTokens??0,apiKey:P.apiKey,baseURL:P.baseUrl,chatConfig:P,actualPreTokens:i0.contextTokens,signal:W?.signal,activeTask:A0,workspaceRoot:J.workspaceRoot||j0(),workspaceAccess:J.workspaceKind==="acp-remote"?"none":"full",sessionId:J.sessionId});if(C.usage)Q(C.usage),yield{kind:"token_usage",usage:F$(C.usage,P.maxContextTokens??0,"auxiliary")};let R8={role:"user",metadata:f0,content:`This session is being continued from a previous conversation. The conversation is summarized above.
|
|
140
140
|
|
|
141
|
-
Please continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.`},t6=[...C.compactedMessages,R8];f=C.success?"llm":"fallback",b=C.preTokens,_=C.postTokens,g=C.sampleAttempts,k=C.inputReductions,b0=C.messagesOmitted,L0=C.filesOmitted,v=C.imagesOmitted,y=C.fallbackTargetTokens,X0=C.fallbackMessagesOmitted,n=C.fallbackMessagesTruncated,F0=C.failureReason;let M8=await Q1($,J,C.summary,{trigger:"auto",reason:"turn_limit",strategy:f,preTokens:C.preTokens,preTokenSource:i0.source,...i0.estimatedPendingTokens!==void 0?{estimatedPendingTokens:i0.estimatedPendingTokens}:{},postTokens:C.postTokens,sampleAttempts:C.sampleAttempts,inputReductions:C.inputReductions,messagesOmitted:C.messagesOmitted,filesOmitted:C.filesOmitted,imagesOmitted:C.imagesOmitted,fallbackTargetTokens:C.fallbackTargetTokens,fallbackMessagesOmitted:C.fallbackMessagesOmitted,fallbackMessagesTruncated:C.fallbackMessagesTruncated,failureReason:C.failureReason,filesIncluded:C.filesIncluded,replacementMessages:t6},{required:$.executionEngine!==void 0});i=await x6(C.memoryPlan,J,M8),J.messages=t6,L.replaceHistory(J.messages),y$.reset(),D=C.success?"completed":"fallback"}catch(P){if(P instanceof Y$)Q(P.usage),yield{kind:"token_usage",usage:F$(P.usage,$.chatService.getConfig().maxContextTokens??0)};throw r.error("[Loop] 轮次上限压缩失败,停止继续执行:",P),P}finally{yield{kind:"compaction",phase:"end",reason:"turn_limit",outcome:D,strategy:f,preTokens:b,preTokenSource:l,estimatedPendingTokens:E,postTokens:_,sampleAttempts:g,inputReductions:k,messagesOmitted:b0,filesOmitted:L0,imagesOmitted:v,fallbackTargetTokens:y,fallbackMessagesOmitted:X0,fallbackMessagesTruncated:n,failureReason:F0,memory:i}}H=0;continue}return{success:!0,finalMessage:U?.reason||"已达到对话轮次上限,用户选择停止",metadata:{turnsCount:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X}}}return{success:!1,error:{type:"max_turns_exceeded",message:h?`子代理已达到轮次上限 (${P0} 轮)。`:`已达到轮次上限 (${P0} 轮)。`},metadata:{turnsCount:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X}}}if(await j.waitForMcpCatalogIdle(W?.signal),W?.signal?.aborted)return B(H,V.length,W.signal);let O=await t0?.drain()??[];if(O.length>0)Q0=void 0,a0=!1,l0=0,yield{kind:"steering_applied",...await E1(O),delivery:NZ?"current_turn":"next_turn",queue:await t0.getSnapshot()},a$=N?M6(L.getHistory(),N):void 0,Q0=a$?.output,a0=a$?.completed===!0,NZ=!0;else if(!NZ)return{success:!0,finalMessage:"",metadata:{turnsCount:0,toolCallsCount:0,duration:Date.now()-K}};if(N&&Q0&&a0){let U=JSON.stringify(Q0);return yield{kind:"structured_output",output:Q0,schemaDigest:N.schemaDigest},{success:!0,finalMessage:U,metadata:{turnsCount:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X,structuredOutput:Q0,structuredOutputSchemaDigest:N.schemaDigest}}}let K0=j.drainMcpCatalogChanges();if(K0.length>0){for(let D of K0)yield{kind:"mcp_catalog_changed",...D};let U=K0.map((D)=>{let f=[D.added.length>0?`added=${D.added.join(",")}`:"",D.removed.length>0?`removed=${D.removed.join(",")}`:"",D.updated.length>0?`updated=${D.updated.join(",")}`:""].filter(Boolean).join(" ");return`revision=${D.revision} server=${X$(D.serverName)} ${f}`}).join(`
|
|
141
|
+
Please continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.`},t6=[...C.compactedMessages,R8];f=C.success?"llm":"fallback",b=C.preTokens,_=C.postTokens,g=C.sampleAttempts,k=C.inputReductions,b0=C.messagesOmitted,L0=C.filesOmitted,v=C.imagesOmitted,y=C.fallbackTargetTokens,X0=C.fallbackMessagesOmitted,n=C.fallbackMessagesTruncated,F0=C.failureReason;let M8=await Q1($,J,C.summary,{trigger:"auto",reason:"turn_limit",strategy:f,preTokens:C.preTokens,preTokenSource:i0.source,...i0.estimatedPendingTokens!==void 0?{estimatedPendingTokens:i0.estimatedPendingTokens}:{},postTokens:C.postTokens,sampleAttempts:C.sampleAttempts,inputReductions:C.inputReductions,messagesOmitted:C.messagesOmitted,filesOmitted:C.filesOmitted,imagesOmitted:C.imagesOmitted,fallbackTargetTokens:C.fallbackTargetTokens,fallbackMessagesOmitted:C.fallbackMessagesOmitted,fallbackMessagesTruncated:C.fallbackMessagesTruncated,failureReason:C.failureReason,filesIncluded:C.filesIncluded,replacementMessages:t6},{required:$.executionEngine!==void 0});i=await x6(C.memoryPlan,J,M8),J.messages=t6,L.replaceHistory(J.messages),y$.reset(),D=C.success?"completed":"fallback"}catch(P){if(P instanceof Y$)Q(P.usage),yield{kind:"token_usage",usage:F$(P.usage,$.chatService.getConfig().maxContextTokens??0,"auxiliary")};throw r.error("[Loop] 轮次上限压缩失败,停止继续执行:",P),P}finally{yield{kind:"compaction",phase:"end",reason:"turn_limit",outcome:D,strategy:f,preTokens:b,preTokenSource:l,estimatedPendingTokens:E,postTokens:_,sampleAttempts:g,inputReductions:k,messagesOmitted:b0,filesOmitted:L0,imagesOmitted:v,fallbackTargetTokens:y,fallbackMessagesOmitted:X0,fallbackMessagesTruncated:n,failureReason:F0,memory:i}}H=0;continue}return{success:!0,finalMessage:U?.reason||"已达到对话轮次上限,用户选择停止",metadata:{turnsCount:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X}}}return{success:!1,error:{type:"max_turns_exceeded",message:h?`子代理已达到轮次上限 (${P0} 轮)。`:`已达到轮次上限 (${P0} 轮)。`},metadata:{turnsCount:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X}}}if(await j.waitForMcpCatalogIdle(W?.signal),W?.signal?.aborted)return B(H,V.length,W.signal);let O=await t0?.drain()??[];if(O.length>0)Q0=void 0,a0=!1,l0=0,yield{kind:"steering_applied",...await E1(O),delivery:NZ?"current_turn":"next_turn",queue:await t0.getSnapshot()},a$=N?M6(L.getHistory(),N):void 0,Q0=a$?.output,a0=a$?.completed===!0,NZ=!0;else if(!NZ)return{success:!0,finalMessage:"",metadata:{turnsCount:0,toolCallsCount:0,duration:Date.now()-K}};if(N&&Q0&&a0){let U=JSON.stringify(Q0);return yield{kind:"structured_output",output:Q0,schemaDigest:N.schemaDigest},{success:!0,finalMessage:U,metadata:{turnsCount:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X,structuredOutput:Q0,structuredOutputSchemaDigest:N.schemaDigest}}}let K0=j.drainMcpCatalogChanges();if(K0.length>0){for(let D of K0)yield{kind:"mcp_catalog_changed",...D};let U=K0.map((D)=>{let f=[D.added.length>0?`added=${D.added.join(",")}`:"",D.removed.length>0?`removed=${D.removed.join(",")}`:"",D.updated.length>0?`updated=${D.updated.join(",")}`:""].filter(Boolean).join(" ");return`revision=${D.revision} server=${X$(D.serverName)} ${f}`}).join(`
|
|
142
142
|
`);L.appendControl("user",{role:"user",content:`<system-reminder>
|
|
143
143
|
The MCP tool catalog changed. Newly added tools are deferred; use ToolSearch to load their schemas before calling them. Removed tools are no longer available.
|
|
144
144
|
${U}
|
|
@@ -160,7 +160,7 @@ MCP task ${X$(U.taskId)} for ${X$(U.serverName)}/${X$(U.toolName)} is ${U.status
|
|
|
160
160
|
|
|
161
161
|
<system-reminder>
|
|
162
162
|
${i2(T1,S.totalFailures)}
|
|
163
|
-
</system-reminder>`}:void 0,l6=A(),yZ=b$&&Y1(A$)?l6.filter((U)=>U.name!=="Task"):l6,M1=P$&&yZ.some((U)=>U.name===P$)?P$:void 0,k1=I0??M1,$1=k1?yZ.filter((U)=>U.name===k1):yZ;L.writeback();let f$=$.chatService.getConfig(),i6=$6(L.systemMessages,$1,f$.model),fZ=y$.project({history:L.getHistory(),pendingMessages:R1?[R1]:[],contextRevision:L.contextRevision,modelName:f$.model,requestProfile:i6}),EZ=F8({contextTokens:fZ.contextTokens,tokenSource:fZ.source,estimatedPendingTokens:fZ.estimatedPendingTokens,maxContextTokens:f$.maxContextTokens,maxOutputTokens:L8({maxContextTokens:f$.maxContextTokens,maxOutputTokens:f$.maxOutputTokens,configuredMaxOutputTokens:$.config.maxOutputTokens})}),x1=yield*N8($,J,H,EZ,W?.signal,R,A0,b8,Q);if(x1.kind==="failed")return u5(H,V.length,K,x1.phase,X);if(x1.kind==="snipped"||x1.kind==="compacted")L.replaceHistory(J.messages),y$.reset();if(EZ.phase==="handoff_band"){let U=await g5({deps:$,context:J,state:L,snapshot:EZ,attemptSpent:F1});if(U.kind==="failed"||U.kind==="suppressed")F1=!0}if(L.writeback(),H=T1,yield{kind:"turn_start",turn:H,maxTurns:P0},W?.signal?.aborted)return B(H-1,V.length,W.signal);if(R1)L.appendControl("user",R1);let r6=W?.stream!==!1,y8=I0;I0=void 0;let f8=L.historyLength+L.pending.length,n6=!h&&($.config.providerForegroundRecoveryMs??0)>0?{mode:"bounded_foreground",budgetMs:$.config.providerForegroundRecoveryMs}:void 0,SZ=J.subagentInfo?.providerAdmissionOwnerId??J.subagentInfo?.parentSessionId??J.sessionId,o6={providerSessionId:J.sessionId,...k1?{toolChoice:{type:"tool",toolName:k1}}:{},...n6?{providerRecovery:n6}:{},providerAdmission:{sessionId:J.sessionId,ownerId:SZ,requestClass:h?"background":"foreground"}},q,e0,Q$=new f6;try{if(r6)e0=new zZ($.toolExecutor,{sessionId:J.sessionId,turnId:W?.turnFinalization?.turnId,taskListId:J.taskListId,goalTaskListId:J.goalTaskListId,userId:J.userId||"default",modelId:$.config.currentModelId,providerAdmissionOwnerId:SZ,workspaceRoot:J.workspaceRoot||j0(),executionRoot:J.executionRoot??J.workspaceRoot??j0(),workspaceKind:J.workspaceKind??"local",environment:$.config.env,worktreeIsolationRequired:f1,worktreeActive:w0.has("EnterWorktree")&&!w0.has("ExitWorktree"),subagentType:J.subagentInfo?.subagentType,signal:W?.signal,confirmationHandler:J.confirmationHandler,permissionMode:J.permissionMode,toolRegistry:j,deferredToolManager:j.deferredToolManager},$.toolExecutor.getRegistry(),$.executionEngine?.getContextManager(),J.sessionId,z,J.subagentInfo,(U,D)=>{Q$.push({toolCall:U,update:D})},$.executionEngine!==void 0),e0.setAdmissionPolicy(m6),e0.setAdmissionRollback(A8),e0.setExecutionPolicy(c6),q=yield*x5($,L.toLLMMessages(),$1,W?.signal,o6,e0);else q=await $.chatService.chat(L.toLLMMessages(),$1,W?.signal,o6)}catch(U){if(S6(U)&&!T6(U)&&bZ.canAttempt()){r.warn("[Loop] 检测到 prompt_too_long 错误,尝试反应式压缩");let D=$.chatService.getConfig(),f=!1,b="failed",l,E,_,g,k,b0,L0,v,y,X0,n,F0,i;yield{kind:"compaction",phase:"start",reason:"context_limit"};try{e0?.discard();let P=await bZ.tryReactiveCompact(J.messages,{modelName:D.model,modelProvider:D.provider,maxContextTokens:D.maxContextTokens??0,apiKey:D.apiKey,baseURL:D.baseUrl,chatConfig:D,signal:W?.signal,activeTask:A0,workspaceRoot:J.workspaceRoot||j0(),workspaceAccess:J.workspaceKind==="acp-remote"?"none":"full",sessionId:J.sessionId});if(l=P.strategy,E=P.preTokens,_=P.postTokens,g=P.sampleAttempts,k=P.inputReductions,b0=P.messagesOmitted,L0=P.filesOmitted,v=P.imagesOmitted,y=P.fallbackTargetTokens,X0=P.fallbackMessagesOmitted,n=P.fallbackMessagesTruncated,F0=P.failureReason,P.usage)Q(P.usage),yield{kind:"token_usage",usage:F$(P.usage,D.maxContextTokens??0)};if(P.success&&P.strategy&&P.summary!==void 0&&P.preTokens!==void 0){let U0=await Q1($,J,P.summary,{trigger:"auto",reason:"context_limit",strategy:P.strategy,preTokens:P.preTokens,postTokens:P.postTokens,sampleAttempts:P.sampleAttempts,inputReductions:P.inputReductions,messagesOmitted:P.messagesOmitted,filesOmitted:P.filesOmitted,imagesOmitted:P.imagesOmitted,fallbackTargetTokens:P.fallbackTargetTokens,fallbackMessagesOmitted:P.fallbackMessagesOmitted,fallbackMessagesTruncated:P.fallbackMessagesTruncated,failureReason:P.failureReason,filesIncluded:P.filesIncluded,replacementMessages:P.messages},{required:$.executionEngine!==void 0});i=await x6(P.memoryPlan,J,U0),J.messages=P.messages,L.replaceHistory(J.messages),y$.reset(),I0=y8,b=P.strategy==="llm"?"completed":"fallback",f=!0,r.info("[Loop] 反应式压缩成功,重试 LLM 调用")}}catch(P){if(P instanceof Y$)Q(P.usage),yield{kind:"token_usage",usage:F$(P.usage,D.maxContextTokens??0)};if(C0(P))throw P;r.error("[Loop] 反应式压缩失败,不重放 Provider 请求",P)}finally{yield{kind:"compaction",phase:"end",reason:"context_limit",outcome:b,strategy:l,preTokens:E,postTokens:_,sampleAttempts:g,inputReductions:k,messagesOmitted:b0,filesOmitted:L0,imagesOmitted:v,fallbackTargetTokens:y,fallbackMessagesOmitted:X0,fallbackMessagesTruncated:n,failureReason:F0,memory:i}}if(f){H--;continue}}else if(S6(U)&&T6(U))r.warn("[Loop] prompt_too_long arrived after Provider output; refusing replay");else if(S6(U))r.warn("[Loop] reactive context recovery already attempted; refusing another replay");throw U}for(let U of q.toolCalls??[]){if(U.type!=="function")continue;let D=L1(U.function.arguments);if(D===null)continue;G1(U.function.name,D),U.function.arguments=JSON.stringify(D)}if(bZ.reset(),R=Date.now(),q.usage)Q(q.usage),yield{kind:"token_usage",usage:F$(q.usage,$.currentModelMaxContextTokens)};y$.recordProviderUsage({usage:q.usage,contextRevision:L.contextRevision,historyLength:f8,modelName:f$.model,requestProfile:i6});let E8=q.usage?.completionTokens??0;if(AZ=ZJ(AZ,E8,o0>0),W?.signal?.aborted)return B(H-1,V.length,W.signal);if(!r6||!!q._nonStreamingFallback){if(q.reasoningContent&&q.reasoningContent.trim())yield{kind:"thinking_delta",delta:q.reasoningContent};if(q.content&&q.content.trim())yield{kind:"content_delta",delta:q.content}}yield{kind:"stream_end"};let I1=hZ(q.finishReason,o0,AZ),TZ=I1.action!=="none"&&Q0!==void 0&&N!==void 0&&(q.toolCalls?.length??0)===0;if(TZ){let U=await t0?.drainOrSeal();if(U&&U.messages.length>0){Q0=void 0,a0=!1,l0=0,L.appendAssistant({role:"assistant",content:q.content||"",reasoningContent:q.reasoningContent});let D=await v0($,J,q.content||"",z,q.reasoningContent);if(D)z=D;yield{kind:"steering_applied",...await E1(U.messages),delivery:"current_turn",queue:await t0.getSnapshot()};continue}C6=!0}if(I1.action==="recover"&&!TZ){let U=await p6(q);if(U.action==="continue")continue;if(U.action==="fail")return U.result;o0++,r.warn(`[Loop] Max output tokens hit (recovery ${o0}/3)`);let D={role:"assistant",content:q.content||"",reasoningContent:q.reasoningContent,tool_calls:q.toolCalls};L.appendToHistory(D);let f=await v0($,J,q.content||"",z,q.reasoningContent);if(f)z=f;let b={role:"user",metadata:f0,content:"Output token limit hit. Resume directly — no apology, no recap. "+"Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."};L.appendToHistory(b);let l=await r0($,J,b.content,z,f0);if(l)z=l;continue}if(!TZ&&(I1.action==="truncated"||I1.action==="budget_stop")){let U=!N&&!q.toolCalls?.length?CZ(q.content,A0,$1.map((_)=>_.name),g1):{action:"none"};if(U.action==="fail"||M1)return z=await V0({deps:$,context:J,state:L,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:z}),{success:!1,error:{type:"intent_fulfillment_failed",message:U.action==="fail"?U.message:"The model exhausted its output budget before invoking the required native tool."},metadata:{turnsCount:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X,outputTruncated:!0}};if(!q.content?.trim()&&!Q0)return{success:!1,error:{type:"intent_fulfillment_failed",message:"The model exhausted its output budget without a non-empty final response."},metadata:{turnsCount:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X,outputTruncated:!0}};let D=g6(),f=D?.finalMessage??q.content??"",b=await u(),l=D||b?{...D?.persistenceMetadata,...b?{turnFinalization:b}:{}}:void 0;L.appendAssistant({role:"assistant",content:f,reasoningContent:D?void 0:q.reasoningContent,tool_calls:D?void 0:q.toolCalls,...l?{metadata:c$(l)}:{}});let E=await v0($,J,f,z,D?void 0:q.reasoningContent,l);if(E)z=E;if(N&&!D)return{success:!1,error:{type:"structured_output_failed",message:"The model reached its output budget before submitting a schema-valid structured response."},metadata:{turnsCount:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X,outputTruncated:!0,structuredOutputSchemaDigest:N.schemaDigest}};if(D)yield D.event;return{success:!0,finalMessage:f,metadata:{turnsCount:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X,outputTruncated:!0,...D?.resultMetadata}}}if(!q.toolCalls||q.toolCalls.length===0){let U=F6(o,[],[]);if(U)yield{kind:"action_stationarity",...U};let D=await t0?.drain()??[];if(D.length>0){if(q.finishReason!=="length")o0=0;Q0=void 0,a0=!1,l0=0,L.appendAssistant({role:"assistant",content:q.content||"",reasoningContent:q.reasoningContent});let I=await v0($,J,q.content||"",z,q.reasoningContent);if(I)z=I;yield{kind:"steering_applied",...await E1(D),delivery:"current_turn",queue:await t0.getSnapshot()};continue}if(N&&!Q0){if(q.finishReason!=="length")o0=0;if(z=await V0({deps:$,context:J,state:L,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:z}),l0>=R6)return{success:!1,error:{type:"structured_output_failed",message:`The model did not call ${u0} with a schema-valid object before the corrective retry budget was exhausted.`},metadata:{turnsCount:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X,structuredOutputSchemaDigest:N.schemaDigest}};l0++;let I=`The final response is invalid because this turn requires the ${u0} tool. Complete any remaining work, then call ${u0} exactly once with an object matching its schema. Do not return JSON as prose.`;L.appendControl("user",{role:"user",content:I});let i0=await r0($,J,I,z,f0);if(i0)z=i0;continue}let f=CZ(q.content,A0,$1.map((I)=>I.name),H>=P0?g1:I6);if(!N&&f.action!=="none"){if(z=await V0({deps:$,context:J,state:L,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:z,...f.action==="retry"?{controlPrompt:f.prompt}:{}}),f.action==="fail")return{success:!1,error:{type:"intent_fulfillment_failed",message:f.message},metadata:{turnsCount:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X}};I6++,P$=f.toolName&&!w0.has(f.toolName)?f.toolName:void 0;continue}if(M1)return z=await V0({deps:$,context:J,state:L,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:z}),{success:!1,error:{type:"intent_fulfillment_failed",message:"The model did not invoke the required native tool after correcting a textual tool call."},metadata:{turnsCount:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X}};let b=await p6(q);if(b.action==="continue")continue;if(b.action==="fail")return b.result;if(q.finishReason!=="length")o0=0;if(q.content&&n2(x,q.content)){z=await V0({deps:$,context:J,state:L,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:z,controlPrompt:`
|
|
163
|
+
</system-reminder>`}:void 0,l6=A(),yZ=b$&&Y1(A$)?l6.filter((U)=>U.name!=="Task"):l6,M1=P$&&yZ.some((U)=>U.name===P$)?P$:void 0,k1=I0??M1,$1=k1?yZ.filter((U)=>U.name===k1):yZ;L.writeback();let f$=$.chatService.getConfig(),i6=$6(L.systemMessages,$1,f$.model),fZ=y$.project({history:L.getHistory(),pendingMessages:R1?[R1]:[],contextRevision:L.contextRevision,modelName:f$.model,requestProfile:i6}),EZ=F8({contextTokens:fZ.contextTokens,tokenSource:fZ.source,estimatedPendingTokens:fZ.estimatedPendingTokens,maxContextTokens:f$.maxContextTokens,maxOutputTokens:L8({maxContextTokens:f$.maxContextTokens,maxOutputTokens:f$.maxOutputTokens,configuredMaxOutputTokens:$.config.maxOutputTokens})}),x1=yield*N8($,J,H,EZ,W?.signal,R,A0,b8,Q);if(x1.kind==="failed")return u5(H,V.length,K,x1.phase,X);if(x1.kind==="snipped"||x1.kind==="compacted")L.replaceHistory(J.messages),y$.reset();if(EZ.phase==="handoff_band"){let U=await g5({deps:$,context:J,state:L,snapshot:EZ,attemptSpent:F1});if(U.kind==="failed"||U.kind==="suppressed")F1=!0}if(L.writeback(),H=T1,yield{kind:"turn_start",turn:H,maxTurns:P0},W?.signal?.aborted)return B(H-1,V.length,W.signal);if(R1)L.appendControl("user",R1);let r6=W?.stream!==!1,y8=I0;I0=void 0;let f8=L.historyLength+L.pending.length,n6=!h&&($.config.providerForegroundRecoveryMs??0)>0?{mode:"bounded_foreground",budgetMs:$.config.providerForegroundRecoveryMs}:void 0,SZ=J.subagentInfo?.providerAdmissionOwnerId??J.subagentInfo?.parentSessionId??J.sessionId,o6={providerSessionId:J.sessionId,...k1?{toolChoice:{type:"tool",toolName:k1}}:{},...n6?{providerRecovery:n6}:{},providerAdmission:{sessionId:J.sessionId,ownerId:SZ,requestClass:h?"background":"foreground"}},q,e0,Q$=new f6;try{if(r6)e0=new zZ($.toolExecutor,{sessionId:J.sessionId,turnId:W?.turnFinalization?.turnId,taskListId:J.taskListId,goalTaskListId:J.goalTaskListId,userId:J.userId||"default",modelId:$.config.currentModelId,providerAdmissionOwnerId:SZ,workspaceRoot:J.workspaceRoot||j0(),executionRoot:J.executionRoot??J.workspaceRoot??j0(),workspaceKind:J.workspaceKind??"local",environment:$.config.env,worktreeIsolationRequired:f1,worktreeActive:w0.has("EnterWorktree")&&!w0.has("ExitWorktree"),subagentType:J.subagentInfo?.subagentType,signal:W?.signal,confirmationHandler:J.confirmationHandler,permissionMode:J.permissionMode,toolRegistry:j,deferredToolManager:j.deferredToolManager},$.toolExecutor.getRegistry(),$.executionEngine?.getContextManager(),J.sessionId,z,J.subagentInfo,(U,D)=>{Q$.push({toolCall:U,update:D})},$.executionEngine!==void 0),e0.setAdmissionPolicy(m6),e0.setAdmissionRollback(A8),e0.setExecutionPolicy(c6),q=yield*x5($,L.toLLMMessages(),$1,W?.signal,o6,e0);else q=await $.chatService.chat(L.toLLMMessages(),$1,W?.signal,o6)}catch(U){if(S6(U)&&!T6(U)&&bZ.canAttempt()){r.warn("[Loop] 检测到 prompt_too_long 错误,尝试反应式压缩");let D=$.chatService.getConfig(),f=!1,b="failed",l,E,_,g,k,b0,L0,v,y,X0,n,F0,i;yield{kind:"compaction",phase:"start",reason:"context_limit"};try{e0?.discard();let P=await bZ.tryReactiveCompact(J.messages,{modelName:D.model,modelProvider:D.provider,maxContextTokens:D.maxContextTokens??0,apiKey:D.apiKey,baseURL:D.baseUrl,chatConfig:D,signal:W?.signal,activeTask:A0,workspaceRoot:J.workspaceRoot||j0(),workspaceAccess:J.workspaceKind==="acp-remote"?"none":"full",sessionId:J.sessionId});if(l=P.strategy,E=P.preTokens,_=P.postTokens,g=P.sampleAttempts,k=P.inputReductions,b0=P.messagesOmitted,L0=P.filesOmitted,v=P.imagesOmitted,y=P.fallbackTargetTokens,X0=P.fallbackMessagesOmitted,n=P.fallbackMessagesTruncated,F0=P.failureReason,P.usage)Q(P.usage),yield{kind:"token_usage",usage:F$(P.usage,D.maxContextTokens??0,"auxiliary")};if(P.success&&P.strategy&&P.summary!==void 0&&P.preTokens!==void 0){let U0=await Q1($,J,P.summary,{trigger:"auto",reason:"context_limit",strategy:P.strategy,preTokens:P.preTokens,postTokens:P.postTokens,sampleAttempts:P.sampleAttempts,inputReductions:P.inputReductions,messagesOmitted:P.messagesOmitted,filesOmitted:P.filesOmitted,imagesOmitted:P.imagesOmitted,fallbackTargetTokens:P.fallbackTargetTokens,fallbackMessagesOmitted:P.fallbackMessagesOmitted,fallbackMessagesTruncated:P.fallbackMessagesTruncated,failureReason:P.failureReason,filesIncluded:P.filesIncluded,replacementMessages:P.messages},{required:$.executionEngine!==void 0});i=await x6(P.memoryPlan,J,U0),J.messages=P.messages,L.replaceHistory(J.messages),y$.reset(),I0=y8,b=P.strategy==="llm"?"completed":"fallback",f=!0,r.info("[Loop] 反应式压缩成功,重试 LLM 调用")}}catch(P){if(P instanceof Y$)Q(P.usage),yield{kind:"token_usage",usage:F$(P.usage,D.maxContextTokens??0,"auxiliary")};if(C0(P))throw P;r.error("[Loop] 反应式压缩失败,不重放 Provider 请求",P)}finally{yield{kind:"compaction",phase:"end",reason:"context_limit",outcome:b,strategy:l,preTokens:E,postTokens:_,sampleAttempts:g,inputReductions:k,messagesOmitted:b0,filesOmitted:L0,imagesOmitted:v,fallbackTargetTokens:y,fallbackMessagesOmitted:X0,fallbackMessagesTruncated:n,failureReason:F0,memory:i}}if(f){H--;continue}}else if(S6(U)&&T6(U))r.warn("[Loop] prompt_too_long arrived after Provider output; refusing replay");else if(S6(U))r.warn("[Loop] reactive context recovery already attempted; refusing another replay");throw U}for(let U of q.toolCalls??[]){if(U.type!=="function")continue;let D=L1(U.function.arguments);if(D===null)continue;G1(U.function.name,D),U.function.arguments=JSON.stringify(D)}if(bZ.reset(),R=Date.now(),q.usage)Q(q.usage),yield{kind:"token_usage",usage:F$(q.usage,$.currentModelMaxContextTokens)};y$.recordProviderUsage({usage:q.usage,contextRevision:L.contextRevision,historyLength:f8,modelName:f$.model,requestProfile:i6});let E8=q.usage?.completionTokens??0;if(AZ=ZJ(AZ,E8,o0>0),W?.signal?.aborted)return B(H-1,V.length,W.signal);if(!r6||!!q._nonStreamingFallback){if(q.reasoningContent&&q.reasoningContent.trim())yield{kind:"thinking_delta",delta:q.reasoningContent};if(q.content&&q.content.trim())yield{kind:"content_delta",delta:q.content}}yield{kind:"stream_end"};let I1=hZ(q.finishReason,o0,AZ),TZ=I1.action!=="none"&&Q0!==void 0&&N!==void 0&&(q.toolCalls?.length??0)===0;if(TZ){let U=await t0?.drainOrSeal();if(U&&U.messages.length>0){Q0=void 0,a0=!1,l0=0,L.appendAssistant({role:"assistant",content:q.content||"",reasoningContent:q.reasoningContent});let D=await v0($,J,q.content||"",z,q.reasoningContent);if(D)z=D;yield{kind:"steering_applied",...await E1(U.messages),delivery:"current_turn",queue:await t0.getSnapshot()};continue}C6=!0}if(I1.action==="recover"&&!TZ){let U=await p6(q);if(U.action==="continue")continue;if(U.action==="fail")return U.result;o0++,r.warn(`[Loop] Max output tokens hit (recovery ${o0}/3)`);let D={role:"assistant",content:q.content||"",reasoningContent:q.reasoningContent,tool_calls:q.toolCalls};L.appendToHistory(D);let f=await v0($,J,q.content||"",z,q.reasoningContent);if(f)z=f;let b={role:"user",metadata:f0,content:"Output token limit hit. Resume directly — no apology, no recap. "+"Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."};L.appendToHistory(b);let l=await r0($,J,b.content,z,f0);if(l)z=l;continue}if(!TZ&&(I1.action==="truncated"||I1.action==="budget_stop")){let U=!N&&!q.toolCalls?.length?CZ(q.content,A0,$1.map((_)=>_.name),g1):{action:"none"};if(U.action==="fail"||M1)return z=await V0({deps:$,context:J,state:L,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:z}),{success:!1,error:{type:"intent_fulfillment_failed",message:U.action==="fail"?U.message:"The model exhausted its output budget before invoking the required native tool."},metadata:{turnsCount:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X,outputTruncated:!0}};if(!q.content?.trim()&&!Q0)return{success:!1,error:{type:"intent_fulfillment_failed",message:"The model exhausted its output budget without a non-empty final response."},metadata:{turnsCount:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X,outputTruncated:!0}};let D=g6(),f=D?.finalMessage??q.content??"",b=await u(),l=D||b?{...D?.persistenceMetadata,...b?{turnFinalization:b}:{}}:void 0;L.appendAssistant({role:"assistant",content:f,reasoningContent:D?void 0:q.reasoningContent,tool_calls:D?void 0:q.toolCalls,...l?{metadata:c$(l)}:{}});let E=await v0($,J,f,z,D?void 0:q.reasoningContent,l);if(E)z=E;if(N&&!D)return{success:!1,error:{type:"structured_output_failed",message:"The model reached its output budget before submitting a schema-valid structured response."},metadata:{turnsCount:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X,outputTruncated:!0,structuredOutputSchemaDigest:N.schemaDigest}};if(D)yield D.event;return{success:!0,finalMessage:f,metadata:{turnsCount:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X,outputTruncated:!0,...D?.resultMetadata}}}if(!q.toolCalls||q.toolCalls.length===0){let U=F6(o,[],[]);if(U)yield{kind:"action_stationarity",...U};let D=await t0?.drain()??[];if(D.length>0){if(q.finishReason!=="length")o0=0;Q0=void 0,a0=!1,l0=0,L.appendAssistant({role:"assistant",content:q.content||"",reasoningContent:q.reasoningContent});let I=await v0($,J,q.content||"",z,q.reasoningContent);if(I)z=I;yield{kind:"steering_applied",...await E1(D),delivery:"current_turn",queue:await t0.getSnapshot()};continue}if(N&&!Q0){if(q.finishReason!=="length")o0=0;if(z=await V0({deps:$,context:J,state:L,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:z}),l0>=R6)return{success:!1,error:{type:"structured_output_failed",message:`The model did not call ${u0} with a schema-valid object before the corrective retry budget was exhausted.`},metadata:{turnsCount:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X,structuredOutputSchemaDigest:N.schemaDigest}};l0++;let I=`The final response is invalid because this turn requires the ${u0} tool. Complete any remaining work, then call ${u0} exactly once with an object matching its schema. Do not return JSON as prose.`;L.appendControl("user",{role:"user",content:I});let i0=await r0($,J,I,z,f0);if(i0)z=i0;continue}let f=CZ(q.content,A0,$1.map((I)=>I.name),H>=P0?g1:I6);if(!N&&f.action!=="none"){if(z=await V0({deps:$,context:J,state:L,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:z,...f.action==="retry"?{controlPrompt:f.prompt}:{}}),f.action==="fail")return{success:!1,error:{type:"intent_fulfillment_failed",message:f.message},metadata:{turnsCount:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X}};I6++,P$=f.toolName&&!w0.has(f.toolName)?f.toolName:void 0;continue}if(M1)return z=await V0({deps:$,context:J,state:L,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:z}),{success:!1,error:{type:"intent_fulfillment_failed",message:"The model did not invoke the required native tool after correcting a textual tool call."},metadata:{turnsCount:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X}};let b=await p6(q);if(b.action==="continue")continue;if(b.action==="fail")return b.result;if(q.finishReason!=="length")o0=0;if(q.content&&n2(x,q.content)){z=await V0({deps:$,context:J,state:L,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:z,controlPrompt:`
|
|
164
164
|
|
|
165
165
|
<system-reminder>
|
|
166
166
|
${o2()}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Bi as H,Ci as I}from"./chunk-
|
|
1
|
+
import{Bi as H,Ci as I}from"./chunk-qbgnb5f4.js";import{Mutex as J}from"async-mutex";class B extends Error{limit;resource="resident_runtimes";retryable=!0;constructor(b){super("Session runtime capacity is full");this.limit=b;this.name="SessionRuntimeCapacityError"}}class D extends Error{constructor(){super("Session runtime residency is closed");this.name="SessionRuntimeResidencyClosedError"}}class A extends Error{constructor(b){super(`Session runtime residency already owns key: ${b}`);this.name="SessionRuntimeResidencyConflictError"}}class K{maxResident;idleMs;now;residents=new Map;reservations=new Map;operations=new J;nextGeneration=1;closed=!1;constructor(b){if(!H(b.maxResident))throw Error("Invalid max resident Session Runtime limit");if(!I(b.idleMs))throw Error("Invalid Session Runtime idle timeout");this.maxResident=b.maxResident,this.idleMs=b.idleMs,this.now=b.now??Date.now}acquire(b){let j=this.residents.get(b);if(!j||j.poisoned)return;return j.pins++,j.lastUsedAt=this.now(),this.createLease(j)}owns(b,j){let q=this.residents.get(b);return Boolean(q&&(j===void 0||q.value===j))}async reserve(b,j){if(!b.trim())throw Error("Session runtime residency key must not be blank");return this.operations.runExclusive(async()=>{if(this.closed)throw new D;if(this.residents.has(b)||this.reservations.has(b))throw new A(b);while(this.retainedCount()>=this.maxResident){if(!j.allowEviction)throw new B(this.maxResident);let z=this.oldestEvictableWebResident();if(!z)throw new B(this.maxResident);await this.disposeResident(z,!0)}let q={generation:this.allocateGeneration(),surface:j.surface};return this.reservations.set(b,q),this.createReservation(b,q)})}async remove(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j)return!1;if(q.pins>0)return!1;return await this.disposeResident(q,!0),!0})}async forget(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j||q.pins>0)return!1;return this.residents.delete(b),!0})}async sweepIdle(){return this.operations.runExclusive(async()=>{if(this.closed)return 0;let b=0;while(!0){let j=this.oldestIdleWebResident();if(!j)return b;await this.disposeResident(j,!0),b++}})}async disposeAll(){await this.operations.runExclusive(async()=>{this.closed=!0,this.reservations.clear();let b;for(let j of[...this.residents.values()])try{await this.disposeResident(j,!1)}catch(q){b??=q}if(this.residents.clear(),b!==void 0)throw b})}getStats(){let b=0;for(let j of this.residents.values())if(j.pins>0)b++;return{resident:this.residents.size,reserved:this.reservations.size,pinned:b,maxResident:this.maxResident}}retainedCount(){return this.residents.size+this.reservations.size}allocateGeneration(){let b=this.nextGeneration;return this.nextGeneration=this.nextGeneration===Number.MAX_SAFE_INTEGER?1:this.nextGeneration+1,b}createReservation(b,j){let q=!1;return{commit:(z)=>{if(q)throw new A(b);if(z.key!==b||z.surface!==j.surface||this.reservations.get(b)!==j||this.closed)throw this.reservations.delete(b),q=!0,this.closed?new D:new A(b);this.reservations.delete(b);let G={...z,generation:j.generation,pins:1,lastUsedAt:this.now(),poisoned:!1};return this.residents.set(b,G),q=!0,this.createLease(G)},cancel:()=>{if(q)return;if(this.reservations.get(b)===j)this.reservations.delete(b);q=!0}}}createLease(b){let j=!1;return{value:b.value,release:()=>{if(j)return;j=!0;let q=this.residents.get(b.key);if(q!==b||q.generation!==b.generation)return;q.pins=Math.max(0,q.pins-1),q.lastUsedAt=this.now()}}}oldestEvictableWebResident(){return this.sortedWebResidents().find((b)=>this.canEvict(b))}oldestIdleWebResident(){let b=this.now();return this.sortedWebResidents().find((j)=>b-j.lastUsedAt>=this.idleMs&&this.canEvict(j))}sortedWebResidents(){return[...this.residents.values()].filter((b)=>b.surface==="web").sort((b,j)=>b.lastUsedAt-j.lastUsedAt||b.generation-j.generation)}canEvict(b){if(b.pins>0||b.poisoned)return!1;try{return b.canEvict()}catch{return!1}}async disposeResident(b,j){if(this.residents.get(b.key)!==b)return;this.residents.delete(b.key);try{await b.dispose()}catch(q){if(j&&!this.closed&&!this.residents.has(b.key))b.lastUsedAt=this.now(),b.poisoned=!0,this.residents.set(b.key,b);throw q}}}
|
|
2
2
|
export{B as v,K as w};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{ch as j1,dh as K0,eh as F1}from"./chunk-kehgewqh.js";import{kh as w0}from"./chunk-kkzznz4w.js";import{th as YO,uh as L1}from"./chunk-1cy4ab77.js";import{xh as I1}from"./chunk-7ajvrtb3.js";import{Ah as $0,yh as B0}from"./chunk-
|
|
1
|
+
import{ch as j1,dh as K0,eh as F1}from"./chunk-kehgewqh.js";import{kh as w0}from"./chunk-kkzznz4w.js";import{th as YO,uh as L1}from"./chunk-1cy4ab77.js";import{xh as I1}from"./chunk-7ajvrtb3.js";import{Ah as $0,yh as B0}from"./chunk-4szhq9af.js";import{Ni as S0,Oi as $O,Si as I0}from"./chunk-qbgnb5f4.js";import{cj as B}from"./chunk-qdbbke8f.js";import{Ej as P,Fj as j,Gj as p,Ij as q,Lj as k1}from"./chunk-rmfzym94.js";import{Yj as k0}from"./chunk-ctrr7v68.js";import{dk as D}from"./chunk-ggdgk3gy.js";import{Ak as t1}from"./chunk-n52n2w5v.js";import T0 from"node:path";import QO from"node:path";import C0 from"node:fs";import L0 from"node:os";import w from"node:path";import RO from"yaml";var G1=2000,W1=50,Y1=1000,O4={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:G1},findings:{type:"array",maxItems:W1,items:{type:"string",minLength:1,maxLength:Y1}}},required:["verdict","summary","findings"],additionalProperties:!1};function q1(O,$){let Q=O.trim().replaceAll(/\s+/g," ");if($)Q=Q.replaceAll($,".");return Q.replace(/\bBearer\s+[^\s"'`]+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted-key]").replace(/\b(api(?:[_-]?|\s+)key|access(?:[_-]?|\s+)token|authorization|cookie|password|passwd|refresh(?:[_-]?|\s+)token|secret|session(?:[_-]?|\s+)token)\b(\s*[:=]\s*)([^\s,;]+)/gi,"$1$2[redacted]")}function NO(O){if(O.length<=w0)return O;let $=" [verification feedback truncated]",Q=O.slice(0,w0-$.length);if(/[\uD800-\uDBFF]$/.test(Q))Q=Q.slice(0,-1);return Q.trimEnd()+$}function X1(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O;if($.verdict!=="pass"&&$.verdict!=="fail"&&$.verdict!=="partial"||typeof $.summary!=="string"||!$.summary.trim()||$.summary.length>G1||!Array.isArray($.findings)||$.findings.length>W1||!$.findings.every((Q)=>typeof Q==="string"&&Q.trim().length>0&&Q.length<=Y1))return;return{verdict:$.verdict,summary:$.summary.trim(),findings:$.findings.map((Q)=>Q.trim())}}function $4(O,$){let Q=X1(O);if(!Q)return;let Z=q1(Q.summary,$),J=Q.findings.map((L)=>q1(L,$));return NO([Z,J.length>0?`Findings:
|
|
2
2
|
${J.map((L)=>`- ${L}`).join(`
|
|
3
3
|
`)}`:""].filter(Boolean).join(`
|
|
4
4
|
|