blade-code 0.10.111 → 0.10.113
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-snj119c2.js → chunk-0210yytk.js} +1 -1
- package/dist/{chunk-agpbarbx.js → chunk-0cmykdaz.js} +1 -1
- package/dist/chunk-0djwmr9n.js +1 -0
- package/dist/{chunk-xgbnb37n.js → chunk-176zc8a3.js} +1 -1
- package/dist/{chunk-cv20apqr.js → chunk-36jpqn5e.js} +1 -1
- package/dist/{chunk-1n23f3qb.js → chunk-39eq0g43.js} +1 -1
- package/dist/{chunk-4je46cyf.js → chunk-3zdvhjsb.js} +94 -94
- package/dist/{chunk-32zgv9dx.js → chunk-5npfhnxn.js} +1 -1
- package/dist/{chunk-vvhnv7ng.js → chunk-5y4b3tkr.js} +1 -1
- package/dist/{chunk-50prvxfw.js → chunk-6vgmh02j.js} +1 -1
- package/dist/{chunk-fymsjr4x.js → chunk-80pzkgqm.js} +1 -1
- package/dist/{chunk-gner6fka.js → chunk-919rht8b.js} +1 -1
- package/dist/{chunk-8pr55zfw.js → chunk-9r3385rd.js} +1 -1
- package/dist/{chunk-h25qd3d7.js → chunk-cebfh25a.js} +1 -1
- package/dist/chunk-e95gnshr.js +1 -0
- package/dist/{chunk-3y8qp69k.js → chunk-egmexjyx.js} +1 -1
- package/dist/{chunk-bq9cg7pa.js → chunk-etq4258m.js} +1 -1
- package/dist/{chunk-ep657gs0.js → chunk-h29mbyse.js} +1 -1
- package/dist/{chunk-ahjh8y56.js → chunk-hb2g6rpz.js} +1 -1
- package/dist/{chunk-tk7yfgay.js → chunk-jjsv2xt1.js} +1 -1
- package/dist/{chunk-zh2vrkyt.js → chunk-kev3cwe9.js} +1 -1
- package/dist/{chunk-kx05z7sx.js → chunk-m525zvkb.js} +1 -1
- package/dist/{chunk-wkvh3xrp.js → chunk-mqb6vpwk.js} +1 -1
- package/dist/{chunk-k7980hzm.js → chunk-n9tx6w5y.js} +2 -2
- package/dist/{chunk-e99c1t8e.js → chunk-nqgsh5ew.js} +1 -1
- package/dist/{chunk-541h9the.js → chunk-pqsh9kqd.js} +1 -1
- package/dist/{chunk-s6xw42mr.js → chunk-r7wwr5f6.js} +1 -1
- package/dist/{chunk-exv2prhq.js → chunk-rrjccake.js} +2 -2
- package/dist/{chunk-zgw04ttb.js → chunk-s9mrvjm3.js} +1 -1
- package/dist/{chunk-zkrtn8b1.js → chunk-spth418m.js} +1 -1
- package/dist/{chunk-d7ytnvqy.js → chunk-v4nankr5.js} +1 -1
- package/dist/{chunk-z1da8k2d.js → chunk-w3wsder6.js} +1 -1
- package/dist/{chunk-2hmc9pr9.js → chunk-xt3vz464.js} +1 -1
- package/dist/{chunk-4k61tkpp.js → chunk-y79b5d72.js} +1 -1
- package/dist/{chunk-j7bdnptp.js → chunk-y8mta9ad.js} +1 -1
- package/dist/{chunk-g4ftk610.js → chunk-yzmgf1vc.js} +1 -1
- package/dist/{chunk-t30jd4wg.js → chunk-z23rwax1.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-6pp5945x.js +0 -1
- package/dist/chunk-ceaee099.js +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{readFileSync as l}from"node:fs";import{dirname as o,join as u}from"node:path";import{fileURLToPath as a}from"node:url";var e={name:"blade-code",version:"0.10.
|
|
1
|
+
import{readFileSync as l}from"node:fs";import{dirname as o,join as u}from"node:path";import{fileURLToPath as a}from"node:url";var e={name:"blade-code",version:"0.10.113",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts --project='!performance' && vitest run --config vitest.config.ts --project=performance","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:real-api":"node scripts/test.js realApi","test:real-api:qualification":"node scripts/test.js realApiQualification","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","browser:install":"playwright install chromium","browser:check":"node scripts/run-bun.js run scripts/browser-check.ts","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","qualify:local":"node scripts/run-bun.js run scripts/qualify.ts local","qualify:production":"node scripts/run-bun.js run scripts/qualify.ts production","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/qualify.ts production","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",prepack:"node scripts/run-bun.js run build",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",repository:{type:"git",url:"git+https://github.com/echoVic/blade-code.git"},homepage:"https://github.com/echoVic/blade-code#readme",bugs:{url:"https://github.com/echoVic/blade-code/issues"},engines:{node:">=22.19.0"},optionalDependencies:{"@vscode/ripgrep":"^1.18.0","better-sqlite3":"^11.8.1","bun-pty":"^0.4.8","node-pty":"1.1.0"},dependencies:{"@agentclientprotocol/sdk":"^1.3.0","@anthropic-ai/sandbox-runtime":"0.0.67","@earendil-works/pi-ai":"0.84.2","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.30.0",ahooks:"^3.9.7",ajv:"^8.17.1","ansi-escapes":"^7.3.0","async-mutex":"^0.5.0",axios:"^1.19.0",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.5.0","gray-matter":"^4.0.3",hono:"^4.13.0",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.18.1",lowlight:"^3.3.0","lru-cache":"^11.5.2",nanoid:"^5.1.6",open:"^10.1.2",picomatch:"^4.0.5",playwright:"1.62.1","proper-lockfile":"^4.1.2",react:"19.2.4","react-dom":"19.2.4",semver:"^7.8.5","string-width":"^8.2.2",typebox:"1.3.10",undici:"^7.16.0","vscode-jsonrpc":"8.2.1","vscode-languageserver-protocol":"3.17.5","vscode-languageserver-types":"3.17.5","write-file-atomic":"^7.0.0",ws:"^8.21.2",yaml:"^2.9.0",yargs:"^18.1.0",zustand:"^5.0.14"},devDependencies:{"@biomejs/biome":"2.5.7","@types/bun":"^1.3.14","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.3","@types/proper-lockfile":"^4.1.4","@types/react":"19.2.10","@types/react-dom":"19.2.3","@types/semver":"^7.8.0","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.18.1","@types/yargs":"^17.0.35","@vitest/coverage-v8":"^4.1.10",jsdom:"^26.0.0",typescript:"^5.9.2",vitest:"^4.1.10"}};var s;function r(){if(s)return s;let i=o(a(import.meta.url));for(let n=0;n<5;n++){try{let t=JSON.parse(l(u(i,"package.json"),"utf8"));if(t.name===e.name&&typeof t.version==="string"&&typeof t.description==="string")return s=t,s}catch{}i=o(i)}return s={name:e.name,version:process.env.BLADE_VERSION??e.version,description:e.description},s}function y(){return{...r()}}function p(){return r().version}function v(){return r().name}function g(){return r().description}function f(){return`v${p()}`}function w(){return`v${p()} © 2025 Blade Code`}
|
|
2
2
|
export{y as Fi,p as Gi,v as Hi,g as Ii,f as Ji,w as Ki};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{cc as M4}from"./chunk-cnhw5mqv.js";import{$c as c2,Id as u0,Kd as K6,Ld as h1,Md as Q6,Td as o$,Wc as vJ,Yc as IJ,Zc as uJ,_c as m2,ec as X$,fd as gJ,gd as T4,hd as R4,id as I2,jd as k1,kd as h4,ld as x4,md as S1,qd as DJ,yd as K1}from"./chunk-tk7yfgay.js";import{Yd as S4}from"./chunk-53h87fmt.js";import{_d as H0,be as bJ,ce as v0}from"./chunk-qdv0n8yt.js";import{df as eJ}from"./chunk-pshyn3yy.js";import{ef as b4,ff as i0,gf as f4,hf as zJ,kf as E1,lf as V6,mf as BJ,nf as jJ,pf as UJ}from"./chunk-q2exry0f.js";import{$f as r0,_f as J$,cg as E4,gg as H4}from"./chunk-cqqmkwvn.js";import{tg as N$}from"./chunk-zh2vrkyt.js";import{Dh as nJ}from"./chunk-4w4wjm49.js";import{Sh as X0}from"./chunk-ecd727xh.js";import{si as k0}from"./chunk-dvv28pkc.js";import{Gi as CJ}from"./chunk-s6xw42mr.js";import{Ri as b$,Ti as r6,Ui as P0,Vi as R1,Xi as hJ,Yi as xJ,Zi as kJ}from"./chunk-rkdxqx8m.js";import{_i as L8}from"./chunk-tf7ezqew.js";function A$($){return $.role==="system"&&Array.isArray($.content)}function f$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class A1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,J){this.context=$;let Z=$.messages.find(A$);if(this._contextualSystemMessages=$.messages.filter(f$),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!A$(W)&&!f$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}get contextRevision(){return this._contextRevision}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!f$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(A$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((J)=>J.id===$.id))return;this._history.push($)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((J)=>!A$(J)&&!f$(J)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(f$),this._history=$.filter((J)=>!A$(J)&&!f$(J)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let J=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((Z)=>!$(Z)),this._pending=this._pending.filter((Z)=>!$(Z)),this._contextualSystemMessages=this._contextualSystemMessages.filter((Z)=>!$(Z)),this.syncContextualSystemMessages(),this._history.length!==J[0]||this._pending.length!==J[1]||this._contextualSystemMessages.length!==J[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function b6($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function E6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function S6($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import Q$ from"node:path";var c4=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"]),l4=/^(LD_.+|DYLD_.+|PATH)$/,M6=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function l$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(M6);if(!V)break;let K=V[1];if(!c4.has(K))break;J=Y}return J}function uZ($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(M6);if(!V)break;let K=V[1];if(l4.test(K))break;J=Y}return J}var i4=[/^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 D2($){let J=$,Z=!0;while(Z){Z=!1;for(let W of i4){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 i$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){Z+=Q,V=!0;continue}if(Q==="'"&&!Y){W=!W,Z+=Q;continue}if(Q==='"'&&!W){Y=!Y,Z+=Q;continue}if(W||Y){Z+=Q;continue}if(Q==="|"){if(K+1<$.length&&$[K+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&K+1<$.length&&$[K+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}if(Q==="&")return null;if(Q===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=Q}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function T6($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let V=$[Y];if(W){W=!1;continue}if(V==="\\"&&!J){W=!0;continue}if(V==="'"&&!Z){J=!J;continue}if(V==='"'&&!J){Z=!Z;continue}if(J)continue;if(V==="$"){let K=$[Y+1];if(K&&/[A-Za-z_@*#?!$0-9({]/.test(K))return!0}if(V==="`")return!0;if(Z)continue;if(V==="|")return!0;if(V===">"||V==="<")return!0;if(V==="{"){let K=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(K)||/^\{[^}]*\.\.[^}]*\}/.test(K))return!0}}return!1}function K$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){if(V=!0,Y){let X=$[K+1];if(X&&'$`"\\'.includes(X))continue;Z+=Q,V=!1}continue}if(Q==="'"&&!Y){W=!W;continue}if(Q==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(Q)){if(Z)J.push(Z),Z="";continue}Z+=Q}if(Z)J.push(Z);return J}var r4=new Set(["npm","pnpm","yarn","bun"]),R6=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),n4=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),o4=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function a4($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function h6($){return $.replace(/\s+2>&1\s*$/,"").trim()}function s4($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=K$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let V=Y[1];if(!V||V==="-")return;let K=Q$.isAbsolute(V)?Q$.resolve(V):Q$.resolve(Z,V);if(!X$.isWithinWorkspace(K,Z))return;return W[2]?.trim()||void 0}function t4($){let J=[],Z=!1,W=!1,Y=!1;for(let V=0;V<$.length;V++){let K=$[V];if(Y){Y=!1;continue}if(K==="\\"&&!Z){Y=!0;continue}if(K==="'"&&!W){Z=!Z;continue}if(K==='"'&&!Z){W=!W;continue}if(K!=="|"||Z||W)continue;if($[V+1]==="|")return;J.push(V)}return J}function e4($){let J=K$($),[Z,W,Y]=J;if(Z!=="head"&&Z!=="tail")return!1;if(J.length===1)return!0;let V=(K)=>K!==void 0&&/^[1-9]\d{0,4}$/.test(K);if(J.length===2)return W?.startsWith("--lines=")&&V(W.slice(8))||W?.startsWith("-")&&V(W.slice(1));return J.length===3&&(W==="-n"||W==="--lines")&&V(Y)}function $5($){let J=h6($.replace(o4,"").trim()),Z=t4(J);if(!Z)return;if(Z.length===0)return x6(J);if(Z.length!==1)return;let W=Z[0];if(W===void 0)return;let Y=h6(J.slice(0,W).trim()),V=J.slice(W+1).trim();if(!Y||!e4(V))return;return x6(Y)}function x6($){let Z=i$($)?.at(-1);if(!Z)return $;let W=K$(Z),[Y,V]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&V==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function y$($,J){let Z=$5($);if(!Z)return!1;let W=l$(Z),Y=i$(W);if(!Y||T6(W)||/[\r\n]/.test(W))return!1;let V=Y.length===1?Y[0]:s4(W,Y,J);if(!V)return!1;let K=K$(V);if(K.length===0||K.some((B)=>[...n4].some((j)=>B===j||B.startsWith(`${j}=`))))return!1;let[Q,X,H]=K;if(r4.has(Q??""))return a4(X==="run"?H:X)||X==="--test";if((Q==="npx"||Q==="bunx")&&R6.has(X??""))return!0;if(R6.has(Q??""))return!0;if(Q==="node"&&X==="--test")return!0;if(Q==="go"&&["build","test","vet"].includes(X??""))return!0;return Q==="cargo"&&["build","check","clippy","test"].includes(X??"")}function cZ($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!Q$.isAbsolute($);let Z=Q$.isAbsolute($)?Q$.resolve($):Q$.resolve(J,$);return X$.isWithinWorkspace(Z,J)}var w2=k0("Agent"),J5=3;function q2($,J,Z){if($!=="length")return{action:"none"};if(J>=J5)return{action:"truncated"};if(b6(Z)==="stop")return w2.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var Z5=[/:\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],W5=/```[\s\S]{50,}```/,k6="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",Y5=2;function G2($,J,Z=!0){if(!$||J>=Y5)return{action:"none"};if(!Z&&W5.test($))return{action:"retry",prompt:k6};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(Z5.some((K)=>K.test(W)))return{action:"retry",prompt:k6};return{action:"none"}}var V5=[/\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}(?:测试|单测|集成测试|检查|构建)/],C6={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},K5={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},Q5="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.",X5="Required verification did not run successfully before the retry limit.",H5=3;function I6($,J,Z,W){if(!Z.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(J)){$.clear();return}if(J==="Bash"&&typeof Z.metadata?.command==="string"&&Z.metadata.exit_code===0&&y$(Z.metadata.command,W)){$.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes(J))return;let Y=Z.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let V of Y)if(typeof V==="string"&&y$(V,W))$.add(V)}function F2($,J,Z){if(!$||!V5.some((X)=>X.test($)))return{action:"none"};let W=Object.keys(C6).filter((X)=>C6[X].test($)),Y=[...J],V=W.filter((X)=>!Y.some((H)=>K5[X].test(H)));if(W.length>0?V.length===0:Y.some((X)=>y$(X)))return{action:"none"};if(Z>=H5)return{action:"fail",message:X5};let Q=W.length>1&&V.length>0?` Missing successful verification categories: ${V.join(", ")}.`:"";return{action:"retry",prompt:`${Q5}${Q}`}}var z5=[/\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|子代理|子智能体)/],u6=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function g6($){return typeof $==="string"&&u6.some((J)=>J.test($))}var B5=[/\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|子代理)/],j5=[/\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 U5($){if(typeof $!=="string")return;if(j5.some((J)=>J.test($)))return"multiple-allowed";return B5.some((J)=>J.test($))?"required":void 0}function r$($){for(let J of $){let Z=U5(J);if(Z!==void 0)return Z==="required"}return!1}var D5="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.",w5="Required delegation did not complete before the retry limit.",q5=3;function p6($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),Y=r$(W),V=!1;if(!Y)for(let K of W){if(u6.some((Q)=>Q.test(K)))break;if(z5.some((Q)=>Q.test(K))){V=!0;break}}if(W.length===0||!Y&&!V||J.has("Task"))return{action:"none"};if(Z>=q5)return{action:"fail",message:w5};return{action:"retry",prompt:D5}}var G5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],F5=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],L5=[/\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 d6($){return L5.reduce((J,Z)=>J.replace(Z," "),$)}function N1($){if(typeof $!=="string")return!1;let J=d6($);return G5.some((Z)=>Z.test(J))}var O5="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.",f5="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.",A5="Required worktree lifecycle did not complete before the retry limit.",y5=3;function m6($,J,Z){if(!$)return{action:"none"};let W=d6($);if(!N1(W))return{action:"none"};let Y=F5.some((K)=>K.test(W));if(J.has("TaskWorktree"))return{action:"none"};let V=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!V)return{action:"none"};if(Z>=y5)return{action:"fail",message:A5};return{action:"retry",tool:V,prompt:V==="EnterWorktree"?O5:f5}}var v6=30000;async function L2($){try{let Z=N$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??X0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((V)=>{W=setTimeout(()=>V("timeout"),v6)});try{let V=await Promise.race([Z,Y]);if(V==="timeout")return w2.warn(`[Loop] Stop hook 超时 (${v6}ms),按 shouldStop: true 处理`),{action:"stop"};let K=V;if(!K.shouldStop)return{action:"continue",reason:K.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return w2.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function N5($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var P5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function _5($){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 b5($){let J=$;for(let X of P5)J=J.replace(X," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:Z;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let V=Y.slice(0,60),K=V.lastIndexOf(" ");return`${(K>36?V.slice(0,K):V).trimEnd()}…`}function c6($){return b5(_5($))}import{EventEmitter as E5}from"events";import l6 from"node:path";function O2($){if(r6($.sessionId),!l6.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:l6.resolve($.projectPath)}}function i6($){let J=O2($);return JSON.stringify([J.projectPath,J.sessionId])}function Z3($,J){return i6($)===i6(J)}class P$ extends E5{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!P$.instance)P$.instance=new P$;return P$.instance}publish($,J,Z,W){let Y=O2($);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 n$=P$.getInstance();var t0=k0("Agent"),P1=new Set;async function S5($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(P1.has(Z))return;if(P1.size>=5000)P1.clear();P1.add(Z);try{let W=$.workspaceRoot,Y=await o$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let V=c6(J);if(!V)return;await o$.updateSessionMetadata(Z,Y.projectPath,{title:V}),n$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:V})}catch(W){t0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var f2=`<turn_aborted>
|
|
1
|
+
import{cc as M4}from"./chunk-cnhw5mqv.js";import{$c as c2,Id as u0,Kd as K6,Ld as h1,Md as Q6,Td as o$,Wc as vJ,Yc as IJ,Zc as uJ,_c as m2,ec as X$,fd as gJ,gd as T4,hd as R4,id as I2,jd as k1,kd as h4,ld as x4,md as S1,qd as DJ,yd as K1}from"./chunk-jjsv2xt1.js";import{Yd as S4}from"./chunk-53h87fmt.js";import{_d as H0,be as bJ,ce as v0}from"./chunk-qdv0n8yt.js";import{df as eJ}from"./chunk-pshyn3yy.js";import{ef as b4,ff as i0,gf as f4,hf as zJ,kf as E1,lf as V6,mf as BJ,nf as jJ,pf as UJ}from"./chunk-q2exry0f.js";import{$f as r0,_f as J$,cg as E4,gg as H4}from"./chunk-cqqmkwvn.js";import{tg as N$}from"./chunk-kev3cwe9.js";import{Dh as nJ}from"./chunk-4w4wjm49.js";import{Sh as X0}from"./chunk-ecd727xh.js";import{si as k0}from"./chunk-dvv28pkc.js";import{Gi as CJ}from"./chunk-r7wwr5f6.js";import{Ri as b$,Ti as r6,Ui as P0,Vi as R1,Xi as hJ,Yi as xJ,Zi as kJ}from"./chunk-rkdxqx8m.js";import{_i as L8}from"./chunk-tf7ezqew.js";function A$($){return $.role==="system"&&Array.isArray($.content)}function f$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class A1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,J){this.context=$;let Z=$.messages.find(A$);if(this._contextualSystemMessages=$.messages.filter(f$),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!A$(W)&&!f$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}get contextRevision(){return this._contextRevision}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!f$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(A$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((J)=>J.id===$.id))return;this._history.push($)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((J)=>!A$(J)&&!f$(J)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(f$),this._history=$.filter((J)=>!A$(J)&&!f$(J)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let J=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((Z)=>!$(Z)),this._pending=this._pending.filter((Z)=>!$(Z)),this._contextualSystemMessages=this._contextualSystemMessages.filter((Z)=>!$(Z)),this.syncContextualSystemMessages(),this._history.length!==J[0]||this._pending.length!==J[1]||this._contextualSystemMessages.length!==J[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function b6($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function E6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function S6($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import Q$ from"node:path";var c4=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"]),l4=/^(LD_.+|DYLD_.+|PATH)$/,M6=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function l$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(M6);if(!V)break;let K=V[1];if(!c4.has(K))break;J=Y}return J}function uZ($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(M6);if(!V)break;let K=V[1];if(l4.test(K))break;J=Y}return J}var i4=[/^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 D2($){let J=$,Z=!0;while(Z){Z=!1;for(let W of i4){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 i$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){Z+=Q,V=!0;continue}if(Q==="'"&&!Y){W=!W,Z+=Q;continue}if(Q==='"'&&!W){Y=!Y,Z+=Q;continue}if(W||Y){Z+=Q;continue}if(Q==="|"){if(K+1<$.length&&$[K+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&K+1<$.length&&$[K+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}if(Q==="&")return null;if(Q===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=Q}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function T6($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let V=$[Y];if(W){W=!1;continue}if(V==="\\"&&!J){W=!0;continue}if(V==="'"&&!Z){J=!J;continue}if(V==='"'&&!J){Z=!Z;continue}if(J)continue;if(V==="$"){let K=$[Y+1];if(K&&/[A-Za-z_@*#?!$0-9({]/.test(K))return!0}if(V==="`")return!0;if(Z)continue;if(V==="|")return!0;if(V===">"||V==="<")return!0;if(V==="{"){let K=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(K)||/^\{[^}]*\.\.[^}]*\}/.test(K))return!0}}return!1}function K$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){if(V=!0,Y){let X=$[K+1];if(X&&'$`"\\'.includes(X))continue;Z+=Q,V=!1}continue}if(Q==="'"&&!Y){W=!W;continue}if(Q==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(Q)){if(Z)J.push(Z),Z="";continue}Z+=Q}if(Z)J.push(Z);return J}var r4=new Set(["npm","pnpm","yarn","bun"]),R6=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),n4=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),o4=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function a4($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function h6($){return $.replace(/\s+2>&1\s*$/,"").trim()}function s4($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=K$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let V=Y[1];if(!V||V==="-")return;let K=Q$.isAbsolute(V)?Q$.resolve(V):Q$.resolve(Z,V);if(!X$.isWithinWorkspace(K,Z))return;return W[2]?.trim()||void 0}function t4($){let J=[],Z=!1,W=!1,Y=!1;for(let V=0;V<$.length;V++){let K=$[V];if(Y){Y=!1;continue}if(K==="\\"&&!Z){Y=!0;continue}if(K==="'"&&!W){Z=!Z;continue}if(K==='"'&&!Z){W=!W;continue}if(K!=="|"||Z||W)continue;if($[V+1]==="|")return;J.push(V)}return J}function e4($){let J=K$($),[Z,W,Y]=J;if(Z!=="head"&&Z!=="tail")return!1;if(J.length===1)return!0;let V=(K)=>K!==void 0&&/^[1-9]\d{0,4}$/.test(K);if(J.length===2)return W?.startsWith("--lines=")&&V(W.slice(8))||W?.startsWith("-")&&V(W.slice(1));return J.length===3&&(W==="-n"||W==="--lines")&&V(Y)}function $5($){let J=h6($.replace(o4,"").trim()),Z=t4(J);if(!Z)return;if(Z.length===0)return x6(J);if(Z.length!==1)return;let W=Z[0];if(W===void 0)return;let Y=h6(J.slice(0,W).trim()),V=J.slice(W+1).trim();if(!Y||!e4(V))return;return x6(Y)}function x6($){let Z=i$($)?.at(-1);if(!Z)return $;let W=K$(Z),[Y,V]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&V==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function y$($,J){let Z=$5($);if(!Z)return!1;let W=l$(Z),Y=i$(W);if(!Y||T6(W)||/[\r\n]/.test(W))return!1;let V=Y.length===1?Y[0]:s4(W,Y,J);if(!V)return!1;let K=K$(V);if(K.length===0||K.some((B)=>[...n4].some((j)=>B===j||B.startsWith(`${j}=`))))return!1;let[Q,X,H]=K;if(r4.has(Q??""))return a4(X==="run"?H:X)||X==="--test";if((Q==="npx"||Q==="bunx")&&R6.has(X??""))return!0;if(R6.has(Q??""))return!0;if(Q==="node"&&X==="--test")return!0;if(Q==="go"&&["build","test","vet"].includes(X??""))return!0;return Q==="cargo"&&["build","check","clippy","test"].includes(X??"")}function cZ($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!Q$.isAbsolute($);let Z=Q$.isAbsolute($)?Q$.resolve($):Q$.resolve(J,$);return X$.isWithinWorkspace(Z,J)}var w2=k0("Agent"),J5=3;function q2($,J,Z){if($!=="length")return{action:"none"};if(J>=J5)return{action:"truncated"};if(b6(Z)==="stop")return w2.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var Z5=[/:\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],W5=/```[\s\S]{50,}```/,k6="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",Y5=2;function G2($,J,Z=!0){if(!$||J>=Y5)return{action:"none"};if(!Z&&W5.test($))return{action:"retry",prompt:k6};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(Z5.some((K)=>K.test(W)))return{action:"retry",prompt:k6};return{action:"none"}}var V5=[/\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}(?:测试|单测|集成测试|检查|构建)/],C6={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},K5={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},Q5="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.",X5="Required verification did not run successfully before the retry limit.",H5=3;function I6($,J,Z,W){if(!Z.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(J)){$.clear();return}if(J==="Bash"&&typeof Z.metadata?.command==="string"&&Z.metadata.exit_code===0&&y$(Z.metadata.command,W)){$.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes(J))return;let Y=Z.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let V of Y)if(typeof V==="string"&&y$(V,W))$.add(V)}function F2($,J,Z){if(!$||!V5.some((X)=>X.test($)))return{action:"none"};let W=Object.keys(C6).filter((X)=>C6[X].test($)),Y=[...J],V=W.filter((X)=>!Y.some((H)=>K5[X].test(H)));if(W.length>0?V.length===0:Y.some((X)=>y$(X)))return{action:"none"};if(Z>=H5)return{action:"fail",message:X5};let Q=W.length>1&&V.length>0?` Missing successful verification categories: ${V.join(", ")}.`:"";return{action:"retry",prompt:`${Q5}${Q}`}}var z5=[/\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|子代理|子智能体)/],u6=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function g6($){return typeof $==="string"&&u6.some((J)=>J.test($))}var B5=[/\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|子代理)/],j5=[/\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 U5($){if(typeof $!=="string")return;if(j5.some((J)=>J.test($)))return"multiple-allowed";return B5.some((J)=>J.test($))?"required":void 0}function r$($){for(let J of $){let Z=U5(J);if(Z!==void 0)return Z==="required"}return!1}var D5="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.",w5="Required delegation did not complete before the retry limit.",q5=3;function p6($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),Y=r$(W),V=!1;if(!Y)for(let K of W){if(u6.some((Q)=>Q.test(K)))break;if(z5.some((Q)=>Q.test(K))){V=!0;break}}if(W.length===0||!Y&&!V||J.has("Task"))return{action:"none"};if(Z>=q5)return{action:"fail",message:w5};return{action:"retry",prompt:D5}}var G5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],F5=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],L5=[/\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 d6($){return L5.reduce((J,Z)=>J.replace(Z," "),$)}function N1($){if(typeof $!=="string")return!1;let J=d6($);return G5.some((Z)=>Z.test(J))}var O5="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.",f5="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.",A5="Required worktree lifecycle did not complete before the retry limit.",y5=3;function m6($,J,Z){if(!$)return{action:"none"};let W=d6($);if(!N1(W))return{action:"none"};let Y=F5.some((K)=>K.test(W));if(J.has("TaskWorktree"))return{action:"none"};let V=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!V)return{action:"none"};if(Z>=y5)return{action:"fail",message:A5};return{action:"retry",tool:V,prompt:V==="EnterWorktree"?O5:f5}}var v6=30000;async function L2($){try{let Z=N$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??X0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((V)=>{W=setTimeout(()=>V("timeout"),v6)});try{let V=await Promise.race([Z,Y]);if(V==="timeout")return w2.warn(`[Loop] Stop hook 超时 (${v6}ms),按 shouldStop: true 处理`),{action:"stop"};let K=V;if(!K.shouldStop)return{action:"continue",reason:K.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return w2.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function N5($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var P5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function _5($){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 b5($){let J=$;for(let X of P5)J=J.replace(X," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:Z;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let V=Y.slice(0,60),K=V.lastIndexOf(" ");return`${(K>36?V.slice(0,K):V).trimEnd()}…`}function c6($){return b5(_5($))}import{EventEmitter as E5}from"events";import l6 from"node:path";function O2($){if(r6($.sessionId),!l6.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:l6.resolve($.projectPath)}}function i6($){let J=O2($);return JSON.stringify([J.projectPath,J.sessionId])}function Z3($,J){return i6($)===i6(J)}class P$ extends E5{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!P$.instance)P$.instance=new P$;return P$.instance}publish($,J,Z,W){let Y=O2($);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 n$=P$.getInstance();var t0=k0("Agent"),P1=new Set;async function S5($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(P1.has(Z))return;if(P1.size>=5000)P1.clear();P1.add(Z);try{let W=$.workspaceRoot,Y=await o$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let V=c6(J);if(!V)return;await o$.updateSessionMetadata(Z,Y.projectPath,{title:V}),n$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:V})}catch(W){t0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var f2=`<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>`,H$="Tool execution was blocked because its durable call record could not be committed. No tool side effect was started.",n6="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 _$ 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 l0($,J,Z,W=null,Y,V={}){let K=V.required??$.executionEngine!==void 0;try{let Q=z$($),X=typeof Z==="string"?Z.trim()!=="":Z.some((H)=>H.type==="text"?H.text.trim()!=="":!0);if(Q&&J.sessionId&&X){let H=await Q.saveMessage(J.sessionId,"user",Z,W,Y,J.subagentInfo);if(K&&!H)throw Error("Durable user-message commit returned no identity");if(Y?.clientVisible!==!1)S5(J,Z);return H}if(K&&J.sessionId&&X)throw Error("Durable user-message storage is unavailable")}catch(Q){if(t0.warn("[Loop] 保存用户消息失败:",Q),K)throw new _$("user_message",{cause:Q})}return null}async function C0($,J,Z,W,Y,V,K={}){let Q=K.required??$.executionEngine!==void 0;try{let X=z$($),H=Boolean(Z.trim()||Y?.trim());if(X&&J.sessionId&&H){let B=await X.saveMessage(J.sessionId,"assistant",Z,W,V,J.subagentInfo,Y);if(Q&&!B)throw Error("Durable assistant-message commit returned no identity");return B}if(Q&&J.sessionId&&H)throw Error("Durable assistant-message storage is unavailable")}catch(X){if(t0.warn("[Loop] 保存助手消息失败:",X),Q)throw new _$("assistant_message",{cause:X})}return null}async function o6($,J,Z){try{let W=z$($);if(W&&J.sessionId)return await W.saveMessage(J.sessionId,"system",f2,Z,void 0,J.subagentInfo)}catch(W){t0.warn("[Loop] 保存中断边界失败:",W)}return null}async function a6($,J,Z,W,Y){try{let V=z$($);if(!V||!J.sessionId||Z.length===0)return null;return await V.saveMessage(J.sessionId,"system",`<contextual-project-instructions-ref count="${Z.length}" />`,Y,{contextualProjectRules:!0,ruleReferences:JSON.parse(JSON.stringify(Z.map((K)=>({...K})))),triggerPaths:[...W]},J.subagentInfo)}catch(V){t0.warn("[Loop] 保存 contextual project rules provenance 失败:",V)}return null}async function A2($,J,Z,W,Y,V={}){try{let K=z$($);if(K&&J.sessionId){let Q=await K.saveToolUse(J.sessionId,Z,W,Y,J.subagentInfo,V.providerToolCallId);if(V.required&&!Q)throw Error("Durable tool-use commit returned no identity");return Q}if(V.required&&J.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(K){if(t0.warn("[Loop] 保存工具调用失败:",K),V.required)throw K}return null}async function _1($,J,Z,W,Y,V,K,Q,X,H={}){try{let B=z$($);if(B&&J.sessionId){let j=await B.saveToolResult(J.sessionId,Z,W,Y,V,K,J.subagentInfo,Q,X);if(H.required&&!j)throw Error("Durable tool-result commit returned no identity");return j}if(H.required&&J.sessionId)throw Error("Durable tool-result storage is unavailable")}catch(B){if(t0.warn("[Loop] 保存工具结果失败:",B),H.required)throw B}return null}async function a$($,J,Z,W,Y={}){try{let V=z$($);if(V&&J.sessionId){let K=await V.saveCompaction(J.sessionId,Z,W,null);if(Y.required&&!K)throw Error("Compaction checkpoint commit returned no identity");return K||null}if(Y.required&&J.sessionId)throw Error("Compaction checkpoint storage is unavailable")}catch(V){if(t0.warn("[Loop] 保存压缩数据失败:",V),Y.required)throw V}return null}async function D0($){let{deps:J,context:Z,state:W,assistantContent:Y,assistantReasoningContent:V,lastMessageUuid:K,controlPrompt:Q,controlMetadata:X}=$;W.appendAssistant({role:"assistant",content:Y,reasoningContent:V});let H=K,B=await C0(J,Z,Y,H,V);if(B)H=B;if(Q!==void 0){let j={role:"user",content:Q};if(X)j.metadata=X;W.appendControl("user",j);let z=await l0(J,Z,j.content,H,X);if(z)H=z}return H}import{createHash as X6}from"node:crypto";import{promises as l5}from"node:fs";import i5 from"node:path";import{nanoid as e0}from"nanoid";import*as J0 from"node:fs/promises";import*as B$ from"node:path";var s6={enabled:!0,maxIndexLines:200};var M5="memory",t6="MEMORY.md";class y2{memoryDir;config;initialized=!1;constructor($,J,Z){if(Z)this.memoryDir=Z;else{let W=b$($);this.memoryDir=B$.join(W,M5)}this.config={...s6,...J}}async initialize(){if(this.initialized)return;await J0.mkdir(this.memoryDir,{recursive:!0}),this.initialized=!0}async loadIndex(){if(!this.config.enabled)return null;await this.initialize();let $=B$.join(this.memoryDir,t6);try{let J=await J0.readFile($,"utf-8");if(!J.trim())return null;let Z=J.split(`
|
|
4
4
|
`),Y=Z.slice(0,this.config.maxIndexLines).join(`
|
|
@@ -160,7 +160,7 @@ ${C.reason}
|
|
|
160
160
|
|
|
161
161
|
<system-reminder>
|
|
162
162
|
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.
|
|
163
|
-
</system-reminder>`;X=await D0({deps:$,context:Z,state:q,assistantContent:G.content||"",assistantReasoningContent:G.reasoningContent,lastMessageUuid:X,controlPrompt:R});continue}let O0=await W?.turnSteering?.drainOrSeal();if(O0&&O0.messages.length>0){await m$("Goal completion evidence invalidated by new user steering"),Z0=void 0,o0=!1,c0=0,q.appendAssistant({role:"assistant",content:G.content||"",reasoningContent:G.reasoningContent});let R=await C0($,Z,G.content||"",X,G.reasoningContent);if(R)X=R;yield{kind:"steering_applied",...await q1(O0.messages),delivery:"current_turn"};continue}let Y0=B4({requested:b0,taskAvailable:N().some((R)=>R.name==="Task"),mutationRevision:q$,verificationRevision:v$,verificationVerdict:q0,verificationFeedback:w$,verificationStallCount:u$,retryCount:H1});if(Y0.action==="retry"){if(H1++,d0=Y0.requireVerificationTask,d0)p0="Task";X=await D0({deps:$,context:Z,state:q,assistantContent:G.content||"",assistantReasoningContent:G.reasoningContent,lastMessageUuid:X,controlPrompt:Y0.prompt});continue}if(Y0.action==="fail")return X=await D0({deps:$,context:Z,state:q,assistantContent:G.content||"",assistantReasoningContent:G.reasoningContent,lastMessageUuid:X}),{success:!1,error:{type:"goal_verification_failed",message:Y0.message},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:S,goalVerificationVerdict:q0,goalVerifierSessionId:E0,goalVerificationEvidenceSha256:x0}};let I=!1,y=!1;if(b0){if(!W?.goalLifecycle||q0!=="pass")return{success:!1,error:{type:"goal_verification_failed",message:"Goal completion reached the final boundary without host-owned verification authority and a fresh PASS."},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:S,goalVerificationVerdict:q0,goalVerifierSessionId:E0,goalVerificationEvidenceSha256:x0}};y=!0}let a=j6(),n=a?.finalMessage??G.content??"",U0=a?.persistenceMetadata,O;if(y){let R=m0?.completionVerification;if(m0?.status!=="verifying"||m0.goalId!==I$||R?.status!=="pass"||R.attempt!==B1||typeof R.verifierSessionId!=="string"||R.verifierSessionId!==E0||typeof R.evidenceSha256!=="string"||R.evidenceSha256!==x0)throw Error("Goal completion lost its persisted verification receipt before finalization");O={goalId:m0.goalId,verificationAttempt:R.attempt,verifierSessionId:R.verifierSessionId,evidenceSha256:R.evidenceSha256,goalUpdatedAt:m0.updatedAt}}let f0=await K0(O),G0=U0||f0?{...U0,...f0?{turnFinalization:f0}:{}}:void 0;q.appendAssistant({role:"assistant",content:n,...G0?{metadata:x$(G0)}:{}});let Q0=await C0($,Z,n,X,U0?void 0:G.reasoningContent,G0);if(Q0)X=Q0;if(y&&W?.goalLifecycle){let R=await W.goalLifecycle.finalizeCompletion();b0=!1,I=!0,yield{kind:"goal_updated",goal:R}}if(a)yield a.event;return{success:!0,finalMessage:n,metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:S,toolSuccessRate:Q.length>0?Q.filter((R)=>R.success).length/Q.length:void 0,totalToolFailures:b.totalFailures||void 0,...I?{goalCompletionVerified:!0,goalVerificationVerdict:"pass",...E0?{goalVerifierSessionId:E0}:{},...x0?{goalVerificationEvidenceSha256:x0}:{}}:{},...B6?{outputTruncated:!0}:{},...a?.resultMetadata}}}if(G.finishReason!=="length")n0=0;q.appendAssistant({role:"assistant",content:G.content||"",reasoningContent:G.reasoningContent,tool_calls:G.toolCalls});{let w=await C0($,Z,G.content||"",X,G.reasoningContent);if(w)X=w}if(W?.signal?.aborted)return B(K,Q.length,W.signal);let O1=G.toolCalls.filter((w)=>w.type==="function"),B2;if(s0?.hasTools()){l.debug(`[Loop] 使用 StreamingToolExecutor 收集 ${O1.length} 个工具结果`);let w=s0;for(let D of w.getQueuedToolCalls()){let A=j.get(D.function.name)?.kind;yield{kind:"tool_start",toolCall:D,toolKind:A}}B2=(async()=>{let D=[];for await(let P of w.getRemainingResults())D.push(P);return D})()}else{let w=new Map,D=new Y1;for(let E of O1){let f=D.admit();if(f){w.set(E.id,f);continue}let p=Q1(E.function.arguments),C=p===null?void 0:w6(E.function.name,p);if(C){w.set(E.id,C);continue}let Y0=j.get(E.function.name)?.kind;yield{kind:"tool_start",toolCall:E,toolKind:Y0}}let P=Promise.resolve(),A=(E,f,p)=>{let C=P.then(()=>A2($,Z,E,f,X,{required:$.executionEngine!==void 0,providerToolCallId:p}));return P=C.then(()=>{return},()=>{return}),C},c=async(E)=>{let f=null;try{let p=w.get(E.id);if(p)return{toolCall:E,result:p,toolUseUuid:null};let C=Q1(E.function.arguments);if(C===null)return{toolCall:E,result:{success:!1,llmContent:"",error:{type:"validation_error",message:`Invalid JSON object in tool arguments. Raw: ${E.function.arguments.slice(0,200)}`},metadata:void 0},toolUseUuid:null};V1(E.function.name,C);try{f=await A(E.function.name,C,E.id)}catch(I){return{toolCall:E,result:{success:!1,llmContent:H$,error:{type:"execution_error",message:H$},metadata:{durableToolUseFailed:!0,summary:"Blocked tool before execution"}},toolUseUuid:null,error:I instanceof Error?I:Error(String(I))}}if(E.function.name==="ExitWorktree"&&j0.has("EnterWorktree")&&!j0.has("ExitWorktree")&&F2($2,t1,0).action!=="none"){let I="Run the requested verification before ExitWorktree. The worktree remains active so Bash can run in isolation.";return{toolCall:E,result:{success:!1,llmContent:I,error:{type:"validation_error",message:I},metadata:{summary:"Blocked ExitWorktree until verification succeeds"}},toolUseUuid:f}}let Y0=await G6(E.function.name,C,{sessionId:Z.sessionId,taskListId:Z.taskListId,goalTaskListId:Z.goalTaskListId,userId:Z.userId||"default",modelId:$.config.currentModelId,providerAdmissionOwnerId:H2,workspaceRoot:Z.workspaceRoot||X0(),environment:$.config.env,worktreeIsolationRequired:w1,worktreeActive:j0.has("EnterWorktree")&&!j0.has("ExitWorktree"),subagentType:Z.subagentInfo?.subagentType,signal:W?.signal,confirmationHandler:Z.sessionId?z0.createConfirmationHandler(Z.confirmationHandler,{sessionId:Z.sessionId,projectPath:Z.workspaceRoot||X0(),toolCallId:f??E.id,toolName:E.function.name}):Z.confirmationHandler,permissionMode:Z.permissionMode,toolRegistry:j,deferredToolManager:j.deferredToolManager,onProgress:(I)=>{Y$.push({toolCall:E,update:{message:I.slice(0,1000)}})},onProgressUpdate:(I)=>{Y$.push({toolCall:E,update:I})}});return{toolCall:E,result:Y0,toolUseUuid:f}}catch(p){return l.error(`Tool execution failed for ${E.function.name}:`,p),{toolCall:E,result:{success:!1,llmContent:"",error:{type:"execution_error",message:p instanceof Error?p.message:"Unknown error"},metadata:void 0},toolUseUuid:f,error:p instanceof Error?p:Error("Unknown error")}}};B2=Promise.all(O1.map(c))}let f1,N6,P6=!1,j2=!1,p4=B2.then((w)=>{f1=w},(w)=>{P6=!0,N6=w}).finally(()=>{j2=!0,Y$.close()});while(!j2||Y$.hasPending){let w=Y$.shift()??(j2?void 0:await Y$.next());if(w)yield{kind:"tool_progress",toolCall:w.toolCall,update:w.update}}if(await p4,P6)throw N6;if(!f1)throw Error("Tool execution completed without results");let d4=new k2;for(let{toolCall:w,result:D,toolUseUuid:P}of f1){let A=w;if(Q.push(D),D.metadata?.abortedBeforeLaunch){let y=D.error?.message??"任务已被用户中止";if(P)try{let a=await _1($,Z,P,A.function.name,null,P,y,void 0,void 0,{required:$.executionEngine!==void 0});if(a)X=a}catch{return _4(K,Q.length,V)}return q.appendToolResult({role:"tool",tool_call_id:A.id,name:A.function.name,content:`Error: ${y}`}),B(K,Q.length,W?.signal)}{let y=D.metadata&&typeof D.metadata==="object"?D.metadata:void 0,n=((Q0)=>Q0==="running"||Q0==="completed"||Q0==="failed"||Q0==="cancelled")(y?.subagentStatus)?y.subagentStatus:"completed",U0=y?.verificationVerdict==="pass"||y?.verificationVerdict==="fail"||y?.verificationVerdict==="partial"?y.verificationVerdict:void 0,O=y&&typeof y.subagentSessionId==="string"?{subagentSessionId:y.subagentSessionId,subagentType:typeof y.subagentType==="string"?y.subagentType:A.function.name,subagentDescription:typeof y.description==="string"?y.description:void 0,subagentStatus:n,subagentSummary:typeof y.subagentSummary==="string"?y.subagentSummary:void 0,subagentResumedFrom:typeof y.subagentResumedFrom==="string"?y.subagentResumedFrom:void 0,subagentRootId:typeof y.subagentRootId==="string"?y.subagentRootId:void 0,subagentResumeDepth:typeof y.subagentResumeDepth==="number"?y.subagentResumeDepth:void 0,verificationVerdict:U0}:void 0,f0=y?(()=>{let{oldContent:Q0,newContent:R,...T0}=y;return x$(T0)})():void 0;if(y?.durableToolUseFailed!==!0&&(P!==null||$.executionEngine===void 0))try{let Q0=await _1($,Z,P??A.id,A.function.name,D.success?x$(D.llmContent):null,P,D.success?void 0:D.error?.message,O,f0,{required:$.executionEngine!==void 0});if(Q0)X=Q0}catch{return _4(K,Q.length,V)}}yield{kind:"tool_result",toolCall:A,result:D};let c=await W6(A,D,$,Z);if(c){if(yield c,!Z.taskListId&&W?.goalLifecycle?.refreshFrontier){let y=await W.goalLifecycle.refreshFrontier();if(y?.ok)yield{kind:"goal_frontier_updated",goal:y.goal,frontier:y.frontier,tasks:y.tasks};else if(y){if(y.goal)yield{kind:"goal_updated",goal:y.goal};return{success:!1,error:{type:"goal_frontier_unavailable",message:y.error.message},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:S}}}}}let E,f=D.metadata&&typeof D.metadata==="object"?D.metadata:void 0,p=A.function.name==="Task"&&f?{subagentSessionId:f.subagentSessionId,subagentType:f.subagentType,subagentStatus:f.subagentStatus,subagentSummary:f.subagentSummary,subagentResumedFrom:f.subagentResumedFrom,subagentRootId:f.subagentRootId,subagentResumeDepth:f.subagentResumeDepth,verificationVerdict:f.verificationVerdict,verificationFeedback:f.verificationFeedback}:void 0;if(D.success){if(J4(b,A.function.name),f?.goalCompletionRequested===!0){if(!W?.goalLifecycle)throw Error("Goal completion candidate has no host lifecycle authority");b0=!0;let O=typeof f.goalCompletionAttempt==="number"?f.goalCompletionAttempt:void 0,f0=typeof f.goalCompletionRequestedAt==="string"?f.goalCompletionRequestedAt:void 0,G0=typeof f.goalId==="string"?f.goalId:void 0;if(z4({goalId:I$,attempt:B1,requestedAt:s1},{goalId:G0,attempt:O,requestedAt:f0}))H1=0,v$=-1,q0=void 0,E0=void 0,w$=void 0,U1=void 0,x0=void 0,m0=void 0;B1=O??B1,s1=f0??s1,I$=G0??I$,j1=typeof f.goalObjective==="string"?f.goalObjective:j1;let R=await W?.goalLifecycle?.getSnapshot();if(R)u$=R.verificationStall?.consecutiveCount,yield{kind:"goal_updated",goal:R}}else if(A.function.name==="UpdateGoal"&&f?.goalStatus==="blocked"){b0=!1,d0=!1,C$=!1,z1=!1,q0=void 0,v$=-1,E0=void 0,w$=void 0,U1=void 0,u$=void 0,x0=void 0,m0=void 0;let O=await W?.goalLifecycle?.getSnapshot();if(O)yield{kind:"goal_updated",goal:O}}let y=G4(d$,A.function.name,D,Z.workspaceRoot);if(y.length>0){if(Z0=void 0,o0=!1,c0=0,q$++,p$=-1,a0=void 0,X1=0,b0){H1=0,await m$("Goal completion evidence invalidated by a workspace mutation");let O=await W?.goalLifecycle?.getSnapshot();if(O)u$=O.verificationStall?.consecutiveCount,yield{kind:"goal_updated",goal:O}}if(W?.goalLifecycle?.clearFrontierStall)yield{kind:"goal_updated",goal:await W.goalLifecycle.clearFrontierStall()}}let a=typeof f?.subagentType==="string"?f.subagentType:typeof f?.subagent_type==="string"?f.subagent_type:void 0,n=a===r0,U0=A.function.name==="Task"&&f?.verificationAgentBuiltin===!0&&(a===J$||n)&&(f?.subagentStatus==="completed"||f?.status==="completed");if(U0){if(a0=(f?.verificationVerdict==="pass"||f?.verificationVerdict==="fail"||f?.verificationVerdict==="partial"?f.verificationVerdict:void 0)??w4(typeof D.llmContent==="string"?D.llmContent:f?.subagentSummary&&typeof f.subagentSummary==="string"?f.subagentSummary:void 0),p$=q$,z1&&n){z1=!1,q0=a0,v$=q$,E0=typeof f?.subagentSessionId==="string"?f.subagentSessionId:void 0;let f0=typeof D.llmContent==="string"?D.llmContent.slice(0,4000):typeof f?.subagentSummary==="string"?f.subagentSummary:void 0,G0=typeof f?.verificationFeedback==="string"&&f.verificationFeedback.trim()?f.verificationFeedback.trim():void 0;if(w$=q0?G0??`Independent verifier returned ${q0.toUpperCase()}.`:void 0,U1=q0!=="pass"&&G0?X6("sha256").update(G0,"utf8").digest("hex"):void 0,q0&&W?.goalLifecycle){let Q0=JSON.stringify({goalId:I$,objective:j1,mutationRevision:q$,verdict:q0,verifierSessionId:E0,evidence:f0});x0=X6("sha256").update(Q0).digest("hex");let R=await W.goalLifecycle.recordVerification({verdict:q0,verifierSessionId:E0,summary:w$,evidenceSha256:x0,feedbackSha256:U1});m0=R,u$=R.verificationStall?.consecutiveCount,yield{kind:"goal_updated",goal:R}}}}if(y.length>0||U0)E={...y.length>0?{modifiedFiles:y}:{},...U0?{verificationAttempted:!0,verificationAgentBuiltin:!0,...a0?{verificationVerdict:a0}:{}}:{}};if(A.function.name==="EnterWorktree"&&D.metadata?.workspaceTransition==="enter")j0.add("EnterWorktree"),j0.delete("ExitWorktree");else if(A.function.name==="ExitWorktree"&&D.metadata?.workspaceTransition==="exit"&&j0.has("EnterWorktree"))j0.add("ExitWorktree");else if(!["EnterWorktree","ExitWorktree"].includes(A.function.name))j0.add(A.function.name);if(A.function.name==="Task"&&D.metadata?.isolation==="worktree")j0.add("TaskWorktree");I6(t1,A.function.name,D,Z.workspaceRoot)}else Z4(b,A.function.name);let C=D.success?D.llmContent||"":yZ(A.function.name,D.error);if(!D.success){let y=W4(b,A.function.name);if(y&&typeof C==="string")C=`${C}
|
|
163
|
+
</system-reminder>`;X=await D0({deps:$,context:Z,state:q,assistantContent:G.content||"",assistantReasoningContent:G.reasoningContent,lastMessageUuid:X,controlPrompt:R});continue}let O0=await W?.turnSteering?.drainOrSeal();if(O0&&O0.messages.length>0){await m$("Goal completion evidence invalidated by new user steering"),Z0=void 0,o0=!1,c0=0,q.appendAssistant({role:"assistant",content:G.content||"",reasoningContent:G.reasoningContent});let R=await C0($,Z,G.content||"",X,G.reasoningContent);if(R)X=R;yield{kind:"steering_applied",...await q1(O0.messages),delivery:"current_turn"};continue}let Y0=B4({requested:b0,taskAvailable:N().some((R)=>R.name==="Task"),mutationRevision:q$,verificationRevision:v$,verificationVerdict:q0,verificationFeedback:w$,verificationStallCount:u$,retryCount:H1});if(Y0.action==="retry"){if(H1++,d0=Y0.requireVerificationTask,d0)p0="Task";X=await D0({deps:$,context:Z,state:q,assistantContent:G.content||"",assistantReasoningContent:G.reasoningContent,lastMessageUuid:X,controlPrompt:Y0.prompt});continue}if(Y0.action==="fail")return X=await D0({deps:$,context:Z,state:q,assistantContent:G.content||"",assistantReasoningContent:G.reasoningContent,lastMessageUuid:X}),{success:!1,error:{type:"goal_verification_failed",message:Y0.message},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:S,goalVerificationVerdict:q0,goalVerifierSessionId:E0,goalVerificationEvidenceSha256:x0}};let I=!1,y=!1;if(b0){if(!W?.goalLifecycle||q0!=="pass")return{success:!1,error:{type:"goal_verification_failed",message:"Goal completion reached the final boundary without host-owned verification authority and a fresh PASS."},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:S,goalVerificationVerdict:q0,goalVerifierSessionId:E0,goalVerificationEvidenceSha256:x0}};y=!0}let a=j6(),n=a?.finalMessage??G.content??"",U0=a?.persistenceMetadata,O;if(y){let R=m0?.completionVerification;if(m0?.status!=="verifying"||m0.goalId!==I$||R?.status!=="pass"||R.attempt!==B1||typeof R.verifierSessionId!=="string"||R.verifierSessionId!==E0||typeof R.evidenceSha256!=="string"||R.evidenceSha256!==x0)throw Error("Goal completion lost its persisted verification receipt before finalization");O={goalId:m0.goalId,verificationAttempt:R.attempt,verifierSessionId:R.verifierSessionId,evidenceSha256:R.evidenceSha256,goalUpdatedAt:m0.updatedAt}}let f0=await K0(O),G0=U0||f0?{...U0,...f0?{turnFinalization:f0}:{}}:void 0;q.appendAssistant({role:"assistant",content:n,...G0?{metadata:x$(G0)}:{}});let Q0=await C0($,Z,n,X,U0?void 0:G.reasoningContent,G0);if(Q0)X=Q0;if(y&&W?.goalLifecycle){let R=await W.goalLifecycle.finalizeCompletion();b0=!1,I=!0,yield{kind:"goal_updated",goal:R}}if(a)yield a.event;return{success:!0,finalMessage:n,metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:S,toolSuccessRate:Q.length>0?Q.filter((R)=>R.success).length/Q.length:void 0,totalToolFailures:b.totalFailures||void 0,...I?{goalCompletionVerified:!0,goalVerificationVerdict:"pass",...E0?{goalVerifierSessionId:E0}:{},...x0?{goalVerificationEvidenceSha256:x0}:{}}:{},...B6?{outputTruncated:!0}:{},...a?.resultMetadata}}}if(G.finishReason!=="length")n0=0;q.appendAssistant({role:"assistant",content:G.content||"",reasoningContent:G.reasoningContent,tool_calls:G.toolCalls});{let w=await C0($,Z,G.content||"",X,G.reasoningContent);if(w)X=w}if(W?.signal?.aborted)return B(K,Q.length,W.signal);let O1=G.toolCalls.filter((w)=>w.type==="function"),B2;if(s0?.hasTools()){l.debug(`[Loop] 使用 StreamingToolExecutor 收集 ${O1.length} 个工具结果`);let w=s0;for(let D of w.getQueuedToolCalls()){let A=j.get(D.function.name)?.kind;yield{kind:"tool_start",toolCall:D,toolKind:A}}B2=(async()=>{let D=[];for await(let P of w.getRemainingResults())D.push(P);return D})()}else{let w=new Map,D=new Y1;for(let E of O1){let f=D.admit();if(f){w.set(E.id,f);continue}let p=Q1(E.function.arguments),C=p===null?void 0:w6(E.function.name,p);if(C){w.set(E.id,C);continue}let Y0=j.get(E.function.name)?.kind;yield{kind:"tool_start",toolCall:E,toolKind:Y0}}let P=Promise.resolve(),A=(E,f,p)=>{let C=P.then(()=>A2($,Z,E,f,X,{required:$.executionEngine!==void 0,providerToolCallId:p}));return P=C.then(()=>{return},()=>{return}),C},c=async(E)=>{let f=null;try{let p=w.get(E.id);if(p)return{toolCall:E,result:p,toolUseUuid:null};let C=Q1(E.function.arguments);if(C===null)return{toolCall:E,result:{success:!1,llmContent:"",error:{type:"validation_error",message:`Invalid JSON object in tool arguments. Raw: ${E.function.arguments.slice(0,200)}`},metadata:void 0},toolUseUuid:null};V1(E.function.name,C);try{f=await A(E.function.name,C,E.id)}catch(I){return{toolCall:E,result:{success:!1,llmContent:H$,error:{type:"execution_error",message:H$},metadata:{durableToolUseFailed:!0,summary:"Blocked tool before execution"}},toolUseUuid:null,error:I instanceof Error?I:Error(String(I))}}if(E.function.name==="ExitWorktree"&&j0.has("EnterWorktree")&&!j0.has("ExitWorktree")&&F2($2,t1,0).action!=="none"){let I="Run the requested verification before ExitWorktree. The worktree remains active so Bash can run in isolation.";return{toolCall:E,result:{success:!1,llmContent:I,error:{type:"validation_error",message:I},metadata:{summary:"Blocked ExitWorktree until verification succeeds"}},toolUseUuid:f}}let Y0=await G6(E.function.name,C,{sessionId:Z.sessionId,taskListId:Z.taskListId,goalTaskListId:Z.goalTaskListId,userId:Z.userId||"default",modelId:$.config.currentModelId,providerAdmissionOwnerId:H2,workspaceRoot:Z.workspaceRoot||X0(),environment:$.config.env,worktreeIsolationRequired:w1,worktreeActive:j0.has("EnterWorktree")&&!j0.has("ExitWorktree"),subagentType:Z.subagentInfo?.subagentType,signal:W?.signal,confirmationHandler:Z.sessionId?z0.createConfirmationHandler(Z.confirmationHandler,{sessionId:Z.sessionId,projectPath:Z.workspaceRoot||X0(),toolCallId:f??E.id,toolName:E.function.name}):Z.confirmationHandler,permissionMode:Z.permissionMode,toolRegistry:j,deferredToolManager:j.deferredToolManager,onProgress:(I)=>{Y$.push({toolCall:E,update:{message:I.slice(0,1000)}})},onProgressUpdate:(I)=>{Y$.push({toolCall:E,update:I})}});return{toolCall:E,result:Y0,toolUseUuid:f}}catch(p){return l.error(`Tool execution failed for ${E.function.name}:`,p),{toolCall:E,result:{success:!1,llmContent:"",error:{type:"execution_error",message:p instanceof Error?p.message:"Unknown error"},metadata:void 0},toolUseUuid:f,error:p instanceof Error?p:Error("Unknown error")}}};B2=Promise.all(O1.map(c))}let f1,N6,P6=!1,j2=!1,p4=B2.then((w)=>{f1=w},(w)=>{P6=!0,N6=w}).finally(()=>{j2=!0,Y$.close()});while(!j2||Y$.hasPending){let w=Y$.shift()??(j2?void 0:await Y$.next());if(w)yield{kind:"tool_progress",toolCall:w.toolCall,update:w.update}}if(await p4,P6)throw N6;if(!f1)throw Error("Tool execution completed without results");let d4=new k2;for(let{toolCall:w,result:D,toolUseUuid:P}of f1){let A=w;if(Q.push(D),D.metadata?.abortedBeforeLaunch){let y=D.error?.message??"任务已被用户中止";if(P)try{let a=await _1($,Z,P,A.function.name,null,P,y,void 0,void 0,{required:$.executionEngine!==void 0});if(a)X=a}catch{return _4(K,Q.length,V)}return q.appendToolResult({role:"tool",tool_call_id:A.id,name:A.function.name,content:`Error: ${y}`}),B(K,Q.length,W?.signal)}{let y=D.metadata&&typeof D.metadata==="object"?D.metadata:void 0,n=((Q0)=>Q0==="running"||Q0==="completed"||Q0==="failed"||Q0==="cancelled")(y?.subagentStatus)?y.subagentStatus:"completed",U0=y?.verificationVerdict==="pass"||y?.verificationVerdict==="fail"||y?.verificationVerdict==="partial"?y.verificationVerdict:void 0,O=y&&typeof y.subagentSessionId==="string"?{subagentSessionId:y.subagentSessionId,subagentType:typeof y.subagentType==="string"?y.subagentType:A.function.name,subagentDescription:typeof y.description==="string"?y.description:void 0,subagentStatus:n,subagentSummary:typeof y.subagentSummary==="string"?y.subagentSummary:void 0,subagentResumedFrom:typeof y.subagentResumedFrom==="string"?y.subagentResumedFrom:void 0,subagentRootId:typeof y.subagentRootId==="string"?y.subagentRootId:void 0,subagentResumeDepth:typeof y.subagentResumeDepth==="number"?y.subagentResumeDepth:void 0,verificationVerdict:U0}:void 0,f0=y?(()=>{let{oldContent:Q0,newContent:R,...T0}=y;return x$(T0)})():void 0;if(y?.durableToolUseFailed!==!0&&(P!==null||$.executionEngine===void 0))try{let Q0=await _1($,Z,P??A.id,A.function.name,D.success?x$(D.llmContent):null,P,D.success?void 0:D.error?.message,O,f0,{required:$.executionEngine!==void 0});if(Q0)X=Q0}catch{return _4(K,Q.length,V)}}yield{kind:"tool_result",toolCall:A,result:D};let c=await W6(A,D,$,Z);if(c){if(yield c,!Z.taskListId&&W?.goalLifecycle?.refreshFrontier){let y=await W.goalLifecycle.refreshFrontier();if(y?.ok)yield{kind:"goal_frontier_updated",goal:y.goal,frontier:y.frontier,tasks:y.tasks};else if(y){if(y.goal)yield{kind:"goal_updated",goal:y.goal};return{success:!1,error:{type:"goal_frontier_unavailable",message:y.error.message},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:S}}}}}let E,f=D.metadata&&typeof D.metadata==="object"?D.metadata:void 0,p=A.function.name==="Task"&&f?{subagentSessionId:f.subagentSessionId,subagentType:f.subagentType,subagentStatus:f.subagentStatus,subagentSummary:f.subagentSummary,subagentResumedFrom:f.subagentResumedFrom,subagentRootId:f.subagentRootId,subagentResumeDepth:f.subagentResumeDepth,verificationVerdict:f.verificationVerdict,verificationFeedback:f.verificationFeedback}:void 0;if(D.success){if(J4(b,A.function.name),f?.goalCompletionRequested===!0){if(!W?.goalLifecycle)throw Error("Goal completion candidate has no host lifecycle authority");b0=!0;let O=typeof f.goalCompletionAttempt==="number"?f.goalCompletionAttempt:void 0,f0=typeof f.goalCompletionRequestedAt==="string"?f.goalCompletionRequestedAt:void 0,G0=typeof f.goalId==="string"?f.goalId:void 0;if(z4({goalId:I$,attempt:B1,requestedAt:s1},{goalId:G0,attempt:O,requestedAt:f0}))H1=0,v$=-1,q0=void 0,E0=void 0,w$=void 0,U1=void 0,x0=void 0,m0=void 0;B1=O??B1,s1=f0??s1,I$=G0??I$,j1=typeof f.goalObjective==="string"?f.goalObjective:j1;let R=await W?.goalLifecycle?.getSnapshot();if(R)u$=R.verificationStall?.consecutiveCount,yield{kind:"goal_updated",goal:R}}else if(A.function.name==="UpdateGoal"&&f?.goalStatus==="blocked"){b0=!1,d0=!1,C$=!1,z1=!1,q0=void 0,v$=-1,E0=void 0,w$=void 0,U1=void 0,u$=void 0,x0=void 0,m0=void 0;let O=await W?.goalLifecycle?.getSnapshot();if(O)yield{kind:"goal_updated",goal:O}}let y=G4(d$,A.function.name,D,Z.workspaceRoot);if(y.length>0){if(Z0=void 0,o0=!1,c0=0,q$++,p$=-1,a0=void 0,X1=0,b0){H1=0,await m$("Goal completion evidence invalidated by a workspace mutation");let O=await W?.goalLifecycle?.getSnapshot();if(O)u$=O.verificationStall?.consecutiveCount,yield{kind:"goal_updated",goal:O}}if(W?.goalLifecycle?.clearFrontierStall){let O=await W.goalLifecycle.clearFrontierStall();if(O)yield{kind:"goal_updated",goal:O}}}let a=typeof f?.subagentType==="string"?f.subagentType:typeof f?.subagent_type==="string"?f.subagent_type:void 0,n=a===r0,U0=A.function.name==="Task"&&f?.verificationAgentBuiltin===!0&&(a===J$||n)&&(f?.subagentStatus==="completed"||f?.status==="completed");if(U0){if(a0=(f?.verificationVerdict==="pass"||f?.verificationVerdict==="fail"||f?.verificationVerdict==="partial"?f.verificationVerdict:void 0)??w4(typeof D.llmContent==="string"?D.llmContent:f?.subagentSummary&&typeof f.subagentSummary==="string"?f.subagentSummary:void 0),p$=q$,z1&&n){z1=!1,q0=a0,v$=q$,E0=typeof f?.subagentSessionId==="string"?f.subagentSessionId:void 0;let f0=typeof D.llmContent==="string"?D.llmContent.slice(0,4000):typeof f?.subagentSummary==="string"?f.subagentSummary:void 0,G0=typeof f?.verificationFeedback==="string"&&f.verificationFeedback.trim()?f.verificationFeedback.trim():void 0;if(w$=q0?G0??`Independent verifier returned ${q0.toUpperCase()}.`:void 0,U1=q0!=="pass"&&G0?X6("sha256").update(G0,"utf8").digest("hex"):void 0,q0&&W?.goalLifecycle){let Q0=JSON.stringify({goalId:I$,objective:j1,mutationRevision:q$,verdict:q0,verifierSessionId:E0,evidence:f0});x0=X6("sha256").update(Q0).digest("hex");let R=await W.goalLifecycle.recordVerification({verdict:q0,verifierSessionId:E0,summary:w$,evidenceSha256:x0,feedbackSha256:U1});m0=R,u$=R.verificationStall?.consecutiveCount,yield{kind:"goal_updated",goal:R}}}}if(y.length>0||U0)E={...y.length>0?{modifiedFiles:y}:{},...U0?{verificationAttempted:!0,verificationAgentBuiltin:!0,...a0?{verificationVerdict:a0}:{}}:{}};if(A.function.name==="EnterWorktree"&&D.metadata?.workspaceTransition==="enter")j0.add("EnterWorktree"),j0.delete("ExitWorktree");else if(A.function.name==="ExitWorktree"&&D.metadata?.workspaceTransition==="exit"&&j0.has("EnterWorktree"))j0.add("ExitWorktree");else if(!["EnterWorktree","ExitWorktree"].includes(A.function.name))j0.add(A.function.name);if(A.function.name==="Task"&&D.metadata?.isolation==="worktree")j0.add("TaskWorktree");I6(t1,A.function.name,D,Z.workspaceRoot)}else Z4(b,A.function.name);let C=D.success?D.llmContent||"":yZ(A.function.name,D.error);if(!D.success){let y=W4(b,A.function.name);if(y&&typeof C==="string")C=`${C}
|
|
164
164
|
|
|
165
165
|
${y}`}if(typeof C==="object"&&C!==null)C=JSON.stringify(C,null,2);if(typeof C==="string")C=NJ(C,A.function.name,{messageBudget:d4});let O0=typeof C==="string"?C:JSON.stringify(C);if(q.appendToolResult({role:"tool",tool_call_id:A.id,name:A.function.name,content:S4(D,O0),...A.function.name==="Task"||E?{metadata:x$({toolCallId:A.id,toolName:A.function.name,error:D.success?null:D.error?.message??null,...p?{metadata:p}:{},...E?{independentVerification:E}:{}})}:{}}),f?.durableToolUseFailed===!0)return{success:!1,error:{type:"tool_persistence_failed",message:H$,details:D.error},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V}};let Y0=Q1(A.function.arguments)??{},I=q6(A.function.name,Y0,D);if(I&&I.files.length>0){for(let n of I.references)_.add(n.id);let y={role:"system",content:I.content,metadata:x$({contextualProjectRules:!0,ruleReferences:I.references,triggerPaths:I.triggerPaths})};q.appendContextualProjectInstructions(y);let a=await a6($,Z,I.references,I.triggerPaths,X);if(a)X=a;yield{kind:"project_rules_loaded",files:I.files.map((n)=>({id:n.id,relativePath:n.relativePath,source:n.source,conditional:n.conditional,contentSha256:n.contentSha256})),triggerPaths:I.triggerPaths,blockedWrite:D.metadata?.contextualProjectRulesRequired===!0}}if(A.function.name===u0&&D.metadata?.structuredOutputRetryExhausted===!0)return{success:!1,error:{type:"structured_output_failed",message:D.error?.message??"Structured output validation retry budget was exhausted."},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:S,structuredOutputSchemaDigest:U?.schemaDigest}};if(W?.signal?.aborted)return B(K,Q.length,W.signal);if(D.metadata?.shouldExitLoop){let y=typeof D.llmContent==="string"?D.llmContent:"循环已退出";return{success:D.success,finalMessage:y,metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,shouldExitLoop:!0,targetMode:D.metadata?.targetMode,planContent:typeof D.metadata?.planContent==="string"?D.metadata.planContent:void 0}}}}let V$=n2(M,O1,f1.map(({result:w})=>w));if(V$){if(yield{kind:"action_stationarity",...V$},V$.phase==="halted")return{success:!1,error:{type:"loop_detected",message:`Stopped after ${V$.runLength} repeated ${V$.toolName} calls without observable progress.`},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:S}};if(V$.phase==="detected"){let w={role:"user",content:`
|
|
166
166
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Qf as a,Rf as b,Sf as c,Tf as d,Uf as e,Vf as f,Wf as g,Xf as h,Yf as i,Zf as j}from"./chunk-
|
|
1
|
+
import{Qf as a,Rf as b,Sf as c,Tf as d,Uf as e,Vf as f,Wf as g,Xf as h,Yf as i,Zf as j}from"./chunk-yzmgf1vc.js";import"./chunk-cqqmkwvn.js";import"./chunk-9g64g1np.js";import"./chunk-935v0gpc.js";import"./chunk-kev3cwe9.js";import"./chunk-eyb9psbc.js";import"./chunk-spth418m.js";import"./chunk-4w4wjm49.js";import"./chunk-6k5k40p8.js";import"./chunk-p3m1jyg5.js";import"./chunk-ecd727xh.js";import"./chunk-x05zyqzf.js";import"./chunk-dvv28pkc.js";import"./chunk-dgf2xzzd.js";import"./chunk-z52s82k7.js";import"./chunk-r7wwr5f6.js";import"./chunk-vbwvsgs1.js";import"./chunk-sr10jsjs.js";import"./chunk-rkdxqx8m.js";import"./chunk-tf7ezqew.js";export{g as withWorkspaceAgentResources,i as snapshotWorkspaceAgentResources,f as resolveWorkspaceAgentResources,j as resetWorkspaceAgentResources,d as refreshWorkspaceCommunicationStyles,h as getWorkspaceAgentResourceCacheStats,e as configureInvocationPluginDirs,c as WorkspaceAgentResourceCapacityError,a as MAX_RESIDENT_WORKSPACE_AGENT_RESOURCES,b as MAX_ACTIVE_WORKSPACE_AGENT_RESOURCES};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Dh as Y}from"./chunk-4w4wjm49.js";import{Eh as on,Fh as F,Gh as o}from"./chunk-6k5k40p8.js";import{Kh as ct,Lh as bt}from"./chunk-p3m1jyg5.js";import{Sh as x}from"./chunk-ecd727xh.js";import{$h as it,Th as Jn,Uh as Xt,Vh as pt,Zh as gt,_h as kn,ai as Rt,bi as Ct,ci as un,di as zt,ei as Bt,fi as On,gi as Kt,hi as Ut,ii as jn,ji as Ht,ki as Yt,li as qt,mi as Vt,ni as Qt,oi as Gt}from"./chunk-x05zyqzf.js";import{si as fn}from"./chunk-dvv28pkc.js";import{vi as $t,yi as J}from"./chunk-dgf2xzzd.js";import{Gi as Pn,Hi as Ln}from"./chunk-
|
|
1
|
+
import{Dh as Y}from"./chunk-4w4wjm49.js";import{Eh as on,Fh as F,Gh as o}from"./chunk-6k5k40p8.js";import{Kh as ct,Lh as bt}from"./chunk-p3m1jyg5.js";import{Sh as x}from"./chunk-ecd727xh.js";import{$h as it,Th as Jn,Uh as Xt,Vh as pt,Zh as gt,_h as kn,ai as Rt,bi as Ct,ci as un,di as zt,ei as Bt,fi as On,gi as Kt,hi as Ut,ii as jn,ji as Ht,ki as Yt,li as qt,mi as Vt,ni as Qt,oi as Gt}from"./chunk-x05zyqzf.js";import{si as fn}from"./chunk-dvv28pkc.js";import{vi as $t,yi as J}from"./chunk-dgf2xzzd.js";import{Gi as Pn,Hi as Ln}from"./chunk-r7wwr5f6.js";import{Ni as h}from"./chunk-vbwvsgs1.js";import{Yi as Tn}from"./chunk-rkdxqx8m.js";var Wt=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function Zt(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function R(n,t="MCP OAuth URL"){let M=new URL(n);if(M.username||M.password)throw Error(`${t} must not contain credentials`);if(M.protocol!=="https:"&&!(M.protocol==="http:"&&Zt(M.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return M}var U=async(n,t)=>{R(n,"MCP OAuth request URL");let M=await fetch(n,{...t,redirect:"manual"});if(M.status>=300&&M.status<400)throw await M.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return M};function k(n){let t=n.oauth;if(!t)return;let M=t;for(let u of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(M[u]!==void 0)throw Error(`MCP OAuth "${u}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(R(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((u)=>u.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let _=t.clientId?.trim();if(_&&_.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let S=t.scopes?.map((u)=>u.trim());if(S){if(S.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(S.some((u)=>!u||u.length>128||!Wt.test(u)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(S).size!==S.length)throw Error("MCP OAuth scopes must not contain duplicates")}let r=t.callbackPort;if(r!==void 0&&(!Number.isInteger(r)||r<1024||r>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,..._?{clientId:_}:{},...S?.length?{scopes:S}:{},...r!==void 0?{callbackPort:r}:{}}}import{randomUUID as v}from"node:crypto";import MM from"node:http";import{auth as cn}from"@modelcontextprotocol/sdk/client/auth.js";import _M from"open";import{createHash as Dt,randomUUID as Jt}from"node:crypto";import{constants as O,promises as L}from"node:fs";import j from"node:path";import kt from"write-file-atomic";var An=1,Ot=1048576,jt=5000,yt=50,Ft=/^[a-f0-9]{64}$/,lt=o.Object({client_id:o.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),vt=o.Object({access_token:o.String({minLength:1,maxLength:65536}),token_type:o.String({minLength:1,maxLength:64}),expires_in:o.Optional(o.Number({minimum:0})),refresh_token:o.Optional(o.String({minLength:1,maxLength:65536})),scope:o.Optional(o.String({maxLength:16384})),id_token:o.Optional(o.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),nM=o.Unsafe({type:"object",properties:{authorizationServerUrl:o.String({format:"uri"}),resourceMetadataUrl:o.Optional(o.String({format:"uri"})),resourceMetadata:o.Optional(o.Unknown()),authorizationServerMetadata:o.Optional(o.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),sn=o.Object({serverUrl:o.String({format:"uri"}),clientId:o.Optional(o.String({minLength:1,maxLength:4096})),clientInformation:o.Optional(lt),tokens:o.Optional(vt),tokenExpiresAt:o.Optional(o.Number({minimum:0})),discoveryState:o.Optional(nM),updatedAt:o.String({format:"date-time"})},{additionalProperties:!1}),En=o.Object({version:o.Literal(An),credentials:o.Record(o.String(),sn)},{additionalProperties:!1});function H(n,t){return n instanceof Error&&"code"in n&&n.code===t}function tM(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return H(t,"EPERM")}}function y(n){return structuredClone(n)}function mn(n){if(Object.keys(n.credentials).some((t)=>!Ft.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function q(n){let t=new URL(n);return t.hash="",t.toString()}function l(n,t,M=[]){return Dt("sha256").update(JSON.stringify({serverUrl:q(n),clientId:t?.trim()||null,scopes:[...M].sort()})).digest("hex")}class I{static locks=new Y;stateRoot;tokenFilePath;constructor(n=Tn()){this.stateRoot=j.join(n,"mcp"),this.tokenFilePath=j.join(this.stateRoot,"oauth-credentials.json")}static coordinationStatsForTests(){return this.locks.getStats()}async getCredential(n){return I.locks.runExclusive(this.tokenFilePath,async()=>{let M=(await this.readStore()).credentials[n];return M?y(M):null})}async updateCredential(n,t){return this.runMutation(async(M)=>{let e=M.credentials[n],_=await t(e?y(e):null);if(_)M.credentials[n]=F(sn,_);else delete M.credentials[n];return _?y(M.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return I.locks.runExclusive(this.tokenFilePath,async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return I.locks.runExclusive(this.tokenFilePath,async()=>{let t=await this.acquireStoreLock();try{let M=await this.readStore(),e=await n(M);return await this.writeStore(M),e}finally{await t()}})}async ensureStateRoot(){await L.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await L.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await L.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>Ot)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await L.readFile(this.tokenFilePath,"utf8")),M=on(En,t);if(!M.success)throw Error("MCP OAuth credential store has an invalid schema");return mn(M.data),M.data}catch(n){if(H(n,"ENOENT"))return{version:An,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=F(En,n);mn(t),await kt(this.tokenFilePath,`${JSON.stringify(t,null,2)}
|
|
2
2
|
`,{mode:384,encoding:"utf8"}),await L.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let n=j.join(this.stateRoot,".oauth-credentials.lock"),t=Jt(),M=Date.now()+jt;while(Date.now()<M)try{let e=await L.open(n,O.O_CREAT|O.O_EXCL|O.O_WRONLY,384);return await e.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:t,createdAt:new Date().toISOString()})}
|
|
3
3
|
`,"utf8"),await e.close(),async()=>{try{if(JSON.parse(await L.readFile(n,"utf8")).token===t)await L.unlink(n)}catch(_){if(!H(_,"ENOENT"))throw _}}}catch(e){if(!H(e,"EEXIST"))throw e;await this.removeDeadLock(n),await new Promise((_)=>setTimeout(_,yt))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(n){let t=await L.lstat(n);if(!t.isFile()||t.isSymbolicLink())throw Error("MCP OAuth credential lock must be a regular file");if(process.getuid&&t.uid!==process.getuid()||(t.mode&511)!==384)throw Error("MCP OAuth credential lock ownership or permissions are invalid");let M=JSON.parse(await L.readFile(n,"utf8"));if(typeof M.pid!=="number"||!Number.isInteger(M.pid)||M.pid<=0)throw Error("MCP OAuth credential lock owner is invalid");if(!tM(M.pid))await L.unlink(n)}}var bn="127.0.0.1",wn=7777,xn="/oauth/callback",eM=300000;class nn extends Error{constructor(n){super(`MCP server "${n}" requires OAuth authorization; run "blade mcp login ${n}" or use the Web MCP panel`);this.name="McpOAuthAuthorizationRequiredError"}}class an extends Error{constructor(n){super(`MCP OAuth credentials are unavailable in this runtime for server "${n}"`);this.name="McpOAuthUnavailableError"}}function rM(n){let t=n?"Authentication complete":"Authentication failed";return`<!doctype html>
|
|
4
4
|
<html lang="en">
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Pe as N}from"./chunk-
|
|
1
|
+
import{Pe as N}from"./chunk-egmexjyx.js";import{tg as $}from"./chunk-kev3cwe9.js";import{Sh as _}from"./chunk-ecd727xh.js";import{qi as Y,si as Z}from"./chunk-dvv28pkc.js";function X(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?1004l"),process.stdout.write("\x1B[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var z=Z("Service");function E(b){switch(b){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class B{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!B.instance)B.instance=new B;return B.instance}initialize(){if(this.initialized){z.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}process.on("uncaughtException",(b)=>{this.handleFatalError("uncaughtException",b)}),process.on("unhandledRejection",(b)=>{let q=b instanceof Error?b:Error(String(b));this.handleFatalError("unhandledRejection",q)}),process.on("SIGTERM",()=>{z.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)z.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else z.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
|
|
2
2
|
再按一次 Ctrl+C 退出
|
|
3
3
|
`)}),this.initialized=!0,z.debug("[GracefulShutdown] 全局错误处理器已初始化")}registerCleanup(b){return this.cleanupHandlers.push(b),z.debug(`[GracefulShutdown] 注册清理函数,当前共 ${this.cleanupHandlers.length} 个`),()=>{let q=this.cleanupHandlers.indexOf(b);if(q!==-1)this.cleanupHandlers.splice(q,1),z.debug(`[GracefulShutdown] 取消注册清理函数,剩余 ${this.cleanupHandlers.length} 个`)}}handleFatalError(b,q){if(this.isShuttingDown){console.error(`[GracefulShutdown] 退出过程中发生额外错误 (${b}):`,q);return}if(console.error(""),console.error("═".repeat(60)),console.error(`Uncaught error (${b})`),console.error("═".repeat(60)),console.error(""),console.error("错误信息:",q.message),console.error(""),q.stack)console.error("堆栈跟踪:"),console.error(q.stack);console.error(""),console.error("═".repeat(60)),console.error(""),this.shutdown(b,1)}async shutdown(b,q=0){if(this.isShuttingDown){z.debug("[GracefulShutdown] 已在退出过程中,跳过重复退出");return}this.isShuttingDown=!0;try{N().command.actions.abort("process-shutdown")}catch(A){z.warn("[GracefulShutdown] Failed to abort the active command",A)}z.info(`[GracefulShutdown] 开始优雅退出 (原因: ${b})`);let Q=setTimeout(()=>{X(),process.exit(q)},5000);Q.unref?.();let U=4000,K;try{await Promise.race([this.runCleanupHandlers(),new Promise((A,J)=>{K=setTimeout(()=>{J(Error(`清理超时 (${U}ms)`))},U),K.unref?.()})])}catch(A){console.error("[GracefulShutdown] 清理过程中发生错误:",A)}finally{if(K)clearTimeout(K)}try{let A=$.getInstance(),J=N(),V=J.session?.sessionId||"unknown",W=J.session?.workspaceRoot||_();if(A.isEnabled(W,V)){let v=J.config?.config?.permissionMode||"default";await A.executeSessionEndHooks(E(b),{projectDir:W,sessionId:V,permissionMode:v})}}catch(A){console.error("[GracefulShutdown] SessionEnd hooks 执行失败:",A)}try{await Y()}catch{}clearTimeout(Q),X(),setTimeout(()=>{process.exit(q)},100)}async runCleanupHandlers(){let b=[...this.cleanupHandlers].reverse();for(let q of b)try{let F=q();if(F instanceof Promise)await F}catch(F){console.error("[GracefulShutdown] 清理函数执行失败:",F)}}isExiting(){return this.isShuttingDown}reset(){this.isShuttingDown=!1,this.cleanupHandlers=[],this.initialized=!1}}var O=()=>{return B.getInstance()},y=(b)=>{return O().registerCleanup(b)},j=()=>{O().initialize()},C=(b=0)=>{O().shutdown("normal",b)};
|
|
4
4
|
export{O as xe,y as ye,j as ze,C as Ae};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{pd as C}from"./chunk-
|
|
1
|
+
import{pd as C}from"./chunk-jjsv2xt1.js";import{jh as F,kh as L}from"./chunk-spth418m.js";import{Mutex as G}from"async-mutex";class $ extends Error{limit;resource="resident_runtimes";retryable=!0;constructor(j){super("Session runtime capacity is full");this.limit=j;this.name="SessionRuntimeCapacityError"}}class X extends Error{constructor(){super("Session runtime residency is closed");this.name="SessionRuntimeResidencyClosedError"}}class W extends Error{constructor(j){super(`Session runtime residency already owns key: ${j}`);this.name="SessionRuntimeResidencyConflictError"}}class U{maxResident;idleMs;now;residents=new Map;reservations=new Map;operations=new G;nextGeneration=1;closed=!1;constructor(j){if(!F(j.maxResident))throw Error("Invalid max resident Session Runtime limit");if(!L(j.idleMs))throw Error("Invalid Session Runtime idle timeout");this.maxResident=j.maxResident,this.idleMs=j.idleMs,this.now=j.now??Date.now}acquire(j){let q=this.residents.get(j);if(!q||q.poisoned)return;return q.pins++,q.lastUsedAt=this.now(),this.createLease(q)}owns(j,q){let z=this.residents.get(j);return Boolean(z&&(q===void 0||z.value===q))}async reserve(j,q){if(!j.trim())throw Error("Session runtime residency key must not be blank");return this.operations.runExclusive(async()=>{if(this.closed)throw new X;if(this.residents.has(j)||this.reservations.has(j))throw new W(j);while(this.retainedCount()>=this.maxResident){if(!q.allowEviction)throw new $(this.maxResident);let H=this.oldestEvictableWebResident();if(!H)throw new $(this.maxResident);await this.disposeResident(H,!0)}let z={generation:this.allocateGeneration(),surface:q.surface};return this.reservations.set(j,z),this.createReservation(j,z)})}async remove(j,q){return this.operations.runExclusive(async()=>{let z=this.residents.get(j);if(!z||q!==void 0&&z.value!==q)return!1;if(z.pins>0)return!1;return await this.disposeResident(z,!0),!0})}async forget(j,q){return this.operations.runExclusive(async()=>{let z=this.residents.get(j);if(!z||q!==void 0&&z.value!==q||z.pins>0)return!1;return this.residents.delete(j),!0})}async sweepIdle(){return this.operations.runExclusive(async()=>{if(this.closed)return 0;let j=0;while(!0){let q=this.oldestIdleWebResident();if(!q)return j;await this.disposeResident(q,!0),j++}})}async disposeAll(){await this.operations.runExclusive(async()=>{this.closed=!0,this.reservations.clear();let j;for(let q of[...this.residents.values()])try{await this.disposeResident(q,!1)}catch(z){j??=z}if(this.residents.clear(),j!==void 0)throw j})}getStats(){let j=0;for(let q of this.residents.values())if(q.pins>0)j++;return{resident:this.residents.size,reserved:this.reservations.size,pinned:j,maxResident:this.maxResident}}retainedCount(){return this.residents.size+this.reservations.size}allocateGeneration(){let j=this.nextGeneration;return this.nextGeneration=this.nextGeneration===Number.MAX_SAFE_INTEGER?1:this.nextGeneration+1,j}createReservation(j,q){let z=!1;return{commit:(H)=>{if(z)throw new W(j);if(H.key!==j||H.surface!==q.surface||this.reservations.get(j)!==q||this.closed)throw this.reservations.delete(j),z=!0,this.closed?new X:new W(j);this.reservations.delete(j);let J={...H,generation:q.generation,pins:1,lastUsedAt:this.now(),poisoned:!1};return this.residents.set(j,J),z=!0,this.createLease(J)},cancel:()=>{if(z)return;if(this.reservations.get(j)===q)this.reservations.delete(j);z=!0}}}createLease(j){let q=!1;return{value:j.value,release:()=>{if(q)return;q=!0;let z=this.residents.get(j.key);if(z!==j||z.generation!==j.generation)return;z.pins=Math.max(0,z.pins-1),z.lastUsedAt=this.now()}}}oldestEvictableWebResident(){return this.sortedWebResidents().find((j)=>this.canEvict(j))}oldestIdleWebResident(){let j=this.now();return this.sortedWebResidents().find((q)=>j-q.lastUsedAt>=this.idleMs&&this.canEvict(q))}sortedWebResidents(){return[...this.residents.values()].filter((j)=>j.surface==="web").sort((j,q)=>j.lastUsedAt-q.lastUsedAt||j.generation-q.generation)}canEvict(j){if(j.pins>0||j.poisoned)return!1;try{return j.canEvict()}catch{return!1}}async disposeResident(j,q){if(this.residents.get(j.key)!==j)return;this.residents.delete(j.key);try{await j.dispose()}catch(z){if(q&&!this.closed&&!this.residents.has(j.key))j.lastUsedAt=this.now(),j.poisoned=!0,this.residents.set(j.key,j);throw z}}}import{createHash as B}from"node:crypto";var P=4,b=1000,Y=4000,D=120000,O=0.2;function w(j){try{return C(j)&&j.retryable}catch{return!1}}function N(j,q){let z=Number.isSafeInteger(q)&&q>0?q:1,H=z-1,J=Math.min(b*2**H,Y),K=B("sha256").update(`${j}\x00${z}`).digest().readUInt32BE(0)/4294967295,Q=1-O+2*O*K;return Math.min(Y,Math.max(0,Math.round(J*Q)))}function _(j){let q=N(j.sessionIdentity,j.failedAttempt),z=j.evidence,H=j.workStillPending===!0&&z!==void 0&&w(z.taskFailure)&&z.outputStarted===!1&&z.toolExecutionStarted===!1&&Number.isInteger(z.toolCallsCount)&&z.toolCallsCount===0,J=Number.isSafeInteger(j.failedAttempt)&&j.failedAttempt>0&&j.failedAttempt<P,Z=j.now??Date.now(),K=Z-j.recoveryStartedAt,Q=Number.isFinite(Z)&&Number.isFinite(j.recoveryStartedAt)&&Number.isFinite(K)&&K>=0&&K+q<=D;return{phase:H?J&&Q?"retry_scheduled":"exhausted":"failed",delayMs:q,retryable:H,withinAttemptBudget:J,withinTimeBudget:Q}}
|
|
2
2
|
export{$ as s,U as t,P as u,D as v,_ as w};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{m as c,n as v,o as d,p as m,q as l,r as a}from"./chunk-
|
|
1
|
+
import{m as c,n as v,o as d,p as m,q as l,r as a}from"./chunk-9r3385rd.js";import{Y as O,da as S}from"./chunk-3zdvhjsb.js";import"./chunk-ypbnczjp.js";import"./chunk-5y4b3tkr.js";import"./chunk-23v8c9b8.js";import{Gb as M,Pb as E}from"./chunk-rrjccake.js";import"./chunk-cnhw5mqv.js";import{Fd as h,Td as f}from"./chunk-jjsv2xt1.js";import"./chunk-53h87fmt.js";import"./chunk-qdv0n8yt.js";import{re as I}from"./chunk-39eq0g43.js";import{te as y,ue as R,ve as g}from"./chunk-h29mbyse.js";import{we as C}from"./chunk-bksfg23m.js";import"./chunk-ng96f4xd.js";import{Te as w}from"./chunk-egmexjyx.js";import"./chunk-v508x7cg.js";import"./chunk-pshyn3yy.js";import"./chunk-q2exry0f.js";import"./chunk-tj2efrs1.js";import"./chunk-hv6hrsnk.js";import"./chunk-cebfh25a.js";import"./chunk-yzmgf1vc.js";import"./chunk-cqqmkwvn.js";import"./chunk-9g64g1np.js";import"./chunk-935v0gpc.js";import"./chunk-kev3cwe9.js";import"./chunk-eyb9psbc.js";import"./chunk-spth418m.js";import{Ch as A}from"./chunk-4w4wjm49.js";import"./chunk-6k5k40p8.js";import"./chunk-p3m1jyg5.js";import{Sh as P}from"./chunk-ecd727xh.js";import"./chunk-x05zyqzf.js";import"./chunk-dvv28pkc.js";import"./chunk-dgf2xzzd.js";import"./chunk-z52s82k7.js";import"./chunk-r7wwr5f6.js";import"./chunk-vbwvsgs1.js";import"./chunk-sr10jsjs.js";import"./chunk-rkdxqx8m.js";import"./chunk-tf7ezqew.js";import s from"yargs";import{hideBin as e}from"yargs/helpers";var i=new Set(Object.values(A));function t(j){if(j&&i.has(j))return j;return}function z(j){if(j.options.outputFormat==="json")j.io.stdout.write(`${JSON.stringify({response:j.response,...j.structuredOutput?{structured_output:j.structuredOutput,output_schema_digest:j.structuredOutputSchemaDigest}:{},input:j.requestInput,model:j.options.model,timestamp:new Date().toISOString()},null,2)}
|
|
2
2
|
`);else if(j.options.outputFormat==="stream-json")j.io.stdout.write(`${JSON.stringify(j.structuredOutput?{type:"structured_output",output:j.structuredOutput,schema_digest:j.structuredOutputSchemaDigest}:{type:"response",content:j.response})}
|
|
3
3
|
`);else j.io.stdout.write(`${j.response}
|
|
4
4
|
`)}function n(j){return j.command("* [message]","Print response and exit (useful for pipes)",(B)=>B.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(B)=>{if(!B.p)return;let q=await o(B);process.exit(q)})}async function o(j,B=process){let q;try{await c();let D=j.forkSession!==!0&&(j.continue===!0||typeof j.resume==="string"&&j.resume.length>0)?await d({message:j.message,_:j._}):await v({message:j.message,_:j._,defaultMessage:"Hello"}),K=D===void 0,T=K?{mode:"agent",content:""}:await m(D);if(T.mode==="output"){if(T.content)B.stdout.write(`${T.content}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as T,b as W,c as X,d as Y}from"./chunk-
|
|
1
|
+
import{a as T,b as W,c as X,d as Y}from"./chunk-nqgsh5ew.js";import"./chunk-3pwq56je.js";import"./chunk-xv3a1se1.js";import"./chunk-w3wsder6.js";import"./chunk-176zc8a3.js";import"./chunk-0cmykdaz.js";import"./chunk-3zdvhjsb.js";import"./chunk-ypbnczjp.js";import"./chunk-5y4b3tkr.js";import"./chunk-23v8c9b8.js";import"./chunk-rrjccake.js";import"./chunk-cnhw5mqv.js";import"./chunk-jjsv2xt1.js";import"./chunk-53h87fmt.js";import"./chunk-qdv0n8yt.js";import{ye as R}from"./chunk-v4nankr5.js";import"./chunk-ng96f4xd.js";import{Ue as Q}from"./chunk-egmexjyx.js";import"./chunk-v508x7cg.js";import"./chunk-pshyn3yy.js";import"./chunk-q2exry0f.js";import"./chunk-tj2efrs1.js";import"./chunk-hv6hrsnk.js";import"./chunk-cebfh25a.js";import"./chunk-yzmgf1vc.js";import"./chunk-cqqmkwvn.js";import"./chunk-9g64g1np.js";import"./chunk-935v0gpc.js";import"./chunk-kev3cwe9.js";import"./chunk-eyb9psbc.js";import"./chunk-spth418m.js";import"./chunk-4w4wjm49.js";import"./chunk-6k5k40p8.js";import"./chunk-p3m1jyg5.js";import"./chunk-ecd727xh.js";import"./chunk-x05zyqzf.js";import"./chunk-dvv28pkc.js";import"./chunk-dgf2xzzd.js";import"./chunk-z52s82k7.js";import{Gi as M}from"./chunk-r7wwr5f6.js";import"./chunk-vbwvsgs1.js";import"./chunk-sr10jsjs.js";import"./chunk-rkdxqx8m.js";import"./chunk-tf7ezqew.js";import m from"chalk";import K from"open";var A=`
|
|
2
2
|
____ _ _
|
|
3
3
|
| __ )| | __ _ __| | ___
|
|
4
4
|
| _ \\| |/ _\` |/ _\` |/ _ \\
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{m as yH,n as bH,o as IH,p as RH,q as gH,r as kH}from"./chunk-8pr55zfw.js";import{A as KH,B as VH,C as p,D as ZH,y as TH,z as JH}from"./chunk-agpbarbx.js";import{$ as FH,E as XH,Y as GH,_ as PH,da as EH}from"./chunk-4je46cyf.js";import"./chunk-ypbnczjp.js";import"./chunk-vvhnv7ng.js";import"./chunk-23v8c9b8.js";import{Gb as UH,Pb as _H,ub as r}from"./chunk-exv2prhq.js";import"./chunk-cnhw5mqv.js";import{Id as m,Td as s,td as jH,xd as xH}from"./chunk-tk7yfgay.js";import"./chunk-53h87fmt.js";import"./chunk-qdv0n8yt.js";import{re as zH}from"./chunk-1n23f3qb.js";import{te as fH,ue as AH,ve as SH}from"./chunk-ep657gs0.js";import{we as MH}from"./chunk-bksfg23m.js";import"./chunk-ng96f4xd.js";import{We as WH}from"./chunk-3y8qp69k.js";import"./chunk-v508x7cg.js";import"./chunk-pshyn3yy.js";import"./chunk-q2exry0f.js";import"./chunk-tj2efrs1.js";import"./chunk-hv6hrsnk.js";import"./chunk-h25qd3d7.js";import"./chunk-g4ftk610.js";import{hg as qH}from"./chunk-cqqmkwvn.js";import"./chunk-9g64g1np.js";import"./chunk-935v0gpc.js";import"./chunk-zh2vrkyt.js";import"./chunk-eyb9psbc.js";import"./chunk-zkrtn8b1.js";import{Ch as DH}from"./chunk-4w4wjm49.js";import{Eh as LH,Gh as H,Hh as $H,Jh as N}from"./chunk-6k5k40p8.js";import{Nh as i,Oh as o}from"./chunk-p3m1jyg5.js";import{Sh as k}from"./chunk-ecd727xh.js";import"./chunk-x05zyqzf.js";import"./chunk-dvv28pkc.js";import"./chunk-dgf2xzzd.js";import"./chunk-z52s82k7.js";import"./chunk-s6xw42mr.js";import"./chunk-vbwvsgs1.js";import"./chunk-sr10jsjs.js";import"./chunk-rkdxqx8m.js";import"./chunk-tf7ezqew.js";import IJ from"yargs";import{hideBin as RJ}from"yargs/helpers";function v(K,V,Q){if(K.off){K.off(V,Q);return}K.removeListener?.(V,Q)}function dH(K,V){if(!K.once&&!K.on||!K.off&&!K.removeListener)throw Error("Writable returned false without an observable drain contract");return new Promise((Q,X)=>{let J=!1,Z=()=>{v(K,"drain",x),v(K,"error",j),V.removeEventListener("abort",P)},W=(F)=>{if(J)return;J=!0,Z(),F()},x=()=>W(Q),j=(F)=>W(()=>X(F??Error("Writable emitted an error"))),P=()=>W(()=>X(V.reason??Error("Writable drain aborted")));if(V.aborted){P();return}let T=K.once?.bind(K)??K.on?.bind(K);T?.("drain",x),T?.("error",j),V.addEventListener("abort",P,{once:!0})})}async function pH(K,V,Q){if(K.destroyed||K.writableEnded)throw Error("Writable is already closed");if(K.write(V)===!1)await dH(K,Q)}class l{options;queues;sinkErrorListeners=[];failed=!1;closing=!1;handleAbort=()=>{this.fail(new p("aborted","Headless output was aborted",{cause:this.options.signal?.reason}))};constructor(K,V={}){this.options=V;let Q=(X)=>new ZH({maxPendingItems:V.maxPendingItems??JH,maxPendingBytes:V.maxPendingBytes??KH,writeTimeoutMs:V.writeTimeoutMs??VH,sizeOf:(J)=>Buffer.byteLength(J),write:(J,Z)=>pH(K[X],J,Z),onFailure:(J)=>this.fail(J)});if(this.queues={stdout:Q("stdout"),stderr:Q("stderr")},this.observeSinkErrors(K.stdout),K.stderr!==K.stdout)this.observeSinkErrors(K.stderr);if(V.signal?.addEventListener("abort",this.handleAbort,{once:!0}),V.signal?.aborted)this.handleAbort()}write(K,V){return this.queues[K].offer(V).accepted}async flush(){await Promise.all([this.queues.stdout.flush(),this.queues.stderr.flush()])}close(K){if(this.closing||this.failed)return;this.closing=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(K),this.queues.stderr.close(K)}stats(){return{stdout:this.queues.stdout.stats(),stderr:this.queues.stderr.stats()}}observeSinkErrors(K){if(!K.on||!K.off&&!K.removeListener)return;let V=(Q)=>{this.fail(new p("write_failed","Headless writable failed",{cause:Q??Error("Writable emitted an error")}))};K.on("error",V),this.sinkErrorListeners.push({writer:K,listener:V})}fail(K){if(this.closing||this.failed)return;this.failed=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(K),this.queues.stderr.close(K),this.options.onFailure?.(K)}removeSinkErrorListeners(){for(let{writer:K,listener:V}of this.sinkErrorListeners.splice(0))v(K,"error",V)}}var YH=1;function D(K){return H.Object({event_version:H.Literal(YH),...K})}var vH=D({type:H.Literal("content_delta"),delta:H.String()}),lH=D({type:H.Literal("thinking_delta"),delta:H.String()}),aH=D({type:H.Literal("thinking"),content:H.String()}),iH=D({type:H.Literal("stream_end")}),oH=D({type:H.Literal("content"),content:H.String()}),sH=D({type:H.Literal("structured_output"),output:H.Record(H.String(),H.Unknown()),schema_digest:H.String({pattern:"^[a-f0-9]{64}$"})}),a=N(["readonly","write","execute"]),rH=H.Object({kind:a,scope:N(["global","session"]),queue_position:H.Integer({minimum:1}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:1})}),nH=D({type:H.Literal("tool_start"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(a)}),tH=D({type:H.Literal("tool_progress"),tool_name:H.String(),message:H.String(),progress:H.Optional(H.Number()),total:H.Optional(H.Number()),admission:H.Optional(rH)}),eH=H.Object({auto_backgrounded:H.Literal(!0),background_reason:H.Literal("foreground_budget"),foreground_budget_ms:H.Integer({minimum:1}),shell_id:H.String({minLength:1,maxLength:128,pattern:"^bash_[A-Za-z0-9-]+$"}),pid:H.Optional(H.Integer({minimum:1})),terminal_transport:N(["local","acp"])}),HJ=D({type:H.Literal("tool_result"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(a),success:H.Optional(H.Boolean()),error_type:H.Optional(H.String()),error_message:H.Optional(H.String()),background:H.Optional(eH)}),JJ=D({type:H.Literal("mcp_catalog_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),KJ=D({type:H.Literal("mcp_content_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),content_kind:N(["resources","resource_templates","prompts"]),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),VJ=D({type:H.Literal("mcp_resource_updated"),revision:H.Integer({minimum:1}),server_name:H.String(),uri:H.String()}),ZJ=D({type:H.Literal("mcp_connection_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),phase:N(["reconnecting","recovered","failed"]),reason:H.String(),attempt:H.Integer({minimum:0}),max_attempts:H.Integer({minimum:0}),next_retry_at:H.Optional(H.Integer({minimum:0})),error:H.Optional(H.String())}),$J=D({type:H.Literal("mcp_log"),revision:H.Integer({minimum:1}),server_name:H.String(),level:N(["debug","info","notice","warning","error","critical","alert","emergency"]),logger:H.Optional(H.String()),message:H.String(),projected_bytes:H.Integer({minimum:0}),data_sha256:H.String(),truncated:H.Boolean(),details_omitted:H.Boolean(),timestamp:H.Integer({minimum:0}),synthetic:H.Optional(H.Boolean())}),qJ=D({type:H.Literal("mcp_instructions_changed"),revision:H.Integer({minimum:0}),server_name:H.String(),action:N(["added","removed"]),reason:N(["snapshot","connection","disconnection"]),text:H.Optional(H.String()),source_bytes:H.Optional(H.Integer({minimum:0})),projected_bytes:H.Optional(H.Integer({minimum:0})),sha256:H.Optional(H.String()),truncated:H.Optional(H.Boolean()),details_omitted:H.Optional(H.Boolean())}),XJ=D({type:H.Literal("mcp_task_changed"),revision:H.Integer({minimum:0}),task_id:H.String(),server_name:H.String(),tool_name:H.String(),status:N(["working","input_required","interrupted","completed","failed","cancelled"]),status_message:H.Optional(H.String()),created_at:H.Integer({minimum:0}),updated_at:H.Integer({minimum:0}),completed_at:H.Optional(H.Integer({minimum:0})),has_result:H.Boolean(),error:H.Optional(H.String())}),YJ=D({type:H.Literal("project_rules_loaded"),files:H.Array(H.Object({id:H.String(),relative_path:H.String(),source:N(["project","local"]),conditional:H.Boolean(),content_sha256:H.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:H.Array(H.String()),blocked_write:H.Boolean()}),BJ=D({type:H.Literal("user_shell_started"),execution_id:H.String(),command:H.String(),auxiliary:H.Boolean()}),NJ=D({type:H.Literal("user_shell_output"),execution_id:H.String(),stream:N(["stdout","stderr"]),chunk:H.String(),stream_truncated:H.Boolean()}),QJ=D({type:H.Literal("user_shell_completed"),execution_id:H.String(),message_id:H.String(),status:N(["completed","failed","aborted","timed_out","spawn_error"]),exit_code:H.Union([H.Integer(),H.Null()]),duration_ms:H.Number({minimum:0}),stdout:H.String(),stderr:H.String(),truncated:H.Boolean(),auxiliary:H.Boolean()}),DJ=D({type:H.Literal("phase"),phase:N(["turn","searching","inspecting","target_hit","executing","completed"]),status:N(["ongoing","hit","done"]),message:H.String(),turn:H.Optional(H.Number()),tool_name:H.Optional(H.String()),target:H.Optional(H.String())}),LJ=D({type:H.Literal("tool_detail"),tool_name:H.String(),detail:H.String()}),WJ=D({type:H.Literal("task_update"),tasks:H.Array(XH)}),jJ=D({type:H.Literal("goal_frontier"),goal_id:H.String({minLength:1}),status:N(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"]),task_list_id:H.String({minLength:1,maxLength:256}),total:H.Integer({minimum:0}),completed:H.Integer({minimum:0}),in_progress:H.Integer({minimum:0}),pending:H.Integer({minimum:0}),blocked:H.Integer({minimum:0}),next_task:H.Optional(H.Object({id:H.String({minLength:1}),subject:H.String({minLength:1,maxLength:512}),priority:N(["high","medium","low"])})),digest_sha256:H.String({pattern:"^[a-f0-9]{64}$"}),observed_at:H.String(),stall_category:H.Optional(N(["waiting_dependency","same_task_no_effect","repeated_deferral"])),stall_count:H.Optional(H.Integer({minimum:1,maximum:3}))}),xJ=D({type:H.Literal("goal"),state:N(["updated","cleared"]),goal_id:H.Optional(H.String()),status:H.Optional(N(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"])),verification_attempt:H.Optional(H.Integer({minimum:1})),verification_status:H.Optional(N(["pending","pass","fail","partial"])),verifier_session_id:H.Optional(H.String()),verification_evidence_sha256:H.Optional(H.String({pattern:"^[a-f0-9]{64}$"})),verification_summary:H.Optional(H.String()),verification_stall_count:H.Optional(H.Integer({minimum:1})),premature_stop_pattern:H.Optional(N(qH)),premature_stop_count:H.Optional(H.Integer({minimum:1})),frontier_stall_category:H.Optional(N(["waiting_dependency","same_task_no_effect","repeated_deferral"])),frontier_stall_count:H.Optional(H.Integer({minimum:1,maximum:3}))}),UJ=D({type:H.Literal("subagent"),state:N(["spawned","completed"]),session_id:H.String(),subagent_type:H.Optional(H.String()),success:H.Optional(H.Boolean()),summary:H.Optional(H.String()),verification_verdict:H.Optional(N(["pass","fail","partial"])),resumed_from:H.Optional(H.String()),root_agent_id:H.Optional(H.String()),resume_depth:H.Optional(H.Integer({minimum:0}))}),_J=D({type:H.Literal("token_usage"),input_tokens:H.Number(),output_tokens:H.Number(),total_tokens:H.Number(),max_context_tokens:H.Number(),cache_read_tokens:H.Optional(H.Number()),cache_write_tokens:H.Optional(H.Number()),prompt_cache_break:H.Optional(H.Object({reason:N(["model_changed","system_prompt_changed","tools_changed","request_policy_changed","ttl_expired","server_side"]),previous_cache_read_tokens:H.Number(),cache_read_tokens:H.Number(),cache_write_tokens:H.Number(),token_drop:H.Number(),elapsed_ms:H.Number(),call_number:H.Number(),system_prompt_changed:H.Boolean(),system_char_delta:H.Number(),tools_changed:H.Boolean(),added_tool_count:H.Number(),removed_tool_count:H.Number(),changed_tool_count:H.Number(),model_changed:H.Boolean(),request_policy_changed:H.Boolean()})),cost_usd:H.Optional(H.Number())}),GJ=D({type:H.Literal("compacting"),state:N(["started","completed"]),reason:H.Optional(N(["threshold","context_limit","turn_limit","manual"])),strategy:H.Optional(N(["llm","fallback","snip"])),outcome:H.Optional(N(["completed","fallback","failed"])),pre_tokens:H.Optional(H.Number({minimum:0})),pre_token_source:H.Optional(N(["provider","provider_plus_estimate","local_estimate"])),estimated_pending_tokens:H.Optional(H.Number({minimum:0})),post_tokens:H.Optional(H.Number({minimum:0})),sample_attempts:H.Optional(H.Integer({minimum:0})),input_reductions:H.Optional(H.Integer({minimum:0})),messages_omitted:H.Optional(H.Integer({minimum:0})),files_omitted:H.Optional(H.Integer({minimum:0})),images_omitted:H.Optional(H.Integer({minimum:0})),fallback_target_tokens:H.Optional(H.Integer({minimum:0})),fallback_messages_omitted:H.Optional(H.Integer({minimum:0})),fallback_messages_truncated:H.Optional(H.Integer({minimum:0})),failure_reason:H.Optional(N(["circuit_open","context_exhausted","deterministic","empty_exhausted","insufficient_reduction","transient_exhausted"]))}),PJ=D({type:H.Literal("provider_retry"),phase:N(["scheduled","waiting","attempt","recovered","exhausted"]),attempt:H.Integer({minimum:0}),max_retries:H.Integer({minimum:0}),reason:N(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),delay_ms:H.Optional(H.Integer({minimum:0})),next_retry_at:H.Optional(H.Integer({minimum:0})),mode:H.Optional(N(["standard","bounded_foreground"])),recovery_budget_ms:H.Optional(H.Integer({minimum:0})),recovery_elapsed_ms:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0})),exhausted_by:H.Optional(N(["attempt_limit","recovery_budget"]))}),FJ=D({type:H.Literal("provider_admission"),phase:N(["queued","admitted","rejected"]),request_class:N(["foreground","background","internal"]),resource:N(["stream","pending_count","pending_bytes"]),scope:N(["global","domain","owner","class"]),reason:H.Optional(N(["capacity","queue_full","wait_timeout","closed"])),queue_position:H.Integer({minimum:0}),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:0}),wait_ms:H.Integer({minimum:0}),max_wait_ms:H.Integer({minimum:0}),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),EJ=D({type:H.Literal("provider_circuit"),phase:N(["opened","waiting","probe","closed","reopened","rejected"]),reason:N(["rate_limit","server_error","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),retry_after_ms:H.Optional(H.Integer({minimum:0})),next_probe_at:H.Optional(H.Integer({minimum:0})),open_duration_ms:H.Integer({minimum:0}),sample_count:H.Optional(H.Integer({minimum:0})),failure_count:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),MJ=D({type:H.Literal("provider_stall"),phase:N(["detected","recovered"]),stall_count:H.Integer({minimum:1}),duration_ms:H.Integer({minimum:0}),warning_after_ms:H.Integer({minimum:1}),timeout_ms:H.Integer({minimum:1}),output_started:H.Boolean()}),zJ=D({type:H.Literal("action_stationarity"),phase:N(["detected","recovered","halted"]),tool_name:H.String(),run_length:H.Integer({minimum:1}),nudge_threshold:H.Integer({minimum:1}),halt_threshold:H.Integer({minimum:1}),progress_aware:H.Boolean()}),fJ=D({type:H.Literal("turn_recovery"),state:N(["completed","resumable","requires_attention"]),turn_id:H.String({minLength:1}),input_message_count:H.Integer({minimum:0}),reason:H.Optional(N(["successful_tool_result","interrupted_tool_call"]))}),AJ=D({type:H.Literal("turn_limit"),turns_count:H.Number(),action:H.Literal("continue")}),SJ=D({type:H.Literal("task_session"),session_id:H.String(),project_path:H.String(),source_project_path:H.String(),isolation:N(["local","worktree"]),worktree_branch:H.Optional(H.String()),base_commit:H.Optional(H.String())}),TJ=D({type:H.Literal("task_admission"),state:N(["queued","running"]),queue_position:H.Optional(H.Integer({minimum:1})),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),max_concurrent_tasks:H.Integer({minimum:1})}),yJ=D({type:H.Literal("output"),content:H.String(),exit_code:H.Number()}),bJ=D({type:H.Literal("error"),message:H.String()}),eJ=$H(H.Union([vH,lH,aH,iH,oH,sH,nH,tH,HJ,JJ,KJ,VJ,ZJ,$J,qJ,XJ,YJ,BJ,NJ,QJ,DJ,LJ,WJ,jJ,xJ,UJ,_J,GJ,FJ,EJ,PJ,MJ,zJ,fJ,AJ,SJ,TJ,yJ,bJ]));function BH(K,V){return{event_version:YH,type:K,...V}}function gJ(K){if(!K||typeof K!=="object"||Array.isArray(K))return;let V=K;if(V.auto_backgrounded!==!0||V.background_reason!=="foreground_budget"||!Number.isSafeInteger(V.foreground_budget_ms)||V.foreground_budget_ms<=0||typeof V.shell_id!=="string"||!/^bash_[A-Za-z0-9-]+$/.test(V.shell_id)||V.shell_id.length>128||V.terminal_transport!=="local"&&V.terminal_transport!=="acp"||V.pid!==void 0&&(!Number.isSafeInteger(V.pid)||V.pid<=0))return;return{auto_backgrounded:!0,background_reason:"foreground_budget",foreground_budget_ms:V.foreground_budget_ms,shell_id:V.shell_id,...V.pid===void 0?{}:{pid:V.pid},terminal_transport:V.terminal_transport}}function kJ(K){let V=new AbortController,Q=(Z)=>{if(!V.signal.aborted)V.abort(Z)},X=()=>Q("interrupt"),J=()=>Q(K?.signal?.reason);if(K?.signal){if(K.signal.addEventListener("abort",J,{once:!0}),K.signal.aborted)J()}else process.once("SIGINT",X),process.once("SIGTERM",X);return{signal:V.signal,abort:Q,dispose:()=>{K?.signal?.removeEventListener("abort",J),process.removeListener("SIGINT",X),process.removeListener("SIGTERM",X)}}}var CJ=N(["text","jsonl"]),hJ=H.Object({headless:H.Optional(H.Boolean()),message:H.Optional(H.String()),_:H.Optional(H.Array(H.Union([H.String(),H.Number()]))),model:H.Optional(H.String()),systemPrompt:H.Optional(H.String()),appendSystemPrompt:H.Optional(H.String()),verificationAgent:H.Optional(H.Boolean()),maxTurns:H.Optional(H.Refine(H.Integer(),(K)=>K===-1||K>0,()=>"must be -1 (unlimited) or a positive integer")),permissionMode:H.Optional(H.Enum(DH)),mcpConfig:H.Optional(H.Array(H.String())),strictMcpConfig:H.Optional(H.Boolean()),sessionId:H.Optional(H.String()),allowedTools:H.Optional(H.Array(H.String())),disallowedTools:H.Optional(H.Array(H.String())),agents:H.Optional(H.String()),continue:H.Optional(H.Boolean()),resume:H.Optional(H.Union([H.String(),H.Boolean()])),forkSession:H.Optional(H.Boolean()),taskIsolation:H.Optional(N(["local","worktree"])),outputFormat:H.Optional(CJ),jsonSchema:H.Optional(H.String()),outputSchema:H.Optional(H.String())});class CH{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(K){this.openedThinking=K}hasOpenThinking(){return this.openedThinking}completeStream(){let K={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,K}}function OJ(K){return K.issues.map((V)=>`${V.path.join(".")||"options"}: ${V.message}`).join("; ")}function wJ(K){let V=LH(hJ,K);if(!V.success)throw Error(`Invalid headless options: ${OJ(V.error)}`);return V.data}function mJ(K){return K.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(V)=>V.positional("message",{describe:"Message to process",type:"string"}).option("headless",{type:"boolean",describe:"Run full agent loop without Ink UI and print events to the terminal"}).option("model",{describe:"Model ID for this run",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("verification-agent",{describe:"Run the built-in independent verification agent after non-trivial changes",type:"boolean",default:!0}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}).option("output-format",{alias:["outputFormat"],choices:["text","jsonl"],describe:"Headless output format",type:"string"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("task-isolation",{alias:["taskIsolation"],choices:["local","worktree"],describe:"Dispatch a new durable task in the selected workspace mode",type:"string"}),async(V)=>{if(!V.headless)return;let Q=await lJ(V);process.exit(Q)})}function L(K,V=""){K.write(`${V}
|
|
1
|
+
import{m as yH,n as bH,o as IH,p as RH,q as gH,r as kH}from"./chunk-9r3385rd.js";import{A as KH,B as VH,C as p,D as ZH,y as TH,z as JH}from"./chunk-0cmykdaz.js";import{$ as FH,E as XH,Y as GH,_ as PH,da as EH}from"./chunk-3zdvhjsb.js";import"./chunk-ypbnczjp.js";import"./chunk-5y4b3tkr.js";import"./chunk-23v8c9b8.js";import{Gb as UH,Pb as _H,ub as r}from"./chunk-rrjccake.js";import"./chunk-cnhw5mqv.js";import{Id as m,Td as s,td as jH,xd as xH}from"./chunk-jjsv2xt1.js";import"./chunk-53h87fmt.js";import"./chunk-qdv0n8yt.js";import{re as zH}from"./chunk-39eq0g43.js";import{te as fH,ue as AH,ve as SH}from"./chunk-h29mbyse.js";import{we as MH}from"./chunk-bksfg23m.js";import"./chunk-ng96f4xd.js";import{We as WH}from"./chunk-egmexjyx.js";import"./chunk-v508x7cg.js";import"./chunk-pshyn3yy.js";import"./chunk-q2exry0f.js";import"./chunk-tj2efrs1.js";import"./chunk-hv6hrsnk.js";import"./chunk-cebfh25a.js";import"./chunk-yzmgf1vc.js";import{hg as qH}from"./chunk-cqqmkwvn.js";import"./chunk-9g64g1np.js";import"./chunk-935v0gpc.js";import"./chunk-kev3cwe9.js";import"./chunk-eyb9psbc.js";import"./chunk-spth418m.js";import{Ch as DH}from"./chunk-4w4wjm49.js";import{Eh as LH,Gh as H,Hh as $H,Jh as N}from"./chunk-6k5k40p8.js";import{Nh as i,Oh as o}from"./chunk-p3m1jyg5.js";import{Sh as k}from"./chunk-ecd727xh.js";import"./chunk-x05zyqzf.js";import"./chunk-dvv28pkc.js";import"./chunk-dgf2xzzd.js";import"./chunk-z52s82k7.js";import"./chunk-r7wwr5f6.js";import"./chunk-vbwvsgs1.js";import"./chunk-sr10jsjs.js";import"./chunk-rkdxqx8m.js";import"./chunk-tf7ezqew.js";import IJ from"yargs";import{hideBin as RJ}from"yargs/helpers";function v(K,V,Q){if(K.off){K.off(V,Q);return}K.removeListener?.(V,Q)}function dH(K,V){if(!K.once&&!K.on||!K.off&&!K.removeListener)throw Error("Writable returned false without an observable drain contract");return new Promise((Q,X)=>{let J=!1,Z=()=>{v(K,"drain",x),v(K,"error",j),V.removeEventListener("abort",P)},W=(F)=>{if(J)return;J=!0,Z(),F()},x=()=>W(Q),j=(F)=>W(()=>X(F??Error("Writable emitted an error"))),P=()=>W(()=>X(V.reason??Error("Writable drain aborted")));if(V.aborted){P();return}let T=K.once?.bind(K)??K.on?.bind(K);T?.("drain",x),T?.("error",j),V.addEventListener("abort",P,{once:!0})})}async function pH(K,V,Q){if(K.destroyed||K.writableEnded)throw Error("Writable is already closed");if(K.write(V)===!1)await dH(K,Q)}class l{options;queues;sinkErrorListeners=[];failed=!1;closing=!1;handleAbort=()=>{this.fail(new p("aborted","Headless output was aborted",{cause:this.options.signal?.reason}))};constructor(K,V={}){this.options=V;let Q=(X)=>new ZH({maxPendingItems:V.maxPendingItems??JH,maxPendingBytes:V.maxPendingBytes??KH,writeTimeoutMs:V.writeTimeoutMs??VH,sizeOf:(J)=>Buffer.byteLength(J),write:(J,Z)=>pH(K[X],J,Z),onFailure:(J)=>this.fail(J)});if(this.queues={stdout:Q("stdout"),stderr:Q("stderr")},this.observeSinkErrors(K.stdout),K.stderr!==K.stdout)this.observeSinkErrors(K.stderr);if(V.signal?.addEventListener("abort",this.handleAbort,{once:!0}),V.signal?.aborted)this.handleAbort()}write(K,V){return this.queues[K].offer(V).accepted}async flush(){await Promise.all([this.queues.stdout.flush(),this.queues.stderr.flush()])}close(K){if(this.closing||this.failed)return;this.closing=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(K),this.queues.stderr.close(K)}stats(){return{stdout:this.queues.stdout.stats(),stderr:this.queues.stderr.stats()}}observeSinkErrors(K){if(!K.on||!K.off&&!K.removeListener)return;let V=(Q)=>{this.fail(new p("write_failed","Headless writable failed",{cause:Q??Error("Writable emitted an error")}))};K.on("error",V),this.sinkErrorListeners.push({writer:K,listener:V})}fail(K){if(this.closing||this.failed)return;this.failed=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(K),this.queues.stderr.close(K),this.options.onFailure?.(K)}removeSinkErrorListeners(){for(let{writer:K,listener:V}of this.sinkErrorListeners.splice(0))v(K,"error",V)}}var YH=1;function D(K){return H.Object({event_version:H.Literal(YH),...K})}var vH=D({type:H.Literal("content_delta"),delta:H.String()}),lH=D({type:H.Literal("thinking_delta"),delta:H.String()}),aH=D({type:H.Literal("thinking"),content:H.String()}),iH=D({type:H.Literal("stream_end")}),oH=D({type:H.Literal("content"),content:H.String()}),sH=D({type:H.Literal("structured_output"),output:H.Record(H.String(),H.Unknown()),schema_digest:H.String({pattern:"^[a-f0-9]{64}$"})}),a=N(["readonly","write","execute"]),rH=H.Object({kind:a,scope:N(["global","session"]),queue_position:H.Integer({minimum:1}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:1})}),nH=D({type:H.Literal("tool_start"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(a)}),tH=D({type:H.Literal("tool_progress"),tool_name:H.String(),message:H.String(),progress:H.Optional(H.Number()),total:H.Optional(H.Number()),admission:H.Optional(rH)}),eH=H.Object({auto_backgrounded:H.Literal(!0),background_reason:H.Literal("foreground_budget"),foreground_budget_ms:H.Integer({minimum:1}),shell_id:H.String({minLength:1,maxLength:128,pattern:"^bash_[A-Za-z0-9-]+$"}),pid:H.Optional(H.Integer({minimum:1})),terminal_transport:N(["local","acp"])}),HJ=D({type:H.Literal("tool_result"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(a),success:H.Optional(H.Boolean()),error_type:H.Optional(H.String()),error_message:H.Optional(H.String()),background:H.Optional(eH)}),JJ=D({type:H.Literal("mcp_catalog_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),KJ=D({type:H.Literal("mcp_content_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),content_kind:N(["resources","resource_templates","prompts"]),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),VJ=D({type:H.Literal("mcp_resource_updated"),revision:H.Integer({minimum:1}),server_name:H.String(),uri:H.String()}),ZJ=D({type:H.Literal("mcp_connection_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),phase:N(["reconnecting","recovered","failed"]),reason:H.String(),attempt:H.Integer({minimum:0}),max_attempts:H.Integer({minimum:0}),next_retry_at:H.Optional(H.Integer({minimum:0})),error:H.Optional(H.String())}),$J=D({type:H.Literal("mcp_log"),revision:H.Integer({minimum:1}),server_name:H.String(),level:N(["debug","info","notice","warning","error","critical","alert","emergency"]),logger:H.Optional(H.String()),message:H.String(),projected_bytes:H.Integer({minimum:0}),data_sha256:H.String(),truncated:H.Boolean(),details_omitted:H.Boolean(),timestamp:H.Integer({minimum:0}),synthetic:H.Optional(H.Boolean())}),qJ=D({type:H.Literal("mcp_instructions_changed"),revision:H.Integer({minimum:0}),server_name:H.String(),action:N(["added","removed"]),reason:N(["snapshot","connection","disconnection"]),text:H.Optional(H.String()),source_bytes:H.Optional(H.Integer({minimum:0})),projected_bytes:H.Optional(H.Integer({minimum:0})),sha256:H.Optional(H.String()),truncated:H.Optional(H.Boolean()),details_omitted:H.Optional(H.Boolean())}),XJ=D({type:H.Literal("mcp_task_changed"),revision:H.Integer({minimum:0}),task_id:H.String(),server_name:H.String(),tool_name:H.String(),status:N(["working","input_required","interrupted","completed","failed","cancelled"]),status_message:H.Optional(H.String()),created_at:H.Integer({minimum:0}),updated_at:H.Integer({minimum:0}),completed_at:H.Optional(H.Integer({minimum:0})),has_result:H.Boolean(),error:H.Optional(H.String())}),YJ=D({type:H.Literal("project_rules_loaded"),files:H.Array(H.Object({id:H.String(),relative_path:H.String(),source:N(["project","local"]),conditional:H.Boolean(),content_sha256:H.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:H.Array(H.String()),blocked_write:H.Boolean()}),BJ=D({type:H.Literal("user_shell_started"),execution_id:H.String(),command:H.String(),auxiliary:H.Boolean()}),NJ=D({type:H.Literal("user_shell_output"),execution_id:H.String(),stream:N(["stdout","stderr"]),chunk:H.String(),stream_truncated:H.Boolean()}),QJ=D({type:H.Literal("user_shell_completed"),execution_id:H.String(),message_id:H.String(),status:N(["completed","failed","aborted","timed_out","spawn_error"]),exit_code:H.Union([H.Integer(),H.Null()]),duration_ms:H.Number({minimum:0}),stdout:H.String(),stderr:H.String(),truncated:H.Boolean(),auxiliary:H.Boolean()}),DJ=D({type:H.Literal("phase"),phase:N(["turn","searching","inspecting","target_hit","executing","completed"]),status:N(["ongoing","hit","done"]),message:H.String(),turn:H.Optional(H.Number()),tool_name:H.Optional(H.String()),target:H.Optional(H.String())}),LJ=D({type:H.Literal("tool_detail"),tool_name:H.String(),detail:H.String()}),WJ=D({type:H.Literal("task_update"),tasks:H.Array(XH)}),jJ=D({type:H.Literal("goal_frontier"),goal_id:H.String({minLength:1}),status:N(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"]),task_list_id:H.String({minLength:1,maxLength:256}),total:H.Integer({minimum:0}),completed:H.Integer({minimum:0}),in_progress:H.Integer({minimum:0}),pending:H.Integer({minimum:0}),blocked:H.Integer({minimum:0}),next_task:H.Optional(H.Object({id:H.String({minLength:1}),subject:H.String({minLength:1,maxLength:512}),priority:N(["high","medium","low"])})),digest_sha256:H.String({pattern:"^[a-f0-9]{64}$"}),observed_at:H.String(),stall_category:H.Optional(N(["waiting_dependency","same_task_no_effect","repeated_deferral"])),stall_count:H.Optional(H.Integer({minimum:1,maximum:3}))}),xJ=D({type:H.Literal("goal"),state:N(["updated","cleared"]),goal_id:H.Optional(H.String()),status:H.Optional(N(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"])),verification_attempt:H.Optional(H.Integer({minimum:1})),verification_status:H.Optional(N(["pending","pass","fail","partial"])),verifier_session_id:H.Optional(H.String()),verification_evidence_sha256:H.Optional(H.String({pattern:"^[a-f0-9]{64}$"})),verification_summary:H.Optional(H.String()),verification_stall_count:H.Optional(H.Integer({minimum:1})),premature_stop_pattern:H.Optional(N(qH)),premature_stop_count:H.Optional(H.Integer({minimum:1})),frontier_stall_category:H.Optional(N(["waiting_dependency","same_task_no_effect","repeated_deferral"])),frontier_stall_count:H.Optional(H.Integer({minimum:1,maximum:3}))}),UJ=D({type:H.Literal("subagent"),state:N(["spawned","completed"]),session_id:H.String(),subagent_type:H.Optional(H.String()),success:H.Optional(H.Boolean()),summary:H.Optional(H.String()),verification_verdict:H.Optional(N(["pass","fail","partial"])),resumed_from:H.Optional(H.String()),root_agent_id:H.Optional(H.String()),resume_depth:H.Optional(H.Integer({minimum:0}))}),_J=D({type:H.Literal("token_usage"),input_tokens:H.Number(),output_tokens:H.Number(),total_tokens:H.Number(),max_context_tokens:H.Number(),cache_read_tokens:H.Optional(H.Number()),cache_write_tokens:H.Optional(H.Number()),prompt_cache_break:H.Optional(H.Object({reason:N(["model_changed","system_prompt_changed","tools_changed","request_policy_changed","ttl_expired","server_side"]),previous_cache_read_tokens:H.Number(),cache_read_tokens:H.Number(),cache_write_tokens:H.Number(),token_drop:H.Number(),elapsed_ms:H.Number(),call_number:H.Number(),system_prompt_changed:H.Boolean(),system_char_delta:H.Number(),tools_changed:H.Boolean(),added_tool_count:H.Number(),removed_tool_count:H.Number(),changed_tool_count:H.Number(),model_changed:H.Boolean(),request_policy_changed:H.Boolean()})),cost_usd:H.Optional(H.Number())}),GJ=D({type:H.Literal("compacting"),state:N(["started","completed"]),reason:H.Optional(N(["threshold","context_limit","turn_limit","manual"])),strategy:H.Optional(N(["llm","fallback","snip"])),outcome:H.Optional(N(["completed","fallback","failed"])),pre_tokens:H.Optional(H.Number({minimum:0})),pre_token_source:H.Optional(N(["provider","provider_plus_estimate","local_estimate"])),estimated_pending_tokens:H.Optional(H.Number({minimum:0})),post_tokens:H.Optional(H.Number({minimum:0})),sample_attempts:H.Optional(H.Integer({minimum:0})),input_reductions:H.Optional(H.Integer({minimum:0})),messages_omitted:H.Optional(H.Integer({minimum:0})),files_omitted:H.Optional(H.Integer({minimum:0})),images_omitted:H.Optional(H.Integer({minimum:0})),fallback_target_tokens:H.Optional(H.Integer({minimum:0})),fallback_messages_omitted:H.Optional(H.Integer({minimum:0})),fallback_messages_truncated:H.Optional(H.Integer({minimum:0})),failure_reason:H.Optional(N(["circuit_open","context_exhausted","deterministic","empty_exhausted","insufficient_reduction","transient_exhausted"]))}),PJ=D({type:H.Literal("provider_retry"),phase:N(["scheduled","waiting","attempt","recovered","exhausted"]),attempt:H.Integer({minimum:0}),max_retries:H.Integer({minimum:0}),reason:N(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),delay_ms:H.Optional(H.Integer({minimum:0})),next_retry_at:H.Optional(H.Integer({minimum:0})),mode:H.Optional(N(["standard","bounded_foreground"])),recovery_budget_ms:H.Optional(H.Integer({minimum:0})),recovery_elapsed_ms:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0})),exhausted_by:H.Optional(N(["attempt_limit","recovery_budget"]))}),FJ=D({type:H.Literal("provider_admission"),phase:N(["queued","admitted","rejected"]),request_class:N(["foreground","background","internal"]),resource:N(["stream","pending_count","pending_bytes"]),scope:N(["global","domain","owner","class"]),reason:H.Optional(N(["capacity","queue_full","wait_timeout","closed"])),queue_position:H.Integer({minimum:0}),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:0}),wait_ms:H.Integer({minimum:0}),max_wait_ms:H.Integer({minimum:0}),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),EJ=D({type:H.Literal("provider_circuit"),phase:N(["opened","waiting","probe","closed","reopened","rejected"]),reason:N(["rate_limit","server_error","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),retry_after_ms:H.Optional(H.Integer({minimum:0})),next_probe_at:H.Optional(H.Integer({minimum:0})),open_duration_ms:H.Integer({minimum:0}),sample_count:H.Optional(H.Integer({minimum:0})),failure_count:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),MJ=D({type:H.Literal("provider_stall"),phase:N(["detected","recovered"]),stall_count:H.Integer({minimum:1}),duration_ms:H.Integer({minimum:0}),warning_after_ms:H.Integer({minimum:1}),timeout_ms:H.Integer({minimum:1}),output_started:H.Boolean()}),zJ=D({type:H.Literal("action_stationarity"),phase:N(["detected","recovered","halted"]),tool_name:H.String(),run_length:H.Integer({minimum:1}),nudge_threshold:H.Integer({minimum:1}),halt_threshold:H.Integer({minimum:1}),progress_aware:H.Boolean()}),fJ=D({type:H.Literal("turn_recovery"),state:N(["completed","resumable","requires_attention"]),turn_id:H.String({minLength:1}),input_message_count:H.Integer({minimum:0}),reason:H.Optional(N(["successful_tool_result","interrupted_tool_call"]))}),AJ=D({type:H.Literal("turn_limit"),turns_count:H.Number(),action:H.Literal("continue")}),SJ=D({type:H.Literal("task_session"),session_id:H.String(),project_path:H.String(),source_project_path:H.String(),isolation:N(["local","worktree"]),worktree_branch:H.Optional(H.String()),base_commit:H.Optional(H.String())}),TJ=D({type:H.Literal("task_admission"),state:N(["queued","running"]),queue_position:H.Optional(H.Integer({minimum:1})),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),max_concurrent_tasks:H.Integer({minimum:1})}),yJ=D({type:H.Literal("output"),content:H.String(),exit_code:H.Number()}),bJ=D({type:H.Literal("error"),message:H.String()}),eJ=$H(H.Union([vH,lH,aH,iH,oH,sH,nH,tH,HJ,JJ,KJ,VJ,ZJ,$J,qJ,XJ,YJ,BJ,NJ,QJ,DJ,LJ,WJ,jJ,xJ,UJ,_J,GJ,FJ,EJ,PJ,MJ,zJ,fJ,AJ,SJ,TJ,yJ,bJ]));function BH(K,V){return{event_version:YH,type:K,...V}}function gJ(K){if(!K||typeof K!=="object"||Array.isArray(K))return;let V=K;if(V.auto_backgrounded!==!0||V.background_reason!=="foreground_budget"||!Number.isSafeInteger(V.foreground_budget_ms)||V.foreground_budget_ms<=0||typeof V.shell_id!=="string"||!/^bash_[A-Za-z0-9-]+$/.test(V.shell_id)||V.shell_id.length>128||V.terminal_transport!=="local"&&V.terminal_transport!=="acp"||V.pid!==void 0&&(!Number.isSafeInteger(V.pid)||V.pid<=0))return;return{auto_backgrounded:!0,background_reason:"foreground_budget",foreground_budget_ms:V.foreground_budget_ms,shell_id:V.shell_id,...V.pid===void 0?{}:{pid:V.pid},terminal_transport:V.terminal_transport}}function kJ(K){let V=new AbortController,Q=(Z)=>{if(!V.signal.aborted)V.abort(Z)},X=()=>Q("interrupt"),J=()=>Q(K?.signal?.reason);if(K?.signal){if(K.signal.addEventListener("abort",J,{once:!0}),K.signal.aborted)J()}else process.once("SIGINT",X),process.once("SIGTERM",X);return{signal:V.signal,abort:Q,dispose:()=>{K?.signal?.removeEventListener("abort",J),process.removeListener("SIGINT",X),process.removeListener("SIGTERM",X)}}}var CJ=N(["text","jsonl"]),hJ=H.Object({headless:H.Optional(H.Boolean()),message:H.Optional(H.String()),_:H.Optional(H.Array(H.Union([H.String(),H.Number()]))),model:H.Optional(H.String()),systemPrompt:H.Optional(H.String()),appendSystemPrompt:H.Optional(H.String()),verificationAgent:H.Optional(H.Boolean()),maxTurns:H.Optional(H.Refine(H.Integer(),(K)=>K===-1||K>0,()=>"must be -1 (unlimited) or a positive integer")),permissionMode:H.Optional(H.Enum(DH)),mcpConfig:H.Optional(H.Array(H.String())),strictMcpConfig:H.Optional(H.Boolean()),sessionId:H.Optional(H.String()),allowedTools:H.Optional(H.Array(H.String())),disallowedTools:H.Optional(H.Array(H.String())),agents:H.Optional(H.String()),continue:H.Optional(H.Boolean()),resume:H.Optional(H.Union([H.String(),H.Boolean()])),forkSession:H.Optional(H.Boolean()),taskIsolation:H.Optional(N(["local","worktree"])),outputFormat:H.Optional(CJ),jsonSchema:H.Optional(H.String()),outputSchema:H.Optional(H.String())});class CH{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(K){this.openedThinking=K}hasOpenThinking(){return this.openedThinking}completeStream(){let K={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,K}}function OJ(K){return K.issues.map((V)=>`${V.path.join(".")||"options"}: ${V.message}`).join("; ")}function wJ(K){let V=LH(hJ,K);if(!V.success)throw Error(`Invalid headless options: ${OJ(V.error)}`);return V.data}function mJ(K){return K.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(V)=>V.positional("message",{describe:"Message to process",type:"string"}).option("headless",{type:"boolean",describe:"Run full agent loop without Ink UI and print events to the terminal"}).option("model",{describe:"Model ID for this run",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("verification-agent",{describe:"Run the built-in independent verification agent after non-trivial changes",type:"boolean",default:!0}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}).option("output-format",{alias:["outputFormat"],choices:["text","jsonl"],describe:"Headless output format",type:"string"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("task-isolation",{alias:["taskIsolation"],choices:["local","worktree"],describe:"Dispatch a new durable task in the selected workspace mode",type:"string"}),async(V)=>{if(!V.headless)return;let Q=await lJ(V);process.exit(Q)})}function L(K,V=""){K.write(`${V}
|
|
2
2
|
`)}function cJ(K){return`[task] [${K.status}] ${K.subject}`}function uJ(){return{requestConfirmation:async(K)=>K.type==="mcpElicitation"?{approved:!1,reason:"headless-mcp-elicitation-unavailable",elicitation:{action:"cancel"}}:K.type==="mcpSampling"?{approved:!1,reason:"headless-mcp-sampling-unavailable"}:{approved:!0,reason:"headless-auto-approved",scope:"session"}}}function dJ(K){if(!(K instanceof Error))return"Unknown error";let X=K.lastError??K;if(X.responseBody)try{let W=JSON.parse(X.responseBody)?.error?.message;if(W)return X.statusCode?`${W} (HTTP ${X.statusCode})`:W}catch{}let J=K.message.match(/Last error:\s*(.+)$/);if(J)return J[1];return K.message}function pJ(K){return K==="jsonl"?"jsonl":"text"}function NH(K,V){let Q=(...X)=>{for(let J of X){let Z=V[J];if(typeof Z==="string"&&Z.trim()!=="")return Z}return};switch(K){case"Read":case"Edit":case"Write":case"UndoEdit":return Q("file_path");case"ApplyPatch":return"multi-file patch";case"NotebookEdit":return Q("notebook_path");case"Grep":return Q("path","pattern");case"Glob":return Q("pattern");case"WebFetch":return Q("url");case"WebSearch":return Q("query");case"Bash":return Q("command","description");case"Task":return Q("description");case"LSP":return Q("filePath","operation");case"EnterWorktree":return Q("name");case"ExitWorktree":return Q("action");default:return}}function vJ(K,V,Q,X){let J=new Set(["Glob","Grep","WebSearch","LS"]),Z=new Set(["Read","WebFetch"]);if(new Set(["Edit","Write","ApplyPatch","NotebookEdit","Bash","LSP","UndoEdit","EnterWorktree","ExitWorktree"]).has(K)&&!X.targetLocked)return{phase:"target_hit",status:"hit",message:`Target locked: ${V}`,shouldLockTarget:!0};if(X.targetLocked)return{phase:"executing",status:"hit",message:Q?`Working within target: ${V}`:`Executing: ${V}`,shouldLockTarget:!1};if(J.has(K))return{phase:"searching",status:"ongoing",message:`Still searching: ${V}`,shouldLockTarget:!1};if(Z.has(K))return{phase:"inspecting",status:"ongoing",message:`Inspecting candidate: ${V}`,shouldLockTarget:!1};return{phase:"executing",status:X.targetLocked?"hit":"ongoing",message:`Executing: ${V}`,shouldLockTarget:!1}}function QH(K,V,Q=!1){let X=(J,Z)=>{K.stdout.write(`${JSON.stringify(BH(J,Z))}
|
|
3
3
|
`)};return{contentDelta(J){if(V==="jsonl"){X("content_delta",{delta:J});return}if(Q)return;K.stdout.write(J)},thinkingDelta(J,Z){if(V==="jsonl")return X("thinking_delta",{delta:J}),Z;if(!Z)K.stderr.write("[thinking] ");return K.stderr.write(J),!0},thinking(J){if(V==="jsonl"){X("thinking",{content:J});return}L(K.stderr,`[thinking] ${J}`)},streamEnd(J,Z){if(V==="jsonl"){X("stream_end",{});return}if(Z)K.stderr.write(`
|
|
4
4
|
`);if(J)K.stdout.write(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$f as L0,_f as b1,ag as z1,fg as N0}from"./chunk-cqqmkwvn.js";import{mg as jO,ng as wO}from"./chunk-9g64g1np.js";import{qg as A1}from"./chunk-935v0gpc.js";import{rg as b0,tg as J0}from"./chunk-
|
|
1
|
+
import{$f as L0,_f as b1,ag as z1,fg as N0}from"./chunk-cqqmkwvn.js";import{mg as jO,ng as wO}from"./chunk-9g64g1np.js";import{qg as A1}from"./chunk-935v0gpc.js";import{rg as b0,tg as J0}from"./chunk-kev3cwe9.js";import{Ah as I0,vh as S0,wh as GO}from"./chunk-spth418m.js";import{Eh as u,Gh as L,Jh as c1}from"./chunk-6k5k40p8.js";import{Sh as M}from"./chunk-ecd727xh.js";import{si as k,ti as S}from"./chunk-dvv28pkc.js";import{Gi as u0}from"./chunk-r7wwr5f6.js";import{Ni as N}from"./chunk-vbwvsgs1.js";import H1 from"node:path";import LO from"node:path";import v0 from"node:fs";import W0 from"node:os";import E from"node:path";import dO from"yaml";var U1=2000,V1=50,j1=1000,Y4={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:U1},findings:{type:"array",maxItems:V1,items:{type:"string",minLength:1,maxLength:j1}}},required:["verdict","summary","findings"],additionalProperties:!1};function F1(O,$){let Q=O.trim().replaceAll(/\s+/g," ");if($)Q=Q.replaceAll($,".");return Q.replace(/\bBearer\s+[^\s"'`]+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted-key]").replace(/\b(api(?:[_-]?|\s+)key|access(?:[_-]?|\s+)token|authorization|cookie|password|passwd|refresh(?:[_-]?|\s+)token|secret|session(?:[_-]?|\s+)token)\b(\s*[:=]\s*)([^\s,;]+)/gi,"$1$2[redacted]")}function hO(O){if(O.length<=N0)return O;let $=" [verification feedback truncated]",Q=O.slice(0,N0-$.length);if(/[\uD800-\uDBFF]$/.test(Q))Q=Q.slice(0,-1);return Q.trimEnd()+$}function B1(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O;if($.verdict!=="pass"&&$.verdict!=="fail"&&$.verdict!=="partial"||typeof $.summary!=="string"||!$.summary.trim()||$.summary.length>U1||!Array.isArray($.findings)||$.findings.length>V1||!$.findings.every((Q)=>typeof Q==="string"&&Q.trim().length>0&&Q.length<=j1))return;return{verdict:$.verdict,summary:$.summary.trim(),findings:$.findings.map((Q)=>Q.trim())}}function X4(O,$){let Q=B1(O);if(!Q)return;let Z=F1(Q.summary,$),J=Q.findings.map((K)=>F1(K,$));return hO([Z,J.length>0?`Findings:
|
|
2
2
|
${J.map((K)=>`- ${K}`).join(`
|
|
3
3
|
`)}`:""].filter(Boolean).join(`
|
|
4
4
|
|