blade-code 0.10.3 → 0.10.4
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-r4pz99sy.js → chunk-1ndryz4h.js} +1 -1
- package/dist/{chunk-xdbg7cn3.js → chunk-5t0vs4hz.js} +1 -1
- package/dist/{chunk-c05t8207.js → chunk-5ze48kg7.js} +1 -1
- package/dist/{chunk-9yytfg19.js → chunk-90fnvvcf.js} +1 -1
- package/dist/{chunk-3wp3h373.js → chunk-9kwt0w46.js} +1 -1
- package/dist/{chunk-c45y8tx1.js → chunk-a7a74pza.js} +74 -74
- package/dist/{chunk-bfw2p0x8.js → chunk-age5tc86.js} +3 -3
- package/dist/{chunk-7hqbwpt5.js → chunk-b9v7waxf.js} +1 -1
- package/dist/{chunk-bn148dr5.js → chunk-csr5vppa.js} +8 -8
- package/dist/{chunk-p5tpzh6f.js → chunk-d4zw0xxe.js} +1 -1
- package/dist/chunk-d5a66cgn.js +160 -0
- package/dist/{chunk-5fxc90rb.js → chunk-d7xb0vp1.js} +1 -1
- package/dist/{chunk-vmg5n0zv.js → chunk-f647z66n.js} +1 -1
- package/dist/{chunk-eezg6pee.js → chunk-ffp3ypbb.js} +1 -1
- package/dist/{chunk-7089z4e1.js → chunk-fx87s3mb.js} +1 -1
- package/dist/chunk-g6h6h8xr.js +1 -0
- package/dist/chunk-jbnrscvz.js +1 -0
- package/dist/{chunk-aa0ffw17.js → chunk-kkd7mm55.js} +1 -1
- package/dist/{chunk-wje6bck2.js → chunk-mxqpg4gy.js} +1 -1
- package/dist/{chunk-zq9r0jx3.js → chunk-n2s54h1r.js} +1 -1
- package/dist/{chunk-jqwntnp1.js → chunk-nr53mq0k.js} +1 -1
- package/dist/{chunk-8th744ef.js → chunk-pehpndk9.js} +1 -1
- package/dist/{chunk-s95rgkd8.js → chunk-rv80ak15.js} +1 -1
- package/dist/{chunk-1g5qc1qx.js → chunk-scq3ns6v.js} +1 -1
- package/dist/{chunk-1cx96gx1.js → chunk-tx8f345j.js} +1 -1
- package/dist/{chunk-nxj1638n.js → chunk-v8kp3ep9.js} +1 -1
- package/dist/{chunk-rcdynprn.js → chunk-ve9cke2g.js} +2 -2
- package/dist/{chunk-vwq9s5nj.js → chunk-vxymgh8e.js} +4 -4
- package/dist/{chunk-da1jvzbz.js → chunk-wdbmbk6h.js} +1 -1
- package/dist/{chunk-pnrx3spk.js → chunk-xkzy5wbm.js} +1 -1
- package/dist/{chunk-grp43mdb.js → chunk-xq8vf15n.js} +1 -1
- package/dist/chunk-ys8bp9jm.js +1 -0
- package/dist/chunk-zswrw5f9.js +3 -0
- package/dist/web/assets/{ChatView-Pqa25Vua.js → ChatView-iK7ff8qU.js} +2 -2
- package/dist/web/assets/{CodeBlockHighlighter-Dxt-FWJk.js → CodeBlockHighlighter-BoJp_Xb0.js} +1 -1
- package/dist/web/assets/{FilePreview-Dj2yppPn.js → FilePreview-Bi1HWOvY.js} +2 -2
- package/dist/web/assets/{MarkdownRenderer-BI2xpTV2.js → MarkdownRenderer-DMW1pg5N.js} +12 -12
- package/dist/web/assets/{McpModal-COw0BcHJ.js → McpModal-CHUqitJ6.js} +1 -1
- package/dist/web/assets/SettingsModal-zsS9O6SW.js +1 -0
- package/dist/web/assets/{SkillsModal-CTZTu9xg.js → SkillsModal-C2oTDXoy.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-DPXkV-qb.js → TaskSwitcher-CncVasNA.js} +1 -1
- package/dist/web/assets/{TerminalPanel-tpUxwaCh.js → TerminalPanel-CBi2mUxx.js} +1 -1
- package/dist/web/assets/index-B7etZcne.css +1 -0
- package/dist/web/assets/index-DvDtvgA4.js +32 -0
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/chunk-8thp1nep.js +0 -1
- package/dist/chunk-9p5f3ryf.js +0 -1
- package/dist/chunk-mgwny24b.js +0 -160
- package/dist/chunk-n3y9ytvg.js +0 -3
- package/dist/chunk-r4j5ca1h.js +0 -1
- package/dist/web/assets/SettingsModal-h4AxN730.js +0 -1
- package/dist/web/assets/index-Dep3eEsS.css +0 -1
- package/dist/web/assets/index-bjyn3NHs.js +0 -32
package/dist/blade.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Rb as W}from"./chunk-
|
|
2
|
+
import{Rb as W}from"./chunk-age5tc86.js";import{Ub as F,Vb as M}from"./chunk-drrdzmaa.js";import"./chunk-b9v7waxf.js";import"./chunk-g6h6h8xr.js";import"./chunk-fvhc1yj8.js";import"./chunk-vxymgh8e.js";import"./chunk-qm11hjd3.js";import{md as T}from"./chunk-qda309d9.js";import"./chunk-csr5vppa.js";import"./chunk-tq52pbde.js";import"./chunk-79s052sw.js";import{qe as N,re as B}from"./chunk-epj56s0n.js";import"./chunk-gxzbv67r.js";import"./chunk-bexgcc2d.js";import"./chunk-nr53mq0k.js";import"./chunk-z906d5tb.js";import"./chunk-948qe2pp.js";import"./chunk-0n97186m.js";import{Ve as K}from"./chunk-9ffr01c3.js";import C from"node:path";var E=process.argv.slice(2),I=p(E),v=I!==null;if(I!==null)T.setGlobalDebug(I);function p(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 u(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 c(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 m(){if(u(E)){let{getVersion:J}=await import("./chunk-kkd7mm55.js");console.log(J());return}let Q=process.cwd(),Y=F(Q);M(Y),N(B());let U=c(E,"--plugin-dir","--pluginDir");if(U.length>0){let{configureInvocationPluginDirs:J}=await import("./chunk-tx8f345j.js");J(U.map((Z)=>C.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:J}=await import("./chunk-ccwskwb3.js");await J.getInstance().trust(B())}if(process.getuid&&process.getuid()===0){let J=!!process.env.SUDO_USER,Z=!!process.env.BLADE_ALLOW_ROOT;if(J&&!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:J}=await import("./chunk-v8kp3ep9.js");if(await J())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:J}=await import("./chunk-xkzy5wbm.js");if(await J())return}if(E.includes("--acp")){let{runAcpIntegration:J}=await import("./chunk-5ze48kg7.js");await J();return}let[{default:X},{hideBin:G},{cliConfig:z,globalOptions:$},{loadConfiguration:_,validateOutput:D,validatePermissions:R},{doctorCommands:S},{installCommands:k},{mcpCommands:O},{projectsCommands:y},{serveCommand:b},{updateCommands:V},{webCommand:P}]=await Promise.all([import("yargs"),import("yargs/helpers"),import("./chunk-ys8bp9jm.js"),import("./chunk-jbnrscvz.js"),import("./chunk-ve9cke2g.js"),import("./chunk-gb54hc78.js"),import("./chunk-rv80ak15.js"),import("./chunk-v93hcxe7.js"),import("./chunk-d4zw0xxe.js"),import("./chunk-5twefby5.js"),import("./chunk-wdbmbk6h.js")]),x=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(S).command(V).command(k).command(P).command(b).completion("completion",!1).help("help","Show help").alias("help","h").alias("version","V").fail((J,Z,L)=>{if(Z){if(console.error("An error occurred:"),console.error(Z.message),v&&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(J)console.error("Error: Invalid arguments:"),console.error(J),console.error(`
|
|
5
|
-
Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(J)=>{let Z=J._.slice(1),L=Z.length>0?Z.join(" "):void 0,h=import("./chunk-4ncbd4k0.js").then(({checkVersionOnStartup:j})=>j()),[{render:A},{createElement:w},{AppWrapper:f}]=await Promise.all([import("ink"),import("react"),import("./chunk-
|
|
5
|
+
Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(J)=>{let Z=J._.slice(1),L=Z.length>0?Z.join(" "):void 0,h=import("./chunk-4ncbd4k0.js").then(({checkVersionOnStartup:j})=>j()),[{render:A},{createElement:w},{AppWrapper:f}]=await Promise.all([import("ink"),import("react"),import("./chunk-d5a66cgn.js")]),H={...J,initialMessage:L,debug:J.debug,print:Boolean(J.print),versionCheckPromise:h};delete H._,delete H.$0,delete H.message,A(w(f,H),{patchConsole:!0,exitOnCtrlC:!1,alternateBuffer:!1})});try{await x.parse()}catch(J){console.error("Error: Parse error:",J),process.exit(1)}}if(K.main==K.module)m().catch(console.error);export{m as main};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{bd as t1,cd as GO}from"./chunk-35yktzm1.js";import{fd as K1}from"./chunk-63ysxybd.js";import{gd as M0,id as B0}from"./chunk-
|
|
1
|
+
import{bd as t1,cd as GO}from"./chunk-35yktzm1.js";import{fd as K1}from"./chunk-63ysxybd.js";import{gd as M0,id as B0}from"./chunk-vxymgh8e.js";import{nd as h,od as M}from"./chunk-qda309d9.js";import{$d as S0,Rd as V0,Sd as u1}from"./chunk-csr5vppa.js";import{ce as u,ee as Y,he as T1}from"./chunk-tq52pbde.js";import{re as x}from"./chunk-epj56s0n.js";import{Ee as P0}from"./chunk-nr53mq0k.js";import{Je as T}from"./chunk-z906d5tb.js";import Z1 from"node:path";import Q$ from"node:path";import w0 from"node:fs";import Z0 from"node:os";import R from"node:path";import LO from"yaml";var J1={name:"verification",description:"Independent verification agent that validates implementation by running builds, tests, linters, and adversarial"+" probes. Strictly read-only — cannot modify code. Use"+" after completing implementation to get an independent quality assessment.",tools:["Read","Glob","Grep","Bash"],systemPrompt:`# Verification Agent
|
|
2
2
|
|
|
3
3
|
You are an **independent verification engineer**. Your sole purpose is to find problems — not to praise or reassure. You are the last line of defense before code ships.
|
|
4
4
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{X as H,Z as J}from"./chunk-
|
|
1
|
+
import{X as H,Z as J}from"./chunk-a7a74pza.js";import{qb as D}from"./chunk-scq3ns6v.js";import{Zc as G}from"./chunk-1ndryz4h.js";import{re as B}from"./chunk-epj56s0n.js";async function U(){await G(B())}async function V(b){let f=b.message||b._?.[0];if(typeof f==="string"&&f.trim())return f;let q=b.stdin??process.stdin;if(!q.isTTY){let z=[];for await(let F of q)z.push(F);return Buffer.concat(z).toString("utf-8").trim()}if(b.defaultMessage!==void 0)return b.defaultMessage;throw Error("No input provided")}async function X(b){if(!H(b))return{mode:"agent",content:b};let f=await J(b,{cwd:B(),surface:"headless",workspaceRoot:B()});if(!f.success)return{mode:"output",content:`Error: ${f.error||"未知错误"}`,exitCode:1};let q=f.data;if(q?.action==="invoke_skill"){let{skillName:z,skillArgs:F}=q;return{mode:"agent",content:F?`Please use the "${z}" skill to help me with: ${F}`:`Please use the "${z}" skill.`}}if(q?.action==="invoke_custom_command"||q?.action==="invoke_plugin_command"){let z=q.processedContent;return{mode:"agent",content:`# Custom Command: /${q.commandName}
|
|
2
2
|
|
|
3
3
|
${z}`}}return{mode:"output",content:f.content||f.message||"",exitCode:0}}function K(b){if(!(b instanceof Error))return!1;return b.message.includes("未找到会话")||b.message.includes("ENOENT")||b.message.includes("no such file")}async function O(b){try{return await D.loadSession(b,B())}catch(f){if(K(f))return null;throw f}}async function $(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 f=B();return D.forkSession(b.resume,{newSessionId:b.sessionId,sourceProjectPath:f,targetProjectPath:f})}return{sessionId:b.resume,messages:await D.loadSession(b.resume)}}if(b.continue){let f=b.forkSession?await D.listSessions({cwd:B()}):await D.listSessions();if(f.length>0){let q=f[0].sessionId;if(b.forkSession){let z=B();return D.forkSession(q,{newSessionId:b.sessionId,sourceProjectPath:z,targetProjectPath:z})}return{sessionId:q,messages:await D.loadSession(q)}}if(b.forkSession)throw Error("Cannot fork: no sessions are available to continue")}if(b.sessionId)return{sessionId:b.sessionId,messages:await O(b.sessionId)??[]};return{sessionId:`${b.fallbackSessionPrefix}-${Date.now()}`,messages:[]}}
|
|
4
4
|
export{U as m,V as n,X as o,$ as p};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{q as o}from"./chunk-
|
|
1
|
+
import{q as o}from"./chunk-90fnvvcf.js";import{E as y,G as k,H as S,J as C,X as f,Y as u,Z as g,_ as c,t as K}from"./chunk-a7a74pza.js";import{ia as n}from"./chunk-mxqpg4gy.js";import{Aa as T,Da as M}from"./chunk-9kwt0w46.js";import{Va as A}from"./chunk-jza1rsan.js";import{ib as E,jb as I,nb as V,qb as U}from"./chunk-scq3ns6v.js";import"./chunk-an96c54z.js";import"./chunk-drrdzmaa.js";import"./chunk-b9v7waxf.js";import"./chunk-g6h6h8xr.js";import{wc as i}from"./chunk-fvhc1yj8.js";import"./chunk-dqvcgwhe.js";import"./chunk-ea7wsges.js";import{Fc as r}from"./chunk-gxmrakrk.js";import"./chunk-fx87s3mb.js";import"./chunk-1ndryz4h.js";import{ad as a}from"./chunk-35yktzm1.js";import"./chunk-63ysxybd.js";import"./chunk-vxymgh8e.js";import"./chunk-qm11hjd3.js";import{nd as R}from"./chunk-qda309d9.js";import"./chunk-csr5vppa.js";import"./chunk-tq52pbde.js";import{le as q,me as h,ne as N}from"./chunk-79s052sw.js";import{re as m}from"./chunk-epj56s0n.js";import"./chunk-gxzbv67r.js";import{Ae as l,xe as d}from"./chunk-bexgcc2d.js";import"./chunk-nr53mq0k.js";import"./chunk-z906d5tb.js";import"./chunk-948qe2pp.js";import"./chunk-0n97186m.js";import"./chunk-9ffr01c3.js";import{Readable as zJ,Writable as WJ}from"node:stream";import*as O from"@agentclientprotocol/sdk";import p from"node:path";import{PROTOCOL_VERSION as $J}from"@agentclientprotocol/sdk";import{nanoid as P}from"nanoid";var X=R("Agent");function x(J){if(!J)return{};return Object.fromEntries(J.map((Z)=>[Z.name,Z.value]))}function e(J){if("command"in J)return{type:"stdio",command:J.command,args:J.args,env:x(J.env)};if("url"in J)return{type:J.type,url:J.url,headers:x("headers"in J?J.headers:void 0)};return null}function JJ(J){let Z={};for(let Q of J){let $=e(Q);if($)Z[Q.name]=$}return Z}function v(J){if(typeof J==="string")return J?[{type:"text",text:J}]:[];return J.flatMap((Z)=>{if(Z.type==="text")return Z.text?[{type:"text",text:Z.text}]:[];let Q=Z.image_url.url,$=/^data:([^;,]+);base64,(.+)$/s.exec(Q);if(!$)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:$[1]??"image/png",data:$[2]??""}]})}function QJ(J){let Z=I(J.metadata);return Z?[{type:"text",text:E(Z)}]:v(J.content)}function ZJ(J){return[`Status: ${J.status}`,`Exit code: ${J.exitCode??"null"}`,`Duration: ${(J.durationMs/1000).toFixed(3)} seconds`].join(`
|
|
2
2
|
`)}class _{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingUserShell=null;pendingResumeRequested=!1;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;messages;mode="default";constructor(J,Z,Q,$,D={}){this.id=J;this.cwd=Z;this.connection=Q;this.clientCapabilities=$;this.options=D;this.messages=[...D.initialMessages??[]]}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return C.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){X.debug(`[AcpSession ${this.id}] Initializing...`),K.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd),X.debug(`[AcpSession ${this.id}] ACP service context initialized`);let J=this.options.mcpServers?JJ(this.options.mcpServers):void 0,Z=K.getInstance().getTerminalService(this.id);this.runtime=await y.create({sessionId:this.id,workspaceRoot:this.cwd,...J?{mcpServers:J}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async($,D)=>{let z=await Z.execute($,{cwd:D.cwd,env:D.env,timeout:D.timeoutMs,signal:D.signal,allowLocalFallback:!1,onOutput:(Y)=>D.onOutput?.("stdout",Y)});return{exitCode:z.exitCode,stdout:z.stdout,stderr:z.stderr,...z.error?{error:z.error}:{},timedOut:z.error==="Command timed out",aborted:z.error==="Command was aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),this.agent=await this.createAgent(),await u(this.cwd),X.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=M.subscribe(($)=>{if($.sessionId!==this.id||$.projectPath!==this.cwd)return;if($.type==="task.delivery"){if(!$.properties.taskDelivery||typeof $.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof $.properties.updatedAt==="string"?$.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":$.properties.taskDelivery,...$.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if($.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof $.properties.updatedAt==="string"?$.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":$.properties.taskStatus,...typeof $.properties.taskStatusReason==="string"?{"blade/taskStatusReason":$.properties.taskStatusReason}:{},...$.properties.taskFailure&&typeof $.properties.taskFailure==="object"?{"blade/taskFailure":$.properties.taskFailure}:{},...typeof $.properties.taskStartedAt==="string"?{"blade/taskStartedAt":$.properties.taskStartedAt}:{},...typeof $.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":$.properties.taskCompletedAt}:{},...$.properties.taskDiffStat&&typeof $.properties.taskDiffStat==="object"?{"blade/taskDiffStat":$.properties.taskDiffStat}:{},...typeof $.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":$.properties.taskQueuePosition}:{},...typeof $.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":$.properties.taskQueueDepth}:{},...typeof $.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":$.properties.taskConcurrencyLimit}:{},...typeof $.properties.taskInFlight==="number"?{"blade/taskInFlight":$.properties.taskInFlight}:{}}})});let Q=await this.runtime.getGoal();if(this.runtime.getPendingSteeringCount()>0||Q?.status==="active")if(this.options.initialMessages===void 0)this.schedulePendingResume();else this.pendingResumeRequested=!0}async replayHistory(){for(let J of this.messages){if(!this.canSendUpdates())return;let Z=J.role==="user"?"user_message_chunk":J.role==="assistant"?"agent_message_chunk":void 0;if(!Z)continue;for(let Q of QJ(J)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:Z,content:Q}))return}}if(this.pendingResumeRequested)this.schedulePendingResume()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);X.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(J,Z){try{X.debug(`[AcpSession ${this.id}] Executing slash command: ${J}`);let Q={cwd:this.cwd,surface:"acp",workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.messages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Y)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let W=await this.runtime.rewindSession(Y);return this.messages=[...W.messages],await this.agent?.destroy(),this.agent=await this.createAgent(),W}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async(Y)=>{if(await this.setReasoningEffort(Y),!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(Y)=>{if(await this.setServiceTier(Y),!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(Y)=>{if(await this.setResponseVerbosity(Y),!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(Y)=>{if(await this.setCommunicationStyle(Y),!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(Y,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let H=!1,F,j=(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}`}}]})},G=this.runtime.resumeSubagent({agentId:Y,prompt:W,onCompleted:(B)=>{if(H)j(B);else F=B}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:G.session.id,status:"in_progress",title:`Resuming ${G.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${G.source.id} at depth ${G.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),H=!0,F)j(F);return G}},mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async(Y)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs(Y)},getPrompt:async(Y,W,H)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Y,W,H)},complete:async(Y,W,H)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Y,W,H)},listTasks:async(Y)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks(Y)},getTask:async(Y)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask(Y)},cancelTask:async(Y,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Y,W)},getLogs:async(Y,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Y,W)},setLoggingLevel:async(Y,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Y,W)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},signal:Z,acp:{sendMessage:(Y)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Y}})},sendToolStart:(Y,W,H)=>{let F=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,j=this.mapToolKind(H);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:F,status:"in_progress",title:`${Y}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(W,null,2)}}],kind:j})},sendToolResult:(Y,W)=>{if(W.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W.summary}})}}},$=await g(J,Q),D=$.data?.action;if(D==="start_goal"||D==="resume_goal")this.schedulePendingResume();if(D==="rewind_session"&&Array.isArray($.data?.messages))this.messages=[...$.data.messages];if(($.message==="compact_completed"||$.message==="compact_fallback")&&$.data?.compactedMessages)this.messages=[...$.data.compactedMessages];let z=$.content||$.message;if(z)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:z}});if($.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${$.error}`}});return{stopReason:$.success?"end_turn":"cancelled"}}catch(Q){return X.error(`[AcpSession ${this.id}] Slash command error:`,Q),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${Q instanceof Error?Q.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async sendAvailableCommands(){try{let J=c(this.cwd),Z=["model","permissions","theme","config","exit","ide"],$=J.filter((D)=>!Z.includes(D.name)).map((D)=>{let z;if(D.usage){let Y=D.usage.replace(/^\/\w+\s*/,"").trim();if(Y)z=Y}if(D.aliases?.length){let Y=`Aliases: ${D.aliases.join(", ")}`;z=z?`${z} | ${Y}`:Y}return{name:D.name,description:D.description,input:z?{hint:z}:void 0}});X.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify($.map((D)=>D.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:$}),X.info(`[AcpSession ${this.id}] Sent ${$.length} available commands`)}catch(J){X.error(`[AcpSession ${this.id}] Failed to send available commands:`,J)}}async prompt(J,Z={}){if(K.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let Q=this.resolvePrompt(J.prompt),$=Q.content,D=Q.displayText;if(D.trimStart().startsWith("!"))return this.handleUserShellCommand(D);if(this.pendingPrompt){if(/^\/goal(?:\s|$)/i.test(D.trim()))return this.handleSlashCommand(D,this.pendingPrompt.signal);let Y=await this.runtime.enqueueSteering($,{allowBeforeTurn:!0});if(!Y.accepted)throw Error(Y.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(X.debug(`[AcpSession ${this.id}] Queued steering for active turn (${Y.queued})`),Y.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let z=new AbortController;this.pendingPrompt=z;try{if(X.debug(`[AcpSession ${this.id}] Received prompt: ${D.slice(0,100)}...`),f(D))return await this.handleSlashCommand(D,z.signal);let Y={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.messages],signal:z.signal,permissionMode:this.mapModeToPermissionMode(),...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async(W)=>{return this.requestPermission(W)}}};if(await T(this.agent.chatStream($,Y,{pendingInputOnly:Z.pendingInputOnly,goalContinuationOnly:Z.goalContinuationOnly}),async(W)=>{switch(W.kind){case"content_delta":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:W.delta}});break;case"tool_start":{let H=W.toolCall,F=H.function.name,j=this.mapToolKind(W.toolKind),G=`Executing ${F}`;if(F==="Task"&&"function"in H)try{let B=JSON.parse(H.function.arguments),L=B.resume_from??B.resume;if(typeof L==="string")G=`Resuming ${String(B.subagent_type||"subagent")} from ${L}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:H.id,status:"in_progress",title:G,content:[],kind:j});break}case"tool_progress":{let H=W.toolCall;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:H.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:W.update.message}}]});break}case"tool_result":{let{toolCall:H,result:F}=W,j=[],G=F.metadata;if(G?.kind==="patch"&&Array.isArray(G.changes))for(let L of G.changes){if(!L||typeof L!=="object"||!("path"in L)||typeof L.path!=="string")continue;j.push({type:"diff",path:L.path,oldText:"oldContent"in L&&typeof L.oldContent==="string"?L.oldContent:null,newText:"newContent"in L&&typeof L.newContent==="string"?L.newContent:null})}else if(G?.kind==="edit"&&typeof G.file_path==="string"&&typeof G.oldContent==="string"&&(typeof G.newContent==="string"||G.newContent===void 0))j.push({type:"diff",path:G.file_path,oldText:G.oldContent,newText:G.newContent??null});else{let L=H.function.name,t=S(k(L,F));j.push({type:"content",content:{type:"text",text:t}})}if(H.function.name==="Task"&&(G?.verificationVerdict==="pass"||G?.verificationVerdict==="fail"||G?.verificationVerdict==="partial"))j.unshift({type:"content",content:{type:"text",text:`Verification result: ${G.verificationVerdict.toUpperCase()}`}});let B=F.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:H.id,status:B,content:j});break}case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${W.revision} (${W.serverName}): +${W.added.length} -${W.removed.length} ~${W.updated.length}
|
|
3
3
|
`}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${W.contentKind} r${W.revision} (${W.serverName}): +${W.added.length} -${W.removed.length} ~${W.updated.length}
|
|
4
4
|
`}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${W.revision} (${W.serverName}): ${W.uri}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{A as r}from"./chunk-
|
|
1
|
+
import{A as r}from"./chunk-a7a74pza.js";import{qb as i}from"./chunk-scq3ns6v.js";import a from"node:path";function n(e){let s=e.replace(/\s+/g," ").trim();return s.length<=72?s:`${s.slice(0,69)}...`}function c(e){let s=e.replace(/\s+/g," ").trim();return s.length<=500?s:`${s.slice(0,497)}...`}function d(e){return`task/${e.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class m{static async createSessionTask(e){if(!e.prompt.trim())throw Error("Task prompt must not be blank");if(!a.isAbsolute(e.sourceProjectPath))throw Error("Task source project path must be absolute");let s=a.resolve(e.sourceProjectPath),t;try{return t=e.isolation==="worktree"?await r.enter({sessionId:e.sessionId,workspaceRoot:s,name:d(e.sessionId)}):void 0,{metadata:await i.createSessionMetadata(e.sessionId,t?.workspaceRoot??s,{title:e.title?.trim()||n(e.prompt),taskPromptSummary:c(e.prompt),taskDispatch:e.dispatch,taskModelId:e.dispatch?.modelId,selectedModelId:e.dispatch?.modelId,reasoningEffort:e.dispatch?.reasoningEffort,serviceTier:e.dispatch?.serviceTier,responseVerbosity:e.dispatch?.responseVerbosity,communicationStyle:e.dispatch?.communicationStyle,communicationStyleDigest:e.dispatch?.communicationStyleDigest,projectInstructionsDigest:e.dispatch?.projectInstructionsDigest,taskRetriedFrom:e.retriedFrom,taskIsolation:e.isolation,taskSourceProjectPath:s,taskWorktree:t}),taskWorktree:t}}catch(o){if(t)await r.exit({sessionId:e.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw o}}}
|
|
2
2
|
export{m as q};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Za as yJ}from"./chunk-jza1rsan.js";import{$a as d2,_a as y$,qb as C0}from"./chunk-1g5qc1qx.js";import{wc as DJ}from"./chunk-fvhc1yj8.js";import{Bc as p2,xc as qJ,yc as H$,zc as QJ}from"./chunk-dqvcgwhe.js";import{id as U$}from"./chunk-vwq9s5nj.js";import{nd as $$}from"./chunk-qda309d9.js";import{ie as wJ}from"./chunk-tq52pbde.js";import{re as i}from"./chunk-epj56s0n.js";import{Me as R2,Oe as _2}from"./chunk-0n97186m.js";function A$($){return $.role==="system"&&Array.isArray($.content)}function d$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class g${systemMessages;_contextualSystemMessages;_history;_pending=[];context;constructor($,J){this.context=$;let Z=$.messages.find(A$);if(this._contextualSystemMessages=$.messages.filter(d$),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!A$(W)&&!d$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!d$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(A$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((J)=>!A$(J)&&!d$(J))}removeMessages($){this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages()}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function w2($){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 D2($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function q2($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import c$ from"node:path";var AJ=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"]),xJ=/^(LD_.+|DYLD_.+|PATH)$/,y2=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function x$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],X=Z[2],z=W.match(y2);if(!z)break;let K=z[1];if(!AJ.has(K))break;J=X}return J}function f1($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],X=Z[2],z=W.match(y2);if(!z)break;let K=z[1];if(xJ.test(K))break;J=X}return J}var kJ=[/^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 A0($){let J=$,Z=!0;while(Z){Z=!1;for(let W of kJ){let X=J.match(W);if(X){J=J.slice(X[0].length),Z=!0;break}}if(J.startsWith("-- "))J=J.slice(3),Z=!0}return J}function m$($){let J=[],Z="",W=!1,X=!1,z=!1;for(let K=0;K<$.length;K++){let Y=$[K];if(z){Z+=Y,z=!1;continue}if(Y==="\\"&&!W){Z+=Y,z=!0;continue}if(Y==="'"&&!X){W=!W,Z+=Y;continue}if(Y==='"'&&!W){X=!X,Z+=Y;continue}if(W||X){Z+=Y;continue}if(Y==="|"){if(K+1<$.length&&$[K+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}return null}if(Y===">"||Y==="<")return null;if(Y==="&"&&K+1<$.length&&$[K+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}if(Y==="&")return null;if(Y===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=Y}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function P2($){let J=!1,Z=!1,W=!1;for(let X=0;X<$.length;X++){let z=$[X];if(W){W=!1;continue}if(z==="\\"&&!J){W=!0;continue}if(z==="'"&&!Z){J=!J;continue}if(z==='"'&&!J){Z=!Z;continue}if(J)continue;if(z==="$"){let K=$[X+1];if(K&&/[A-Za-z_@*#?!$0-9({]/.test(K))return!0}if(z==="`")return!0;if(Z)continue;if(z==="|")return!0;if(z===">"||z==="<")return!0;if(z==="{"){let K=$.slice(X);if(/^\{[^}]*,[^}]*\}/.test(K)||/^\{[^}]*\.\.[^}]*\}/.test(K))return!0}}return!1}function u$($){let J=[],Z="",W=!1,X=!1,z=!1;for(let K=0;K<$.length;K++){let Y=$[K];if(z){Z+=Y,z=!1;continue}if(Y==="\\"&&!W){if(z=!0,X){let Q=$[K+1];if(Q&&'$`"\\'.includes(Q))continue;Z+=Y,z=!1}continue}if(Y==="'"&&!X){W=!W;continue}if(Y==='"'&&!W){X=!X;continue}if(!W&&!X&&/[ \t]/.test(Y)){if(Z)J.push(Z),Z="";continue}Z+=Y}if(Z)J.push(Z);return J}var MJ=new Set(["npm","pnpm","yarn","bun"]),U2=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),TJ=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]);function RJ($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function hJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function P$($){let J=x$(hJ($)),Z=m$(J);if(!Z||Z.length!==1||P2(J)||/[\r\n]/.test(J))return!1;let W=u$(J);if(W.length===0||W.some((Y)=>[...TJ].some((Q)=>Y===Q||Y.startsWith(`${Q}=`))))return!1;let[X,z,K]=W;if(MJ.has(X??""))return RJ(z==="run"?K:z)||z==="--test";if((X==="npx"||X==="bunx")&&U2.has(z??""))return!0;if(U2.has(X??""))return!0;if(X==="node"&&z==="--test")return!0;if(X==="go"&&["build","test","vet"].includes(z??""))return!0;return X==="cargo"&&["build","check","clippy","test"].includes(z??"")}function M1($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!c$.isAbsolute($);let Z=c$.isAbsolute($)?c$.resolve($):c$.resolve(J,$);return y$.isWithinWorkspace(Z,J)}var x0=$$("Agent"),CJ=3;function k0($,J,Z){if($!=="length")return{action:"none"};if(J>=CJ)return{action:"truncated"};if(w2(Z)==="stop")return x0.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var pJ=[/:\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],dJ=/```[\s\S]{50,}```/,b2="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",gJ=2;function M0($,J,Z=!0){if(!$||J>=gJ)return{action:"none"};if(!Z&&dJ.test($))return{action:"retry",prompt:b2};let W=$.slice(-200),X=W.match(/```/g);if(X&&X.length%2!==0)return{action:"none"};if(pJ.some((K)=>K.test(W)))return{action:"retry",prompt:b2};return{action:"none"}}var mJ=[/\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}(?:测试|单测|集成测试|检查|构建)/],O2={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},uJ={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},cJ="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.",iJ="Required verification did not run successfully before the retry limit.",rJ=3;function L2($,J,Z){if(!Z.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(J)){$.clear();return}if(J==="Bash"&&typeof Z.metadata?.command==="string"&&Z.metadata.exit_code===0&&P$(Z.metadata.command)){$.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes(J))return;let W=Z.metadata?.verificationCommands;if(!Array.isArray(W))return;for(let X of W)if(typeof X==="string"&&P$(X))$.add(X)}function T0($,J,Z){if(!$||!mJ.some((Q)=>Q.test($)))return{action:"none"};let W=Object.keys(O2).filter((Q)=>O2[Q].test($)),X=[...J],z=W.filter((Q)=>!X.some((D)=>uJ[Q].test(D)));if(W.length>0?z.length===0:X.some(P$))return{action:"none"};if(Z>=rJ)return{action:"fail",message:iJ};let Y=W.length>1&&z.length>0?` Missing successful verification categories: ${z.join(", ")}.`:"";return{action:"retry",prompt:`${cJ}${Y}`}}var lJ=[/\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|子代理|子智能体)/],F2=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function v2($){return typeof $==="string"&&F2.some((J)=>J.test($))}var nJ=[/\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|子代理)/],oJ=[/\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 sJ($){if(typeof $!=="string")return;if(oJ.some((J)=>J.test($)))return"multiple-allowed";return nJ.some((J)=>J.test($))?"required":void 0}function r$($){for(let J of $){let Z=sJ(J);if(Z!==void 0)return Z==="required"}return!1}var aJ="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.",tJ="Required delegation did not complete before the retry limit.",eJ=3;function I2($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),X=r$(W),z=!1;if(!X)for(let K of W){if(F2.some((Y)=>Y.test(K)))break;if(lJ.some((Y)=>Y.test(K))){z=!0;break}}if(W.length===0||!X&&!z||J.has("Task"))return{action:"none"};if(Z>=eJ)return{action:"fail",message:tJ};return{action:"retry",prompt:aJ}}var $Z=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],JZ=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],ZZ=[/\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 E2($){return ZZ.reduce((J,Z)=>J.replace(Z," "),$)}function l$($){if(typeof $!=="string")return!1;let J=E2($);return $Z.some((Z)=>Z.test(J))}var WZ="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.",XZ="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.",zZ="Required worktree lifecycle did not complete before the retry limit.",KZ=3;function N2($,J,Z){if(!$)return{action:"none"};let W=E2($);if(!l$(W))return{action:"none"};let X=JZ.some((K)=>K.test(W));if(J.has("TaskWorktree"))return{action:"none"};let z=!J.has("EnterWorktree")?"EnterWorktree":X&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!z)return{action:"none"};if(Z>=KZ)return{action:"fail",message:zZ};return{action:"retry",tool:z,prompt:z==="EnterWorktree"?WZ:XZ}}var G2=30000;async function R0($){try{let Z=U$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??i(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,X=new Promise((z)=>{W=setTimeout(()=>z("timeout"),G2)});try{let z=await Promise.race([Z,X]);if(z==="timeout")return x0.warn(`[Loop] Stop hook 超时 (${G2}ms),按 shouldStop: true 处理`),{action:"stop"};let K=z;if(!K.shouldStop)return{action:"continue",reason:K.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return x0.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function YZ($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var QZ=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function VZ($){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 BZ($){let J=$;for(let Q of QZ)J=J.replace(Q," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),X=W&&W[1].length>=6?W[1]:Z;if(X=X.trim().replace(/[\s.。!!??,,;;::-]+$/,""),X.length<=60)return X;let z=X.slice(0,60),K=z.lastIndexOf(" ");return`${(K>36?z.slice(0,K):z).trimEnd()}…`}function S2($){return BZ(VZ($))}import{EventEmitter as HZ}from"events";import f2 from"node:path";function h0($){if(_2($.sessionId),!f2.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:f2.resolve($.projectPath)}}function r1($){let J=h0($);return JSON.stringify([J.projectPath,J.sessionId])}class b$ extends HZ{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!b$.instance)b$.instance=new b$;return b$.instance}publish($,J,Z,W){let X=h0($);this.emit("event",{sessionId:X.sessionId,projectPath:X.projectPath,type:J,...W!==void 0?{seq:W}:{},properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var A2=b$.getInstance();var X$=$$("Agent"),n$=new Set;async function jZ($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(n$.has(Z))return;if(n$.size>=5000)n$.clear();n$.add(Z);try{let W=$.workspaceRoot,X=await C0.findSessionMetadata(Z,W);if(!X)return;if(X.title&&X.title.trim())return;let z=S2(J);if(!z)return;await C0.updateSessionMetadata(Z,X.projectPath,{title:z}),A2.publish({sessionId:Z,projectPath:X.projectPath},"session.updated",{title:z})}catch(W){X$.debug?.("[Loop] 自动生成会话标题失败:",W)}}var p0=`<turn_aborted>
|
|
1
|
+
import{Za as yJ}from"./chunk-jza1rsan.js";import{$a as d2,_a as y$,qb as C0}from"./chunk-scq3ns6v.js";import{wc as DJ}from"./chunk-fvhc1yj8.js";import{Bc as p2,xc as qJ,yc as H$,zc as QJ}from"./chunk-dqvcgwhe.js";import{id as U$}from"./chunk-vxymgh8e.js";import{nd as $$}from"./chunk-qda309d9.js";import{ie as wJ}from"./chunk-tq52pbde.js";import{re as i}from"./chunk-epj56s0n.js";import{Me as R2,Oe as _2}from"./chunk-0n97186m.js";function A$($){return $.role==="system"&&Array.isArray($.content)}function d$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class g${systemMessages;_contextualSystemMessages;_history;_pending=[];context;constructor($,J){this.context=$;let Z=$.messages.find(A$);if(this._contextualSystemMessages=$.messages.filter(d$),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!A$(W)&&!d$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!d$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(A$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((J)=>!A$(J)&&!d$(J))}removeMessages($){this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages()}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function w2($){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 D2($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function q2($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import c$ from"node:path";var AJ=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"]),xJ=/^(LD_.+|DYLD_.+|PATH)$/,y2=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function x$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],X=Z[2],z=W.match(y2);if(!z)break;let K=z[1];if(!AJ.has(K))break;J=X}return J}function f1($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],X=Z[2],z=W.match(y2);if(!z)break;let K=z[1];if(xJ.test(K))break;J=X}return J}var kJ=[/^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 A0($){let J=$,Z=!0;while(Z){Z=!1;for(let W of kJ){let X=J.match(W);if(X){J=J.slice(X[0].length),Z=!0;break}}if(J.startsWith("-- "))J=J.slice(3),Z=!0}return J}function m$($){let J=[],Z="",W=!1,X=!1,z=!1;for(let K=0;K<$.length;K++){let Y=$[K];if(z){Z+=Y,z=!1;continue}if(Y==="\\"&&!W){Z+=Y,z=!0;continue}if(Y==="'"&&!X){W=!W,Z+=Y;continue}if(Y==='"'&&!W){X=!X,Z+=Y;continue}if(W||X){Z+=Y;continue}if(Y==="|"){if(K+1<$.length&&$[K+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}return null}if(Y===">"||Y==="<")return null;if(Y==="&"&&K+1<$.length&&$[K+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}if(Y==="&")return null;if(Y===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=Y}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function P2($){let J=!1,Z=!1,W=!1;for(let X=0;X<$.length;X++){let z=$[X];if(W){W=!1;continue}if(z==="\\"&&!J){W=!0;continue}if(z==="'"&&!Z){J=!J;continue}if(z==='"'&&!J){Z=!Z;continue}if(J)continue;if(z==="$"){let K=$[X+1];if(K&&/[A-Za-z_@*#?!$0-9({]/.test(K))return!0}if(z==="`")return!0;if(Z)continue;if(z==="|")return!0;if(z===">"||z==="<")return!0;if(z==="{"){let K=$.slice(X);if(/^\{[^}]*,[^}]*\}/.test(K)||/^\{[^}]*\.\.[^}]*\}/.test(K))return!0}}return!1}function u$($){let J=[],Z="",W=!1,X=!1,z=!1;for(let K=0;K<$.length;K++){let Y=$[K];if(z){Z+=Y,z=!1;continue}if(Y==="\\"&&!W){if(z=!0,X){let Q=$[K+1];if(Q&&'$`"\\'.includes(Q))continue;Z+=Y,z=!1}continue}if(Y==="'"&&!X){W=!W;continue}if(Y==='"'&&!W){X=!X;continue}if(!W&&!X&&/[ \t]/.test(Y)){if(Z)J.push(Z),Z="";continue}Z+=Y}if(Z)J.push(Z);return J}var MJ=new Set(["npm","pnpm","yarn","bun"]),U2=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),TJ=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]);function RJ($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function hJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function P$($){let J=x$(hJ($)),Z=m$(J);if(!Z||Z.length!==1||P2(J)||/[\r\n]/.test(J))return!1;let W=u$(J);if(W.length===0||W.some((Y)=>[...TJ].some((Q)=>Y===Q||Y.startsWith(`${Q}=`))))return!1;let[X,z,K]=W;if(MJ.has(X??""))return RJ(z==="run"?K:z)||z==="--test";if((X==="npx"||X==="bunx")&&U2.has(z??""))return!0;if(U2.has(X??""))return!0;if(X==="node"&&z==="--test")return!0;if(X==="go"&&["build","test","vet"].includes(z??""))return!0;return X==="cargo"&&["build","check","clippy","test"].includes(z??"")}function M1($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!c$.isAbsolute($);let Z=c$.isAbsolute($)?c$.resolve($):c$.resolve(J,$);return y$.isWithinWorkspace(Z,J)}var x0=$$("Agent"),CJ=3;function k0($,J,Z){if($!=="length")return{action:"none"};if(J>=CJ)return{action:"truncated"};if(w2(Z)==="stop")return x0.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var pJ=[/:\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],dJ=/```[\s\S]{50,}```/,b2="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",gJ=2;function M0($,J,Z=!0){if(!$||J>=gJ)return{action:"none"};if(!Z&&dJ.test($))return{action:"retry",prompt:b2};let W=$.slice(-200),X=W.match(/```/g);if(X&&X.length%2!==0)return{action:"none"};if(pJ.some((K)=>K.test(W)))return{action:"retry",prompt:b2};return{action:"none"}}var mJ=[/\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}(?:测试|单测|集成测试|检查|构建)/],O2={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},uJ={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},cJ="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.",iJ="Required verification did not run successfully before the retry limit.",rJ=3;function L2($,J,Z){if(!Z.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(J)){$.clear();return}if(J==="Bash"&&typeof Z.metadata?.command==="string"&&Z.metadata.exit_code===0&&P$(Z.metadata.command)){$.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes(J))return;let W=Z.metadata?.verificationCommands;if(!Array.isArray(W))return;for(let X of W)if(typeof X==="string"&&P$(X))$.add(X)}function T0($,J,Z){if(!$||!mJ.some((Q)=>Q.test($)))return{action:"none"};let W=Object.keys(O2).filter((Q)=>O2[Q].test($)),X=[...J],z=W.filter((Q)=>!X.some((D)=>uJ[Q].test(D)));if(W.length>0?z.length===0:X.some(P$))return{action:"none"};if(Z>=rJ)return{action:"fail",message:iJ};let Y=W.length>1&&z.length>0?` Missing successful verification categories: ${z.join(", ")}.`:"";return{action:"retry",prompt:`${cJ}${Y}`}}var lJ=[/\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|子代理|子智能体)/],F2=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function v2($){return typeof $==="string"&&F2.some((J)=>J.test($))}var nJ=[/\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|子代理)/],oJ=[/\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 sJ($){if(typeof $!=="string")return;if(oJ.some((J)=>J.test($)))return"multiple-allowed";return nJ.some((J)=>J.test($))?"required":void 0}function r$($){for(let J of $){let Z=sJ(J);if(Z!==void 0)return Z==="required"}return!1}var aJ="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.",tJ="Required delegation did not complete before the retry limit.",eJ=3;function I2($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),X=r$(W),z=!1;if(!X)for(let K of W){if(F2.some((Y)=>Y.test(K)))break;if(lJ.some((Y)=>Y.test(K))){z=!0;break}}if(W.length===0||!X&&!z||J.has("Task"))return{action:"none"};if(Z>=eJ)return{action:"fail",message:tJ};return{action:"retry",prompt:aJ}}var $Z=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],JZ=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],ZZ=[/\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 E2($){return ZZ.reduce((J,Z)=>J.replace(Z," "),$)}function l$($){if(typeof $!=="string")return!1;let J=E2($);return $Z.some((Z)=>Z.test(J))}var WZ="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.",XZ="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.",zZ="Required worktree lifecycle did not complete before the retry limit.",KZ=3;function N2($,J,Z){if(!$)return{action:"none"};let W=E2($);if(!l$(W))return{action:"none"};let X=JZ.some((K)=>K.test(W));if(J.has("TaskWorktree"))return{action:"none"};let z=!J.has("EnterWorktree")?"EnterWorktree":X&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!z)return{action:"none"};if(Z>=KZ)return{action:"fail",message:zZ};return{action:"retry",tool:z,prompt:z==="EnterWorktree"?WZ:XZ}}var G2=30000;async function R0($){try{let Z=U$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??i(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,X=new Promise((z)=>{W=setTimeout(()=>z("timeout"),G2)});try{let z=await Promise.race([Z,X]);if(z==="timeout")return x0.warn(`[Loop] Stop hook 超时 (${G2}ms),按 shouldStop: true 处理`),{action:"stop"};let K=z;if(!K.shouldStop)return{action:"continue",reason:K.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return x0.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function YZ($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var QZ=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function VZ($){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 BZ($){let J=$;for(let Q of QZ)J=J.replace(Q," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),X=W&&W[1].length>=6?W[1]:Z;if(X=X.trim().replace(/[\s.。!!??,,;;::-]+$/,""),X.length<=60)return X;let z=X.slice(0,60),K=z.lastIndexOf(" ");return`${(K>36?z.slice(0,K):z).trimEnd()}…`}function S2($){return BZ(VZ($))}import{EventEmitter as HZ}from"events";import f2 from"node:path";function h0($){if(_2($.sessionId),!f2.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:f2.resolve($.projectPath)}}function r1($){let J=h0($);return JSON.stringify([J.projectPath,J.sessionId])}class b$ extends HZ{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!b$.instance)b$.instance=new b$;return b$.instance}publish($,J,Z,W){let X=h0($);this.emit("event",{sessionId:X.sessionId,projectPath:X.projectPath,type:J,...W!==void 0?{seq:W}:{},properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var A2=b$.getInstance();var X$=$$("Agent"),n$=new Set;async function jZ($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(n$.has(Z))return;if(n$.size>=5000)n$.clear();n$.add(Z);try{let W=$.workspaceRoot,X=await C0.findSessionMetadata(Z,W);if(!X)return;if(X.title&&X.title.trim())return;let z=S2(J);if(!z)return;await C0.updateSessionMetadata(Z,X.projectPath,{title:z}),A2.publish({sessionId:Z,projectPath:X.projectPath},"session.updated",{title:z})}catch(W){X$.debug?.("[Loop] 自动生成会话标题失败:",W)}}var p0=`<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>`;function V$($){return $.executionEngine?.getContextManager()}async function s($,J,Z,W=null,X){try{let z=V$($),K=typeof Z==="string"?Z.trim()!=="":Z.some((Y)=>Y.type==="text"?Y.text.trim()!=="":!0);if(z&&J.sessionId&&K){let Y=await z.saveMessage(J.sessionId,"user",Z,W,X,J.subagentInfo);return jZ(J,Z),Y}}catch(z){X$.warn("[Loop] 保存用户消息失败:",z)}return null}async function h($,J,Z,W,X){try{let z=V$($);if(z&&J.sessionId&&(Z.trim()||X?.trim()))return await z.saveMessage(J.sessionId,"assistant",Z,W,void 0,J.subagentInfo,X)}catch(z){X$.warn("[Loop] 保存助手消息失败:",z)}return null}async function x2($,J,Z){try{let W=V$($);if(W&&J.sessionId)return await W.saveMessage(J.sessionId,"system",p0,Z,void 0,J.subagentInfo)}catch(W){X$.warn("[Loop] 保存中断边界失败:",W)}return null}async function k2($,J,Z,W,X){try{let z=V$($);if(!z||!J.sessionId||Z.length===0)return null;return await z.saveMessage(J.sessionId,"system",`<contextual-project-instructions-ref count="${Z.length}" />`,X,{contextualProjectRules:!0,ruleReferences:JSON.parse(JSON.stringify(Z.map((K)=>({...K})))),triggerPaths:[...W]},J.subagentInfo)}catch(z){X$.warn("[Loop] 保存 contextual project rules provenance 失败:",z)}return null}async function d0($,J,Z,W,X){try{let z=V$($);if(z&&J.sessionId)return await z.saveToolUse(J.sessionId,Z,W,X,J.subagentInfo)}catch(z){X$.warn("[Loop] 保存工具调用失败:",z)}return null}async function o$($,J,Z,W,X,z,K,Y,Q){try{let D=V$($);if(D&&J.sessionId)return await D.saveToolResult(J.sessionId,Z,W,X,z,K,J.subagentInfo,Y,Q)}catch(D){X$.warn("[Loop] 保存工具结果失败:",D)}return null}async function s$($,J,Z,W){try{let X=V$($);if(X&&J.sessionId)return await X.saveCompaction(J.sessionId,Z,W,null)}catch(X){X$.warn("[Loop] 保存压缩数据失败:",X)}return null}import{promises as LZ}from"node:fs";import FZ from"node:path";import{nanoid as z$}from"nanoid";import*as R from"node:fs/promises";import*as B$ from"node:path";var M2={enabled:!0,maxIndexLines:200};var wZ="memory",T2="MEMORY.md";class g0{memoryDir;config;initialized=!1;constructor($,J,Z){if(Z)this.memoryDir=Z;else{let W=R2($);this.memoryDir=B$.join(W,wZ)}this.config={...M2,...J}}async initialize(){if(this.initialized)return;await R.mkdir(this.memoryDir,{recursive:!0}),this.initialized=!0}async loadIndex(){if(!this.config.enabled)return null;await this.initialize();let $=B$.join(this.memoryDir,T2);try{let J=await R.readFile($,"utf-8");if(!J.trim())return null;let Z=J.split(`
|
|
4
4
|
`),X=Z.slice(0,this.config.maxIndexLines).join(`
|