blade-code 0.10.73 → 0.10.75
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-4ehgjdm0.js → chunk-03947xkg.js} +1 -1
- package/dist/{chunk-yvnm25nb.js → chunk-0cbpjhq7.js} +1 -1
- package/dist/chunk-0jmvv2vb.js +1 -0
- package/dist/{chunk-tvv3syt3.js → chunk-1zkwxaa0.js} +1 -1
- package/dist/{chunk-p0qjjyex.js → chunk-1zwq624e.js} +2 -2
- package/dist/{chunk-ah12xhh6.js → chunk-22aaybx2.js} +1 -1
- package/dist/chunk-22s3r2xy.js +2 -0
- package/dist/{chunk-cvvtrvk6.js → chunk-22sw5bv4.js} +2 -2
- package/dist/{chunk-vhadycw2.js → chunk-2faga011.js} +2 -2
- package/dist/{chunk-3r0x2p7z.js → chunk-2m4mgw58.js} +2 -2
- package/dist/{chunk-tzytnhbp.js → chunk-2qqmmxqf.js} +2 -2
- package/dist/{chunk-a37mn58w.js → chunk-2v10cw32.js} +1 -1
- package/dist/{chunk-traa01dd.js → chunk-44zkyzrj.js} +1 -1
- package/dist/chunk-4mgjj8zg.js +1 -0
- package/dist/{chunk-vw0gg08s.js → chunk-4ppgfhqd.js} +2 -2
- package/dist/{chunk-2wdxpdz3.js → chunk-57jj40er.js} +2 -2
- package/dist/chunk-5a132j64.js +1 -0
- package/dist/chunk-5dz30k5z.js +6 -0
- package/dist/{chunk-jeazjp08.js → chunk-5tat9wy9.js} +3 -3
- package/dist/{chunk-r5bpvfym.js → chunk-6bka1j4q.js} +1 -1
- package/dist/chunk-7yppfbgr.js +1 -0
- package/dist/{chunk-0hrj06t7.js → chunk-99nevk7k.js} +1 -1
- package/dist/chunk-a6kbpq05.js +1 -0
- package/dist/{chunk-8fm3xamc.js → chunk-agxs6rwh.js} +1 -1
- package/dist/{chunk-ne7vres8.js → chunk-bj5msq36.js} +1 -1
- package/dist/{chunk-k82ff14t.js → chunk-c03xn5s3.js} +1 -1
- package/dist/{chunk-xjc0bthz.js → chunk-c74e0jx1.js} +2 -2
- package/dist/{chunk-yx82ang3.js → chunk-d2eahefk.js} +2 -2
- package/dist/{chunk-67ddp3ns.js → chunk-egp0crrc.js} +3 -3
- package/dist/{chunk-r8wbvxn7.js → chunk-fbgzeb3m.js} +1 -1
- package/dist/chunk-fefz145r.js +1 -0
- package/dist/chunk-ffkdx471.js +1 -0
- package/dist/{chunk-ax610gqh.js → chunk-fj297dmj.js} +1 -1
- package/dist/chunk-fpkq3ch3.js +1 -0
- package/dist/{chunk-b28zsp1t.js → chunk-g3fbgp1k.js} +3 -3
- package/dist/{chunk-948efzyp.js → chunk-gbrwzpyg.js} +2 -2
- package/dist/{chunk-a5e4sy4q.js → chunk-gz2fx7th.js} +2 -2
- package/dist/{chunk-b3413dtc.js → chunk-h4d37zt2.js} +1 -1
- package/dist/{chunk-sxjs66h6.js → chunk-hzy5jzkp.js} +1 -1
- package/dist/{chunk-4khtsmrf.js → chunk-kaf6m50a.js} +1 -1
- package/dist/{chunk-3hv57n95.js → chunk-kb5xaar0.js} +311 -289
- package/dist/{chunk-77hn7hf6.js → chunk-m6yfwyva.js} +1 -1
- package/dist/{chunk-9e6dcbqq.js → chunk-m88zk362.js} +2 -2
- package/dist/{chunk-q6ak67n8.js → chunk-n0x5z56v.js} +2 -2
- package/dist/{chunk-tmvg7taj.js → chunk-nfyxb2q5.js} +1 -1
- package/dist/{chunk-mefb27ch.js → chunk-p7ww2tcn.js} +1 -1
- package/dist/{chunk-meee1cbq.js → chunk-pdansrbx.js} +1 -1
- package/dist/{chunk-p7y79y6c.js → chunk-qp8mejbn.js} +1 -1
- package/dist/{chunk-kka51s0k.js → chunk-qtt17d5s.js} +1 -1
- package/dist/{chunk-zxn7f308.js → chunk-qw5j84ny.js} +2 -2
- package/dist/chunk-qxjsfp2c.js +1 -0
- package/dist/{chunk-skw3b17a.js → chunk-qyxbee3w.js} +1 -1
- package/dist/{chunk-wp0794r2.js → chunk-r297pq3s.js} +2 -2
- package/dist/{chunk-jkh9s1ht.js → chunk-rc7jnds2.js} +1 -1
- package/dist/{chunk-5d1gbm41.js → chunk-rdtgv0n8.js} +2 -2
- package/dist/{chunk-y36rdy4v.js → chunk-rjgfy07e.js} +2 -2
- package/dist/{chunk-n1w40gq2.js → chunk-s7gf2ds9.js} +2 -2
- package/dist/chunk-ssfvcnat.js +1 -0
- package/dist/chunk-swvp6j18.js +1 -0
- package/dist/{chunk-xv92c582.js → chunk-tnjq10zs.js} +1 -1
- package/dist/chunk-v0znd20r.js +1 -0
- package/dist/{chunk-a0ns74mh.js → chunk-v4ek6q8t.js} +1 -1
- package/dist/chunk-vbxtqh24.js +1 -0
- package/dist/chunk-vkpddj6a.js +1 -0
- package/dist/chunk-w1m7wz1y.js +10 -0
- package/dist/{chunk-js4vqnds.js → chunk-xbj18hxh.js} +1 -1
- package/dist/{chunk-c9e0fbyh.js → chunk-xkz9ecdx.js} +1 -1
- package/dist/{chunk-bhhdvqe7.js → chunk-xts31qj4.js} +2 -2
- package/dist/chunk-yjbq4jeg.js +2 -0
- package/dist/{chunk-9cgsheg0.js → chunk-yk8s8kjt.js} +2 -2
- package/dist/{chunk-1ava19kd.js → chunk-yz80dp1a.js} +2 -2
- package/dist/{chunk-4cpgcm7q.js → chunk-zph2jekm.js} +2 -2
- package/dist/web/assets/ChatView-Bjl8VJFM.js +18 -0
- package/dist/web/assets/{CodeBlockHighlighter-XaY8h0vd.js → CodeBlockHighlighter-i8Yc4Qe4.js} +1 -1
- package/dist/web/assets/{FilePreview-CVHV6oga.js → FilePreview-DbU1IMtz.js} +1 -1
- package/dist/web/assets/{KanbanBoard-D1_61uZi.js → KanbanBoard-Fe4qkgpi.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-DUPwAzs4.js → MarkdownRenderer-CdeC66uL.js} +3 -3
- package/dist/web/assets/{SettingsModal-DHnU7uMN.js → SettingsModal-mbG701yW.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-CpXhLtO5.js → TaskSwitcher-DF-q_rMi.js} +1 -1
- package/dist/web/assets/{TerminalPanel-eYsA-A62.js → TerminalPanel-BxAmwOXK.js} +1 -1
- package/dist/web/assets/{index-gjBOFzd1.js → index-BTj86SSJ.js} +3 -3
- package/dist/web/assets/{teamService-Bb2kW8Hh.js → teamService-Cnno2N5h.js} +1 -1
- package/dist/web/index.html +1 -1
- package/package.json +1 -1
- package/dist/chunk-0qqzd0hq.js +0 -1
- package/dist/chunk-1cyy8wqj.js +0 -10
- package/dist/chunk-3fzy7q6x.js +0 -1
- package/dist/chunk-64jq6jcr.js +0 -2
- package/dist/chunk-8h35w91f.js +0 -1
- package/dist/chunk-fdmcef2p.js +0 -2
- package/dist/chunk-fgh6mjdp.js +0 -6
- package/dist/chunk-hswyrd88.js +0 -1
- package/dist/chunk-jsg7vmxp.js +0 -1
- package/dist/chunk-vxd30mnx.js +0 -1
- package/dist/chunk-wbzvy99s.js +0 -1
- package/dist/chunk-wg3z2epq.js +0 -1
- package/dist/chunk-xkc6v9nb.js +0 -1
- package/dist/chunk-yg6c4xrs.js +0 -1
- package/dist/chunk-z8a5ebep.js +0 -1
- package/dist/chunk-z95pw8nb.js +0 -1
- package/dist/chunk-zh2x0tcm.js +0 -1
- package/dist/chunk-zr1mg5kq.js +0 -1
- package/dist/web/assets/ChatView-Dm-DMbOV.js +0 -18
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Tb as dJ}from"./chunk-r8wbvxn7.js";import{$b as s6,Ac as i$,Kc as b0,Mc as R2,Nc as O1,Oc as C2,Ub as $$,Vc as R$,ac as t6,bc as q2,cc as O2,ic as e6,jc as cJ,kc as iJ,lc as j2,mc as F1,nc as lJ,oc as rJ,pc as U1,sc as k6}from"./chunk-2wdxpdz3.js";import{_c as V0,bd as d6,cd as _0}from"./chunk-wp0794r2.js";import{de as jJ}from"./chunk-c9e0fbyh.js";import{ee as gJ,fe as c0,ge as hJ,je as uJ,ke as h2,me as x6}from"./chunk-y36rdy4v.js";import{We as l0,Xe as R0,_e as mJ}from"./chunk-4khtsmrf.js";import{hf as z$}from"./chunk-67ddp3ns.js";import{rg as QJ}from"./chunk-p7y79y6c.js";import{Eg as J0}from"./chunk-ah12xhh6.js";import{eh as y0}from"./chunk-tzytnhbp.js";import{sh as a6}from"./chunk-xjc0bthz.js";import{Dh as j$,Fh as y6,Gh as D0,Hh as q1,Jh as n6,Lh as o6}from"./chunk-zxn7f308.js";import{Mh as y5}from"./chunk-0hrj06t7.js";function Q$($){return $.role==="system"&&Array.isArray($.content)}function X$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class X1{systemMessages;_contextualSystemMessages;_history;_pending=[];context;constructor($,J){this.context=$;let Z=$.messages.find(Q$);if(this._contextualSystemMessages=$.messages.filter(X$),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!Q$(W)&&!X$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}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(!X$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(Q$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((J)=>J.id===$.id))return;this._history.push($)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((J)=>!Q$(J)&&!X$(J))}restoreDurableHistory($){this._contextualSystemMessages=$.filter(X$),this._history=$.filter((J)=>!Q$(J)&&!X$(J)),this._pending=[],this.syncContextualSystemMessages()}removeMessages($){this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages()}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function Z6($){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 W6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function Y6($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import e0 from"node:path";var Z4=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"]),W4=/^(LD_.+|DYLD_.+|PATH)$/,K6=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function k$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],K=W.match(K6);if(!K)break;let H=K[1];if(!Z4.has(H))break;J=Y}return J}function g8($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],K=W.match(K6);if(!K)break;let H=K[1];if(W4.test(H))break;J=Y}return J}var Y4=[/^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 a1($){let J=$,Z=!0;while(Z){Z=!1;for(let W of Y4){let Y=J.match(W);if(Y){J=J.slice(Y[0].length),Z=!0;break}}if(J.startsWith("-- "))J=J.slice(3),Z=!0}return J}function M$($){let J=[],Z="",W=!1,Y=!1,K=!1;for(let H=0;H<$.length;H++){let X=$[H];if(K){Z+=X,K=!1;continue}if(X==="\\"&&!W){Z+=X,K=!0;continue}if(X==="'"&&!Y){W=!W,Z+=X;continue}if(X==='"'&&!W){Y=!Y,Z+=X;continue}if(W||Y){Z+=X;continue}if(X==="|"){if(H+1<$.length&&$[H+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",H++;continue}return null}if(X===">"||X==="<")return null;if(X==="&"&&H+1<$.length&&$[H+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",H++;continue}if(X==="&")return null;if(X===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=X}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function H6($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let K=$[Y];if(W){W=!1;continue}if(K==="\\"&&!J){W=!0;continue}if(K==="'"&&!Z){J=!J;continue}if(K==='"'&&!J){Z=!Z;continue}if(J)continue;if(K==="$"){let H=$[Y+1];if(H&&/[A-Za-z_@*#?!$0-9({]/.test(H))return!0}if(K==="`")return!0;if(Z)continue;if(K==="|")return!0;if(K===">"||K==="<")return!0;if(K==="{"){let H=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(H)||/^\{[^}]*\.\.[^}]*\}/.test(H))return!0}}return!1}function t0($){let J=[],Z="",W=!1,Y=!1,K=!1;for(let H=0;H<$.length;H++){let X=$[H];if(K){Z+=X,K=!1;continue}if(X==="\\"&&!W){if(K=!0,Y){let Q=$[H+1];if(Q&&'$`"\\'.includes(Q))continue;Z+=X,K=!1}continue}if(X==="'"&&!Y){W=!W;continue}if(X==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(X)){if(Z)J.push(Z),Z="";continue}Z+=X}if(Z)J.push(Z);return J}var K4=new Set(["npm","pnpm","yarn","bun"]),X6=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),H4=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),X4=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function Q4($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function Q6($){return $.replace(/\s+2>&1\s*$/,"").trim()}function V4($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=t0(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let K=Y[1];if(!K||K==="-")return;let H=e0.isAbsolute(K)?e0.resolve(K):e0.resolve(Z,K);if(!$$.isWithinWorkspace(H,Z))return;return W[2]?.trim()||void 0}function z4($){let J=[],Z=!1,W=!1,Y=!1;for(let K=0;K<$.length;K++){let H=$[K];if(Y){Y=!1;continue}if(H==="\\"&&!Z){Y=!0;continue}if(H==="'"&&!W){Z=!Z;continue}if(H==='"'&&!Z){W=!W;continue}if(H!=="|"||Z||W)continue;if($[K+1]==="|")return;J.push(K)}return J}function B4($){let J=t0($),[Z,W,Y]=J;if(Z!=="head"&&Z!=="tail")return!1;if(J.length===1)return!0;let K=(H)=>H!==void 0&&/^[1-9]\d{0,4}$/.test(H);if(J.length===2)return W?.startsWith("--lines=")&&K(W.slice(8))||W?.startsWith("-")&&K(W.slice(1));return J.length===3&&(W==="-n"||W==="--lines")&&K(Y)}function D4($){let J=Q6($.replace(X4,"").trim()),Z=z4(J);if(!Z)return;if(Z.length===0)return V6(J);if(Z.length!==1)return;let W=Z[0];if(W===void 0)return;let Y=Q6(J.slice(0,W).trim()),K=J.slice(W+1).trim();if(!Y||!B4(K))return;return V6(Y)}function V6($){let Z=M$($)?.at(-1);if(!Z)return $;let W=t0(Z),[Y,K]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&K==="vitest")||W.some((X)=>X==="--configLoader"||X.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function V$($,J){let Z=D4($);if(!Z)return!1;let W=k$(Z),Y=M$(W);if(!Y||H6(W)||/[\r\n]/.test(W))return!1;let K=Y.length===1?Y[0]:V4(W,Y,J);if(!K)return!1;let H=t0(K);if(H.length===0||H.some((D)=>[...H4].some((w)=>D===w||D.startsWith(`${w}=`))))return!1;let[X,Q,V]=H;if(K4.has(X??""))return Q4(Q==="run"?V:Q)||Q==="--test";if((X==="npx"||X==="bunx")&&X6.has(Q??""))return!0;if(X6.has(X??""))return!0;if(X==="node"&&Q==="--test")return!0;if(X==="go"&&["build","test","vet"].includes(Q??""))return!0;return X==="cargo"&&["build","check","clippy","test"].includes(Q??"")}function i8($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!e0.isAbsolute($);let Z=e0.isAbsolute($)?e0.resolve($):e0.resolve(J,$);return $$.isWithinWorkspace(Z,J)}var s1=y0("Agent"),j4=3;function t1($,J,Z){if($!=="length")return{action:"none"};if(J>=j4)return{action:"truncated"};if(Z6(Z)==="stop")return s1.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var w4=[/:\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],U4=/```[\s\S]{50,}```/,z6="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",L4=2;function e1($,J,Z=!0){if(!$||J>=L4)return{action:"none"};if(!Z&&U4.test($))return{action:"retry",prompt:z6};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(w4.some((H)=>H.test(W)))return{action:"retry",prompt:z6};return{action:"none"}}var G4=[/\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}(?:测试|单测|集成测试|检查|构建)/],B6={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},q4={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},O4="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.",N4="Required verification did not run successfully before the retry limit.",F4=3;function j6($,J,Z,W){if(!Z.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(J)){$.clear();return}if(J==="Bash"&&typeof Z.metadata?.command==="string"&&Z.metadata.exit_code===0&&V$(Z.metadata.command,W)){$.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes(J))return;let Y=Z.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let K of Y)if(typeof K==="string"&&V$(K,W))$.add(K)}function $2($,J,Z){if(!$||!G4.some((Q)=>Q.test($)))return{action:"none"};let W=Object.keys(B6).filter((Q)=>B6[Q].test($)),Y=[...J],K=W.filter((Q)=>!Y.some((V)=>q4[Q].test(V)));if(W.length>0?K.length===0:Y.some((Q)=>V$(Q)))return{action:"none"};if(Z>=F4)return{action:"fail",message:N4};let X=W.length>1&&K.length>0?` Missing successful verification categories: ${K.join(", ")}.`:"";return{action:"retry",prompt:`${O4}${X}`}}var y4=[/\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|子代理|子智能体)/],w6=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function U6($){return typeof $==="string"&&w6.some((J)=>J.test($))}var P4=[/\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|子代理)/],_4=[/\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 A4($){if(typeof $!=="string")return;if(_4.some((J)=>J.test($)))return"multiple-allowed";return P4.some((J)=>J.test($))?"required":void 0}function V1($){for(let J of $){let Z=A4(J);if(Z!==void 0)return Z==="required"}return!1}var f4="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.",b4="Required delegation did not complete before the retry limit.",T4=3;function L6($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((H)=>H.trim()).filter(Boolean),Y=V1(W),K=!1;if(!Y)for(let H of W){if(w6.some((X)=>X.test(H)))break;if(y4.some((X)=>X.test(H))){K=!0;break}}if(W.length===0||!Y&&!K||J.has("Task"))return{action:"none"};if(Z>=T4)return{action:"fail",message:b4};return{action:"retry",prompt:f4}}var E4=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],S4=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],x4=[/\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 G6($){return x4.reduce((J,Z)=>J.replace(Z," "),$)}function z1($){if(typeof $!=="string")return!1;let J=G6($);return E4.some((Z)=>Z.test(J))}var k4="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.",M4="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.",h4="Required worktree lifecycle did not complete before the retry limit.",R4=3;function q6($,J,Z){if(!$)return{action:"none"};let W=G6($);if(!z1(W))return{action:"none"};let Y=S4.some((H)=>H.test(W));if(J.has("TaskWorktree"))return{action:"none"};let K=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!K)return{action:"none"};if(Z>=R4)return{action:"fail",message:h4};return{action:"retry",tool:K,prompt:K==="EnterWorktree"?k4:M4}}var D6=30000;async function J2($){try{let Z=z$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??J0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((K)=>{W=setTimeout(()=>K("timeout"),D6)});try{let K=await Promise.race([Z,Y]);if(K==="timeout")return s1.warn(`[Loop] Stop hook 超时 (${D6}ms),按 shouldStop: true 处理`),{action:"stop"};let H=K;if(!H.shouldStop)return{action:"continue",reason:H.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return s1.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function C4($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var I4=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function v4($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((J)=>{if(typeof J==="string")return J;if(J&&typeof J==="object"&&"text"in J){let Z=J.text;return typeof Z==="string"?Z:""}return""}).join(" ");return""}function p4($){let J=$;for(let Q of I4)J=J.replace(Q," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:Z;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let K=Y.slice(0,60),H=K.lastIndexOf(" ");return`${(H>36?K.slice(0,H):K).trimEnd()}…`}function O6($){return p4(v4($))}import{EventEmitter as g4}from"events";import N6 from"node:path";function Z2($){if(y6($.sessionId),!N6.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:N6.resolve($.projectPath)}}function F6($){let J=Z2($);return JSON.stringify([J.projectPath,J.sessionId])}function WZ($,J){return F6($)===F6(J)}class B$ extends g4{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!B$.instance)B$.instance=new B$;return B$.instance}publish($,J,Z,W){let Y=Z2($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:J,...W!==void 0?{seq:W}:{},properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var h$=B$.getInstance();var u0=y0("Agent"),B1=new Set;async function u4($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(B1.has(Z))return;if(B1.size>=5000)B1.clear();B1.add(Z);try{let W=$.workspaceRoot,Y=await R$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let K=O6(J);if(!K)return;await R$.updateSessionMetadata(Z,Y.projectPath,{title:K}),h$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:K})}catch(W){u0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var W2=`<turn_aborted>
|
|
1
|
+
import{Ub as dJ}from"./chunk-fbgzeb3m.js";import{Bc as i$,Lc as b0,Nc as R2,Oc as O1,Pc as C2,Vb as $$,Wc as R$,ac as s6,bc as t6,cc as q2,dc as O2,jc as e6,kc as cJ,lc as iJ,mc as j2,nc as F1,oc as lJ,pc as rJ,qc as U1,tc as k6}from"./chunk-57jj40er.js";import{$c as V0,cd as d6,dd as _0}from"./chunk-r297pq3s.js";import{ee as jJ}from"./chunk-xkz9ecdx.js";import{fe as gJ,ge as c0,he as hJ,ke as uJ,le as h2,ne as x6}from"./chunk-rjgfy07e.js";import{$e as mJ,Xe as l0,Ye as R0}from"./chunk-kaf6m50a.js";import{if as z$}from"./chunk-egp0crrc.js";import{sg as QJ}from"./chunk-qp8mejbn.js";import{Fg as J0}from"./chunk-22aaybx2.js";import{fh as y0}from"./chunk-2qqmmxqf.js";import{th as a6}from"./chunk-c74e0jx1.js";import{Eh as j$,Gh as y6,Hh as D0,Ih as q1,Kh as n6,Mh as o6}from"./chunk-qw5j84ny.js";import{Nh as y5}from"./chunk-99nevk7k.js";function Q$($){return $.role==="system"&&Array.isArray($.content)}function X$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class X1{systemMessages;_contextualSystemMessages;_history;_pending=[];context;constructor($,J){this.context=$;let Z=$.messages.find(Q$);if(this._contextualSystemMessages=$.messages.filter(X$),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!Q$(W)&&!X$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}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(!X$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(Q$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((J)=>J.id===$.id))return;this._history.push($)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((J)=>!Q$(J)&&!X$(J))}restoreDurableHistory($){this._contextualSystemMessages=$.filter(X$),this._history=$.filter((J)=>!Q$(J)&&!X$(J)),this._pending=[],this.syncContextualSystemMessages()}removeMessages($){this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages()}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function Z6($){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 W6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function Y6($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import e0 from"node:path";var Z4=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"]),W4=/^(LD_.+|DYLD_.+|PATH)$/,K6=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function k$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],K=W.match(K6);if(!K)break;let H=K[1];if(!Z4.has(H))break;J=Y}return J}function g8($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],K=W.match(K6);if(!K)break;let H=K[1];if(W4.test(H))break;J=Y}return J}var Y4=[/^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 a1($){let J=$,Z=!0;while(Z){Z=!1;for(let W of Y4){let Y=J.match(W);if(Y){J=J.slice(Y[0].length),Z=!0;break}}if(J.startsWith("-- "))J=J.slice(3),Z=!0}return J}function M$($){let J=[],Z="",W=!1,Y=!1,K=!1;for(let H=0;H<$.length;H++){let X=$[H];if(K){Z+=X,K=!1;continue}if(X==="\\"&&!W){Z+=X,K=!0;continue}if(X==="'"&&!Y){W=!W,Z+=X;continue}if(X==='"'&&!W){Y=!Y,Z+=X;continue}if(W||Y){Z+=X;continue}if(X==="|"){if(H+1<$.length&&$[H+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",H++;continue}return null}if(X===">"||X==="<")return null;if(X==="&"&&H+1<$.length&&$[H+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",H++;continue}if(X==="&")return null;if(X===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=X}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function H6($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let K=$[Y];if(W){W=!1;continue}if(K==="\\"&&!J){W=!0;continue}if(K==="'"&&!Z){J=!J;continue}if(K==='"'&&!J){Z=!Z;continue}if(J)continue;if(K==="$"){let H=$[Y+1];if(H&&/[A-Za-z_@*#?!$0-9({]/.test(H))return!0}if(K==="`")return!0;if(Z)continue;if(K==="|")return!0;if(K===">"||K==="<")return!0;if(K==="{"){let H=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(H)||/^\{[^}]*\.\.[^}]*\}/.test(H))return!0}}return!1}function t0($){let J=[],Z="",W=!1,Y=!1,K=!1;for(let H=0;H<$.length;H++){let X=$[H];if(K){Z+=X,K=!1;continue}if(X==="\\"&&!W){if(K=!0,Y){let Q=$[H+1];if(Q&&'$`"\\'.includes(Q))continue;Z+=X,K=!1}continue}if(X==="'"&&!Y){W=!W;continue}if(X==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(X)){if(Z)J.push(Z),Z="";continue}Z+=X}if(Z)J.push(Z);return J}var K4=new Set(["npm","pnpm","yarn","bun"]),X6=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),H4=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),X4=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function Q4($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function Q6($){return $.replace(/\s+2>&1\s*$/,"").trim()}function V4($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=t0(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let K=Y[1];if(!K||K==="-")return;let H=e0.isAbsolute(K)?e0.resolve(K):e0.resolve(Z,K);if(!$$.isWithinWorkspace(H,Z))return;return W[2]?.trim()||void 0}function z4($){let J=[],Z=!1,W=!1,Y=!1;for(let K=0;K<$.length;K++){let H=$[K];if(Y){Y=!1;continue}if(H==="\\"&&!Z){Y=!0;continue}if(H==="'"&&!W){Z=!Z;continue}if(H==='"'&&!Z){W=!W;continue}if(H!=="|"||Z||W)continue;if($[K+1]==="|")return;J.push(K)}return J}function B4($){let J=t0($),[Z,W,Y]=J;if(Z!=="head"&&Z!=="tail")return!1;if(J.length===1)return!0;let K=(H)=>H!==void 0&&/^[1-9]\d{0,4}$/.test(H);if(J.length===2)return W?.startsWith("--lines=")&&K(W.slice(8))||W?.startsWith("-")&&K(W.slice(1));return J.length===3&&(W==="-n"||W==="--lines")&&K(Y)}function D4($){let J=Q6($.replace(X4,"").trim()),Z=z4(J);if(!Z)return;if(Z.length===0)return V6(J);if(Z.length!==1)return;let W=Z[0];if(W===void 0)return;let Y=Q6(J.slice(0,W).trim()),K=J.slice(W+1).trim();if(!Y||!B4(K))return;return V6(Y)}function V6($){let Z=M$($)?.at(-1);if(!Z)return $;let W=t0(Z),[Y,K]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&K==="vitest")||W.some((X)=>X==="--configLoader"||X.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function V$($,J){let Z=D4($);if(!Z)return!1;let W=k$(Z),Y=M$(W);if(!Y||H6(W)||/[\r\n]/.test(W))return!1;let K=Y.length===1?Y[0]:V4(W,Y,J);if(!K)return!1;let H=t0(K);if(H.length===0||H.some((D)=>[...H4].some((w)=>D===w||D.startsWith(`${w}=`))))return!1;let[X,Q,V]=H;if(K4.has(X??""))return Q4(Q==="run"?V:Q)||Q==="--test";if((X==="npx"||X==="bunx")&&X6.has(Q??""))return!0;if(X6.has(X??""))return!0;if(X==="node"&&Q==="--test")return!0;if(X==="go"&&["build","test","vet"].includes(Q??""))return!0;return X==="cargo"&&["build","check","clippy","test"].includes(Q??"")}function i8($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!e0.isAbsolute($);let Z=e0.isAbsolute($)?e0.resolve($):e0.resolve(J,$);return $$.isWithinWorkspace(Z,J)}var s1=y0("Agent"),j4=3;function t1($,J,Z){if($!=="length")return{action:"none"};if(J>=j4)return{action:"truncated"};if(Z6(Z)==="stop")return s1.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var w4=[/:\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],U4=/```[\s\S]{50,}```/,z6="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",L4=2;function e1($,J,Z=!0){if(!$||J>=L4)return{action:"none"};if(!Z&&U4.test($))return{action:"retry",prompt:z6};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(w4.some((H)=>H.test(W)))return{action:"retry",prompt:z6};return{action:"none"}}var G4=[/\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}(?:测试|单测|集成测试|检查|构建)/],B6={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},q4={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},O4="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.",N4="Required verification did not run successfully before the retry limit.",F4=3;function j6($,J,Z,W){if(!Z.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(J)){$.clear();return}if(J==="Bash"&&typeof Z.metadata?.command==="string"&&Z.metadata.exit_code===0&&V$(Z.metadata.command,W)){$.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes(J))return;let Y=Z.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let K of Y)if(typeof K==="string"&&V$(K,W))$.add(K)}function $2($,J,Z){if(!$||!G4.some((Q)=>Q.test($)))return{action:"none"};let W=Object.keys(B6).filter((Q)=>B6[Q].test($)),Y=[...J],K=W.filter((Q)=>!Y.some((V)=>q4[Q].test(V)));if(W.length>0?K.length===0:Y.some((Q)=>V$(Q)))return{action:"none"};if(Z>=F4)return{action:"fail",message:N4};let X=W.length>1&&K.length>0?` Missing successful verification categories: ${K.join(", ")}.`:"";return{action:"retry",prompt:`${O4}${X}`}}var y4=[/\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|子代理|子智能体)/],w6=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function U6($){return typeof $==="string"&&w6.some((J)=>J.test($))}var P4=[/\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|子代理)/],_4=[/\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 A4($){if(typeof $!=="string")return;if(_4.some((J)=>J.test($)))return"multiple-allowed";return P4.some((J)=>J.test($))?"required":void 0}function V1($){for(let J of $){let Z=A4(J);if(Z!==void 0)return Z==="required"}return!1}var f4="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.",b4="Required delegation did not complete before the retry limit.",T4=3;function L6($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((H)=>H.trim()).filter(Boolean),Y=V1(W),K=!1;if(!Y)for(let H of W){if(w6.some((X)=>X.test(H)))break;if(y4.some((X)=>X.test(H))){K=!0;break}}if(W.length===0||!Y&&!K||J.has("Task"))return{action:"none"};if(Z>=T4)return{action:"fail",message:b4};return{action:"retry",prompt:f4}}var E4=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],S4=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],x4=[/\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 G6($){return x4.reduce((J,Z)=>J.replace(Z," "),$)}function z1($){if(typeof $!=="string")return!1;let J=G6($);return E4.some((Z)=>Z.test(J))}var k4="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.",M4="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.",h4="Required worktree lifecycle did not complete before the retry limit.",R4=3;function q6($,J,Z){if(!$)return{action:"none"};let W=G6($);if(!z1(W))return{action:"none"};let Y=S4.some((H)=>H.test(W));if(J.has("TaskWorktree"))return{action:"none"};let K=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!K)return{action:"none"};if(Z>=R4)return{action:"fail",message:h4};return{action:"retry",tool:K,prompt:K==="EnterWorktree"?k4:M4}}var D6=30000;async function J2($){try{let Z=z$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??J0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((K)=>{W=setTimeout(()=>K("timeout"),D6)});try{let K=await Promise.race([Z,Y]);if(K==="timeout")return s1.warn(`[Loop] Stop hook 超时 (${D6}ms),按 shouldStop: true 处理`),{action:"stop"};let H=K;if(!H.shouldStop)return{action:"continue",reason:H.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return s1.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function C4($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var I4=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function v4($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((J)=>{if(typeof J==="string")return J;if(J&&typeof J==="object"&&"text"in J){let Z=J.text;return typeof Z==="string"?Z:""}return""}).join(" ");return""}function p4($){let J=$;for(let Q of I4)J=J.replace(Q," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:Z;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let K=Y.slice(0,60),H=K.lastIndexOf(" ");return`${(H>36?K.slice(0,H):K).trimEnd()}…`}function O6($){return p4(v4($))}import{EventEmitter as g4}from"events";import N6 from"node:path";function Z2($){if(y6($.sessionId),!N6.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:N6.resolve($.projectPath)}}function F6($){let J=Z2($);return JSON.stringify([J.projectPath,J.sessionId])}function WZ($,J){return F6($)===F6(J)}class B$ extends g4{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!B$.instance)B$.instance=new B$;return B$.instance}publish($,J,Z,W){let Y=Z2($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:J,...W!==void 0?{seq:W}:{},properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var h$=B$.getInstance();var u0=y0("Agent"),B1=new Set;async function u4($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(B1.has(Z))return;if(B1.size>=5000)B1.clear();B1.add(Z);try{let W=$.workspaceRoot,Y=await R$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let K=O6(J);if(!K)return;await R$.updateSessionMetadata(Z,Y.projectPath,{title:K}),h$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:K})}catch(W){u0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var W2=`<turn_aborted>
|
|
2
2
|
The previous turn was interrupted. Commands or tool calls may have partially completed; inspect the workspace and running processes before retrying.
|
|
3
3
|
</turn_aborted>`,J$="Tool execution was blocked because its durable call record could not be committed. No tool side effect was started.",P6="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 D$ extends Error{phase;constructor($,J){super($==="user_message"?"Conversation input could not be committed. No further model request was started.":"Model output could not be committed. The run was stopped before any further model request or successful completion.",J);this.phase=$;this.name="DurableConversationPersistenceError"}}function Z$($){return $.executionEngine?.getContextManager()}async function h0($,J,Z,W=null,Y,K={}){let H=K.required??$.executionEngine!==void 0;try{let X=Z$($),Q=typeof Z==="string"?Z.trim()!=="":Z.some((V)=>V.type==="text"?V.text.trim()!=="":!0);if(X&&J.sessionId&&Q){let V=await X.saveMessage(J.sessionId,"user",Z,W,Y,J.subagentInfo);if(H&&!V)throw Error("Durable user-message commit returned no identity");if(Y?.clientVisible!==!1)u4(J,Z);return V}if(H&&J.sessionId&&Q)throw Error("Durable user-message storage is unavailable")}catch(X){if(u0.warn("[Loop] 保存用户消息失败:",X),H)throw new D$("user_message",{cause:X})}return null}async function P0($,J,Z,W,Y,K,H={}){let X=H.required??$.executionEngine!==void 0;try{let Q=Z$($),V=Boolean(Z.trim()||Y?.trim());if(Q&&J.sessionId&&V){let D=await Q.saveMessage(J.sessionId,"assistant",Z,W,K,J.subagentInfo,Y);if(X&&!D)throw Error("Durable assistant-message commit returned no identity");return D}if(X&&J.sessionId&&V)throw Error("Durable assistant-message storage is unavailable")}catch(Q){if(u0.warn("[Loop] 保存助手消息失败:",Q),X)throw new D$("assistant_message",{cause:Q})}return null}async function _6($,J,Z){try{let W=Z$($);if(W&&J.sessionId)return await W.saveMessage(J.sessionId,"system",W2,Z,void 0,J.subagentInfo)}catch(W){u0.warn("[Loop] 保存中断边界失败:",W)}return null}async function A6($,J,Z,W,Y){try{let K=Z$($);if(!K||!J.sessionId||Z.length===0)return null;return await K.saveMessage(J.sessionId,"system",`<contextual-project-instructions-ref count="${Z.length}" />`,Y,{contextualProjectRules:!0,ruleReferences:JSON.parse(JSON.stringify(Z.map((H)=>({...H})))),triggerPaths:[...W]},J.subagentInfo)}catch(K){u0.warn("[Loop] 保存 contextual project rules provenance 失败:",K)}return null}async function Y2($,J,Z,W,Y,K={}){try{let H=Z$($);if(H&&J.sessionId){let X=await H.saveToolUse(J.sessionId,Z,W,Y,J.subagentInfo,K.providerToolCallId);if(K.required&&!X)throw Error("Durable tool-use commit returned no identity");return X}if(K.required&&J.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(H){if(u0.warn("[Loop] 保存工具调用失败:",H),K.required)throw H}return null}async function D1($,J,Z,W,Y,K,H,X,Q,V={}){try{let D=Z$($);if(D&&J.sessionId){let w=await D.saveToolResult(J.sessionId,Z,W,Y,K,H,J.subagentInfo,X,Q);if(V.required&&!w)throw Error("Durable tool-result commit returned no identity");return w}if(V.required&&J.sessionId)throw Error("Durable tool-result storage is unavailable")}catch(D){if(u0.warn("[Loop] 保存工具结果失败:",D),V.required)throw D}return null}async function C$($,J,Z,W,Y={}){try{let K=Z$($);if(K&&J.sessionId){let H=await K.saveCompaction(J.sessionId,Z,W,null);if(Y.required&&!H)throw Error("Compaction checkpoint commit returned no identity");return H||null}if(Y.required&&J.sessionId)throw Error("Compaction checkpoint storage is unavailable")}catch(K){if(u0.warn("[Loop] 保存压缩数据失败:",K),Y.required)throw K}return null}async function H0($){let{deps:J,context:Z,state:W,assistantContent:Y,assistantReasoningContent:K,lastMessageUuid:H,controlPrompt:X,controlMetadata:Q}=$;W.appendAssistant({role:"assistant",content:Y,reasoningContent:K});let V=H,D=await P0(J,Z,Y,V,K);if(D)V=D;if(X!==void 0){let w={role:"user",content:X};if(Q)w.metadata=Q;W.appendControl("user",w);let B=await h0(J,Z,w.content,V,Q);if(B)V=B}return V}import{createHash as nJ}from"node:crypto";import{promises as s4}from"node:fs";import t4 from"node:path";import{nanoid as d0}from"nanoid";import*as r from"node:fs/promises";import*as W$ from"node:path";var f6={enabled:!0,maxIndexLines:200};var m4="memory",b6="MEMORY.md";class K2{memoryDir;config;initialized=!1;constructor($,J,Z){if(Z)this.memoryDir=Z;else{let W=j$($);this.memoryDir=W$.join(W,m4)}this.config={...f6,...J}}async initialize(){if(this.initialized)return;await r.mkdir(this.memoryDir,{recursive:!0}),this.initialized=!0}async loadIndex(){if(!this.config.enabled)return null;await this.initialize();let $=W$.join(this.memoryDir,b6);try{let J=await r.readFile($,"utf-8");if(!J.trim())return null;let Z=J.split(`
|
|
4
4
|
`),Y=Z.slice(0,this.config.maxIndexLines).join(`
|
|
@@ -80,7 +80,7 @@ Full output saved to: ${X}`}catch{return`${J}
|
|
|
80
80
|
|
|
81
81
|
${Y}`}}import k5 from"node:path";import{nanoid as M5}from"nanoid";import*as q0 from"node:fs/promises";import*as c6 from"node:path";import{Mutex as G5}from"async-mutex";import q5 from"write-file-atomic";var u6=120,B2=128;function g$($){if(!Array.isArray($)||$.length>120||!$.every((J)=>typeof J==="string"&&J.length>0&&J.length<=128))return;return[...new Set($)]}function L5($){if(!$||typeof $!=="object"||Array.isArray($))return[];if(!("recovery"in $)||!$.recovery)return[];let J=$.recovery;if(typeof J!=="object"||Array.isArray(J))return[];if(!("version"in J)||J.version!==1||!("inputMessageIds"in J)||!("hadSuccessfulToolResult"in J)||typeof J.hadSuccessfulToolResult!=="boolean"||!("emptyFinalCorrectionSpent"in J)||typeof J.emptyFinalCorrectionSpent!=="boolean"||!("acknowledgedInputMessageIds"in $))return[];let Z=g$(J.inputMessageIds),W=g$($.acknowledgedInputMessageIds);if(!Z||!W)return[];let Y=new Set(Z);return W.filter((K)=>Y.has(K))}function L1($,J){let Z=$[J];if(Z?.type!=="turn_aborted")return[];let W=L5(Z.data);if(W.length===0)return[];let Y=-1;for(let H=J-1;H>=0;H--){let X=$[H];if(X.type==="turn_started"){if(X.data.turnId!==Z.data.turnId)return[];Y=H;break}if(X.type==="turn_completed"||X.type==="turn_aborted")return[]}if(Y<0)return[];let K=new Set;for(let H=Y+1;H<J;H++){let X=$[H];if(X.type!=="message_created"||X.data.role!=="user")continue;let Q=X.data.metadata,V=X.data.inboxMessageId!==void 0?X.data.inboxMessageId:Q!==null&&typeof Q==="object"&&!Array.isArray(Q)?Q.inboxMessageId:void 0;if(typeof V==="string"&&V.length>0&&V.length<=128)K.add(V)}return W.filter((H)=>K.has(H))}var G1=1,u$=8388608;function m6($,J){let Z={version:G1,sessionId:$,messages:J.map(({recovered:W,...Y})=>Y)};return`${JSON.stringify(Z)}
|
|
82
82
|
`}function D2($,J){return $ instanceof Error&&"code"in $&&$.code===J}function O5($){if(typeof $==="string")return!0;if(!Array.isArray($))return!1;return $.every((J)=>{if(!J||typeof J!=="object"||!("type"in J))return!1;if(J.type==="text")return"text"in J&&typeof J.text==="string";return J.type==="image_url"&&"image_url"in J&&typeof J.image_url==="object"&&J.image_url!==null&&"url"in J.image_url&&typeof J.image_url.url==="string"})}function N5($,J,Z){let W;try{W=JSON.parse($)}catch(K){throw Error(`Invalid steering inbox JSON: ${J}`,{cause:K})}if(!W||typeof W!=="object"||!("version"in W)||W.version!==G1||!("sessionId"in W)||W.sessionId!==Z||!("messages"in W)||!Array.isArray(W.messages))throw Error(`Invalid steering inbox record: ${J}`);let Y=W.messages.map((K)=>{if(!K||typeof K!=="object"||!("id"in K)||typeof K.id!=="string"||!("content"in K)||!O5(K.content)||!("queuedAt"in K)||typeof K.queuedAt!=="number"||"persisted"in K&&typeof K.persisted!=="boolean"||"origin"in K&&K.origin!=="user"&&K.origin!=="background_subagent"&&K.origin!=="team_message"||"metadata"in K&&(K.metadata===null||typeof K.metadata!=="object"||Array.isArray(K.metadata))||"outputSchema"in K&&K.outputSchema!==void 0&&(!K.outputSchema||typeof K.outputSchema!=="object"||Array.isArray(K.outputSchema)))throw Error(`Invalid steering inbox message: ${J}`);let H="outputSchema"in K&&K.outputSchema!==void 0?O1(K.outputSchema).schema:void 0;return{id:K.id,content:K.content,queuedAt:K.queuedAt,..."persisted"in K&&K.persisted===!0?{persisted:!0}:{},..."origin"in K&&K.origin?{origin:K.origin}:{},..."metadata"in K&&K.metadata?{metadata:JSON.parse(JSON.stringify(K.metadata))}:{},...H?{outputSchema:H}:{}}});return{version:G1,sessionId:Z,messages:Y}}function F5($){return new Set($.flatMap((J,Z)=>{if(J.type==="inbox_acknowledged")return J.data.messageIds;if(J.type==="turn_aborted")return L1($,Z);return[]}))}class N1{workspaceRoot;sessionId;filePath;mutex=new G5;messages=[];constructor($,J,Z){this.workspaceRoot=$;this.sessionId=J;this.filePath=Z}static async open($,J){let Z=new N1($,J,q1($,J));return await Z.loadAndReconcile(),Z}async enqueue($,J){return this.mutex.runExclusive(async()=>{if(J&&!J(this.messages))return!1;let Z=[...this.messages,{...$,recovered:!1}],W=m6(this.sessionId,Z);if(Buffer.byteLength(W)>u$)return!1;return await this.persist(Z,W),this.messages=Z,!0})}async acknowledge($){if($.length===0)return;let J=new Set($);await this.mutex.runExclusive(async()=>{let Z=this.messages.filter((W)=>!J.has(W.id));this.messages=Z,await this.persist(Z)})}list(){return this.messages.map(($)=>({...$,content:typeof $.content==="string"?$.content:$.content.map((J)=>J.type==="text"?{...J}:{...J,image_url:{...J.image_url}}),...$.outputSchema?{outputSchema:JSON.parse(JSON.stringify($.outputSchema))}:{},...$.metadata?{metadata:JSON.parse(JSON.stringify($.metadata))}:{}}))}count(){return this.messages.length}recoveredCount(){return this.messages.filter(($)=>$.recovered).length}async loadAndReconcile(){await this.mutex.runExclusive(async()=>{let $={version:G1,sessionId:this.sessionId,messages:[]};try{if((await q0.stat(this.filePath)).size>u$)throw Error(`Steering inbox exceeds ${u$} bytes: ${this.filePath}`);await q0.chmod(this.filePath,384),$=N5(await q0.readFile(this.filePath,"utf8"),this.filePath,this.sessionId)}catch(Y){if(!D2(Y,"ENOENT"))throw Y}let J=D0(this.workspaceRoot,this.sessionId),Z=new Set;try{Z=F5(d6(await q0.readFile(J,"utf8"),J))}catch(Y){if(!D2(Y,"ENOENT"))throw Y}let W=$.messages.filter((Y)=>!Z.has(Y.id)).map((Y)=>({...Y,recovered:!0}));if(this.messages=W,W.length!==$.messages.length)await this.persist(W)})}async persist($,J){if(await q0.mkdir(c6.dirname(this.filePath),{recursive:!0,mode:448}),$.length===0){await q0.unlink(this.filePath).catch((W)=>{if(!D2(W,"ENOENT"))throw W});return}let Z=J??m6(this.sessionId,$);if(Buffer.byteLength(Z)>u$)throw Error(`Steering inbox exceeds ${u$} bytes: ${this.filePath}`);await q5(this.filePath,Z,{encoding:"utf8",mode:384,fsync:!0})}}import*as f0 from"node:fs/promises";import*as $J from"node:path";import{nanoid as e}from"nanoid";var i6=256;class X0{sessionId;projectPath;static instances=new Map;store;subscribers=new Set;highestSeq=0;constructor($,J){this.sessionId=$;this.projectPath=J;this.store=new _0(D0(J,$))}static for($,J){let Z=`${J}\x00${$}`,W=X0.instances.get(Z);if(!W)W=new X0($,J),X0.instances.set(Z,W),X0.pruneIdleInstances(Z);else X0.instances.delete(Z),X0.instances.set(Z,W);return W}static release($,J){X0.instances.delete(`${J}\x00${$}`)}static pruneIdleInstances($){if(X0.instances.size<=i6)return;for(let[J,Z]of X0.instances){if(J===$||Z.subscribers.size>0)continue;if(X0.instances.delete(J),X0.instances.size<=i6)return}}get lastSeq(){return this.highestSeq}async commit($){let J=await this.store.append($);return this.record(J),J}async commitBatch($){if($.length===0)return[];let J=await this.store.appendBatch($);for(let Z of J)this.record(Z);return J}async commitValidated($){let J=await this.store.appendValidated($);return this.record(J),J}async commitValidatedBatch($){let J=await this.store.appendValidatedBatch($);for(let Z of J)this.record(Z);return J}emitDelta($){for(let J of this.subscribers)J.onDelta?.($);h$.publish({sessionId:this.sessionId,projectPath:this.projectPath},"delta",{delta:$})}subscribe($,J){if(this.subscribers.add($),J?.fromSeq!==void 0)this.replay($,J.fromSeq);return()=>{this.subscribers.delete($),X0.pruneIdleInstances()}}async replay($,J){let Z=await this.store.readFromSeq(J);for(let W of Z){if(j2(W))continue;await $.onCommitted(W)}}record($){if(typeof $.seq==="number"&&$.seq>this.highestSeq)this.highestSeq=$.seq;if(j2($))return;for(let J of this.subscribers){let Z=J.onCommitted($);if(Z)Promise.resolve(Z).catch(()=>{return})}h$.publish({sessionId:this.sessionId,projectPath:this.projectPath},`committed.${$.type}`,{event:$},$.seq)}}function L$($){let J=null,Z=null;for(let W of $){if(W.type==="turn_started"){J=W.data;continue}if(W.type==="turn_completed")Z={type:"turn_completed",data:W.data};else if(W.type==="turn_aborted")Z={type:"turn_aborted",data:W.data};else continue;if(J?.turnId===Z.data.turnId)J=null}return{active:J,lastTerminal:Z}}class A0 extends Error{}var P5="Tool execution was interrupted by a process restart. The operation may have partially completed. Inspect the workspace, running processes, and external state before deciding whether to retry it.";function w2($,J){let Z=$.findLastIndex((W)=>W.type==="turn_started"&&W.data.turnId===J);if(Z<0)return!1;return $.slice(Z+1).some((W)=>{if(W.type!=="message_created"||W.data.role!=="user")return!1;let Y=W.data.metadata;return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)&&Y.clientVisible===!1&&Y.emptyFinalCorrection===!0})}function l6($,J){let Z=$.findLastIndex((Y)=>Y.type==="turn_started"&&Y.data.turnId===J);if(Z<0)return[];let W=[];for(let Y of $.slice(Z+1)){if(Y.type==="turn_started"&&Y.data.turnId!==J||(Y.type==="turn_completed"||Y.type==="turn_aborted")&&Y.data.turnId===J)break;if(Y.type!=="message_created"||Y.data.role!=="user")continue;let K=Y.data.metadata,H=Y.data.inboxMessageId!==void 0?Y.data.inboxMessageId:K!==null&&typeof K==="object"&&!Array.isArray(K)?K.inboxMessageId:void 0;if(typeof H==="string"&&H.length>0&&H.length<=B2)W.push(H)}return[...new Set(W)]}function JJ($){if(!$||typeof $!=="object"||Array.isArray($))return;if(!("version"in $)||$.version!==1)return;let J="inputMessageIds"in $?g$($.inputMessageIds):void 0;if(!J||!("hadSuccessfulToolResult"in $)||typeof $.hadSuccessfulToolResult!=="boolean"||!("emptyFinalCorrectionSpent"in $)||typeof $.emptyFinalCorrectionSpent!=="boolean")return;return{inputMessageIds:J,hadSuccessfulToolResult:$.hadSuccessfulToolResult,emptyFinalCorrectionSpent:$.emptyFinalCorrectionSpent}}function ZJ($){return new Set($.flatMap((J,Z)=>{if(J.type==="inbox_acknowledged")return J.data.messageIds;if(J.type==="turn_aborted")return L1($,Z);return[]}))}function WJ($,J,Z=[]){let W=JJ(J.data.recovery);if(!W)return;let Y=ZJ($);for(let H of Z)Y.add(H);let K=W.inputMessageIds.filter((H)=>!Y.has(H));if(K.length===0)return;return{turnId:J.data.turnId,outcome:"aborted",inputMessageIds:K,hadSuccessfulToolResult:W.hadSuccessfulToolResult,emptyFinalCorrectionSpent:W.emptyFinalCorrectionSpent}}function U2($){for(let J=$.length-1;J>=0;J--){let Z=$[J];if(Z.type!=="turn_aborted")continue;let W=WJ($,Z);if(W)return W}return}var _5=1e4,A5=1e5,f5=2592000000,r6=128,b5=1e6;function T5($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(typeof J.goalId!=="string"||J.goalId.length===0||J.goalId.length>r6||typeof J.verificationAttempt!=="number"||!Number.isSafeInteger(J.verificationAttempt)||J.verificationAttempt<1||J.verificationAttempt>b5||typeof J.verifierSessionId!=="string"||J.verifierSessionId.length===0||J.verifierSessionId.length>r6||typeof J.evidenceSha256!=="string"||!/^[a-f0-9]{64}$/.test(J.evidenceSha256)||typeof J.goalUpdatedAt!=="string"||!Number.isFinite(Date.parse(J.goalUpdatedAt)))return;return{goalId:J.goalId,verificationAttempt:J.verificationAttempt,verifierSessionId:J.verifierSessionId,evidenceSha256:J.evidenceSha256,goalUpdatedAt:J.goalUpdatedAt}}function YJ($,J){let Z=$.data.metadata;if(!Z||typeof Z!=="object"||Array.isArray(Z))return;let W=Z.turnFinalization;if(!W||typeof W!=="object"||Array.isArray(W))return;let Y=W,K=Y.turnId,H=Y.inputMessageIds,X=Y.turnsCount,Q=Y.toolCallsCount,V=Y.durationMs,D=Array.isArray(H)?H.filter((B)=>typeof B==="string"&&B.length>0&&B.length<=B2):[];if(typeof K!=="string"||K.length===0||K.length>128||J!==void 0&&K!==J||!Array.isArray(H)||H.length>u6||D.length!==H.length||typeof X!=="number"||!Number.isSafeInteger(X)||X<0||X>_5||typeof Q!=="number"||!Number.isSafeInteger(Q)||Q<0||Q>A5||typeof V!=="number"||!Number.isSafeInteger(V)||V<0||V>f5)return;let w;if("goalFinalization"in Y){if(w=T5(Y.goalFinalization),!w)return}return{turnId:K,inputMessageIds:[...new Set(D)],turnsCount:X,toolCallsCount:Q,durationMs:V,...w?{goalFinalization:w}:{}}}function E5($,J){let Z=$.findLastIndex((W)=>W.type==="turn_started"&&W.data.turnId===J);if(Z<0)return;for(let W=$.length-1;W>Z;W--){let Y=$[W];if(Y?.type!=="message_created")continue;let K=YJ(Y,J);if(K)return K}return}function S5($){for(let J=$.length-1;J>=0;J--){let Z=$[J];if(Z?.type!=="message_created")continue;let W=YJ(Z);if(!W?.goalFinalization)continue;if(!$.slice(0,J).some((K)=>K.type==="turn_started"&&K.data.turnId===W.turnId))continue;return{turnId:W.turnId,finalization:W}}return}function m$($,J){let Z=J?$.findLastIndex((Q)=>Q.type==="turn_started"&&Q.data.turnId===J):-1;if(J&&Z<0)return{all:[],orphaned:[],hadSuccessfulResult:!1};let W=new Map,Y=new Set,K=new Set,H=new Set;for(let Q of $.slice(Z+1)){if(Q.type==="interaction_requested"){H.add(Q.data.toolCallId);continue}if(Q.type!=="part_created")continue;let V=Q.data.payload&&typeof Q.data.payload==="object"&&!Array.isArray(Q.data.payload)?Q.data.payload:{},D=typeof V.toolCallId==="string"?V.toolCallId:Q.data.partId;if(Q.data.partType==="tool_call")W.set(D,{toolCallId:D,messageId:Q.data.messageId,toolName:typeof V.toolName==="string"?V.toolName:"unknown",input:V.input??null});else if(Q.data.partType==="tool_result"){if(Y.add(D),Y.add(Q.data.partId),Y.add(Q.data.messageId),W.has(D)&&V.error===null)K.add(D)}}let X=[...W.values()];return{all:X,orphaned:X.filter((Q)=>!Y.has(Q.toolCallId)&&!H.has(Q.toolCallId)),hadSuccessfulResult:X.some((Q)=>K.has(Q.toolCallId))}}class i0{projectPath;maxSessions;version;constructor($=J0(),J=100,Z=a6()){this.projectPath=$,this.maxSessions=J,this.version=Z}createEvent($,J,Z){return{id:e(),sessionId:J,projectPath:this.projectPath,timestamp:new Date().toISOString(),type:$,cwd:this.projectPath,gitBranch:n6(this.projectPath),version:this.version,data:Z}}log($){return X0.for($,this.projectPath)}async ensureSessionCreated($,J){let Z=D0(this.projectPath,$);if((await new _0(Z).readAll()).length>0)return;let K=new Date().toISOString(),H={sessionId:$,rootId:J?.parentSessionId??$,parentId:J?.parentSessionId,relationType:J?"subagent":void 0,resumedFrom:J?.resumedFrom,rootAgentId:J?.rootAgentId,resumeDepth:J?.resumeDepth,title:void 0,status:"running",taskStatus:J?"running":"queued",taskFailure:null,agentType:J?.subagentType,model:void 0,permission:void 0,createdAt:K,updatedAt:K},X=this.createEvent("session_created",$,H);await this.log($).commit(X)}buildCompactionMetadata($){let J={trigger:$.trigger,preTokens:$.preTokens};if($.reason)J.reason=$.reason;if($.strategy)J.strategy=$.strategy;if($.postTokens!==void 0)J.postTokens=$.postTokens;if($.filesIncluded)J.filesIncluded=$.filesIncluded;if($.replacementMessages)J.checkpointVersion=s6;return J}async initialize(){try{let $=j$(this.projectPath);await f0.mkdir($,{recursive:!0,mode:493}),console.log(`[PersistentStore] 初始化存储目录: ${$}`)}catch($){console.warn("[PersistentStore] 无法创建持久化存储目录:",$)}}async saveMessage($,J,Z,W=null,Y,K,H){try{await this.ensureSessionCreated($,K);let X=new Date().toISOString(),Q=e(),V={messageId:Q,role:J,parentMessageId:W??void 0,inboxMessageId:Y?.inboxMessageId,createdAt:X,model:Y?.model,usage:Y?.usage,metadata:Y?JSON.parse(JSON.stringify(Y)):void 0},D=this.createEvent("message_created",$,V),w=J==="assistant"&&H?.trim()?[this.createEvent("part_created",$,{partId:e(),messageId:Q,partType:"reasoning",payload:{text:H},createdAt:X})]:[],B=typeof Z==="string"?[this.createEvent("part_created",$,{partId:e(),messageId:Q,partType:"text",payload:{text:Z},createdAt:X})]:Z.map((j)=>this.createEvent("part_created",$,{partId:e(),messageId:Q,partType:j.type==="text"?"text":"image",payload:j.type==="text"?{text:j.text}:{mimeType:x5(j.image_url.url)??"image/png",dataUrl:j.image_url.url},createdAt:X}));return await this.log($).commitBatch([D,...w,...B]),Q}catch(X){throw console.error(`[PersistentStore] 保存消息失败 (session: ${$}):`,X),X}}async acknowledgeInboxMessages($,J){if(J.length===0)return;await this.ensureSessionCreated($);let Z=new Date().toISOString();await this.log($).commit(this.createEvent("inbox_acknowledged",$,{messageIds:[...J],acknowledgedAt:Z}))}async persistBackgroundSubagentCompletion($,J){if(J.inboxMessageId!==`background-subagent-completion:${J.childSessionId}`)return{eligible:!1,acknowledged:!1,persisted:!1};await this.ensureSessionCreated($);let Z={eligible:!1,acknowledged:!1,persisted:!1};return await this.log($).commitValidatedBatch((W)=>{let Y=V0(W),K=Y.some((B)=>B.type==="inbox_acknowledged"&&B.data.messageIds.includes(J.inboxMessageId)),H=Y.find((B)=>B.type==="message_created"&&B.data.inboxMessageId===J.inboxMessageId),X=Y.findLast((B)=>{if(B.type!=="part_created"||B.data.partType!=="tool_call"||!B.data.payload||typeof B.data.payload!=="object"||Array.isArray(B.data.payload))return!1;let j=B.data.payload;if(j.toolName!=="Task"||!j.input||typeof j.input!=="object"||Array.isArray(j.input))return!1;let P=j.input,k=P.resume_from??P.resume;return P.run_in_background===!0&&P.subagent_session_id===J.childSessionId&&P.description===J.subagentRef.subagentDescription&&(P.subagent_type===void 0||P.subagent_type===J.subagentRef.subagentType)&&(P.resume_from===void 0||P.resume===void 0||P.resume_from===P.resume)&&(k===void 0?J.subagentRef.subagentResumedFrom===void 0:k===J.subagentRef.subagentResumedFrom)});if(!X)return Z={eligible:!1,acknowledged:K,persisted:!1,...H?{messageId:H.data.messageId}:{}},[];if(K)return Z={eligible:!0,acknowledged:!0,persisted:!1,...H?{messageId:H.data.messageId}:{}},[];let Q=Y.find((B)=>B.type==="part_created"&&B.data.partType==="subtask_ref"&&B.data.payload!==null&&typeof B.data.payload==="object"&&!Array.isArray(B.data.payload)&&B.data.payload.childSessionId===J.childSessionId&&B.data.payload.status===J.subagentRef.subagentStatus);if(H&&Q)return Z={eligible:!0,acknowledged:!1,persisted:!1,messageId:H.data.messageId},[];let V=new Date().toISOString(),D=H?.data.messageId??e(),w=[];if(!H){let B={messageId:D,role:"user",inboxMessageId:J.inboxMessageId,createdAt:V,metadata:JSON.parse(JSON.stringify(J.metadata))};w.push(this.createEvent("message_created",$,B)),w.push(this.createEvent("part_created",$,{partId:e(),messageId:D,partType:"text",payload:{text:J.content},createdAt:V}))}if(!Q){let B=Y.findLast((P)=>P.type==="part_created"&&P.data.partType==="subtask_ref"&&P.data.messageId===X.data.messageId&&P.data.payload!==null&&typeof P.data.payload==="object"&&!Array.isArray(P.data.payload)&&P.data.payload.childSessionId===J.childSessionId),j=B?.data.payload&&typeof B.data.payload==="object"&&!Array.isArray(B.data.payload)?B.data.payload:void 0;w.push(this.createEvent("part_created",$,{partId:e(),messageId:X.data.messageId,partType:"subtask_ref",payload:{childSessionId:J.subagentRef.subagentSessionId,agentType:J.subagentRef.subagentType,description:J.subagentRef.subagentDescription??"",status:J.subagentRef.subagentStatus,summary:J.subagentRef.subagentSummary??"",resumedFrom:J.subagentRef.subagentResumedFrom??null,rootAgentId:J.subagentRef.subagentRootId??J.subagentRef.subagentSessionId,resumeDepth:J.subagentRef.subagentResumeDepth??0,verificationVerdict:J.subagentRef.verificationVerdict??null,startedAt:typeof j?.startedAt==="string"?j.startedAt:V,finishedAt:V},createdAt:V}))}return Z={eligible:!0,acknowledged:!1,persisted:w.length>0,messageId:D},w}),Z}async saveTurnStart($,J){await this.ensureSessionCreated($);try{await this.log($).commitValidated((Z)=>{let W=V0(Z);if(W.some((K)=>K.type==="turn_started"&&K.data.turnId===J.turnId))throw new A0;let Y=L$(W).active;if(Y)throw Error(`Session already has an active turn: ${Y.turnId}`);return this.createEvent("turn_started",$,J)})}catch(Z){if(!(Z instanceof A0))throw Z}}async saveTurnCompletion($,J,Z=[]){await this.ensureSessionCreated($);try{await this.log($).commitValidatedBatch((W)=>{let Y=V0(W),K=new Set(Y.flatMap((V)=>V.type==="inbox_acknowledged"?V.data.messageIds:[])),H=[...new Set(Z)].filter((V)=>!K.has(V)),X=Y.findLast((V)=>(V.type==="turn_completed"||V.type==="turn_aborted")&&V.data.turnId===J.turnId);if(X){if(X.type==="turn_aborted"||H.length===0)throw new A0;return[this.createEvent("inbox_acknowledged",$,{messageIds:H,acknowledgedAt:J.completedAt})]}let Q=L$(Y).active;if(!Q||Q.turnId!==J.turnId)throw Error(`Turn is not active: ${J.turnId}`);return[...H.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:H,acknowledgedAt:J.completedAt})]:[],this.createEvent("turn_completed",$,J)]})}catch(W){if(!(W instanceof A0))throw W}}async saveTurnAbort($,J,Z={}){let W=Z.acknowledgeInputMessageIds??[],Y=g$(W);if(!Y)throw Error("Invalid turn abort acknowledgement input message IDs");let K=Y;await this.ensureSessionCreated($);let H,X=[];try{await this.log($).commitValidatedBatch((Q)=>{let V=V0(Q),D=ZJ(V),w=V.findLast((E)=>(E.type==="turn_completed"||E.type==="turn_aborted")&&E.data.turnId===J.turnId);if(w){if(w.type==="turn_completed")throw H=void 0,X=[],new A0;let E=JJ(w.data.recovery),O0=E?K.filter((T0)=>E.inputMessageIds.includes(T0)):[],r$=O0.filter((T0)=>!D.has(T0));if(X=O0,H=WJ(V,w,O0),r$.length===0)throw new A0;return[this.createEvent("inbox_acknowledged",$,{messageIds:r$,acknowledgedAt:J.abortedAt})]}let B=L$(V).active;if(!B||B.turnId!==J.turnId)throw Error(`Turn is not active: ${J.turnId}`);let j=m$(V,B.turnId),P=l6(V,B.turnId),k=U2(V),h=new Set(J.recovery?.inputMessageIds??[]),f=k?k.inputMessageIds.filter((E)=>h.has(E)):[],S=[...new Set([...P,...f])],T={version:1,inputMessageIds:S,hadSuccessfulToolResult:j.hadSuccessfulResult||J.recovery?.hadSuccessfulToolResult===!0,emptyFinalCorrectionSpent:w2(V,B.turnId)||J.recovery?.emptyFinalCorrectionSpent===!0};H={turnId:J.turnId,outcome:"aborted",inputMessageIds:T.inputMessageIds,hadSuccessfulToolResult:T.hadSuccessfulToolResult,emptyFinalCorrectionSpent:T.emptyFinalCorrectionSpent};let v=K.filter((E)=>S.includes(E)),p=v.filter((E)=>!D.has(E));X=v;let G=new Set(D);for(let E of v)G.add(E);let R=T.inputMessageIds.filter((E)=>!G.has(E));H=R.length>0?{turnId:J.turnId,outcome:"aborted",inputMessageIds:R,hadSuccessfulToolResult:T.hadSuccessfulToolResult,emptyFinalCorrectionSpent:T.emptyFinalCorrectionSpent}:void 0;let{acknowledgedInputMessageIds:g,...B0}=J;return[this.createEvent("turn_aborted",$,{...B0,...v.length>0?{acknowledgedInputMessageIds:v}:{},recovery:T}),...p.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:p,acknowledgedAt:J.abortedAt})]:[]]})}catch(Q){if(!(Q instanceof A0))throw Q}return{...H?{recovery:H}:{},acknowledgedInputMessageIds:X}}async loadInterruptedToolCalls($){let J=await this.loadEvents($);if(!J)return[];let Z=V0(J),W=L$(Z).active;return W?m$(Z,W.turnId).orphaned.map((Y)=>({...Y,input:structuredClone(Y.input)})):[]}async loadBackgroundTaskChildIds($){let J=await this.loadEvents($);if(!J)return new Set;let Z=V0(J).flatMap((W)=>{if(W.type!=="part_created"||W.data.partType!=="tool_call"||!W.data.payload||typeof W.data.payload!=="object"||Array.isArray(W.data.payload))return[];let Y=W.data.payload;if(Y.toolName!=="Task"||!Y.input||typeof Y.input!=="object"||Array.isArray(Y.input))return[];let K=Y.input;return K.run_in_background===!0&&typeof K.subagent_session_id==="string"?[K.subagent_session_id]:[]});return new Set(Z)}async recoverInterruptedTurn($,J={}){await this.ensureSessionCreated($);let Z;try{await this.log($).commitValidatedBatch((W)=>{let Y=V0(W),K=L$(Y).active,H=m$(Y);if(!K&&H.orphaned.length===0){if(Z=U2(Y),Z)return[];throw new A0}let X=K?E5(Y,K.turnId):void 0;if(K&&X&&H.orphaned.length===0){let T=m$(Y,K.turnId);Z={turnId:K.turnId,outcome:"completed",inputMessageIds:X.inputMessageIds,hadSuccessfulToolResult:T.hadSuccessfulResult,emptyFinalCorrectionSpent:w2(Y,K.turnId),finalization:X};let v=new Set(Y.flatMap((R)=>R.type==="inbox_acknowledged"?R.data.messageIds:[])),p=X.inputMessageIds.filter((R)=>!v.has(R)),G=new Date().toISOString();return[...p.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:p,acknowledgedAt:G})]:[],this.createEvent("turn_completed",$,{turnId:K.turnId,completedAt:G,turnsCount:X.turnsCount,toolCallsCount:X.toolCallsCount,durationMs:X.durationMs})]}let Q=K?m$(Y,K.turnId):void 0,V=Q?.orphaned.some((T)=>{let v=J.adoptedToolResults?.get(T.toolCallId);return v?.toolCallId===T.toolCallId&&v.toolName===T.toolName&&v.error===void 0})??!1,D=new Set(K?.inputMessageIds??[]),w=K?U2(Y):void 0,B=w?w.inputMessageIds.filter((T)=>D.has(T)):[],j=B.length>0,P=K?l6(Y,K.turnId):[];Z=K?{turnId:K.turnId,outcome:"aborted",inputMessageIds:[...new Set([...P,...B])],hadSuccessfulToolResult:(Q?.hadSuccessfulResult??!1)||V||j&&w?.hadSuccessfulToolResult===!0,emptyFinalCorrectionSpent:w2(Y,K.turnId)||j&&w?.emptyFinalCorrectionSpent===!0}:void 0;let k=K?Q?.all.length??0:0,h=new Date().toISOString(),f=K?Date.parse(K.startedAt):Number.NaN,S=H.orphaned.flatMap((T)=>{let v=J.adoptedToolResults?.get(T.toolCallId),p=v?.toolCallId===T.toolCallId&&v.toolName===T.toolName?v:void 0,G=this.createEvent("part_created",$,{partId:T.toolCallId,messageId:p?T.messageId:T.toolCallId,partType:"tool_result",payload:p?{toolCallId:T.toolCallId,toolName:T.toolName,output:p.output,error:p.error??null,...p.metadata===void 0?{}:{metadata:p.metadata}}:{toolCallId:T.toolCallId,toolName:T.toolName,output:null,error:P5,metadata:{processRestartRecovery:!0,sideEffectsUncertain:!0}},createdAt:h});if(!p?.subagentRef)return[G];let R=p.subagentRef;return[G,this.createEvent("part_created",$,{partId:e(),messageId:T.messageId,partType:"subtask_ref",payload:{childSessionId:R.subagentSessionId,agentType:R.subagentType,description:R.subagentDescription??"",status:R.subagentStatus,summary:R.subagentSummary??"",resumedFrom:R.subagentResumedFrom??null,rootAgentId:R.subagentRootId??R.subagentSessionId,resumeDepth:R.subagentResumeDepth??0,verificationVerdict:R.verificationVerdict??null,startedAt:h,finishedAt:h},createdAt:h})]});return K?[...S,this.createEvent("turn_aborted",$,{turnId:K.turnId,cause:"process_restart",abortedAt:h,turnsCount:0,toolCallsCount:k,durationMs:Number.isFinite(f)?Math.max(0,Date.now()-f):0,recovery:Z?{version:1,inputMessageIds:Z.inputMessageIds,hadSuccessfulToolResult:Z.hadSuccessfulToolResult,emptyFinalCorrectionSpent:Z.emptyFinalCorrectionSpent}:void 0})]:S})}catch(W){if(!(W instanceof A0))throw W}return Z}async loadLatestGoalFinalization($){let J=await this.loadEvents($);return J?S5(J):void 0}async saveInteractionRequest($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(Z.some((Y)=>Y.type==="interaction_requested"&&Y.data.requestId===J.requestId))throw Error(`Interaction request already exists: ${J.requestId}`);return this.createEvent("interaction_requested",$,J)})}async saveInteractionResponse($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((K)=>K.type==="interaction_requested"&&K.data.requestId===J.requestId))throw Error(`Interaction request not found: ${J.requestId}`);if(Z.some((K)=>K.type==="interaction_responded"&&K.data.requestId===J.requestId))throw Error(`Interaction already responded: ${J.requestId}`);return this.createEvent("interaction_responded",$,J)})}async saveInteractionRecovery($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((K)=>K.type==="interaction_responded"&&K.data.requestId===J.requestId))throw Error(`Interaction response not found: ${J.requestId}`);if(Z.some((K)=>K.type==="interaction_recovered"&&K.data.requestId===J.requestId))throw Error(`Interaction already recovered: ${J.requestId}`);return this.createEvent("interaction_recovered",$,J)})}async saveReviewStart($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(Z.some((K)=>K.type==="review_started"&&K.data.reviewId===J.reviewId))throw Error(`Review already exists: ${J.reviewId}`);if(Z.some((K)=>K.type==="review_started"&&!Z.some((H)=>H.type==="review_completed"&&H.data.reviewId===K.data.reviewId)))throw Error("Session already has an active review");return this.createEvent("review_started",$,J)})}async saveReviewCompletion($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((K)=>K.type==="review_started"&&K.data.reviewId===J.reviewId))throw Error(`Review not found: ${J.reviewId}`);if(Z.some((K)=>K.type==="review_completed"&&K.data.reviewId===J.reviewId))throw Error(`Review already completed: ${J.reviewId}`);return this.createEvent("review_completed",$,J)})}async saveToolUse($,J,Z,W=null,Y,K){try{if(K!==void 0&&(K.length===0||K.length>512))throw Error("Provider tool call identity must contain 1-512 characters");await this.ensureSessionCreated($,Y);let H=new Date().toISOString(),X=W??e(),Q=[];if(!W){let w={messageId:X,role:"assistant",parentMessageId:void 0,createdAt:H};Q.push(this.createEvent("message_created",$,w))}let V=K??e(),D={partId:V,messageId:X,partType:"tool_call",payload:{toolCallId:V,toolName:J,input:Z},createdAt:H};if(Q.push(this.createEvent("part_created",$,D)),J==="Task"&&Z&&typeof Z==="object"){let w=Z,B=typeof w.subagent_session_id==="string"?w.subagent_session_id:void 0,j=typeof w.subagent_type==="string"?w.subagent_type:void 0;if(B&&j){let P={partId:e(),messageId:X,partType:"subtask_ref",payload:{childSessionId:B,agentType:j,status:"running",summary:typeof w.description==="string"?w.description:"",startedAt:H},createdAt:H};Q.push(this.createEvent("part_created",$,P))}}return await this.log($).commitBatch(Q),V}catch(H){throw console.error(`[PersistentStore] 保存工具调用失败 (session: ${$}):`,H),H}}async saveToolResult($,J,Z,W,Y=null,K,H,X,Q){try{await this.ensureSessionCreated($,H);let V=new Date().toISOString(),D=Y??e();return await this.log($).commitValidatedBatch((w)=>{let B=X?.subagentStatus==="running"?V0(w).findLast((S)=>S.type==="part_created"&&S.data.partType==="subtask_ref"&&S.data.payload!==null&&typeof S.data.payload==="object"&&!Array.isArray(S.data.payload)&&S.data.payload.childSessionId===X.subagentSessionId&&(S.data.payload.status==="completed"||S.data.payload.status==="failed"||S.data.payload.status==="cancelled")):void 0,j=B?.data.payload,P=Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:{},k=j?{...P,subagentSessionId:j.childSessionId,subagentType:j.agentType,description:j.description,subagentStatus:j.status,subagentSummary:j.summary,subagentResumedFrom:j.resumedFrom,subagentRootId:j.rootAgentId,subagentResumeDepth:j.resumeDepth,verificationVerdict:j.verificationVerdict}:Q,h=[];if(!Y){let S={messageId:D,role:"assistant",parentMessageId:void 0,createdAt:V};h.push(this.createEvent("message_created",$,S))}let f={partId:J,messageId:D,partType:"tool_result",payload:{toolCallId:J,toolName:Z,output:W,error:K??null,...k===void 0?{}:{metadata:k}},createdAt:V};if(h.push(this.createEvent("part_created",$,f)),X&&!B){let S=X.subagentStatus==="running"?null:V,T={partId:e(),messageId:D,partType:"subtask_ref",payload:{childSessionId:X.subagentSessionId,agentType:X.subagentType,description:X.subagentDescription??"",status:X.subagentStatus,summary:X.subagentSummary??"",resumedFrom:X.subagentResumedFrom??null,rootAgentId:X.subagentRootId??X.subagentSessionId,resumeDepth:X.subagentResumeDepth??0,verificationVerdict:X.verificationVerdict??null,startedAt:V,finishedAt:S},createdAt:V};h.push(this.createEvent("part_created",$,T))}return h}),J}catch(V){throw console.error(`[PersistentStore] 保存工具结果失败 (session: ${$}):`,V),V}}async saveCompaction($,J,Z,W=null){try{await this.ensureSessionCreated($);let Y=new Date().toISOString(),K=e(),H={messageId:K,role:"system",parentMessageId:W??void 0,createdAt:Y},X=this.buildCompactionMetadata(Z),Q={partId:e(),messageId:K,partType:"summary",payload:{text:J,metadata:X,...Z.replacementMessages?{replacementMessages:t6(Z.replacementMessages)}:{}},createdAt:Y},V=[this.createEvent("message_created",$,H),this.createEvent("part_created",$,Q)];return await this.log($).commitBatch(V),K}catch(Y){throw console.error(`[PersistentStore] 保存压缩失败 (session: ${$}):`,Y),Y}}async recordTokenBudgetHandoff($,J){await this.ensureSessionCreated($);let Z=F1([]),W=await this.log($).commitValidatedBatch((K)=>{if(Z=F1(V0(K)),Z.kind!=="none")return[];let H=new Date().toISOString();return[this.createEvent("token_budget_handoff_recorded",$,{...J,messageId:`${e6}${e()}`,createdAt:H})]});if(Z.kind==="valid")return{outcome:"existing",event:Z.event};if(Z.kind==="suppressed")return{outcome:"suppressed",recordId:Z.recordId};if(W.length!==1)throw Error("Token budget handoff commit produced an impossible result");let Y=F1(W);if(Y.kind!=="valid")throw Error("Token budget handoff commit produced an invalid event");return{outcome:"created",event:Y.event}}async initSession($,J){await this.ensureSessionCreated($,J)}async loadEvents($){try{let J=D0(this.projectPath,$),W=await new _0(J).readAll();return W.length>0?V0(W):null}catch{return null}}async loadSession($){try{let J=D0(this.projectPath,$),Z=new _0(J),W=V0(await Z.readAll());if(W.length===0)return null;let Y=W.find((K)=>K.type==="session_created");return{sessionId:$,userId:void 0,preferences:{},configuration:{},startTime:new Date(Y?.timestamp??W[0].timestamp).getTime()}}catch{return null}}async loadConversation($){try{let J=D0(this.projectPath,$),Z=new _0(J),W=V0(await Z.readAll());if(W.length===0)return null;let Y=new Map;for(let Q of W){if(Q.type==="message_created")Y.set(Q.data.messageId,{id:Q.data.messageId,role:Q.data.role,content:"",timestamp:new Date(Q.timestamp).getTime()});if(Q.type==="part_created"&&Q.data.partType==="text"){let V=Y.get(Q.data.messageId);if(V){let D=Q.data.payload;V.content=D.text??""}}if(Q.type==="part_created"&&Q.data.partType==="image"){let V=Y.get(Q.data.messageId);if(V)V.content=V.content?`${V.content}
|
|
83
|
-
[Image]`:"[Image]"}}let K=Array.from(Y.values()),H=W[W.length-1],X=new Date(H.timestamp).getTime();return{messages:K,topics:[],lastActivity:X}}catch{return null}}async listSessions(){try{let $=j$(this.projectPath);return(await f0.readdir($)).filter((Z)=>Z.endsWith(".jsonl")).map((Z)=>Z.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){try{let J=D0(this.projectPath,$),Z=new _0(J);if(!(await Z.getStats()).exists)return null;let Y=await Z.readAll();if(Y.length===0)return null;let K=V0(Y),H=Y[Y.length-1],X=K.filter((Q)=>Q.type==="message_created"&&["user","assistant"].includes(Q.data.role)).length;return{sessionId:$,lastActivity:new Date(H.timestamp).getTime(),messageCount:X,topics:[]}}catch{return null}}async deleteSession($){try{let J=D0(this.projectPath,$);await new _0(J).delete(),await f0.unlink(q1(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W});try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-
|
|
83
|
+
[Image]`:"[Image]"}}let K=Array.from(Y.values()),H=W[W.length-1],X=new Date(H.timestamp).getTime();return{messages:K,topics:[],lastActivity:X}}catch{return null}}async listSessions(){try{let $=j$(this.projectPath);return(await f0.readdir($)).filter((Z)=>Z.endsWith(".jsonl")).map((Z)=>Z.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){try{let J=D0(this.projectPath,$),Z=new _0(J);if(!(await Z.getStats()).exists)return null;let Y=await Z.readAll();if(Y.length===0)return null;let K=V0(Y),H=Y[Y.length-1],X=K.filter((Q)=>Q.type==="message_created"&&["user","assistant"].includes(Q.data.role)).length;return{sessionId:$,lastActivity:new Date(H.timestamp).getTime(),messageCount:X,topics:[]}}catch{return null}}async deleteSession($){try{let J=D0(this.projectPath,$);await new _0(J).delete(),await f0.unlink(q1(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W});try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-4mgjj8zg.js"),K=await W();if(K)Y(K,$,this.projectPath)}catch{}}catch(J){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,J)}}async cleanupOldSessions(){try{let $=await this.listSessions();if($.length<=this.maxSessions)return;let W=(await Promise.all($.map((Y)=>this.getSessionSummary(Y)))).filter((Y)=>Y!==null).sort((Y,K)=>K.lastActivity-Y.lastActivity).slice(this.maxSessions).map((Y)=>Y.sessionId);await Promise.all(W.map((Y)=>this.deleteSession(Y))),console.log(`[PersistentStore] 已清理 ${W.length} 个旧会话`)}catch($){console.error("[PersistentStore] 清理旧会话失败:",$)}}async getStorageStats(){try{let $=await this.listSessions(),J=0;for(let Z of $){let W=D0(this.projectPath,Z),K=await new _0(W).getStats();J+=K.size}return{totalSessions:$.length,totalSize:J,projectPath:this.projectPath}}catch{return{totalSessions:0,totalSize:0,projectPath:this.projectPath}}}async checkStorageHealth(){try{let $=j$(this.projectPath);await f0.mkdir($,{recursive:!0,mode:493});let J=$J.join($,".health-check");return await f0.writeFile(J,"test","utf-8"),await f0.unlink(J),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return o6()}}function x5($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}var KJ=131072,L2=new QJ;function G2($,J){return`${k5.resolve($)}\x00${J}`}function N2($,J){let Z=JSON.stringify($);if(Z===void 0)throw Error(`${J} is not JSON serializable`);if(Buffer.byteLength(Z,"utf8")>KJ)throw Error(`${J} exceeds ${KJ} bytes`);return JSON.parse(Z)}function HJ($){if($.type==="askUserQuestion")return"question";if($.type==="mcpElicitation")return"elicitation";if($.type==="permission"||$.type==="mcpSampling")return"permission";return}function h5($,J){return JSON.stringify($)===JSON.stringify(J)}function R5($,J){if($.request.interactionType!=="elicitation")return N2(J,"Interaction response");return N2({approved:J.approved,...J.reason?{reason:J.reason}:{},...J.elicitation?{elicitation:{action:J.elicitation.action}}:{},...J.openExternalUrl?{openExternalUrl:!0}:{}},"Interaction response")}function XJ($){let J=$.request.details;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid durable interaction details: ${$.request.requestId}`);return J}function C5($){let J=$.response?.response;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid durable interaction response: ${$.request.requestId}`);return J}function I5($){if(!$.answers||Object.keys($.answers).length===0)return"No structured answers were provided.";return Object.entries($.answers).map(([J,Z])=>{let W=Array.isArray(Z)?Z.join(", "):Z;return`${J}: ${W}`}).join(`
|
|
84
84
|
`)}function v5($,J){let{request:Z}=$;if(Z.interactionType==="question"){let H=I5(J);return{toolOutput:`User answers:
|
|
85
85
|
${H}`,inbox:`The process restarted while waiting for a structured answer. The recovered user response is:
|
|
86
86
|
${H}
|
|
@@ -163,4 +163,4 @@ ${b}`}if(typeof M==="object"&&M!==null)M=JSON.stringify(M,null,2);if(typeof M===
|
|
|
163
163
|
${DJ(a0)}
|
|
164
164
|
</system-reminder>`,metadata:i$};G.appendControl("user",U);let z=await h0($,Z,U.content,Q,i$);if(z)Q=z}}if(W?.signal?.aborted)return D(H,X.length,W.signal);if(H>=T0&&(r$||B0)){if(u.info(`Warning: 达到轮次上限 ${T0} 轮`),W?.onTurnLimitReached){let U=await W.onTurnLimitReached({turnsCount:H});if(U?.continue){G.writeback();let z="failed",_,F,I;yield{kind:"compaction",phase:"start",reason:"turn_limit"};try{let y=$.chatService.getConfig(),N=await w$.compact(Z.messages,{trigger:"auto",modelName:y.model,modelProvider:y.provider,maxContextTokens:y.maxContextTokens??0,apiKey:y.apiKey,baseURL:y.baseUrl,actualPreTokens:n$,signal:W?.signal,activeTask:U0,workspaceRoot:Z.workspaceRoot||J0(),sessionId:Z.sessionId});if(N.usage)yield{kind:"token_usage",usage:S1(N.usage,y.maxContextTokens??0)};let A={role:"user",content:`This session is being continued from a previous conversation. The conversation is summarized above.
|
|
165
165
|
|
|
166
|
-
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.`},M=[...N.compactedMessages,A];_=N.success?"llm":"fallback",F=N.preTokens,I=N.postTokens,await C$($,Z,N.summary,{trigger:"auto",reason:"turn_limit",strategy:_,preTokens:N.preTokens,postTokens:N.postTokens,filesIncluded:N.filesIncluded,replacementMessages:M},{required:$.executionEngine!==void 0}),Z.messages=M,G.replaceHistory(Z.messages),z=N.success?"completed":"fallback"}catch(y){throw u.error("[Loop] 轮次上限压缩失败,停止继续执行:",y),y}finally{yield{kind:"compaction",phase:"end",reason:"turn_limit",outcome:z,strategy:_,preTokens:F,postTokens:I}}H=0;continue}return{success:!0,finalMessage:U?.reason||"已达到对话轮次上限,用户选择停止",metadata:{turnsCount:H,toolCallsCount:X.length,duration:Date.now()-K,tokensUsed:n}}}return{success:!1,error:{type:"max_turns_exceeded",message:B0?`子代理已达到轮次上限 (${T0} 轮)。`:`已达到轮次上限 (${T0} 轮)。`},metadata:{turnsCount:H,toolCallsCount:X.length,duration:Date.now()-K,tokensUsed:n}}}}}catch(O){if(O instanceof D$)try{let q=Z.sessionId?await R$.loadSessionModelContext(Z.sessionId,Z.workspaceRoot):p;G.restoreDurableHistory(q)}catch(q){u.error("[Loop] Failed to reload durable context after message commit failure:",q),G.restoreDurableHistory(p)}throw O}finally{if(W?.transientInput==="goal_continuation")G.removeMessages((O)=>{let q=O.metadata;return q!==null&&typeof q==="object"&&!Array.isArray(q)&&q.transientGoalContinuation===!0});G.writeback()}}catch(w){if(c0(w))return D(H,X.length,W?.signal);if(w instanceof D$)return{success:!1,error:{type:"message_persistence_failed",message:w.message},metadata:{turnsCount:H,toolCallsCount:X.length,duration:Date.now()-K}};let B=y8(w);return u.error(`API 调用失败: ${B}`),{success:!1,error:{type:"api_error",message:B,details:w},metadata:{turnsCount:H,toolCallsCount:X.length,duration:Date.now()-K}}}finally{if(V)Z.messages.push({role:"system",content:W2}),await _6($,Z,Q)}}export{K2 as
|
|
166
|
+
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.`},M=[...N.compactedMessages,A];_=N.success?"llm":"fallback",F=N.preTokens,I=N.postTokens,await C$($,Z,N.summary,{trigger:"auto",reason:"turn_limit",strategy:_,preTokens:N.preTokens,postTokens:N.postTokens,filesIncluded:N.filesIncluded,replacementMessages:M},{required:$.executionEngine!==void 0}),Z.messages=M,G.replaceHistory(Z.messages),z=N.success?"completed":"fallback"}catch(y){throw u.error("[Loop] 轮次上限压缩失败,停止继续执行:",y),y}finally{yield{kind:"compaction",phase:"end",reason:"turn_limit",outcome:z,strategy:_,preTokens:F,postTokens:I}}H=0;continue}return{success:!0,finalMessage:U?.reason||"已达到对话轮次上限,用户选择停止",metadata:{turnsCount:H,toolCallsCount:X.length,duration:Date.now()-K,tokensUsed:n}}}return{success:!1,error:{type:"max_turns_exceeded",message:B0?`子代理已达到轮次上限 (${T0} 轮)。`:`已达到轮次上限 (${T0} 轮)。`},metadata:{turnsCount:H,toolCallsCount:X.length,duration:Date.now()-K,tokensUsed:n}}}}}catch(O){if(O instanceof D$)try{let q=Z.sessionId?await R$.loadSessionModelContext(Z.sessionId,Z.workspaceRoot):p;G.restoreDurableHistory(q)}catch(q){u.error("[Loop] Failed to reload durable context after message commit failure:",q),G.restoreDurableHistory(p)}throw O}finally{if(W?.transientInput==="goal_continuation")G.removeMessages((O)=>{let q=O.metadata;return q!==null&&typeof q==="object"&&!Array.isArray(q)&&q.transientGoalContinuation===!0});G.writeback()}}catch(w){if(c0(w))return D(H,X.length,W?.signal);if(w instanceof D$)return{success:!1,error:{type:"message_persistence_failed",message:w.message},metadata:{turnsCount:H,toolCallsCount:X.length,duration:Date.now()-K}};let B=y8(w);return u.error(`API 调用失败: ${B}`),{success:!1,error:{type:"api_error",message:B,details:w},metadata:{turnsCount:H,toolCallsCount:X.length,duration:Date.now()-K}}}finally{if(V)Z.messages.push({role:"system",content:W2}),await _6($,Z,Q)}}export{K2 as Za,k$ as _a,g8 as $a,a1 as ab,M$ as bb,Q6 as cb,D4 as db,V$ as eb,i8 as fb,L$ as gb,Z2 as hb,F6 as ib,WZ as jb,h$ as kb,X0 as lb,i0 as mb,t1 as nb,e1 as ob,j6 as pb,J2 as qb,bJ as rb,TJ as sb,SJ as tb,Q$ as ub,X1 as vb,C4 as wb,h0 as xb,P0 as yb,Y2 as zb,D1 as Ab,C$ as Bb,m0 as Cb,w$ as Db,N1 as Eb,Z0 as Fb,n3 as Gb,MJ as Hb,E1 as Ib,RJ as Jb,CJ as Kb,IJ as Lb,O8 as Mb,k2 as Nb,oJ as Ob,R8 as Pb};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{nh as N,qh as M}from"./chunk-bj5msq36.js";import{Lh as H}from"./chunk-qw5j84ny.js";import{createModels as _,createProvider as Y,envApiKeyAuth as x,getSupportedThinkingLevels as E}from"@earendil-works/pi-ai";import{anthropicMessagesApi as F}from"@earendil-works/pi-ai/api/anthropic-messages.lazy";import{openAICompletionsApi as U}from"@earendil-works/pi-ai/api/openai-completions.lazy";import{builtinProviders as P}from"@earendil-works/pi-ai/providers/all";var K=/^[a-z][a-z0-9._-]{0,63}$/,z=/^[A-Z_][A-Z0-9_]*$/,s=new Set(["openai-completions","anthropic-messages"]);function B(u){return typeof u==="string"&&s.has(u)}function X(u,$){let h=`modelProviders.${u}`,b=[];if(!K.test(u))b.push(`${h}: id must match ${K.source}`);if(!$.name?.trim())b.push(`${h}: name must not be empty`);if(!B($.wireApi))b.push(`${h}: wireApi must be openai-completions or anthropic-messages`);try{let w=new URL($.baseUrl);if(!["http:","https:"].includes(w.protocol))b.push(`${h}: baseUrl must be an absolute HTTP(S) URL`)}catch{b.push(`${h}: baseUrl must be an absolute HTTP(S) URL`)}if($.apiKeyEnv!==void 0&&!z.test($.apiKeyEnv))b.push(`${h}: apiKeyEnv must be a valid environment variable name`);if("apiKey"in $)b.push(`${h}: API keys must be stored separately in auth.json`);return b}function J(u,$){let h=$.trim().replace(/\/+$/,"");if(u==="anthropic-messages"&&/\/v1$/i.test(h))return h.slice(0,-3);return h}import{promises as Z}from"node:fs";import j from"node:path";import{Mutex as R}from"async-mutex";import T from"write-file-atomic";class Q{filePath;mutex=new R;constructor(u=j.join(H(),"auth.json")){this.filePath=u}async read(u){return(await this.readAll())[u]}async list(){let u=await this.readAll();return Object.entries(u).map(([$,h])=>({providerId:$,type:h.type}))}async modify(u,$){return this.mutex.runExclusive(async()=>{let h=await this.readAll(),b=h[u],w=await $(b);if(w===void 0)return b;return h[u]=w,await this.writeAll(h),w})}async delete(u){await this.mutex.runExclusive(async()=>{let $=await this.readAll();if(!(u in $))return;delete $[u],await this.writeAll($)})}async readAll(){try{let u=await Z.readFile(this.filePath,"utf8"),$=JSON.parse(u);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch(u){if(u.code==="ENOENT")return{};throw u}}async writeAll(u){let $=j.dirname(this.filePath);await Z.mkdir($,{recursive:!0,mode:448}),await Z.chmod($,448),await T(this.filePath,`${JSON.stringify(u,null,2)}
|
|
2
2
|
`,{mode:384}),await Z.chmod(this.filePath,384)}}var q="openai-compatible",G="anthropic-compatible",D="https://api.openai.com/v1",V="https://api.anthropic.com",A=128000,C=32768,t={input:0,output:0,cacheRead:0,cacheWrite:0},f=["openai","anthropic","deepseek","google","moonshotai","moonshotai-cn","zai","zai-coding-cn"];class L{credentials;models;compatibleModels=new Map;anthropicCompatibleModels=new Map;customProviderConfigs=new Map;customProviderModels=new Map;reservedProviderIds=new Set;constructor(u=new Q){this.credentials=u,this.models=_({credentials:u});for(let $ of P())this.models.setProvider($);this.installOpenAICompatibleProvider(),this.installAnthropicCompatibleProvider();for(let $ of this.models.getProviders())this.reservedProviderIds.add($.id)}async listProviders(){return Promise.all(this.models.getProviders().map(async(u)=>{let $=u.getModels(),h=this.customProviderConfigs.get(u.id),b=this.getFactoryWireApi(u.id);return{id:u.id,name:u.name,modelCount:$.length,defaultBaseUrl:u.baseUrl??$[0]?.baseUrl,supportsApiKey:Boolean(u.auth.apiKey),supportsOAuth:Boolean(u.auth.oauth),configured:b?!1:Boolean(await this.models.checkAuth(u.id)),custom:Boolean(h),factoryWireApi:b,wireApi:h?.wireApi,apiKeyEnv:h?.apiKeyEnv}}))}listModels(u){return this.models.getModels(u).map(($)=>this.toCatalogEntry($))}getModel(u,$){let h=this.models.getModel(u,$);if(!h&&u===q)this.registerOpenAICompatibleModel($),h=this.models.getModel(u,$);if(!h&&u===G)this.registerAnthropicCompatibleModel($),h=this.models.getModel(u,$);if(!h&&this.customProviderConfigs.has(u))this.registerCustomProviderModel(u,$),h=this.models.getModel(u,$);if(!h)throw Error(`Unknown pi-ai model: ${u}/${$}`);return h}resolveConfig(u){let $=this.getModel(u.provider,u.model),h=u.overrides;return{...$,...h?.baseUrl?{baseUrl:J($.api,h.baseUrl)}:{},...h?.maxOutputTokens?{maxTokens:h.maxOutputTokens}:{}}}async setApiKey(u,$){this.requireProvider(u),await this.credentials.modify(u,async()=>({type:"api_key",key:$}))}async clearCredential(u){this.requireProvider(u),await this.credentials.delete(u)}async isConfigured(u){return this.requireProvider(u),Boolean(await this.models.checkAuth(u))}isReservedProviderId(u){return this.reservedProviderIds.has(u)}configureModelProviders(u,$){for(let h of this.customProviderConfigs.keys())this.models.deleteProvider(h);this.customProviderConfigs.clear(),this.customProviderModels.clear();for(let[h,b]of Object.entries(u)){let w=$.filter((k)=>k.provider===h).map((k)=>k.model);this.registerModelProvider(h,b,w)}}registerModelProvider(u,$,h=[]){if(this.isReservedProviderId(u))throw Error(`modelProviders.${u}: built-in provider ids cannot be overridden`);let b=X(u,$);if(b.length>0)throw Error(b.join("; "));let w={...$,name:$.name.trim(),baseUrl:J($.wireApi,$.baseUrl),...$.apiKeyEnv?{apiKeyEnv:$.apiKeyEnv.trim()}:{}};this.customProviderConfigs.set(u,w);let k=new Map;for(let y of new Set(h)){let W=y.trim();if(!W)continue;k.set(W,this.createCompatibleModel(u,W,w.wireApi,w.baseUrl))}this.customProviderModels.set(u,k),this.installCustomProvider(u)}unregisterModelProvider(u){if(!this.customProviderConfigs.has(u))return;this.customProviderConfigs.delete(u),this.customProviderModels.delete(u),this.models.deleteProvider(u)}requireProvider(u){if(!this.models.getProvider(u))throw Error(`Unknown pi-ai provider: ${u}`)}registerOpenAICompatibleModel(u){let $=u.trim();if(!$)throw Error("OpenAI-compatible model ID must not be empty");if(this.compatibleModels.has($))return;let h=this.createCompatibleModel(q,$,"openai-completions",D);this.compatibleModels.set($,h),this.installOpenAICompatibleProvider()}registerAnthropicCompatibleModel(u){let $=u.trim();if(!$)throw Error("Anthropic-compatible model ID must not be empty");if(this.anthropicCompatibleModels.has($))return;let h=this.createCompatibleModel(G,$,"anthropic-messages",V);this.anthropicCompatibleModels.set($,h),this.installAnthropicCompatibleProvider()}registerCustomProviderModel(u,$){let h=$.trim();if(!h)throw Error("Custom provider model ID must not be empty");let b=this.customProviderConfigs.get(u),w=this.customProviderModels.get(u);if(!b||!w||w.has(h))return;w.set(h,this.createCompatibleModel(u,h,b.wireApi,b.baseUrl)),this.installCustomProvider(u)}createCompatibleModel(u,$,h,b){let w=this.models.getModels().filter((y)=>y.provider!==u&&!this.customProviderConfigs.has(y.provider)&&y.id===$),k=f.flatMap((y)=>w.filter((W)=>W.provider===y))[0]??w[0];return{id:$,name:k?.name??$,api:h,provider:u,baseUrl:b,reasoning:k?.reasoning??!1,input:k?[...k.input]:["text"],cost:{...t},contextWindow:k?.contextWindow??A,maxTokens:k?.maxTokens??C,...k?.thinkingLevelMap?{thinkingLevelMap:{...k.thinkingLevelMap}}:{}}}installOpenAICompatibleProvider(){this.models.setProvider(Y({id:q,name:"Custom OpenAI Endpoint",baseUrl:D,auth:{apiKey:x("OpenAI-compatible API key",["OPENAI_COMPATIBLE_API_KEY","BLADE_API_KEY"])},models:[...this.compatibleModels.values()],api:U()}))}installAnthropicCompatibleProvider(){this.models.setProvider(Y({id:G,name:"Custom Anthropic Endpoint",baseUrl:V,auth:{apiKey:x("Anthropic-compatible API key",["ANTHROPIC_API_KEY","BLADE_API_KEY"])},models:[...this.anthropicCompatibleModels.values()],api:F()}))}installCustomProvider(u){let $=this.customProviderConfigs.get(u),h=this.customProviderModels.get(u);if(!$||!h)return;let b=$.apiKeyEnv?[$.apiKeyEnv]:[];this.models.setProvider(Y({id:u,name:$.name,baseUrl:$.baseUrl,auth:{apiKey:x(`${$.name} API key`,b)},models:[...h.values()],api:$.wireApi==="anthropic-messages"?F():U()}))}getFactoryWireApi(u){if(u===q)return"openai-completions";if(u===G)return"anthropic-messages";return}toCatalogEntry(u){return{id:u.id,name:u.name,provider:u.provider,api:u.api,baseUrl:u.baseUrl,reasoning:u.reasoning,supportedReasoningEfforts:E(u),supportedServiceTiers:M(u),supportedResponseVerbosities:N(u),input:[...u.input],contextWindow:u.contextWindow,maxTokens:u.maxTokens,cost:{...u.cost}}}}var S;function hu(){return S??=new L,S}
|
|
3
|
-
export{K as
|
|
3
|
+
export{K as hh,X as ih,J as jh,L as kh,hu as lh};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{q as
|
|
1
|
+
import{th as d,vh as h}from"./chunk-c74e0jx1.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"max-queued-task-bytes":{alias:["maxQueuedTaskBytes"],type:"number",describe:"Maximum retained bytes across queued top-level tasks",group:"AI Options:",default:void 0},"max-resident-session-runtimes":{alias:["maxResidentSessionRuntimes"],type:"number",describe:"Maximum initialized Session runtimes resident in this process",group:"AI Options:",default:void 0},"session-runtime-idle-ms":{alias:["sessionRuntimeIdleMs"],type:"number",describe:"Idle time before an evictable Web Session runtime is disposed",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
|
|
2
|
+
export{q as sd,w as td};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Kh as $,Lh as F}from"./chunk-qw5j84ny.js";import{promises as J}from"node:fs";import Q from"node:path";import{Mutex as U}from"async-mutex";import w from"write-file-atomic";var X=1;function D(k){if(!k||typeof k!=="object"||Array.isArray(k))return!1;let q=k;return typeof q.path==="string"&&Q.isAbsolute(q.path)&&typeof q.boundAt==="string"}async function Z(k){if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k);if(!(await J.stat(q)).isDirectory())throw Error("Project path must be a directory");return q}class K{filePath;mutex=new U;constructor(k=Q.join(F(),"bound-projects.json")){this.filePath=k}async list(k){let q=await this.read(),z=await Z(k),H=new Map;for(let C of q.projects)H.set(C.path,C);if(!H.has(z))H.set(z,{path:z,boundAt:new Date(0).toISOString()});return(await Promise.all([...H.values()].map(async(C)=>{let L=!1;try{L=(await J.stat(C.path)).isDirectory()}catch{}return{path:C.path,name:Q.basename(C.path)||C.path,...L?{gitBranch:$(C.path)}:{},available:L,isCurrent:C.path===z,boundAt:C.boundAt}}))).sort((C,L)=>{if(C.isCurrent!==L.isCurrent)return C.isCurrent?-1:1;return C.name.localeCompare(L.name)})}async bind(k,q){return this.mutex.runExclusive(async()=>{let z=await Z(k),H=await this.read(),W=H.projects.find((M)=>M.path===z),C=W??{path:z,boundAt:new Date().toISOString()};if(!W)H.projects.push(C),await this.write(H);let L=await Z(q),A=$(z);return{path:z,name:Q.basename(z)||z,...A?{gitBranch:A}:{},available:!0,isCurrent:z===L,boundAt:C.boundAt}})}async unbind(k){return this.mutex.runExclusive(async()=>{if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k).catch(()=>Q.resolve(k)),z=await this.read(),H=z.projects.filter((W)=>W.path!==q);if(H.length===z.projects.length)return!1;return z.projects=H,await this.write(z),!0})}async read(){try{let k=await J.readFile(this.filePath,"utf8"),q=JSON.parse(k);if(q.version!==X||!Array.isArray(q.projects))return{version:X,projects:[]};return{version:X,projects:q.projects.filter(D)}}catch(k){if(k.code==="ENOENT"||k instanceof SyntaxError)return{version:X,projects:[]};throw k}}async write(k){let q=Q.dirname(this.filePath);await J.mkdir(q,{recursive:!0,mode:448}),await J.chmod(q,448),await w(this.filePath,`${JSON.stringify(k,null,2)}
|
|
2
2
|
`,{mode:384}),await J.chmod(this.filePath,384)}}var _=new K;
|
|
3
3
|
export{_ as l};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Aa as H}from"./chunk-yk8s8kjt.js";import"./chunk-fbgzeb3m.js";import"./chunk-qyxbee3w.js";import{Zd as $,de as T}from"./chunk-xts31qj4.js";import"./chunk-v508x7cg.js";import"./chunk-xkz9ecdx.js";import"./chunk-egp0crrc.js";import"./chunk-03947xkg.js";import"./chunk-zph2jekm.js";import"./chunk-qp8mejbn.js";import"./chunk-c03xn5s3.js";import"./chunk-yjbq4jeg.js";import{Fg as k}from"./chunk-22aaybx2.js";import"./chunk-qtt17d5s.js";import"./chunk-2qqmmxqf.js";import"./chunk-gbrwzpyg.js";import"./chunk-bj5msq36.js";import"./chunk-c74e0jx1.js";import"./chunk-yz80dp1a.js";import"./chunk-p7ww2tcn.js";import"./chunk-qw5j84ny.js";import"./chunk-99nevk7k.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
|
|
2
2
|
blade mcp
|
|
3
3
|
`),console.log(`管理 MCP 服务器
|
|
4
4
|
`),console.log("Commands:"),console.log(" blade mcp add <name> <commandOrUrl> [args...] 添加 MCP 服务器"),console.log(" blade mcp remove <name> 删除 MCP 服务器 [aliases: rm]"),console.log(" blade mcp list 列出所有 MCP 服务器并检查健康状态 [aliases: ls]"),console.log(" blade mcp get <name> 获取服务器详情"),console.log(" blade mcp login <name> 登录远程 MCP OAuth"),console.log(" blade mcp logout <name> 清除远程 MCP OAuth 凭证"),console.log(` blade mcp add-json <name> <json> 从 JSON 字符串添加服务器
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var i="verification",E="goal-verification",e="review";function t(n){return n==="verification"||n==="goal-verification"}function o(n){return t(n)||n==="review"}
|
|
2
|
-
export{i as
|
|
2
|
+
export{i as Xe,E as Ye,e as Ze,t as _e,o as $e};
|