blade-code 0.10.84 → 0.10.86
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-ny3ykftf.js → chunk-00xsfm2j.js} +1 -1
- package/dist/{chunk-gc2xnw9g.js → chunk-0nb8999e.js} +1 -1
- package/dist/{chunk-m62t9s2x.js → chunk-2dq84j8s.js} +1 -1
- package/dist/{chunk-rf3g9kkv.js → chunk-2ps02f7j.js} +1 -1
- package/dist/{chunk-2cbkr660.js → chunk-4y34e9ty.js} +1 -1
- package/dist/{chunk-58021qed.js → chunk-6n63ev2e.js} +1 -1
- package/dist/{chunk-0xd2q6xj.js → chunk-90b512gm.js} +1 -1
- package/dist/{chunk-ypd8hctc.js → chunk-9erhm3gg.js} +1 -1
- package/dist/{chunk-1zn0yfkf.js → chunk-9vmxd900.js} +1 -1
- package/dist/{chunk-7s0crdpp.js → chunk-9zm7v41x.js} +1 -1
- package/dist/{chunk-tmbhspse.js → chunk-b1mh28yd.js} +1 -1
- package/dist/{chunk-vb0af8db.js → chunk-b8p2mwq9.js} +1 -1
- package/dist/{chunk-86e21rqs.js → chunk-bthb5c55.js} +1 -1
- package/dist/{chunk-sv7wey68.js → chunk-bwt1djsp.js} +1 -1
- package/dist/{chunk-5zqdgwrx.js → chunk-cdx9tebt.js} +1 -1
- package/dist/{chunk-z4vbah7d.js → chunk-deeh2eq1.js} +1 -1
- package/dist/{chunk-84kwsrcv.js → chunk-gk79etn6.js} +1 -1
- package/dist/{chunk-9t99f87v.js → chunk-gzjt969t.js} +1 -1
- package/dist/{chunk-8jfk34vk.js → chunk-hazs43pe.js} +1 -1
- package/dist/chunk-hm92k82b.js +1 -0
- package/dist/{chunk-smrxrd3w.js → chunk-hxgzj76t.js} +1 -1
- package/dist/{chunk-ev4swr8g.js → chunk-j2s2g9ep.js} +1 -1
- package/dist/{chunk-tv6brgn1.js → chunk-k6m9wmsq.js} +1 -1
- package/dist/{chunk-5ehcky33.js → chunk-mp90dsxs.js} +1 -1
- package/dist/{chunk-a17x4y58.js → chunk-p3jvzk1f.js} +1 -1
- package/dist/{chunk-hepfsgx5.js → chunk-t5d4p0gc.js} +1 -1
- package/dist/{chunk-a129n4rb.js → chunk-tap68662.js} +1 -1
- package/dist/{chunk-d1x4n3q3.js → chunk-vt654hsf.js} +1 -1
- package/dist/{chunk-fa20qwhr.js → chunk-wktx761x.js} +2 -2
- package/dist/chunk-x564avfw.js +1 -0
- package/dist/{chunk-4mevry12.js → chunk-x89n28mq.js} +1 -1
- package/dist/{chunk-3083qhmh.js → chunk-xwtx2vng.js} +1 -1
- package/dist/{chunk-wr5xpc0t.js → chunk-yq5vm0hf.js} +1 -1
- package/dist/{chunk-3htjbswb.js → chunk-z21es9vg.js} +1 -1
- package/dist/{chunk-p72my37n.js → chunk-zg8g2jcr.js} +1 -1
- package/dist/{chunk-kat6tef6.js → chunk-zpbbcdme.js} +3 -3
- package/dist/{chunk-q86z54xg.js → chunk-zpryec89.js} +1 -1
- package/dist/web/assets/ChatView-juDcmnHV.js +18 -0
- package/dist/web/assets/{CodeBlockHighlighter-DxATdO6i.js → CodeBlockHighlighter-BR4c98oZ.js} +1 -1
- package/dist/web/assets/FilePreview-DKgh-Chb.js +8 -0
- package/dist/web/assets/{KanbanBoard-DEUuLh0H.js → KanbanBoard-CQU0UQP8.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-BA9VgOyM.js → MarkdownRenderer-BVPIxk31.js} +3 -3
- package/dist/web/assets/{SettingsModal-CXq3qDgQ.js → SettingsModal-CuUrUdWR.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-CUcZEUQH.js → TaskSwitcher-DB7by2ch.js} +1 -1
- package/dist/web/assets/{TerminalPanel-CcC6f3H_.js → TerminalPanel-BN9ftZUH.js} +1 -1
- package/dist/web/assets/index-BdnOTMNi.css +1 -0
- package/dist/web/assets/index-ebnhtfFC.js +11 -0
- package/dist/web/assets/{teamService-BX1zdQBb.js → teamService-CFKFv0qS.js} +1 -1
- package/dist/web/assets/{vendor-icons-DovdPN7M.js → vendor-icons-CX5BfgqQ.js} +1 -1
- package/dist/web/index.html +3 -3
- package/package.json +1 -1
- package/dist/chunk-h5pexxkw.js +0 -1
- package/dist/chunk-j0ma9as0.js +0 -1
- package/dist/web/assets/ChatView-DRn47Y3l.js +0 -18
- package/dist/web/assets/FilePreview-D21mo4fn.js +0 -8
- package/dist/web/assets/index-8G4ejlcH.css +0 -1
- package/dist/web/assets/index-CfVQVVVI.js +0 -11
package/dist/blade.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Cd as W}from"./chunk-
|
|
2
|
+
import{Cd as W}from"./chunk-x89n28mq.js";import{Fd as F,Gd as M}from"./chunk-skg520wq.js";import"./chunk-bthb5c55.js";import"./chunk-v508x7cg.js";import"./chunk-g9xjcfrf.js";import"./chunk-z21es9vg.js";import"./chunk-272swnyr.js";import"./chunk-zpryec89.js";import"./chunk-7m5q8vxf.js";import"./chunk-sk8h4m9m.js";import"./chunk-hg8d4vhj.js";import{Sg as N,Tg as B}from"./chunk-sb84vdcf.js";import"./chunk-hjr9r44k.js";import{sh as T}from"./chunk-ffa6hhee.js";import"./chunk-t1633e8m.js";import"./chunk-m5f934fh.js";import"./chunk-p3jvzk1f.js";import"./chunk-rwvaapta.js";import"./chunk-83caxxbt.js";import"./chunk-shr5cg46.js";import{$h as J}from"./chunk-6jsmac0q.js";import v from"node:path";var E=process.argv.slice(2),I=u(E),p=I!==null;if(I!==null)T.setGlobalDebug(I);function u(Q){for(let Y=0;Y<Q.length;Y+=1){let U=Q[Y];if(U==="--debug"||U==="-d"){let X=Q[Y+1];return X&&!X.startsWith("-")?X:!0}if(U.startsWith("--debug="))return U.slice(8)||!0}return null}function c(Q){return Q.length===1&&(Q[0]==="--version"||Q[0]==="-V")}function q(Q,...Y){return Q.some((U)=>Y.some((X)=>U===X||U.startsWith(`${X}=`)))}function m(Q,...Y){let U=[];for(let X=0;X<Q.length;X+=1){let G=Q[X],z=Y.find(($)=>G.startsWith(`${$}=`));if(z){let $=G.slice(z.length+1);if($)U.push($);continue}if(Y.includes(G)){let $=Q[X+1];if($&&!$.startsWith("-"))U.push($),X+=1}}return U}async function t(){if(c(E)){let{getVersion:K}=await import("./chunk-k6m9wmsq.js");console.log(K());return}let Q=process.cwd(),Y=F(Q);M(Y),N(B());let U=m(E,"--plugin-dir","--pluginDir");if(U.length>0){let{configureInvocationPluginDirs:K}=await import("./chunk-4y34e9ty.js");K(U.map((Z)=>v.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:K}=await import("./chunk-7jp7e0zj.js");await K.getInstance().trust(B())}if(process.getuid&&process.getuid()===0){let K=!!process.env.SUDO_USER,Z=!!process.env.BLADE_ALLOW_ROOT;if(K&&!Z)console.error(""),console.error("Error: 请不要使用 sudo 运行 blade"),console.error(""),console.error("原因:"),console.error(" 使用 sudo 会创建属于 root 的配置文件,"),console.error(" 导致普通用户无法访问。"),console.error(""),console.error("正确用法:"),console.error(" blade # 直接运行,不要加 sudo"),console.error(""),console.error("如果遇到权限错误,请运行:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("如果你确实需要以 root 运行(容器/CI),设置环境变量:"),console.error(" BLADE_ALLOW_ROOT=1 blade"),console.error(""),process.exit(1)}if(q(E,"--headless")){let{handleHeadlessMode:K}=await import("./chunk-mp90dsxs.js");if(await K())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-hazs43pe.js");if(await K())return}if(E.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-b1mh28yd.js");await K();return}let[{default:X},{hideBin:G},{cliConfig:z,globalOptions:$},{loadConfiguration:_,validateOutput:D,validatePermissions:R},{doctorCommands:S},{installCommands:k},{mcpCommands:O},{projectsCommands:y},{scheduleCommands:b},{serveCommand:V},{updateCommands:P},{webCommand:x}]=await Promise.all([import("yargs"),import("yargs/helpers"),import("./chunk-x564avfw.js"),import("./chunk-j2s2g9ep.js"),import("./chunk-wktx761x.js"),import("./chunk-jf4bxxyf.js"),import("./chunk-cdx9tebt.js"),import("./chunk-jndq361v.js"),import("./chunk-e1ry8aj5.js"),import("./chunk-9zm7v41x.js"),import("./chunk-0nb8999e.js"),import("./chunk-vt654hsf.js")]),A=X(G(process.argv)).scriptName(z.scriptName).usage(z.usage).version(z.version).locale(z.locale).showHelpOnFail(z.showHelpOnFail).demandCommand(0,"").recommendCommands().strict(z.strict).parserConfiguration({"populate--":!0}).options($).middleware([_,R,D]).command(O).command(y).command(b).command(S).command(P).command(k).command(x).command(V).completion("completion",!1).help("help","Show help").alias("help","h").alias("version","V").fail((K,Z,L)=>{if(Z){if(console.error("An error occurred:"),console.error(Z.message),p&&Z.stack)console.error(`
|
|
3
3
|
Stack trace:`),console.error(Z.stack);else console.error(`
|
|
4
4
|
Run with --debug to show the stack trace.`);process.exit(1)}if(K)console.error("Error: Invalid arguments:"),console.error(K),console.error(`
|
|
5
|
-
Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let Z=K._.slice(1),L=Z.length>0?Z.join(" "):void 0,h=import("./chunk-
|
|
5
|
+
Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let Z=K._.slice(1),L=Z.length>0?Z.join(" "):void 0,h=import("./chunk-hm92k82b.js").then(({checkVersionOnStartup:C})=>C()),[{render:w},{createElement:f},{AppWrapper:j}]=await Promise.all([import("ink"),import("react"),import("./chunk-90b512gm.js")]),H={...K,initialMessage:L,debug:K.debug,print:Boolean(K.print),versionCheckPromise:h};delete H._,delete H.$0,delete H.message,w(f(j,H),{patchConsole:!0,exitOnCtrlC:!1,alternateBuffer:!1})});try{await A.parse()}catch(K){console.error("Error: Parse error:",K),process.exit(1)}}if(J.main==J.module)t().catch(console.error);export{t as main};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{K as I}from"./chunk-
|
|
1
|
+
import{K as I}from"./chunk-zpbbcdme.js";import{Yc as M}from"./chunk-gk79etn6.js";import P from"node:path";function w(s){let a=s.replace(/\s+/g," ").trim();return a.length<=72?a:`${a.slice(0,69)}...`}function W(s){let a=s.replace(/\s+/g," ").trim();return a.length<=500?a:`${a.slice(0,497)}...`}function A(s){return`task/${s.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class C{static async createSessionTask(s){if(!s.prompt.trim())throw Error("Task prompt must not be blank");if(!P.isAbsolute(s.sourceProjectPath))throw Error("Task source project path must be absolute");let a=P.resolve(s.sourceProjectPath),t;try{return t=s.isolation==="worktree"?await I.enter({sessionId:s.sessionId,workspaceRoot:a,name:A(s.sessionId)}):void 0,{metadata:await M.createSessionMetadata(s.sessionId,t?.workspaceRoot??a,{title:s.title?.trim()||w(s.prompt),taskPromptSummary:W(s.prompt),taskPriority:s.taskPriority,taskKind:s.taskKind,taskDueAt:s.taskDueAt,taskDispatch:s.dispatch,taskModelId:s.dispatch?.modelId,selectedModelId:s.dispatch?.modelId,permissionMode:s.dispatch?.permissionMode,reasoningEffort:s.dispatch?.reasoningEffort,serviceTier:s.dispatch?.serviceTier,responseVerbosity:s.dispatch?.responseVerbosity,communicationStyle:s.dispatch?.communicationStyle,communicationStyleDigest:s.dispatch?.communicationStyleDigest,projectInstructionsDigest:s.dispatch?.projectInstructionsDigest,taskRetriedFrom:s.retriedFrom,taskIsolation:s.isolation,taskSourceProjectPath:a,taskWorktree:t}),taskWorktree:t}}catch(k){if(t)await I.exit({sessionId:s.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw k}}}var $=256,V=8388608,x=30000;class i extends Error{kind;pendingItems;pendingBytes;constructor(s,a,t){super(a,t);this.kind=s;this.name="BoundedSerialEgressError",this.pendingItems=t?.pendingItems,this.pendingBytes=t?.pendingBytes}}function T(s){s.catch(()=>{return})}class K{options;pending=[];flushWaiters=[];pendingBytes=0;nextSequence=0;completedSequence=0;draining=!1;closed=!1;failure;activeWriteAbort;activeWriteStop;activeWriteTimeout;constructor(s){this.options=s;if(this.assertPositiveInteger(s.maxPendingItems,"maxPendingItems"),this.assertPositiveInteger(s.maxPendingBytes,"maxPendingBytes"),this.assertPositiveInteger(s.writeTimeoutMs,"writeTimeoutMs"),s.signal?.addEventListener("abort",this.handleAbort,{once:!0}),s.signal?.aborted)this.handleAbort()}offer(s){if(this.closed)return{accepted:!1,error:this.failure??new i("closed","Egress is already closed")};let a;try{a=this.options.sizeOf(s)}catch(h){return this.rejectAdmission(new i("invalid_size","Egress size calculation failed",{cause:h}))}if(!Number.isSafeInteger(a)||a<0)return this.rejectAdmission(new i("invalid_size","Egress size must be a non-negative safe integer"));if(a>this.options.maxPendingBytes)return this.rejectAdmission(new i("oversized",`Egress value requires ${a} bytes; limit is ${this.options.maxPendingBytes}`));if(this.pending.length>=this.options.maxPendingItems||this.pendingBytes+a>this.options.maxPendingBytes)return this.rejectAdmission(new i("overflow",`Egress pending limit exceeded (${this.pending.length} items, ${this.pendingBytes} bytes)`));let t,k,c=new Promise((h,m)=>{t=h,k=m});return T(c),this.nextSequence+=1,this.pending.push({value:s,bytes:a,sequence:this.nextSequence,resolve:t,reject:k,completion:c}),this.pendingBytes+=a,this.startDrain(),{accepted:!0,completion:c}}flush(){if(this.failure){let c=Promise.reject(this.failure);return T(c),c}let s=this.nextSequence;if(s<=this.completedSequence)return Promise.resolve();let a,t,k=new Promise((c,h)=>{a=c,t=h});return T(k),this.flushWaiters.push({targetSequence:s,resolve:a,reject:t}),k}close(s){let a=s instanceof i?s:new i("closed","Egress was closed",{cause:s});this.fail(a)}stats(){return{closed:this.closed,pendingItems:this.pending.length,pendingBytes:this.pendingBytes}}handleAbort=()=>{this.fail(new i("aborted","Egress was aborted",{cause:this.options.signal?.reason}))};rejectAdmission(s){return this.fail(s),{accepted:!1,error:s}}startDrain(){if(this.draining||this.closed)return;this.draining=!0;let s=this.drain();T(s)}async drain(){try{while(!this.closed){let s=this.pending[0];if(!s)return;try{await this.writeOne(s.value)}catch(a){this.fail(this.normalizeWriteError(a));return}if(this.closed||this.pending[0]!==s)return;this.pending.shift(),this.pendingBytes-=s.bytes,this.completedSequence=s.sequence,s.resolve(),this.settleFlushWaiters()}}finally{if(this.draining=!1,!this.closed&&this.pending.length>0)this.startDrain()}}async writeOne(s){let a=new AbortController;this.activeWriteAbort=a;let t,k,c=new Promise((S,f)=>{k=f});T(c),this.activeWriteStop=k;let h=Promise.resolve().then(()=>this.options.write(s,a.signal));T(h);let m=new Promise((S,f)=>{t=setTimeout(()=>{let D=new i("write_timeout",`Egress write timed out after ${this.options.writeTimeoutMs}ms`);a.abort(D),f(D)},this.options.writeTimeoutMs),this.activeWriteTimeout=t});T(m);try{await Promise.race([h,m,c])}finally{if(t!==void 0)clearTimeout(t);if(this.activeWriteTimeout===t)this.activeWriteTimeout=void 0;if(this.activeWriteAbort===a)this.activeWriteAbort=void 0;if(this.activeWriteStop===k)this.activeWriteStop=void 0}}normalizeWriteError(s){if(s instanceof i)return s;return new i("write_failed","Egress write failed",{cause:s})}fail(s){if(this.closed)return;if(s.pendingItems??=this.pending.length,s.pendingBytes??=this.pendingBytes,this.closed=!0,this.failure=s,this.options.signal?.removeEventListener("abort",this.handleAbort),this.activeWriteTimeout!==void 0)clearTimeout(this.activeWriteTimeout),this.activeWriteTimeout=void 0;this.activeWriteAbort?.abort(s),this.activeWriteStop?.(s),this.activeWriteAbort=void 0,this.activeWriteStop=void 0;let a=this.pending.splice(0);this.pendingBytes=0;for(let t of a)t.reject(s);for(let t of this.flushWaiters.splice(0))t.reject(s);try{this.options.onFailure?.(s)}catch{}}settleFlushWaiters(){for(let s=0;s<this.flushWaiters.length;){let a=this.flushWaiters[s];if(a.targetSequence>this.completedSequence){s+=1;continue}this.flushWaiters.splice(s,1),a.resolve()}}assertPositiveInteger(s,a){if(!Number.isSafeInteger(s)||s<=0)throw RangeError(`${a} must be a positive safe integer`)}}
|
|
2
2
|
export{C as v,$ as w,V as x,x as y,i as z,K as A};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as o}from"./chunk-
|
|
1
|
+
import{a as o}from"./chunk-yq5vm0hf.js";import"./chunk-p3jvzk1f.js";import"./chunk-6jsmac0q.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{ma as F,oa as L}from"./chunk-
|
|
1
|
+
import{ma as F,oa as L}from"./chunk-zpbbcdme.js";import{Oc as $,Qc as B,Yc as Q}from"./chunk-gk79etn6.js";import{Ye as y}from"./chunk-t5d4p0gc.js";import{Tg as V}from"./chunk-sb84vdcf.js";async function j(){await y(V())}async function I(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(!z.isTTY){let G=[];for await(let K of z)G.push(K);return Buffer.concat(G).toString("utf-8").trim()}if(b.defaultMessage!==void 0)return b.defaultMessage;throw Error("No input provided")}async function M(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(z.isTTY)return;let G=[];for await(let Z of z)G.push(Buffer.isBuffer(Z)?Z:Buffer.from(Z));return Buffer.concat(G).toString("utf-8").trim()||void 0}async function R(b){if(!F(b))return{mode:"agent",content:b};let q=await L(b,{cwd:V(),surface:"headless",workspaceRoot:V()});if(!q.success)return{mode:"output",content:`Error: ${q.error||"未知错误"}`,exitCode:1};let z=q.data;if(z?.action==="invoke_skill"){let{skillName:G,skillArgs:K}=z;return{mode:"agent",content:K?`Please use the "${G}" skill to help me with: ${K}`:`Please use the "${G}" skill.`}}if(z?.action==="invoke_custom_command"||z?.action==="invoke_plugin_command"){let G=z.processedContent;return{mode:"agent",content:`# Custom Command: /${z.commandName}
|
|
2
2
|
|
|
3
3
|
${G}`}}return{mode:"output",content:q.content||q.message||"",exitCode:0}}import{readFile as D,stat as H}from"node:fs/promises";import J from"node:path";function x(b,q){let z;try{z=JSON.parse(b)}catch(G){throw Error(`Invalid JSON output schema from ${q}`,{cause:G})}return B(z).schema}async function _(b){if(b.jsonSchema!==void 0&&b.outputSchema!==void 0)throw Error("--json-schema cannot be combined with --output-schema");if(b.jsonSchema!==void 0)return x(b.jsonSchema,"--json-schema");if(b.outputSchema===void 0)return;let q=J.resolve(b.outputSchema),z=await H(q);if(!z.isFile())throw Error(`Output schema path is not a regular file: ${q}`);if(z.size>$)throw Error(`Output schema exceeds ${$} bytes: ${q}`);return x(await D(q,"utf8"),q)}function N(b){if(!(b instanceof Error))return!1;return b.message.includes("未找到会话")||b.message.includes("ENOENT")||b.message.includes("no such file")}async function W(b){try{return await Q.loadSessionModelContext(b,V())}catch(q){if(N(q))return null;throw q}}async function C(b){if(b.resume===!0||b.resume==="true")throw Error("--resume without a session ID is only supported in interactive UI mode");if(typeof b.resume==="string"&&b.resume.length>0){if(b.forkSession){let G=V(),K=await Q.forkSession(b.resume,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G});return{...K,messages:await Q.loadSessionModelContext(K.sessionId,G)}}let[q,z]=await Promise.all([Q.loadSessionModelContext(b.resume),Q.findSessionMetadata(b.resume)]);return{sessionId:b.resume,messages:q,metadata:z}}if(b.continue){let q=b.forkSession?await Q.listSessions({cwd:V()}):await Q.listSessions();if(q.length>0){let z=q[0].sessionId;if(b.forkSession){let G=V(),K=await Q.forkSession(z,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G});return{...K,messages:await Q.loadSessionModelContext(K.sessionId,G)}}return{sessionId:z,messages:await Q.loadSessionModelContext(z),metadata:q[0]}}if(b.forkSession)throw Error("Cannot fork: no sessions are available to continue")}if(b.sessionId){let q=await W(b.sessionId);return{sessionId:b.sessionId,messages:q??[],...q?{metadata:await Q.findSessionMetadata(b.sessionId,V())}:{}}}return{sessionId:`${b.fallbackSessionPrefix}-${Date.now()}`,messages:[]}}
|
|
4
4
|
export{j as m,I as n,M as o,R as p,_ as q,C as r};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Ae as c,ye as a,ze as b}from"./chunk-
|
|
1
|
+
import{Ae as c,ye as a,ze as b}from"./chunk-deeh2eq1.js";import"./chunk-zpryec89.js";import"./chunk-7m5q8vxf.js";import"./chunk-sk8h4m9m.js";import"./chunk-hg8d4vhj.js";import"./chunk-sb84vdcf.js";import"./chunk-hjr9r44k.js";import"./chunk-ffa6hhee.js";import"./chunk-t1633e8m.js";import"./chunk-m5f934fh.js";import"./chunk-p3jvzk1f.js";import"./chunk-rwvaapta.js";import"./chunk-83caxxbt.js";import"./chunk-shr5cg46.js";import"./chunk-6jsmac0q.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,a as cloneWorkspaceModelConfig};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$e as i,Te as a,Ue as b,Ve as c,We as d,Xe as e,Ye as f,Ze as g,_e as h,af as j}from"./chunk-
|
|
1
|
+
import{$e as i,Te as a,Ue as b,Ve as c,We as d,Xe as e,Ye as f,Ze as g,_e as h,af as j}from"./chunk-t5d4p0gc.js";import"./chunk-sr4zv59p.js";import"./chunk-ww51801m.js";import"./chunk-7rfhmbqw.js";import"./chunk-z21es9vg.js";import"./chunk-272swnyr.js";import"./chunk-zpryec89.js";import"./chunk-7m5q8vxf.js";import"./chunk-sk8h4m9m.js";import"./chunk-hg8d4vhj.js";import"./chunk-sb84vdcf.js";import"./chunk-hjr9r44k.js";import"./chunk-ffa6hhee.js";import"./chunk-t1633e8m.js";import"./chunk-m5f934fh.js";import"./chunk-p3jvzk1f.js";import"./chunk-rwvaapta.js";import"./chunk-83caxxbt.js";import"./chunk-shr5cg46.js";import"./chunk-6jsmac0q.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{Tb as _4}from"./chunk-r8wbvxn7.js";import{Dc as V1,Nc as I0,Pc as V6,Qc as R1,Rc as K6,Ub as X$,Yc as n$,cc as xJ,dc as kJ,ec as d2,fc as m2,lc as CJ,mc as b4,nc as E4,oc as v2,pc as x1,qc as S4,rc as T4,sc as E1,vc as UJ}from"./chunk-84kwsrcv.js";import{bd as F0,ed as _J,fd as k0}from"./chunk-r77pcb0f.js";import{ge as aJ}from"./chunk-g9xjcfrf.js";import{he as P4,ie as i0,je as F4,ke as HJ,ne as b1,oe as Y6,pe as zJ,qe as BJ,se as jJ}from"./chunk-b2p9qm6j.js";import{bf as J$,cf as r0,ff as N4,jf as K4}from"./chunk-sr4zv59p.js";import{uf as A$}from"./chunk-3htjbswb.js";import{Eg as lJ}from"./chunk-7m5q8vxf.js";import{Tg as H0}from"./chunk-sb84vdcf.js";import{th as h0}from"./chunk-ffa6hhee.js";import{Hh as hJ}from"./chunk-a17x4y58.js";import{Sh as _$,Uh as i6,Vh as y0,Wh as M1,Yh as MJ,_h as RJ}from"./chunk-shr5cg46.js";import{$h as w8}from"./chunk-6jsmac0q.js";function f$($){return $.role==="system"&&Array.isArray($.content)}function O$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class f1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,J){this.context=$;let Z=$.messages.find(f$);if(this._contextualSystemMessages=$.messages.filter(O$),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!f$(W)&&!O$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}get contextRevision(){return this._contextRevision}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!O$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(f$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((J)=>J.id===$.id))return;this._history.push($)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((J)=>!f$(J)&&!O$(J)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(O$),this._history=$.filter((J)=>!f$(J)&&!O$(J)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let J=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((Z)=>!$(Z)),this._pending=this._pending.filter((Z)=>!$(Z)),this._contextualSystemMessages=this._contextualSystemMessages.filter((Z)=>!$(Z)),this.syncContextualSystemMessages(),this._history.length!==J[0]||this._pending.length!==J[1]||this._contextualSystemMessages.length!==J[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function _6($){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 b6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function E6($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import Q$ from"node:path";var g4=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"]),p4=/^(LD_.+|DYLD_.+|PATH)$/,S6=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function c$($){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(S6);if(!V)break;let K=V[1];if(!g4.has(K))break;J=Y}return J}function kZ($){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(S6);if(!V)break;let K=V[1];if(p4.test(K))break;J=Y}return J}var d4=[/^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 U2($){let J=$,Z=!0;while(Z){Z=!1;for(let W of d4){let Y=J.match(W);if(Y){J=J.slice(Y[0].length),Z=!0;break}}if(J.startsWith("-- "))J=J.slice(3),Z=!0}return J}function l$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){Z+=Q,V=!0;continue}if(Q==="'"&&!Y){W=!W,Z+=Q;continue}if(Q==='"'&&!W){Y=!Y,Z+=Q;continue}if(W||Y){Z+=Q;continue}if(Q==="|"){if(K+1<$.length&&$[K+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&K+1<$.length&&$[K+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}if(Q==="&")return null;if(Q===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=Q}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function 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 m4=new Set(["npm","pnpm","yarn","bun"]),M6=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),c4=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),l4=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function i4($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function R6($){return $.replace(/\s+2>&1\s*$/,"").trim()}function r4($,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 n4($){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 o4($){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 a4($){let J=R6($.replace(l4,"").trim()),Z=n4(J);if(!Z)return;if(Z.length===0)return h6(J);if(Z.length!==1)return;let W=Z[0];if(W===void 0)return;let Y=R6(J.slice(0,W).trim()),V=J.slice(W+1).trim();if(!Y||!o4(V))return;return h6(Y)}function h6($){let Z=l$($)?.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=a4($);if(!Z)return!1;let W=c$(Z),Y=l$(W);if(!Y||T6(W)||/[\r\n]/.test(W))return!1;let V=Y.length===1?Y[0]:r4(W,Y,J);if(!V)return!1;let K=K$(V);if(K.length===0||K.some((B)=>[...c4].some((j)=>B===j||B.startsWith(`${j}=`))))return!1;let[Q,X,H]=K;if(m4.has(Q??""))return i4(X==="run"?H:X)||X==="--test";if((Q==="npx"||Q==="bunx")&&M6.has(X??""))return!0;if(M6.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 gZ($,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 D2=h0("Agent"),s4=3;function w2($,J,Z){if($!=="length")return{action:"none"};if(J>=s4)return{action:"truncated"};if(_6(Z)==="stop")return D2.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var t4=[/:\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],e4=/```[\s\S]{50,}```/,x6="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",$5=2;function q2($,J,Z=!0){if(!$||J>=$5)return{action:"none"};if(!Z&&e4.test($))return{action:"retry",prompt:x6};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(t4.some((K)=>K.test(W)))return{action:"retry",prompt:x6};return{action:"none"}}var J5=[/\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}(?:测试|单测|集成测试|检查|构建)/],k6={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},Z5={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},W5="The user explicitly required verification, but it has not run successfully. Do not finish or explain. Your next action must be a Bash tool call that runs the requested test, lint, type-check, or build command. Inspect the command result and fix any failure before finishing.",Y5="Required verification did not run successfully before the retry limit.",V5=3;function v6($,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 G2($,J,Z){if(!$||!J5.some((X)=>X.test($)))return{action:"none"};let W=Object.keys(k6).filter((X)=>k6[X].test($)),Y=[...J],V=W.filter((X)=>!Y.some((H)=>Z5[X].test(H)));if(W.length>0?V.length===0:Y.some((X)=>y$(X)))return{action:"none"};if(Z>=V5)return{action:"fail",message:Y5};let Q=W.length>1&&V.length>0?` Missing successful verification categories: ${V.join(", ")}.`:"";return{action:"retry",prompt:`${W5}${Q}`}}var K5=[/\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|子代理|子智能体)/],I6=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function u6($){return typeof $==="string"&&I6.some((J)=>J.test($))}var Q5=[/\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|子代理)/],X5=[/\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 H5($){if(typeof $!=="string")return;if(X5.some((J)=>J.test($)))return"multiple-allowed";return Q5.some((J)=>J.test($))?"required":void 0}function i$($){for(let J of $){let Z=H5(J);if(Z!==void 0)return Z==="required"}return!1}var z5="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.",B5="Required delegation did not complete before the retry limit.",j5=3;function g6($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),Y=i$(W),V=!1;if(!Y)for(let K of W){if(I6.some((Q)=>Q.test(K)))break;if(K5.some((Q)=>Q.test(K))){V=!0;break}}if(W.length===0||!Y&&!V||J.has("Task"))return{action:"none"};if(Z>=j5)return{action:"fail",message:B5};return{action:"retry",prompt:z5}}var U5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],D5=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],w5=[/\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 p6($){return w5.reduce((J,Z)=>J.replace(Z," "),$)}function A1($){if(typeof $!=="string")return!1;let J=p6($);return U5.some((Z)=>Z.test(J))}var q5="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.",G5="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.",F5="Required worktree lifecycle did not complete before the retry limit.",L5=3;function d6($,J,Z){if(!$)return{action:"none"};let W=p6($);if(!A1(W))return{action:"none"};let Y=D5.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>=L5)return{action:"fail",message:F5};return{action:"retry",tool:V,prompt:V==="EnterWorktree"?q5:G5}}var C6=30000;async function F2($){try{let Z=A$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??H0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((V)=>{W=setTimeout(()=>V("timeout"),C6)});try{let V=await Promise.race([Z,Y]);if(V==="timeout")return D2.warn(`[Loop] Stop hook 超时 (${C6}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 D2.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function O5($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var f5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function y5($){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 A5($){let J=$;for(let X of f5)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 m6($){return A5(y5($))}import{EventEmitter as P5}from"events";import c6 from"node:path";function L2($){if(i6($.sessionId),!c6.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:c6.resolve($.projectPath)}}function l6($){let J=L2($);return JSON.stringify([J.projectPath,J.sessionId])}function tZ($,J){return l6($)===l6(J)}class P$ extends P5{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=L2($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:J,...W!==void 0?{seq:W}:{},properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var r$=P$.getInstance();var t0=h0("Agent"),P1=new Set;async function N5($,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 n$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let V=m6(J);if(!V)return;await n$.updateSessionMetadata(Z,Y.projectPath,{title:V}),r$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:V})}catch(W){t0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var O2=`<turn_aborted>
|
|
1
|
+
import{Tb as _4}from"./chunk-r8wbvxn7.js";import{Dc as V1,Nc as I0,Pc as V6,Qc as R1,Rc as K6,Ub as X$,Yc as n$,cc as xJ,dc as kJ,ec as d2,fc as m2,lc as CJ,mc as b4,nc as E4,oc as v2,pc as x1,qc as S4,rc as T4,sc as E1,vc as UJ}from"./chunk-gk79etn6.js";import{bd as F0,ed as _J,fd as k0}from"./chunk-r77pcb0f.js";import{ge as aJ}from"./chunk-g9xjcfrf.js";import{he as P4,ie as i0,je as F4,ke as HJ,ne as b1,oe as Y6,pe as zJ,qe as BJ,se as jJ}from"./chunk-b2p9qm6j.js";import{bf as J$,cf as r0,ff as N4,jf as K4}from"./chunk-sr4zv59p.js";import{uf as A$}from"./chunk-z21es9vg.js";import{Eg as lJ}from"./chunk-7m5q8vxf.js";import{Tg as H0}from"./chunk-sb84vdcf.js";import{th as h0}from"./chunk-ffa6hhee.js";import{Hh as hJ}from"./chunk-p3jvzk1f.js";import{Sh as _$,Uh as i6,Vh as y0,Wh as M1,Yh as MJ,_h as RJ}from"./chunk-shr5cg46.js";import{$h as w8}from"./chunk-6jsmac0q.js";function f$($){return $.role==="system"&&Array.isArray($.content)}function O$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class f1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,J){this.context=$;let Z=$.messages.find(f$);if(this._contextualSystemMessages=$.messages.filter(O$),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!f$(W)&&!O$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}get contextRevision(){return this._contextRevision}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!O$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(f$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((J)=>J.id===$.id))return;this._history.push($)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((J)=>!f$(J)&&!O$(J)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(O$),this._history=$.filter((J)=>!f$(J)&&!O$(J)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let J=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((Z)=>!$(Z)),this._pending=this._pending.filter((Z)=>!$(Z)),this._contextualSystemMessages=this._contextualSystemMessages.filter((Z)=>!$(Z)),this.syncContextualSystemMessages(),this._history.length!==J[0]||this._pending.length!==J[1]||this._contextualSystemMessages.length!==J[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function _6($){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 b6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function E6($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import Q$ from"node:path";var g4=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"]),p4=/^(LD_.+|DYLD_.+|PATH)$/,S6=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function c$($){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(S6);if(!V)break;let K=V[1];if(!g4.has(K))break;J=Y}return J}function kZ($){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(S6);if(!V)break;let K=V[1];if(p4.test(K))break;J=Y}return J}var d4=[/^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 U2($){let J=$,Z=!0;while(Z){Z=!1;for(let W of d4){let Y=J.match(W);if(Y){J=J.slice(Y[0].length),Z=!0;break}}if(J.startsWith("-- "))J=J.slice(3),Z=!0}return J}function l$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){Z+=Q,V=!0;continue}if(Q==="'"&&!Y){W=!W,Z+=Q;continue}if(Q==='"'&&!W){Y=!Y,Z+=Q;continue}if(W||Y){Z+=Q;continue}if(Q==="|"){if(K+1<$.length&&$[K+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&K+1<$.length&&$[K+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}if(Q==="&")return null;if(Q===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=Q}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function 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 m4=new Set(["npm","pnpm","yarn","bun"]),M6=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),c4=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),l4=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function i4($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function R6($){return $.replace(/\s+2>&1\s*$/,"").trim()}function r4($,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 n4($){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 o4($){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 a4($){let J=R6($.replace(l4,"").trim()),Z=n4(J);if(!Z)return;if(Z.length===0)return h6(J);if(Z.length!==1)return;let W=Z[0];if(W===void 0)return;let Y=R6(J.slice(0,W).trim()),V=J.slice(W+1).trim();if(!Y||!o4(V))return;return h6(Y)}function h6($){let Z=l$($)?.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=a4($);if(!Z)return!1;let W=c$(Z),Y=l$(W);if(!Y||T6(W)||/[\r\n]/.test(W))return!1;let V=Y.length===1?Y[0]:r4(W,Y,J);if(!V)return!1;let K=K$(V);if(K.length===0||K.some((B)=>[...c4].some((j)=>B===j||B.startsWith(`${j}=`))))return!1;let[Q,X,H]=K;if(m4.has(Q??""))return i4(X==="run"?H:X)||X==="--test";if((Q==="npx"||Q==="bunx")&&M6.has(X??""))return!0;if(M6.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 gZ($,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 D2=h0("Agent"),s4=3;function w2($,J,Z){if($!=="length")return{action:"none"};if(J>=s4)return{action:"truncated"};if(_6(Z)==="stop")return D2.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var t4=[/:\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],e4=/```[\s\S]{50,}```/,x6="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",$5=2;function q2($,J,Z=!0){if(!$||J>=$5)return{action:"none"};if(!Z&&e4.test($))return{action:"retry",prompt:x6};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(t4.some((K)=>K.test(W)))return{action:"retry",prompt:x6};return{action:"none"}}var J5=[/\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}(?:测试|单测|集成测试|检查|构建)/],k6={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},Z5={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},W5="The user explicitly required verification, but it has not run successfully. Do not finish or explain. Your next action must be a Bash tool call that runs the requested test, lint, type-check, or build command. Inspect the command result and fix any failure before finishing.",Y5="Required verification did not run successfully before the retry limit.",V5=3;function v6($,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 G2($,J,Z){if(!$||!J5.some((X)=>X.test($)))return{action:"none"};let W=Object.keys(k6).filter((X)=>k6[X].test($)),Y=[...J],V=W.filter((X)=>!Y.some((H)=>Z5[X].test(H)));if(W.length>0?V.length===0:Y.some((X)=>y$(X)))return{action:"none"};if(Z>=V5)return{action:"fail",message:Y5};let Q=W.length>1&&V.length>0?` Missing successful verification categories: ${V.join(", ")}.`:"";return{action:"retry",prompt:`${W5}${Q}`}}var K5=[/\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|子代理|子智能体)/],I6=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function u6($){return typeof $==="string"&&I6.some((J)=>J.test($))}var Q5=[/\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|子代理)/],X5=[/\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 H5($){if(typeof $!=="string")return;if(X5.some((J)=>J.test($)))return"multiple-allowed";return Q5.some((J)=>J.test($))?"required":void 0}function i$($){for(let J of $){let Z=H5(J);if(Z!==void 0)return Z==="required"}return!1}var z5="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.",B5="Required delegation did not complete before the retry limit.",j5=3;function g6($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),Y=i$(W),V=!1;if(!Y)for(let K of W){if(I6.some((Q)=>Q.test(K)))break;if(K5.some((Q)=>Q.test(K))){V=!0;break}}if(W.length===0||!Y&&!V||J.has("Task"))return{action:"none"};if(Z>=j5)return{action:"fail",message:B5};return{action:"retry",prompt:z5}}var U5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],D5=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],w5=[/\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 p6($){return w5.reduce((J,Z)=>J.replace(Z," "),$)}function A1($){if(typeof $!=="string")return!1;let J=p6($);return U5.some((Z)=>Z.test(J))}var q5="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.",G5="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.",F5="Required worktree lifecycle did not complete before the retry limit.",L5=3;function d6($,J,Z){if(!$)return{action:"none"};let W=p6($);if(!A1(W))return{action:"none"};let Y=D5.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>=L5)return{action:"fail",message:F5};return{action:"retry",tool:V,prompt:V==="EnterWorktree"?q5:G5}}var C6=30000;async function F2($){try{let Z=A$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??H0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((V)=>{W=setTimeout(()=>V("timeout"),C6)});try{let V=await Promise.race([Z,Y]);if(V==="timeout")return D2.warn(`[Loop] Stop hook 超时 (${C6}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 D2.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function O5($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var f5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function y5($){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 A5($){let J=$;for(let X of f5)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 m6($){return A5(y5($))}import{EventEmitter as P5}from"events";import c6 from"node:path";function L2($){if(i6($.sessionId),!c6.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:c6.resolve($.projectPath)}}function l6($){let J=L2($);return JSON.stringify([J.projectPath,J.sessionId])}function tZ($,J){return l6($)===l6(J)}class P$ extends P5{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=L2($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:J,...W!==void 0?{seq:W}:{},properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var r$=P$.getInstance();var t0=h0("Agent"),P1=new Set;async function N5($,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 n$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let V=m6(J);if(!V)return;await n$.updateSessionMetadata(Z,Y.projectPath,{title:V}),r$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:V})}catch(W){t0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var O2=`<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.",r6="Tool execution completed, but its durable result record could not be committed. Further model and tool execution was stopped. The operation may have completed; inspect external state before retrying.";class N$ extends Error{phase;constructor($,J){super($==="user_message"?"Conversation input could not be committed. No further model request was started.":"Model output could not be committed. The run was stopped before any further model request or successful completion.",J);this.phase=$;this.name="DurableConversationPersistenceError"}}function 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)N5(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 N$("user_message",{cause:Q})}return null}async function x0($,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 N$("assistant_message",{cause:X})}return null}async function n6($,J,Z){try{let W=z$($);if(W&&J.sessionId)return await W.saveMessage(J.sessionId,"system",O2,Z,void 0,J.subagentInfo)}catch(W){t0.warn("[Loop] 保存中断边界失败:",W)}return null}async function o6($,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 f2($,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 N1($,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 o$($,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 U0($){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 x0(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 Q6}from"node:crypto";import{promises as p5}from"node:fs";import d5 from"node:path";import{nanoid as e0}from"nanoid";import*as J0 from"node:fs/promises";import*as B$ from"node:path";var a6={enabled:!0,maxIndexLines:200};var _5="memory",s6="MEMORY.md";class y2{memoryDir;config;initialized=!1;constructor($,J,Z){if(Z)this.memoryDir=Z;else{let W=_$($);this.memoryDir=B$.join(W,_5)}this.config={...a6,...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,s6);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(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as RY,c as MY,d as TY}from"./chunk-
|
|
1
|
+
import{b as RY,c as MY,d as TY}from"./chunk-yq5vm0hf.js";import{j as DJ,k as VJ}from"./chunk-gd2sw9zm.js";import{u as s2}from"./chunk-gzjt969t.js";import{B as c6,D as gY,F as OQ,G as XQ,H as v6,L as A6,M as P6,Q as j1,S as e4,T as $6,W as y6,Y as z2,Z as nJ,_ as tJ,ba as sJ,ca as eJ,ga as L4,ha as $9,ja as t6,ka as s6,la as mY,ma as O6,oa as z6,qa as x6}from"./chunk-zpbbcdme.js";import{ua as qJ,va as OJ,wa as zJ,za as EY}from"./chunk-b8p2mwq9.js";import{Ba as b6}from"./chunk-tpxs85cg.js";import{Eb as QQ,ib as L6,jb as B6,vb as w6}from"./chunk-6n63ev2e.js";import{Pb as W2}from"./chunk-r8wbvxn7.js";import{Cc as s4,Jc as Y6,Kc as $Q,Lc as Z6,Nc as d2,Vc as O2,Yc as C0,jc as _6,xc as t4}from"./chunk-gk79etn6.js";import"./chunk-d2pwwdab.js";import"./chunk-r77pcb0f.js";import{zd as PY}from"./chunk-fv8b98tz.js";import{Ad as H2,Bd as e2,Dd as C1}from"./chunk-x89n28mq.js";import"./chunk-skg520wq.js";import{Hd as k$,Id as a0,Jd as Q$,Kd as jQ,Ld as g$,Md as r2,Nd as v9,Od as Q4,Pd as MJ,Qd as D9,Rd as V$,Sd as l0,Td as jY,Ud as o0,Vd as AY,Wd as D8,Xd as N2,_d as U6,fe as p0}from"./chunk-bthb5c55.js";import"./chunk-v508x7cg.js";import"./chunk-g9xjcfrf.js";import"./chunk-b2p9qm6j.js";import{ve as J4}from"./chunk-0q5bz3nm.js";import"./chunk-44dzrn0p.js";import"./chunk-deeh2eq1.js";import{He as Q8,Ke as _Y,Pe as iJ,Ye as hY}from"./chunk-t5d4p0gc.js";import"./chunk-sr4zv59p.js";import"./chunk-ww51801m.js";import"./chunk-7rfhmbqw.js";import{sf as gQ,uf as q1}from"./chunk-z21es9vg.js";import"./chunk-272swnyr.js";import{Bg as oJ,Cg as VY,wg as DY}from"./chunk-zpryec89.js";import"./chunk-7m5q8vxf.js";import"./chunk-sk8h4m9m.js";import{Lg as m$,Mg as a2,Og as mQ}from"./chunk-hg8d4vhj.js";import{Tg as d0}from"./chunk-sb84vdcf.js";import"./chunk-hjr9r44k.js";import{qh as vY,th as t1}from"./chunk-ffa6hhee.js";import{vh as kJ,wh as SJ,zh as h1}from"./chunk-t1633e8m.js";import"./chunk-m5f934fh.js";import{Lh as bJ}from"./chunk-p3jvzk1f.js";import{Oh as F4}from"./chunk-rwvaapta.js";import"./chunk-83caxxbt.js";import{Zh as e8}from"./chunk-shr5cg46.js";import{$h as EQ}from"./chunk-6jsmac0q.js";import{useMemoizedFn as u8}from"ahooks";import{useEffect as S7,useState as l8}from"react";import{useMemoizedFn as s0}from"ahooks";import{Box as z$}from"ink";import{useEffect as _$,useMemo as R7,useRef as p8}from"react";import{useShallow as uY}from"zustand/react/shallow";import{useStore as xY}from"zustand";function t($){return xY(V$,$)}var lY=[],j$=()=>t(($)=>$.session.sessionId),T1=()=>t(($)=>$.session.workspaceRoot),B4=()=>t(($)=>$.session.messages),w4=()=>t(($)=>$.session.clearCount),b4=()=>t(($)=>$.session.isCompacting),A4=()=>t(($)=>$.session.tokenUsage.estimatedCostUsd),P4=()=>t(($)=>{let{totalInputTokens:Q,cacheReadTokens:Y,cacheWriteTokens:J}=$.session.tokenUsage;return L4({totalInputTokens:Q,cacheReadTokens:Y,cacheWriteTokens:J}).hitRate}),y4=()=>t(($)=>$.session.providerCircuit),R4=()=>t(($)=>$.session.providerAdmission),M4=()=>t(($)=>$.session.providerRetry),T4=()=>t(($)=>$.session.providerStall),C4=()=>t(($)=>$.session.actionStationarity),i1=()=>t(($)=>$.session.actions),I4=()=>t(($)=>{let{totalTokens:Q,maxContextTokens:Y}=$.session.tokenUsage;if(Y<=0)return 100;let J=Math.max(0,100-Q/Y*100);return Math.round(J)}),f4=()=>t(($)=>$.app.initializationStatus),k4=()=>t(($)=>$.app.initializationError),D2=()=>t(($)=>$.app.activeModal),S4=()=>t(($)=>$.app.tasks),v4=()=>t(($)=>$.app.modelEditorTarget),D4=()=>t(($)=>$.app.sessionSelectorData),V4=()=>t(($)=>$.app.awaitingSecondCtrlC),n1=()=>t(($)=>$.app.actions),V2=()=>t(($)=>$.app.sideConversation),j4=()=>t(($)=>$.app.teams),j2=()=>t(($)=>$.app.initializationStatus==="ready"),h4=()=>t(($)=>$.app.tasks.length>0),h$=()=>t(($)=>$.config.config?.permissionMode||"default"),E4=()=>t(($)=>$.config.config?.models??lY),h2=()=>t(($)=>{let Q=$.config.config;if(!Q)return;let Y=Q.currentModelId;return Q.models.find((Z)=>Z.id===Y)??Q.models[0]}),E2=()=>t(($)=>$.config.config?.currentModelId),g4=()=>t(($)=>$.config.config?.agentTeamsEnabled===!0),b0=()=>t(($)=>{return a0.getTheme()}),m4=()=>t(($)=>$.config.config?.codeTheme??"default"),e0=()=>t(($)=>$.focus.currentFocus),p4=()=>t(($)=>$.focus.actions),E$=()=>t(($)=>$.command.isProcessing),c4=()=>t(($)=>$.command.actions),g2=()=>t(($)=>$.command.pendingCommands),x4=()=>t(($)=>$.command.recoveredSteeringCount),m2=()=>t(($)=>$.app.reasoningEffort!=="off"),p2=()=>t(($)=>$.app.reasoningEffort),c2=()=>t(($)=>$.app.serviceTier),x2=()=>t(($)=>$.app.responseVerbosity),u2=()=>t(($)=>$.app.communicationStyle),u4=()=>t(($)=>$.session.currentThinkingContent),l4=()=>t(($)=>$.session.thinkingExpanded),d4=()=>t(($)=>$.session.currentStreamingMessageId),r4=()=>t(uY(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),a4=()=>t(($)=>$.session.finalizingStreamingMessageId),o4=()=>t(($)=>$.session.historyExpanded),i4=()=>t(($)=>$.session.expandedMessageCount);import{useMemoizedFn as s1}from"ahooks";import{useEffect as c$,useRef as s8}from"react";function dY($){if(!($ instanceof Error))return"未知错误";let J=$.lastError??$;if(J.responseBody)try{let K=JSON.parse(J.responseBody)?.error?.message;if(K){let U=J.statusCode?` (HTTP ${J.statusCode})`:"";return`${K}${U}`}}catch{}let Z=$.message.match(/Last error:\s*(.+)$/);if(Z)return Z[1];return $.message}function rY($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function aY($){if(!($ instanceof Error))return!1;let Q=$.message;return Q.includes("can only concatenate str")||Q.includes("image_url")||Q.includes("multimodal")||Q.includes("vision")||Q.includes("does not support images")}function l2($){let Q=rY($),Y=aY($),J;if(Y)J="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else J=dY($);return{displayMessage:J,isAbort:Q,isVisionNotSupported:Y}}import{appendFileSync as oY,mkdirSync as iY,writeFileSync as nY}from"node:fs";import tY from"node:os";import a8 from"node:path";var n4=null;function sY(){let $=process.env.BLADE_STORAGE_ROOT||a8.join(tY.homedir(),".blade");return a8.join($,"logs","stream-debug.log")}function eY($){if(n4===$)return;let Q=a8.dirname($);iY(Q,{recursive:!0,mode:493}),nY($,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
|
|
2
2
|
`),n4=$}function o8($,Q,Y){try{let J=sY();eY(J);let Z=new Date().toISOString(),X=Y?` | ${JSON.stringify(Y)}`:"",K=`[${Z}] [${$}] ${Q}${X}
|
|
3
3
|
`;oY(J,K)}catch{}}var q2=t1("UI");function Q6($,Q){let Y=!1;return(J)=>{switch(J.kind){case"content_delta":if(Y||$.signal.aborted)break;Q.contentDeltaCount++,Q.contentDeltaTotalLen+=J.delta.length,o8("loopEventHandler","onContentDelta",{callCount:Q.contentDeltaCount,deltaLen:J.delta.length,totalLen:Q.contentDeltaTotalLen}),$.streamingBuffer.batchAppendContent(J.delta);break;case"thinking_delta":if(Y||$.signal.aborted)break;if($.thinkingModeEnabled)$.streamingBuffer.batchAppendThinking(J.delta);break;case"stream_end":{if($.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),q2.debug("[loopEventHandler] stream_end",{contentDeltaCount:Q.contentDeltaCount,contentDeltaTotalLen:Q.contentDeltaTotalLen,streamFinalized:Y,signalAborted:$.signal.aborted}),o8("loopEventHandler","onStreamEnd",{contentDeltaCallCount:Q.contentDeltaCount,contentDeltaTotalLen:Q.contentDeltaTotalLen,streamFinalized:Y,signalAborted:$.signal.aborted}),Y||$.signal.aborted){Y=!0;break}let{extraContent:Z,extraThinking:X}=$.streamingBuffer.drainPendingBuffers(),K=$.getStreamingMessageId();if(K){if(Z)g$(K,Z);r2(K)}$.sessionActions.finalizeStreamingMessage(Z,X),Y=!0;break}case"model_fallback":Y=!0,$.sessionActions.setProviderAdmission(null),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),$.streamingBuffer.resetStreamingBuffers(),$.sessionActions.discardStreamingMessage(),$.sessionActions.setCurrentThinkingContent(null);break;case"provider_admission":{let{kind:Z,...X}=J;$.sessionActions.setProviderAdmission(J.phase==="queued"?X:null);break}case"provider_circuit":{let{kind:Z,...X}=J;$.sessionActions.setProviderCircuit(J.phase==="closed"?null:X);break}case"provider_retry":{let{kind:Z,...X}=J;$.sessionActions.setProviderRetry(J.phase==="recovered"?null:X);break}case"provider_stall":{let{kind:Z,...X}=J;$.sessionActions.setProviderStall(J.phase==="detected"?X:null);break}case"action_stationarity":{let{kind:Z,...X}=J;$.sessionActions.setActionStationarity(J.phase==="recovered"?null:X);break}case"tool_start":{let Z=J.toolCall;if(!("function"in Z))break;if(Z.function.name===d2)break;if(q2.debug("[loopEventHandler] tool_start",{toolName:Z.function.name,toolKind:J.toolKind}),["TaskCreate","TaskUpdate","TaskList"].includes(Z.function.name))break;try{let X=JSON.parse(Z.function.arguments),K=e4(Z.function.name,X);$.sessionActions.addToolMessage(K,{toolCallId:Z.id,toolName:Z.function.name,phase:"start",summary:K,params:X})}catch(X){q2.error("[loopEventHandler] onToolStart error:",X)}break}case"tool_progress":{let Z=J.toolCall;if(!("function"in Z))break;if(Z.function.name===d2)break;let X=J.update.total!==void 0?` ${Math.max(0,Math.min(100,Math.round((J.update.progress??0)/J.update.total*100)))}%`:"",K=`${Z.function.name}${X}: ${J.update.message}`;$.sessionActions.addToolMessage(K,{toolCallId:Z.id,toolName:Z.function.name,phase:"progress",summary:K,...J.update.admission?{admission:J.update.admission}:{}});break}case"tool_result":{let Z=J.toolCall;if(!("function"in Z))break;if(Z.function.name===d2)break;q2.debug("[loopEventHandler] tool_result",{toolName:Z.function.name,success:J.result.success});let X=s4($6(Z.function.name,J.result),t4);$.sessionActions.addToolMessage(X.summary,{toolCallId:Z.id,toolName:Z.function.name,phase:"complete",summary:X.summary,detail:X.detail});break}case"structured_output":$.sessionActions.replaceLastAssistantMessage(JSON.stringify(J.output,null,2));break;case"token_usage":$.sessionActions.updateTokenUsage(J.usage);break;case"compaction":if($.sessionActions.setCompacting(J.phase==="start"),J.phase==="end"){if($.sessionActions.resetContextUsage(),J.outcome!=="failed")Q.compactionCount=(Q.compactionCount??0)+1}break;case"turn_start":q2.debug("[loopEventHandler] turn_start",{turn:J.turn,maxTurns:J.maxTurns}),$.sessionActions.updateTokenUsage({turnCount:J.turn}),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),Y=!1;break;case"task_update":$.appActions.setTasks(J.tasks);break;case"mcp_catalog_changed":{let Z=`MCP catalog r${J.revision}: +${J.added.length} -${J.removed.length} ~${J.updated.length}`;$.sessionActions.addToolMessage(Z,{toolName:"MCP Catalog",phase:"complete",summary:Z,detail:[J.added.length>0?`Added: ${J.added.join(", ")}`:"",J.removed.length>0?`Removed: ${J.removed.join(", ")}`:"",J.updated.length>0?`Updated: ${J.updated.join(", ")}`:""].filter(Boolean).join(`
|
|
4
4
|
`)});break}case"mcp_content_changed":{let Z=`MCP ${J.contentKind} r${J.revision}: +${J.added.length} -${J.removed.length} ~${J.updated.length}`;$.sessionActions.addToolMessage(Z,{toolName:"MCP Content",phase:"complete",summary:Z,detail:[J.added.length>0?`Added: ${J.added.join(", ")}`:"",J.removed.length>0?`Removed: ${J.removed.join(", ")}`:"",J.updated.length>0?`Updated: ${J.updated.join(", ")}`:""].filter(Boolean).join(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{j as L4,k as B4}from"./chunk-gd2sw9zm.js";import{l as O1}from"./chunk-01zar8q6.js";import{s as J0,t as n$}from"./chunk-
|
|
1
|
+
import{j as L4,k as B4}from"./chunk-gd2sw9zm.js";import{l as O1}from"./chunk-01zar8q6.js";import{s as J0,t as n$}from"./chunk-9vmxd900.js";import{u as oO}from"./chunk-gzjt969t.js";import{A as O$,v as v$,w as s1,x as r1,y as e1,z as x0}from"./chunk-00xsfm2j.js";import{$ as Y4,C as k4,F as y$,G as N0,H as R1,I as n0,J as L1,K as EO,L as m$,M as h$,N as g$,O as B1,P as mO,Q as S0,T as y0,U as f0,W as i4,X as u$,Y as p$,Z as Z4,_ as J4,aa as z4,ba as G4,ca as X4,da as V4,ea as N4,fa as K4,ia as H4,la as Ox,qa as q4}from"./chunk-zpbbcdme.js";import{ta as N$,za as UO}from"./chunk-b8p2mwq9.js";import{Da as z1,Ga as P4,Ha as E1,Ia as d$,Ja as l$,Ka as y4,La as f4,Ma as k1,Na as m4,Oa as sO,Pa as A4,Qa as M4,Ra as T4,Sa as i$,Ta as c$,Ua as a$,Va as o$,Wa as o1,Xa as m1}from"./chunk-tpxs85cg.js";import{Eb as nO,gb as gO,hb as p,jb as S,kb as f$,vb as H1}from"./chunk-6n63ev2e.js";import{Pb as R$}from"./chunk-r8wbvxn7.js";import{Ac as I0,Bc as M1,Cc as P0,Ec as k$,Kc as q$,Lc as I$,Nc as z0,Qc as U1,Vc as P$,Wc as _1,Xc as D1,Yc as R,jc as E$,uc as t0}from"./chunk-gk79etn6.js";import{Sd as d4,Wd as QO,_d as U$,fe as BO}from"./chunk-bthb5c55.js";import{ge as F1}from"./chunk-g9xjcfrf.js";import{xe as C$}from"./chunk-44dzrn0p.js";import{ze as o0}from"./chunk-deeh2eq1.js";import{He as l4,Je as C4,Me as Q4,Qe as j0,Re as b0,Ve as zx,Ye as jO,Ze as C0,af as Gx}from"./chunk-t5d4p0gc.js";import{of as _$,pf as S$}from"./chunk-ww51801m.js";import{tf as z$,uf as Z0}from"./chunk-z21es9vg.js";import{Bg as T0,Mf as V$,eg as T$,hg as j$,jg as b$,wg as G$}from"./chunk-zpryec89.js";import{Eg as K1}from"./chunk-7m5q8vxf.js";import{Fg as q,Hg as V,Ig as eO,Kg as JO}from"./chunk-sk8h4m9m.js";import{Mg as r0,Pg as W1}from"./chunk-hg8d4vhj.js";import{Tg as c}from"./chunk-sb84vdcf.js";import{th as o}from"./chunk-ffa6hhee.js";import{zh as cO}from"./chunk-t1633e8m.js";import{Bh as W$,Ch as A$,Eh as F$,Fh as M$}from"./chunk-m5f934fh.js";import{Hh as Q0}from"./chunk-p3jvzk1f.js";import{Oh as f1}from"./chunk-rwvaapta.js";import{Uh as i0,Yh as x$,Zh as s0}from"./chunk-shr5cg46.js";import{$h as I1}from"./chunk-6jsmac0q.js";var U3={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function _3(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{existsSync as h1,readFileSync as g0}from"node:fs";import{createServer as c2}from"node:http";import{networkInterfaces as a2}from"node:os";import{dirname as o2,extname as n2,join as dO}from"node:path";import{fileURLToPath as t2}from"node:url";import{brotliCompressSync as s2,gzipSync as r2,constants as e2}from"node:zlib";import{Hono as O3}from"hono";import{cors as $3}from"hono/cors";import{WebSocketServer as x3}from"ws";var $0=o("Service"),Nx=30000,Kx=new Set(["completed","failed","cancelled","interrupted"]);class G1{dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor(O){this.dispatch=O.dispatch,this.store=O.store??o1.getInstance(),this.tickMs=O.tickMs??Nx}start(){if(this.timer)return;$0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=S.subscribe((O)=>{if(O.type!=="task.status")return;let $=O.properties.taskStatus;if(typeof $!=="string"||!Kx.has($))return;this.recordTerminalStatus(O.sessionId,$,typeof O.properties.taskStatusReason==="string"?O.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,$0.info("[TaskScheduler] Stopped scheduler tick loop")}async tick(O=new Date){if(this.ticking)return;this.ticking=!0;try{let $=await this.store.list();for(let x of $)await this.evaluate(x,O)}catch($){$0.warn("[TaskScheduler] Tick failed:",$)}finally{this.ticking=!1}}async evaluate(O,$){if(!O.enabled)return;if(this.inFlight.has(O.id))return;if(O.expiresAt&&new Date(O.expiresAt).getTime()<=$.getTime()){await this.store.update(O.id,{enabled:!1,nextRunAt:null}),$0.info(`[TaskScheduler] Schedule ${O.id} expired; disabled`);return}if(!O.nextRunAt)return;if(!(new Date(O.nextRunAt).getTime()<=$.getTime()))return;await this.fire(O,$)}async fire(O,$=new Date,x={}){if(this.inFlight.has(O.id))throw Error(`Schedule ${O.id} is already dispatching`);this.inFlight.add(O.id);let Q=$.toISOString();try{let Z=await this.dispatch({prompt:O.prompt,title:O.title??Wx(O),sourceProjectPath:O.projectPath,isolation:O.dispatch.isolation??"worktree",permissionMode:O.dispatch.permissionMode??"default",modelId:O.dispatch.modelId,reasoningEffort:O.dispatch.reasoningEffort,serviceTier:O.dispatch.serviceTier,responseVerbosity:O.dispatch.responseVerbosity,communicationStyle:O.dispatch.communicationStyle}),G=O.trigger.kind==="once"?null:x.manual?O.nextRunAt?new Date(O.nextRunAt):null:z1(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:Q,lastRunSessionId:Z.session.sessionId,lastStatus:Z.status,lastError:void 0,runCount:O.runCount+1,nextRunAt:G?G.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled}),S.publish({sessionId:Z.session.sessionId,projectPath:O.projectPath},"schedule.fired",{scheduleId:O.id,firedAt:Q,sessionId:Z.session.sessionId,runId:Z.runId,status:Z.status}),$0.info(`[TaskScheduler] Fired schedule ${O.id} -> session ${Z.session.sessionId} (${Z.status})`)}catch(Z){let G=Z instanceof Error?Z.message:String(Z);$0.warn(`[TaskScheduler] Schedule ${O.id} dispatch failed:`,Z);let z=O.trigger.kind==="once"?null:x.manual?O.nextRunAt?new Date(O.nextRunAt):null:z1(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:Q,lastStatus:"error",lastError:G,nextRunAt:z?z.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled})}finally{this.inFlight.delete(O.id)}}async recordTerminalStatus(O,$,x){let Z=(await this.store.list()).find((G)=>G.lastRunSessionId===O);if(!Z)return;await this.store.update(Z.id,{lastStatus:$,...x?{lastError:x}:{lastError:void 0}})}}function Wx(O){return`Scheduled: ${O.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class xO extends Error{code;statusCode;details;constructor(O,$,x=500,Q){super($);this.code=O;this.statusCode=x;this.details=Q;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class f extends xO{constructor(O,$){super("NOT_FOUND",$?`${O} not found: ${$}`:`${O} not found`,404)}}class _ extends xO{constructor(O){super("BAD_REQUEST",O,400)}}class k extends xO{constructor(O){super("CONFLICT",O,409)}}class kO extends xO{constructor(O,$){super("TOO_MANY_REQUESTS",O,429,$)}}class qO extends xO{constructor(O="Server is shutting down"){super("SERVICE_UNAVAILABLE",O,503)}}class LO extends xO{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class t extends xO{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var T3=V.Object({error:V.Object({code:V.String(),message:V.String(),details:V.Optional(V.Record(V.String(),V.Unknown()))})});import{Hono as Fx}from"hono";var X1=o("Service"),Ux=V.Object({updates:V.Record(V.String(),V.Any()),options:V.Optional(V.Object({scope:V.Optional(JO(["local","project","global"])),immediate:V.Optional(V.Boolean())}))});function _x(O){return{currentModelId:O.currentModelId,permissionMode:O.permissionMode,language:O.language,codeTheme:O.codeTheme,uiTheme:O.uiTheme,autoSaveSessions:O.autoSaveSessions,notifyBuild:O.notifyBuild,notifyErrors:O.notifyErrors,notifySounds:O.notifySounds,privacyTelemetry:O.privacyTelemetry,privacyCrash:O.privacyCrash,agentTeamsEnabled:O.agentTeamsEnabled===!0,communicationStyle:O.communicationStyle,maxConcurrentTasks:O.maxConcurrentTasks,maxQueuedTasks:O.maxQueuedTasks,maxQueuedTaskBytes:O.maxQueuedTaskBytes,maxResidentSessionRuntimes:O.maxResidentSessionRuntimes,sessionRuntimeIdleMs:O.sessionRuntimeIdleMs}}var n1=()=>{let O=new Fx;return O.get("/",async($)=>{try{let x=QO();return $.json(x?_x(x):{})}catch(x){return X1.error("[ConfigRoutes] Failed to get config:",x),$.json({})}}),O.put("/",async($)=>{try{let x=await $.req.json(),Q=q(Ux,x);if(!Q.success)throw new _("Invalid config update format");let{updates:Z,options:G}=Q.data;return await BO().updateConfig(Z,G),$.json({success:!0,updates:Z})}catch(x){throw X1.error("[ConfigRoutes] Failed to update config:",x),x}}),O.get("/permissions",async($)=>{try{let x=QO();return $.json(x?.permissions||{})}catch(x){return X1.error("[ConfigRoutes] Failed to get permissions:",x),$.json({})}}),O};import{Hono as Dx}from"hono";import{streamSSE as Hx}from"hono/streaming";function t1(O){let $="";if(O.id!==void 0)$+=`id: ${O.id}
|
|
2
2
|
`;if(O.event!==void 0)$+=`event: ${O.event}
|
|
3
3
|
`;for(let x of O.data.split(/\r\n|\r|\n/))$+=`data: ${x}
|
|
4
4
|
`;if(O.retry!==void 0)$+=`retry: ${O.retry}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{kg as H,lg as I}from"./chunk-
|
|
1
|
+
import{kg as H,lg as I}from"./chunk-zpryec89.js";import{Mutex as J}from"async-mutex";class B extends Error{limit;resource="resident_runtimes";retryable=!0;constructor(b){super("Session runtime capacity is full");this.limit=b;this.name="SessionRuntimeCapacityError"}}class D extends Error{constructor(){super("Session runtime residency is closed");this.name="SessionRuntimeResidencyClosedError"}}class A extends Error{constructor(b){super(`Session runtime residency already owns key: ${b}`);this.name="SessionRuntimeResidencyConflictError"}}class K{maxResident;idleMs;now;residents=new Map;reservations=new Map;operations=new J;nextGeneration=1;closed=!1;constructor(b){if(!H(b.maxResident))throw Error("Invalid max resident Session Runtime limit");if(!I(b.idleMs))throw Error("Invalid Session Runtime idle timeout");this.maxResident=b.maxResident,this.idleMs=b.idleMs,this.now=b.now??Date.now}acquire(b){let j=this.residents.get(b);if(!j||j.poisoned)return;return j.pins++,j.lastUsedAt=this.now(),this.createLease(j)}owns(b,j){let q=this.residents.get(b);return Boolean(q&&(j===void 0||q.value===j))}async reserve(b,j){if(!b.trim())throw Error("Session runtime residency key must not be blank");return this.operations.runExclusive(async()=>{if(this.closed)throw new D;if(this.residents.has(b)||this.reservations.has(b))throw new A(b);while(this.retainedCount()>=this.maxResident){if(!j.allowEviction)throw new B(this.maxResident);let z=this.oldestEvictableWebResident();if(!z)throw new B(this.maxResident);await this.disposeResident(z,!0)}let q={generation:this.allocateGeneration(),surface:j.surface};return this.reservations.set(b,q),this.createReservation(b,q)})}async remove(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j)return!1;if(q.pins>0)return!1;return await this.disposeResident(q,!0),!0})}async forget(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j||q.pins>0)return!1;return this.residents.delete(b),!0})}async sweepIdle(){return this.operations.runExclusive(async()=>{if(this.closed)return 0;let b=0;while(!0){let j=this.oldestIdleWebResident();if(!j)return b;await this.disposeResident(j,!0),b++}})}async disposeAll(){await this.operations.runExclusive(async()=>{this.closed=!0,this.reservations.clear();let b;for(let j of[...this.residents.values()])try{await this.disposeResident(j,!1)}catch(q){b??=q}if(this.residents.clear(),b!==void 0)throw b})}getStats(){let b=0;for(let j of this.residents.values())if(j.pins>0)b++;return{resident:this.residents.size,reserved:this.reservations.size,pinned:b,maxResident:this.maxResident}}retainedCount(){return this.residents.size+this.reservations.size}allocateGeneration(){let b=this.nextGeneration;return this.nextGeneration=this.nextGeneration===Number.MAX_SAFE_INTEGER?1:this.nextGeneration+1,b}createReservation(b,j){let q=!1;return{commit:(z)=>{if(q)throw new A(b);if(z.key!==b||z.surface!==j.surface||this.reservations.get(b)!==j||this.closed)throw this.reservations.delete(b),q=!0,this.closed?new D:new A(b);this.reservations.delete(b);let G={...z,generation:j.generation,pins:1,lastUsedAt:this.now(),poisoned:!1};return this.residents.set(b,G),q=!0,this.createLease(G)},cancel:()=>{if(q)return;if(this.reservations.get(b)===j)this.reservations.delete(b);q=!0}}}createLease(b){let j=!1;return{value:b.value,release:()=>{if(j)return;j=!0;let q=this.residents.get(b.key);if(q!==b||q.generation!==b.generation)return;q.pins=Math.max(0,q.pins-1),q.lastUsedAt=this.now()}}}oldestEvictableWebResident(){return this.sortedWebResidents().find((b)=>this.canEvict(b))}oldestIdleWebResident(){let b=this.now();return this.sortedWebResidents().find((j)=>b-j.lastUsedAt>=this.idleMs&&this.canEvict(j))}sortedWebResidents(){return[...this.residents.values()].filter((b)=>b.surface==="web").sort((b,j)=>b.lastUsedAt-j.lastUsedAt||b.generation-j.generation)}canEvict(b){if(b.pins>0||b.poisoned)return!1;try{return b.canEvict()}catch{return!1}}async disposeResident(b,j){if(this.residents.get(b.key)!==b)return;this.residents.delete(b.key);try{await b.dispose()}catch(q){if(j&&!this.closed&&!this.residents.has(b.key))b.lastUsedAt=this.now(),b.poisoned=!0,this.residents.set(b.key,b);throw q}}}
|
|
2
2
|
export{B as s,K as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{f as a,g as i,h as l,i as m}from"./chunk-
|
|
1
|
+
import{f as a,g as i,h as l,i as m}from"./chunk-9erhm3gg.js";import"./chunk-gd2sw9zm.js";import"./chunk-01zar8q6.js";import"./chunk-9vmxd900.js";import"./chunk-gzjt969t.js";import"./chunk-00xsfm2j.js";import"./chunk-zpbbcdme.js";import"./chunk-b8p2mwq9.js";import"./chunk-tpxs85cg.js";import"./chunk-6n63ev2e.js";import"./chunk-r8wbvxn7.js";import"./chunk-gk79etn6.js";import"./chunk-d2pwwdab.js";import"./chunk-r77pcb0f.js";import{Bd as n}from"./chunk-x89n28mq.js";import"./chunk-skg520wq.js";import{Xd as s}from"./chunk-bthb5c55.js";import"./chunk-v508x7cg.js";import"./chunk-g9xjcfrf.js";import"./chunk-b2p9qm6j.js";import"./chunk-0q5bz3nm.js";import"./chunk-44dzrn0p.js";import"./chunk-deeh2eq1.js";import"./chunk-t5d4p0gc.js";import"./chunk-sr4zv59p.js";import"./chunk-ww51801m.js";import"./chunk-7rfhmbqw.js";import"./chunk-z21es9vg.js";import"./chunk-272swnyr.js";import"./chunk-zpryec89.js";import"./chunk-7m5q8vxf.js";import"./chunk-sk8h4m9m.js";import"./chunk-hg8d4vhj.js";import"./chunk-sb84vdcf.js";import"./chunk-hjr9r44k.js";import"./chunk-ffa6hhee.js";import"./chunk-t1633e8m.js";import"./chunk-m5f934fh.js";import"./chunk-p3jvzk1f.js";import"./chunk-rwvaapta.js";import"./chunk-83caxxbt.js";import"./chunk-shr5cg46.js";import"./chunk-6jsmac0q.js";import v from"chalk";var C={command:"serve",describe:"Start a headless Blade server (no browser)",builder:a,handler:async(p)=>{let r=i(p);if(await s(),!process.env.BLADE_SERVER_PASSWORD)console.log(v.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let e=await m.listenAsync(r);if(console.log(`Blade server listening on http://${e.hostname}:${e.port}`),r.hostname==="0.0.0.0"){let o=l();for(let g of o)console.log(` Network: http://${g}:${e.port}`)}let t,c=new Promise((o)=>{t=o}),d=n(async()=>{await e.stop(),t()});try{await c}finally{d(),await e.stop()}}};export{C as serveCommand};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{s as hz,t as Sz}from"./chunk-
|
|
1
|
+
import{s as hz,t as Sz}from"./chunk-9vmxd900.js";import{u as b}from"./chunk-gzjt969t.js";import{A as Gz,v as yz,w as Xz,x as Dz,y as Lz,z as Bz}from"./chunk-00xsfm2j.js";import{E as N,L as $z,M as Qz,Q as Wz,T as Yz,U as Hz,Y as jz,ma as Fz,na as Uz,oa as Vz,pa as wz}from"./chunk-zpbbcdme.js";import{za as Tz}from"./chunk-b8p2mwq9.js";import{Ba as Zz}from"./chunk-tpxs85cg.js";import{Eb as Jz,jb as e,vb as zz}from"./chunk-6n63ev2e.js";import{Pb as I}from"./chunk-r8wbvxn7.js";import{Cc as o,Ec as n,Kc as C,Lc as s,Nc as x,Qc as t,Vc as q,Yc as U,jc as l,tc as i,uc as r,zc as a}from"./chunk-gk79etn6.js";import"./chunk-d2pwwdab.js";import"./chunk-r77pcb0f.js";import{Bd as Mz}from"./chunk-x89n28mq.js";import"./chunk-skg520wq.js";import{Wd as Nz,Xd as Ez}from"./chunk-bthb5c55.js";import"./chunk-v508x7cg.js";import{ge as f}from"./chunk-g9xjcfrf.js";import{le as v}from"./chunk-b2p9qm6j.js";import"./chunk-0q5bz3nm.js";import{we as xz}from"./chunk-44dzrn0p.js";import"./chunk-deeh2eq1.js";import"./chunk-t5d4p0gc.js";import"./chunk-sr4zv59p.js";import{mf as bz}from"./chunk-ww51801m.js";import"./chunk-7rfhmbqw.js";import"./chunk-z21es9vg.js";import"./chunk-272swnyr.js";import{eg as qz,hg as Pz}from"./chunk-zpryec89.js";import"./chunk-7m5q8vxf.js";import"./chunk-sk8h4m9m.js";import{Lg as S,Mg as d,Og as M,Pg as k}from"./chunk-hg8d4vhj.js";import{Tg as Oz}from"./chunk-sb84vdcf.js";import"./chunk-hjr9r44k.js";import{th as T}from"./chunk-ffa6hhee.js";import"./chunk-t1633e8m.js";import{Ah as Az,Dh as Rz}from"./chunk-m5f934fh.js";import"./chunk-p3jvzk1f.js";import"./chunk-rwvaapta.js";import"./chunk-83caxxbt.js";import{Zh as m}from"./chunk-shr5cg46.js";import"./chunk-6jsmac0q.js";import{Readable as vz,Writable as lz}from"node:stream";import*as y from"@agentclientprotocol/sdk";import _z from"node:path";import{PROTOCOL_VERSION as mz,RequestError as dz}from"@agentclientprotocol/sdk";import{RequestError as Cz}from"@agentclientprotocol/sdk";import{nanoid as h}from"nanoid";var G=T("Agent");function p(z){if(!z)return{};return Object.fromEntries(z.map((Z)=>[Z.name,Z.value]))}function fz(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:p(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:p("headers"in z?z.headers:void 0)};return null}function uz(z){let Z={};for(let J of z){let Y=fz(J);if(Y)Z[J.name]=Y}return Z}function Kz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((Z)=>{if(Z.type==="text")return Z.text?[{type:"text",text:Z.text}]:[];let J=Z.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(J);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function gz(z){let Z=s(z.metadata);return Z?[{type:"text",text:C(Z)}]:Kz(z.content)}function cz(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
|
|
2
2
|
`)}function pz(z){if(!v(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...i("capacity"),resource:z.resource}}class E{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingPromptCompletion=null;pendingUserShell=null;pendingUserShellCompletion=null;pendingSideConversation=null;pendingSideConversationCompletion=null;pendingResumeRequested=!1;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;destroyFinished=!1;destroyPromise;messages;contextMessages;mode;updateEgress;constructor(z,Z,J,Y,H={}){this.id=z;this.cwd=Z;this.connection=J;this.clientCapabilities=Y;this.options=H;this.messages=[...H.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(H.permissionMode),this.updateEgress=new Gz({maxPendingItems:Xz,maxPendingBytes:Dz,writeTimeoutMs:Lz,signal:J.signal,sizeOf:(W)=>Buffer.byteLength(JSON.stringify(W)),write:async(W)=>{await J.sessionUpdate(W)},onFailure:(W)=>this.handleUpdateEgressFailure(W)})}async refreshPersistedMessages(){let[z,Z]=await Promise.all([U.loadSession(this.id,this.cwd),U.loadSessionModelContext(this.id,this.cwd)]);if(z.length>0)this.messages=z;if(Z.length>0)this.contextMessages=Z}async loadModelContextOr(z){let Z=await U.loadSessionModelContext(this.id,this.cwd);return Z.length>0?Z:[...z]}mapPermissionModeToMode(z){switch(z){case"yolo":return"yolo";case"autoEdit":return"auto-edit";case"plan":return"plan";case"default":default:return"default"}}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return jz.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(G.debug(`[AcpSession ${this.id}] Initializing...`),await U.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),N.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd,async(W)=>{await this.sendUpdateAndWait(W)}),G.debug(`[AcpSession ${this.id}] ACP service context initialized`),await Jz.resolvePendingWithHandler(this.cwd,this.id,{requestConfirmation:(W)=>this.requestPermission(W)}))await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let Z=this.options.mcpServers?uz(this.options.mcpServers):void 0,J=N.getInstance().getTerminalService(this.id);if(this.runtime=await Wz.create({sessionId:this.id,workspaceRoot:this.cwd,permissionMode:this.mapModeToPermissionMode(),...Z?{mcpServers:Z}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async(W,Q)=>{let j=await J.execute(W,{cwd:Q.cwd,env:Q.env,timeout:Q.timeoutMs,signal:Q.signal,allowLocalFallback:!1,onOutput:(D)=>Q.onOutput?.("stdout",D)});return{exitCode:j.exitCode,stdout:j.stdout,stderr:j.stderr,...j.error?{error:j.error}:{},timedOut:j.failureKind==="timeout",aborted:j.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),await b.recoverInterrupted(this.cwd,this.id,this.runtime))await this.refreshPersistedMessages();this.agent=await this.createAgent(),await Uz(this.cwd),G.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=e.subscribe((W)=>{if(W.sessionId!==this.id||W.projectPath!==this.cwd)return;if(W.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":W.properties}}),this.schedulePendingResume();return}if(W.type==="task.delivery"){if(!W.properties.taskDelivery||typeof W.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof W.properties.updatedAt==="string"?W.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":W.properties.taskDelivery,...W.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(W.type.startsWith("team.")){let{teamName:Q,messageId:j,content:D}=W.properties,X=W.properties.metadata;if(W.type==="team.message.received"&&typeof Q==="string"&&typeof j==="string"&&typeof D==="string"&&Qz(X,{messageId:j,teamName:Q}))(async()=>{let L=await this.runtime?.enqueueSteering(D,{allowBeforeTurn:!0,messageId:j,origin:"team_message",metadata:X});if(!L?.accepted)return;if(await new $z(Q,m()).markDelivered([j]),L.delivery==="next_turn")this.schedulePendingResume()})().catch((L)=>{G.warn(`[AcpSession ${this.id}] Failed to deliver teammate message`,L)});this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/teamEvent":{type:W.type,...W.properties}}});return}if(W.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof W.properties.updatedAt==="string"?W.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":W.properties.taskStatus,...typeof W.properties.taskStatusReason==="string"?{"blade/taskStatusReason":W.properties.taskStatusReason}:{},...W.properties.taskFailure&&typeof W.properties.taskFailure==="object"?{"blade/taskFailure":W.properties.taskFailure}:{},...typeof W.properties.taskStartedAt==="string"?{"blade/taskStartedAt":W.properties.taskStartedAt}:{},...typeof W.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":W.properties.taskCompletedAt}:{},...W.properties.taskDiffStat&&typeof W.properties.taskDiffStat==="object"?{"blade/taskDiffStat":W.properties.taskDiffStat}:{},...typeof W.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":W.properties.taskQueuePosition}:{},...typeof W.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":W.properties.taskQueueDepth}:{},...typeof W.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":W.properties.taskConcurrencyLimit}:{},...typeof W.properties.taskInFlight==="number"?{"blade/taskInFlight":W.properties.taskInFlight}:{}}})});let H=await this.runtime.getGoal();if(this.runtime.getPendingSteeringCount()>0||H?.status==="active"||H?.status==="verifying")if(this.options.initialMessages===void 0)this.schedulePendingResume();else this.pendingResumeRequested=!0}async replayHistory(){for(let Z of this.messages){if(!this.canSendUpdates())return;if(!n(Z))continue;let J=Z.role==="user"?"user_message_chunk":Z.role==="assistant"?"agent_message_chunk":void 0;if(!J)continue;for(let Y of gz(Z)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:J,content:Y}))return}}let z=await this.runtime?.getGoal();if(z&&!await this.sendUpdateAndWait(this.goalSessionUpdate(z)))return;if(this.pendingResumeRequested)this.schedulePendingResume()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);G.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendAvailableCommands()},500)}async handleSlashCommand(z,Z){try{G.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let J={cwd:this.cwd,surface:"acp",workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.contextMessages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let j=await this.runtime.rewindSession(Q);return this.messages=[...j.messages],this.contextMessages=await this.loadModelContextOr(j.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),j}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async(Q)=>{if(await this.setReasoningEffort(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()}},serviceTier:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()},set:async(Q)=>{if(await this.setServiceTier(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()}},responseVerbosity:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()},set:async(Q)=>{if(await this.setResponseVerbosity(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()}},communicationStyle:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()},set:async(Q)=>{if(await this.setCommunicationStyle(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()}},subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let D=!1,X,L=(B)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:B.id,status:B.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:B.result?.message||B.result?.error||`Subagent ${B.status}`}}]})},F=this.runtime.resumeSubagent({agentId:Q,prompt:j,onCompleted:(B)=>{if(D)L(B);else X=B}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:F.session.id,status:"in_progress",title:`Resuming ${F.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${F.source.id} at depth ${F.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),D=!0,X)L(X);return F}},mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs(Q)},getPrompt:async(Q,j,D)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Q,j,D)},complete:async(Q,j,D)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Q,j,D)},listTasks:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks(Q)},getTask:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask(Q)},cancelTask:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Q,j)},getLogs:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Q,j)},setLoggingLevel:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Q,j)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},sideConversation:{ask:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.askSideQuestion(Q,{signal:j})}},codeReview:{run:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let D=await b.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:Q,signal:j,onEvent:(F)=>{if(F.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:F.toolCall.id,status:"in_progress",title:`Review: ${F.toolCall.function.name}`,content:[],kind:this.mapToolKind(F.toolKind)});else if(F.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:F.toolCall.id,status:F.result.success?"completed":"failed",content:[]})}}),X=await D.completion,L=(await b.list(this.cwd,this.id)).find((F)=>F.start.reviewId===D.reviewId);if(!L)throw Error(`Review not found: ${D.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:D.reviewId,status:X.status,findings:X.findings.length,content:l(L.start,X)}}},signal:Z,acp:{sendMessage:(Q)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}})},sendToolStart:(Q,j,D)=>{let X=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,L=this.mapToolKind(D);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:X,status:"in_progress",title:`${Q}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(j,null,2)}}],kind:L})},sendToolResult:(Q,j)=>{if(j.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:j.summary}})}}},Y=await Vz(z,J),H=Y.data?.action;if(H==="start_goal"||H==="resume_goal")this.schedulePendingResume();if(H==="rewind_session"&&Array.isArray(Y.data?.messages))this.messages=[...Y.data.messages],this.contextMessages=await this.loadModelContextOr(Y.data.messages);if((Y.message==="compact_completed"||Y.message==="compact_fallback")&&Y.data?.compactedMessages){this.contextMessages=[...Y.data.compactedMessages];let Q=await U.loadSession(this.id,this.cwd);if(Q.length>0)this.messages=Q}let W=Y.content||Y.message;if(W)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W}});if(Y.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Y.error}`}});return await this.flushUpdates(),{stopReason:Y.success?"end_turn":"cancelled"}}catch(J){if(Z.aborted||J instanceof Error&&J.name==="AbortError")return{stopReason:"cancelled"};return G.error(`[AcpSession ${this.id}] Slash command error:`,J),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${J instanceof Error?J.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async handleSideConversationCommand(z){if(this.pendingSideConversation)throw Error("A side conversation is already running");let Z=new AbortController,J,Y=new Promise((H)=>{J=H});this.pendingSideConversation=Z,this.pendingSideConversationCompletion=Y;try{return await this.handleSlashCommand(z,Z.signal)}catch(H){if(Z.signal.aborted||H instanceof Error&&H.name==="AbortError")return{stopReason:"cancelled"};throw H}finally{if(J(),this.pendingSideConversationCompletion===Y)this.pendingSideConversationCompletion=null;if(this.pendingSideConversation===Z)this.pendingSideConversation=null}}async sendAvailableCommands(){try{let z=wz(this.cwd,this.runtime?.getAgentResources()),Z=["model","permissions","theme","config","exit","ide"],Y=z.filter((H)=>!Z.includes(H.name)&&(H.name!=="team"||this.runtime?.getConfig().agentTeamsEnabled===!0)).map((H)=>{let W;if(H.usage){let Q=H.usage.replace(/^\/\w+\s*/,"").trim();if(Q)W=Q}if(H.aliases?.length){let Q=`Aliases: ${H.aliases.join(", ")}`;W=W?`${W} | ${Q}`:Q}return{name:H.name,description:H.description,input:W?{hint:W}:void 0}});G.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map((H)=>H.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Y}),G.info(`[AcpSession ${this.id}] Sent ${Y.length} available commands`)}catch(z){G.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,Z={}){if(N.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let J=this.resolvePrompt(z.prompt),Y=J.content,H=J.displayText,W=z._meta?.outputSchema??(Z.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((B)=>B.outputSchema)?.outputSchema:void 0),Q;if(W!==void 0)Q=t(W).schema;if(H.trimStart().startsWith("!")){if(Q)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(H)}let j=Zz(H);if(j){if(Q)throw Error("Output schemas cannot be combined with slash commands");if(Array.isArray(Y)&&Y.some((B)=>B.type==="image_url"))throw Error("Side conversations do not accept image attachments");return this.handleSideConversationCommand(j.question?`/btw ${j.question}`:"/btw")}if(this.pendingPrompt){if(Q)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test(H.trim()))return this.handleSlashCommand(H,this.pendingPrompt.signal);let B=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!B.accepted)throw Error(B.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(G.debug(`[AcpSession ${this.id}] Queued steering for active turn (${B.queued})`),B.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let D=new AbortController,X=!1,L,F=new Promise((B)=>{L=B});this.pendingPrompt=D,this.pendingPromptCompletion=F;try{if(G.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),Fz(H)){if(Q)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(H,D.signal)}let B={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.contextMessages],signal:D.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async($)=>{this.mode=this.mapPermissionModeToMode($),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async($)=>{return this.requestPermission($)}}},A=await zz(this.agent.chatStream(Y,B,{pendingInputOnly:Z.pendingInputOnly,goalContinuationOnly:Z.goalContinuationOnly,outputSchema:Q}),async($)=>{switch($.kind){case"content_delta":if(Q)break;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:$.delta}});break;case"tool_start":{let V=$.toolCall,O=V.function.name;if(O===x)break;let R=this.mapToolKind($.toolKind),w=`Executing ${O}`;if(O==="Task"&&"function"in V)try{let P=JSON.parse(V.function.arguments),K=P.resume_from??P.resume;if(typeof K==="string")w=`Resuming ${String(P.subagent_type||"subagent")} from ${K}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:V.id,status:"in_progress",title:w,content:[],kind:R});break}case"tool_progress":{let V=$.toolCall;if(V.function.name===x)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:$.update.message}}]});break}case"tool_result":{let V=$.toolCall;if(V.function.name===x)break;let O=$.result,R=[],w=O.metadata;if(w?.kind==="patch"&&Array.isArray(w.changes))for(let K of w.changes){if(!K||typeof K!=="object"||!("path"in K)||typeof K.path!=="string")continue;R.push({type:"diff",path:K.path,oldText:"oldContent"in K&&typeof K.oldContent==="string"?K.oldContent:null,newText:"newContent"in K&&typeof K.newContent==="string"?K.newContent:null})}else if(w?.kind==="edit"&&typeof w.file_path==="string"&&typeof w.oldContent==="string"&&(typeof w.newContent==="string"||w.newContent===void 0))R.push({type:"diff",path:w.file_path,oldText:w.oldContent,newText:w.newContent??null});else{let K=V.function.name,kz=Hz(o(Yz(K,O),a));R.push({type:"content",content:{type:"text",text:kz}})}if(V.function.name==="Task"&&(w?.verificationVerdict==="pass"||w?.verificationVerdict==="fail"||w?.verificationVerdict==="partial"))R.unshift({type:"content",content:{type:"text",text:`Verification result: ${w.verificationVerdict.toUpperCase()}`}});let P=O.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:P,content:R});break}case"structured_output":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify($.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
|
|
3
3
|
`}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${$.contentKind} r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
|
|
4
4
|
`}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${$.revision} (${$.serverName}): ${$.uri}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Pb as Xt,Qb as fn,Rb as yn,Sb as En}from"./chunk-r8wbvxn7.js";import{uf as Bt}from"./chunk-
|
|
1
|
+
import{Pb as Xt,Qb as fn,Rb as yn,Sb as En}from"./chunk-r8wbvxn7.js";import{uf as Bt}from"./chunk-z21es9vg.js";import{Af as vi,Bf as sn,Cf as zt,Df as U,Ef as en,Ff as xt,Gf as mt,If as rn,Jf as Tn,Kf as B,Lf as dn,Mf as on,Nf as pn,Of as lt,Pf as cn,Qf as un,Rf as Mn,Tf as S,Wf as wn,Xf as Gt,Yf as Ut,Zf as h,_f as Ht,zf as gt}from"./chunk-zpryec89.js";import{Fg as X,Hg as g}from"./chunk-sk8h4m9m.js";import{Tg as It}from"./chunk-sb84vdcf.js";import{Hh as tn,Ih as nn}from"./chunk-p3jvzk1f.js";import{$h as ns}from"./chunk-6jsmac0q.js";import{EventEmitter as bs}from"events";import Un from"node:path";function hn(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function An(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${hn(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:An(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
|
|
2
2
|
${s.map((r)=>` - ${r.field}: ${r.message}`).join(`
|
|
3
3
|
`)}`;throw new Jt(e,s)}function st(t){if(!t||typeof t!=="object")return;let i=t;if(i.type==="object"&&i.properties)i.required??=[],i.additionalProperties??=!1;for(let n of Object.values(i))if(Array.isArray(n))for(let s of n)st(s);else st(n)}function et(t){let i=JSON.parse(JSON.stringify(t,(n,s)=>n.startsWith("~")?void 0:s));return st(i),i}class rt{toolName;params;executeFn;descriptionFn;affectedPathsFn;constructor(t,i,n,s,e){this.toolName=t;this.params=i;this.executeFn=n;this.descriptionFn=s;this.affectedPathsFn=e}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute(t,i,n){let s={signal:t,updateOutput:i,...n};return this.executeFn(this.params,s)}}function jt(t){return{name:t.name,displayName:t.displayName,kind:t.kind,isConcurrencySafe:t.isConcurrencySafe??!1,parallelism:t.parallelism??(t.isConcurrencySafe?"shared":"exclusive"),strict:t.strict??!1,description:t.description,version:t.version||"1.0.0",category:t.category,tags:t.tags||[],getFunctionDeclaration(){let i=et(t.schema),n=t.description.short;if(t.description.long)n+=`
|
|
4
4
|
|