blade-code 0.10.70 → 0.10.71
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-31k6x4kn.js → chunk-0tm20v38.js} +2 -2
- package/dist/{chunk-728anavt.js → chunk-0vrgrw71.js} +1 -1
- package/dist/{chunk-p9vaaayr.js → chunk-1je1xw6v.js} +1 -1
- package/dist/{chunk-g28pgqyn.js → chunk-1pjkgfez.js} +1 -1
- package/dist/{chunk-qstf0gpe.js → chunk-1w83z8j0.js} +1 -1
- package/dist/{chunk-r9n8y8m1.js → chunk-2428hhvj.js} +1 -1
- package/dist/{chunk-0p0e70cy.js → chunk-2px6hzdc.js} +1 -1
- package/dist/chunk-3as0bkqy.js +1 -0
- package/dist/{chunk-bkajr86v.js → chunk-3hy06st1.js} +1 -1
- package/dist/{chunk-qm5c9wew.js → chunk-4ke8k0xw.js} +2 -2
- package/dist/{chunk-ffym3kf3.js → chunk-4pexpa3h.js} +1 -1
- package/dist/{chunk-63121s4r.js → chunk-5te2jqt3.js} +1 -1
- package/dist/{chunk-b39p4f5r.js → chunk-82htkvz8.js} +1 -1
- package/dist/chunk-8j568nm6.js +1 -0
- package/dist/{chunk-wepvrnmh.js → chunk-92x15fzx.js} +1 -1
- package/dist/{chunk-4aam3qhk.js → chunk-93tvxmqg.js} +1 -1
- package/dist/{chunk-1z9k5dmz.js → chunk-97aywyzn.js} +1 -1
- package/dist/{chunk-ypgjqg23.js → chunk-9hchc346.js} +1 -1
- package/dist/{chunk-8wea3qty.js → chunk-9q852bsc.js} +2 -2
- package/dist/{chunk-w2gr97qt.js → chunk-ahg9vjb6.js} +1 -1
- package/dist/{chunk-wahhwjp9.js → chunk-axtzde5k.js} +1 -1
- package/dist/{chunk-y9d9nqnn.js → chunk-azw0jckv.js} +1 -1
- package/dist/{chunk-sch01e04.js → chunk-be30r8an.js} +1 -1
- package/dist/{chunk-d2vrbbvd.js → chunk-byqxaa9v.js} +1 -1
- package/dist/{chunk-7b5s752s.js → chunk-cff9gphh.js} +1 -1
- package/dist/{chunk-5wnx38ze.js → chunk-ckqpt15b.js} +1 -1
- package/dist/{chunk-0kmrvxsz.js → chunk-d3ttqmyt.js} +3 -3
- package/dist/{chunk-pw87f92g.js → chunk-dwb2nmms.js} +1 -1
- package/dist/{chunk-brdxkp0y.js → chunk-fcmgwzrj.js} +1 -1
- package/dist/{chunk-832va1mp.js → chunk-fcv8b6ny.js} +1 -1
- package/dist/{chunk-z77c18j5.js → chunk-gtcxybv5.js} +1 -1
- package/dist/chunk-gvbx0t4j.js +1 -0
- package/dist/{chunk-ysmqje92.js → chunk-j0p54tqt.js} +1 -1
- package/dist/{chunk-20vj0npz.js → chunk-j9q1wyxg.js} +1 -1
- package/dist/chunk-jzntxp7f.js +3 -0
- package/dist/{chunk-f7yfcw8s.js → chunk-mtphps19.js} +1 -1
- package/dist/chunk-n827nys9.js +1 -0
- package/dist/{chunk-cmpj3a5a.js → chunk-nwzpnx7m.js} +1 -1
- package/dist/{chunk-wkpacysr.js → chunk-nx31fkkf.js} +2 -2
- package/dist/{chunk-83b4vfjs.js → chunk-qgrq04hb.js} +1 -1
- package/dist/chunk-qnsvae10.js +1 -0
- package/dist/chunk-r9d4mjxj.js +2 -0
- package/dist/{chunk-b2p4kd07.js → chunk-rm9hbew3.js} +1 -1
- package/dist/{chunk-smjkx71w.js → chunk-s77sbxr7.js} +1 -1
- package/dist/chunk-sp3bn8qh.js +1 -0
- package/dist/{chunk-d808m826.js → chunk-t2wgf9tq.js} +1 -1
- package/dist/{chunk-1bcp0qc4.js → chunk-trn6r1g3.js} +1 -1
- package/dist/{chunk-0p95nha3.js → chunk-v7p533ff.js} +1 -1
- package/dist/{chunk-h94vfh7s.js → chunk-vthgpdbd.js} +1 -1
- package/dist/{chunk-k6shq7rk.js → chunk-wfy851et.js} +1 -1
- package/dist/chunk-wneeq8cr.js +1 -0
- package/dist/{chunk-4md4sd4j.js → chunk-wrfay5r3.js} +1 -1
- package/dist/{chunk-sh17gjxv.js → chunk-x9tvjkjv.js} +1 -1
- package/dist/{chunk-rpfa4a56.js → chunk-xdz5zrjt.js} +1 -1
- package/dist/chunk-xzz69esf.js +1 -0
- package/dist/{chunk-q919ypcz.js → chunk-zdnk7qtn.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-2z75emht.js +0 -1
- package/dist/chunk-3j413cgh.js +0 -1
- package/dist/chunk-8bsyhr4v.js +0 -1
- package/dist/chunk-c0qm0wwk.js +0 -1
- package/dist/chunk-cx5s0rf3.js +0 -1
- package/dist/chunk-e3asq942.js +0 -1
- package/dist/chunk-jrr361h1.js +0 -2
- package/dist/chunk-nea4rcdf.js +0 -1
- package/dist/chunk-v3kkv21n.js +0 -1
- package/dist/chunk-wj6t3tv2.js +0 -3
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{oa as R,pa as g0,ua as v3,va as q9,wa as h0}from"./chunk-
|
|
1
|
+
import{oa as R,pa as g0,ua as v3,va as q9,wa as h0}from"./chunk-qgrq04hb.js";import{Aa as m4,Ra as EJ,xa as wJ,za as LJ}from"./chunk-92x15fzx.js";import{$a as a9,Db as y9,Gb as v9,Sa as L$,Ta as V1,Ua as Z9,Va as c$,Wa as p8,Xa as Y9,Ya as n8,Za as W9,_a as X9,db as Q0,fb as g2,ib as t2,kb as c6,lb as s2,mb as e2,pb as Y$,vb as _5,wb as A3,xb as l7}from"./chunk-nx31fkkf.js";import{Bc as P3,Fc as k9,Kc as Q3,Lc as V3,Mb as H0,Nb as N1,Nc as n,Ob as v$,Pb as V2,Qb as n4,Rb as a2,Sb as o2,jc as z5,kc as D0,lc as t0,uc as r4,vc as u0,wc as z1,xc as X3,yc as U3}from"./chunk-97aywyzn.js";import{Oc as g,Pc as e9,Qc as $7,Rc as i$}from"./chunk-0wxkymqv.js";import{Sc as bJ,Vc as AJ,cd as jJ,id as MJ}from"./chunk-mtphps19.js";import{td as hZ,ud as IZ}from"./chunk-bjqjdw34.js";import{Gd as $5,Hd as _0,Id as f,Ld as q0,Md as m2,Nd as K1,Od as M$,Pd as $4,Qd as m$,Rd as S9,Wd as U1}from"./chunk-1je1xw6v.js";import{Xd as a$}from"./chunk-0j22w4wh.js";import{$d as f9,ae as C9,de as F3,ee as u2}from"./chunk-zdnk7qtn.js";import{ge as R0,he as k$}from"./chunk-wrfay5r3.js";import{ie as M3}from"./chunk-yn51162x.js";import{ke as $3,le as Z3,me as J3}from"./chunk-fcv8b6ny.js";import{Ae as H5,Be as s$,Ce as e$,De as W3,He as w4,Je as P0,Ke as X$,Me as d2,Ne as z3,ne as l2,oe as i2,qe as n2,re as r2,se as H1,te as X7,ve as z$,we as s0,xe as i0,ye as v5,ze as W1}from"./chunk-axtzde5k.js";import{Pe as G1,Re as J$,Se as R2}from"./chunk-hat9v5c5.js";import{Te as l3,Ve as Y3,We as V5,Xe as gZ}from"./chunk-cdy9efgm.js";import{$e as A0,Ze as y4}from"./chunk-4ke8k0xw.js";import{af as $2,bf as i4,cf as Z2,df as $1}from"./chunk-m57w4p91.js";import{$f as A9,Af as $9,Gf as n$,Jf as i8,Tf as D9,Uf as w9,Vf as L9,Wf as E9,Xf as s6,Yf as N9,Zf as j$,_f as b9,ag as j9,cg as HZ,eg as G3,ff as bZ,fg as e7,gg as X0,kf as AZ,mf as R4,rf as y3,vf as jZ,xf as o7,zf as e8}from"./chunk-82htkvz8.js";import{jg as Y1}from"./chunk-h0ft81a3.js";import{kg as G2,lg as S5,mg as _,ng as K7,og as S,pg as l}from"./chunk-v0rsz1rt.js";import{rg as p7,sg as c7}from"./chunk-xz6y0w4n.js";import{ug as F2,wg as C}from"./chunk-k0pa8874.js";import{Xg as i}from"./chunk-t2wgf9tq.js";import{ah as t7,bh as s7}from"./chunk-2px6hzdc.js";import{ch as n3,fh as p3}from"./chunk-t8xmh4w2.js";import{jh as t3}from"./chunk-azw0jckv.js";import{ph as K3,qh as k0}from"./chunk-jzntxp7f.js";import{Bh as W0,uh as Q2,wh as b$,yh as a7,zh as UZ}from"./chunk-9q852bsc.js";import{Dh as r0}from"./chunk-wfy851et.js";import{randomUUID as R5}from"crypto";import{randomUUID as dJ}from"node:crypto";var xJ=String.raw`
|
|
2
2
|
const { spawn } = require('node:child_process');
|
|
3
3
|
const [ownerPidValue, command, ...args] = process.argv.slice(1);
|
|
4
4
|
const ownerPid = Number(ownerPidValue);
|
|
@@ -781,7 +781,7 @@ ${V0}
|
|
|
781
781
|
</approved-plan>
|
|
782
782
|
|
|
783
783
|
IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof H==="string")J0=H+k;else J0=[...H,{type:"text",text:k}]}P=yield*this.runLoop(J0,O,{...A,inputMessageId:void 0})}if(!this.sessionRuntime||!b)return P;let y=await this.sessionRuntime.recordGoalProgress({tokens:P.metadata?.tokensUsed??0,elapsedMs:P.metadata?.duration??0});if(y)yield{kind:"goal_updated",goal:y};if(!P.success||O.signal?.aborted){if(y=await this.sessionRuntime.pauseActiveGoal(O.signal?.aborted?"goal paused after user cancellation":P.error?.message??"goal paused after turn failure"),y)yield{kind:"goal_updated",goal:y}}if(P.success&&!O.signal?.aborted&&E<20)await this.sessionRuntime.waitForBackgroundSubagentFollowUp(b,O.signal);let $0=P.success&&!O.signal?.aborted&&E<20,v=VU(P);if(N=await this.sessionRuntime.finishTurn(b,{continuePending:$0,...v?{acknowledgeInput:!0}:{},outcome:P.success&&!O.signal?.aborted?{status:"completed",turnsCount:P.metadata?.turnsCount??0,toolCallsCount:P.metadata?.toolCallsCount??0,durationMs:P.metadata?.duration??0}:{status:"aborted",cause:O.signal?.aborted?"cancelled":"failed",turnsCount:P.metadata?.turnsCount??0,toolCallsCount:P.metadata?.toolCallsCount??0,durationMs:P.metadata?.duration??0}}),N){E++,q=!0,B=!1,w=null,H="",D=void 0,F=T(),yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:j()};continue}if(!P.success||O.signal?.aborted)return P;if(y=await this.sessionRuntime.getGoal(),!y||y.status!=="active"&&y.status!=="verifying")return P;if(w=await this.sessionRuntime.beginGoalContinuation(),!w)return P;N=await this.sessionRuntime.beginTurn("goal"),q=!1,B=!0,H=U6(w),D=void 0,F=void 0,yield{kind:"goal_continuation_started",goal:w,continuation:w.continuationCount},yield{kind:"goal_updated",goal:w}}}finally{if(this.sessionRuntime&&N)await this.sessionRuntime.finishTurn(N)}}let z=typeof Q==="string"?Q:Q.filter((H)=>H.type==="text").map((H)=>H.text).join(`
|
|
784
|
-
`),K={id:this.generateTaskId(),type:"simple",prompt:z};return{success:!0,finalMessage:(await this.executeTask(K)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-
|
|
784
|
+
`),K={id:this.generateTaskId(),type:"simple",prompt:z};return{success:!0,finalMessage:(await this.executeTask(K)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-ckqpt15b.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){p.debug("Processing Plan mode message...");let{prompt:Y}=await u$({projectPath:Z.workspaceRoot||C(),mode:"plan",includeEnvironment:!0,environmentOptions:P9,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot}),W;if(typeof $==="string")W=S1($);else{let X=$.filter((U)=>U.type==="text");if(X.length>0){let U=X[0];W=$.map((Q)=>Q===U?{type:"text",text:S1(U.text)}:Q)}else W=[{type:"text",text:S1("")},...$]}return yield*this.executeLoop(W,Z,J,Y)}async*runLoop($,Z,J){p.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z.workspaceRoot||C());return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await u$({projectPath:$,replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:P9,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let W=this.buildLoopDependencies();return v9(W,$,Z,J,Y)}takeStartupAdoptedToolResultEvents(){return(this.sessionRuntime?.takeStartupAdoptedToolResults()??[]).flatMap(({call:Z,result:J})=>{let Y={id:Z.toolCallId,type:"function",function:{name:Z.toolName,arguments:JSON.stringify(Z.input)}},W=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,X=J.error===void 0,U=J.output,Q={success:X,llmContent:typeof U==="string"||U!==null&&typeof U==="object"?U:U===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(U),...J.error?{error:{type:"execution_error",message:J.error}}:{},...W?{metadata:W}:{}},V=[{kind:"tool_result",toolCall:Y,result:Q}],z=y9(Y,Q);if(z)V.push(z);return V})}buildLoopDependencies(){return{chatService:this.chatService,toolExecutor:this.toolExecutor,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,p.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($),staticProjectRules:this.sessionRuntime?.getStaticProjectRules(),hydrateProjectRules:this.sessionRuntime?($)=>this.sessionRuntime.hydrateProjectRules($):void 0,resolveContextualProjectRules:this.sessionRuntime?($,Z,J,Y)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,Y):void 0}}async chatWithSystem($,Z){if(!this.isInitialized)throw Error("Agent未初始化");let J=[{role:"system",content:$},{role:"user",content:Z}];return(await this.chatService.chat(J)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.toolExecutor?this.toolExecutor.getRegistry().getAll():[]}getToolRegistry(){return this.toolExecutor.getRegistry()}applyToolWhitelist($){let Z=this.toolExecutor.getRegistry(),Y=Z.getAll().filter((W)=>!$.includes(W.name));for(let W of Y)Z.unregister(W.name);p.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let Y of Z.getAll())if(J.has(Y.name))Z.unregister(Y.name);p.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let Y=Z.get(J.kind)||0;Z.set(J.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.name)}}async destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=(async()=>{this.log("销毁Agent..."),await this.activeOperations.shutdown("agent-destroy");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}})(),this.destroyPromise}syncRuntimeState(){if(!this.sessionRuntime)return;this.chatService=this.sessionRuntime.getChatService(),this.executionEngine=this.sessionRuntime.getExecutionEngine(),this.attachmentCollector=this.sessionRuntime.getAttachmentCollector(),this.currentModelId=this.sessionRuntime.getCurrentModelId(),this.currentModelMaxContextTokens=this.sessionRuntime.getCurrentModelMaxContextTokens()}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}log($,Z){p.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){p.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await u$({projectPath:this.sessionRuntime?.workspaceRoot??C(),replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot});if(J.prompt)this.log("系统提示配置验证成功"),p.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await p2({sessionId:"default",configDir:W0(),workspaceRoot:C(),resourceRoot:C(),agentResources:this.agentResources});p.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;p.debug(`Builtin tools registered: ${Z} tools`),p.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw p.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await D2({workspaceRoot:C(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){p.debug("No MCP servers configured");return}let Z=h0.createIsolated({artifactWriter:new P1(`legacy-${QU()}`)});this.legacyMcpRegistry=Z;for(let[X,U]of Object.entries($))try{p.debug(`Connecting to MCP server: ${X}`),await Z.registerServer(X,U),p.debug(`MCP server "${X}" connected`)}catch(Q){p.warn(`Warning: MCP server "${X}" connection failed:`,Q)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(I1(Z));let W=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:W.revision,reason:"snapshot",replace:!0,instructions:W.instructions,removed:[]}),Z.on("catalogChanged",(X)=>{J.replaceMcpTools(X.tools,X)}),Z.on("contentCatalogChanged",(X)=>{J.queueMcpContentChange(X)}),Z.on("resourceUpdated",(X)=>{J.queueMcpResourceUpdated(X)}),Z.on("connectionLifecycleChanged",(X)=>{J.queueMcpConnectionChange(X)}),Z.on("log",(X)=>{J.queueMcpLog(X)}),Z.on("instructionsChanged",(X)=>{J.queueMcpInstructionsChange({revision:X.revision,reason:X.reason,replace:!1,instructions:X.action==="added"&&X.instruction?[{serverName:X.serverName,...X.instruction}]:[],removed:X.action==="removed"?[X.serverName]:[]})}),Y.tools.length>0)p.debug(`Registered ${Y.tools.length} MCP tools`),p.debug(`[MCP Tools] ${Y.tools.map((X)=>X.name).join(", ")}`)}catch($){p.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await P0(C());if(this.agentResources=d2($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)p.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else p.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;p.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{return Z.some((W)=>{if(W===Y.name)return!0;let X=W.match(/^(\w+)\(.*\)$/);if(X&&X[1]===Y.name)return!0;return!1})});return p.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)p.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let Z=[];for(let Y of $)if(Y.type==="text")Z.push(Y.text);if(Z.length===0)return $;let J=Z.join(`
|
|
785
785
|
`);try{let Y=await this.attachmentCollector.collect(J);if(Y.length===0)return $;p.debug(`Processed ${Y.length} @ file mentions in multimodal message`);let W=this.buildAttachmentText(Y);if(!W)return $;return[...$,{type:"text",text:W}]}catch(Y){return p.error("Failed to process @ mentions in multimodal message:",Y),$}}buildAttachmentText($){let Z=[],J=[];for(let W of $)if(W.type==="file"){let X=W.metadata?.lineRange?` (lines ${W.metadata.lineRange.start}${W.metadata.lineRange.end?`-${W.metadata.lineRange.end}`:""})`:"";Z.push(`<file path="${W.path}"${X?` range="${X}"`:""}>`,W.content,"</file>")}else if(W.type==="directory")Z.push(`<directory path="${W.path}">`,W.content,"</directory>");else if(W.type==="error")J.push(`- @${W.path}: ${W.error}`);let Y="";if(Z.length>0)Y+=`
|
|
786
786
|
|
|
787
787
|
<system-reminder>
|
|
@@ -1582,7 +1582,7 @@ ${J}
|
|
|
1582
1582
|
`)),{success:!0,message:"Schedules listed",content:V.join(`
|
|
1583
1583
|
`)}}case"create":{let Q=SK(X);if("error"in Q)return Y.sendMessage(`创建失败:${Q.error}`),{success:!1,error:Q.error};let V={prompt:Q.prompt,projectPath:U,trigger:Q.trigger,isolation:"worktree",permissionMode:"default",enabled:!0};try{let z=await $.create(V),K=z.nextRunAt?new Date(z.nextRunAt).toLocaleString():"(无)";return Y.sendMessage(`[OK] 已创建定时任务 \`${z.id}\`
|
|
1584
1584
|
${m4(z.trigger)} · 下次运行: ${K}`),{success:!0,message:`Schedule ${z.id} created`}}catch(z){let K=z instanceof Error?z.message:String(z);return Y.sendMessage(`创建失败:${K}`),{success:!1,error:K}}}case"remove":case"rm":{let Q=X[0];if(!Q)return Y.sendMessage("用法:/schedule remove <id>"),{success:!1,error:"Missing schedule id"};let V=await $.remove(Q);return Y.sendMessage(V?`[OK] 已删除 \`${Q}\``:`未找到 \`${Q}\``),{success:V,message:V?"Removed":"Not found"}}case"enable":case"disable":{let Q=X[0];if(!Q)return Y.sendMessage(`用法:/schedule ${W} <id>`),{success:!1,error:"Missing schedule id"};let V=await $.setEnabled(Q,W==="enable");return Y.sendMessage(V?`[OK] 已${W==="enable"?"启用":"停用"} \`${Q}\``:`未找到 \`${Q}\``),{success:Boolean(V),message:V?"Updated":"Not found"}}case"run":{let Q=X[0];if(!Q)return Y.sendMessage("用法:/schedule run <id>"),{success:!1,error:"Missing schedule id"};try{return await fK(Q),Y.sendMessage(`[OK] 已触发 \`${Q}\``),{success:!0,message:"Schedule triggered"}}catch(V){let z=V instanceof Error?V.message:String(V);return Y.sendMessage(`运行失败:${z}`),{success:!1,error:z}}}default:return Y.sendMessage(`未知子命令: ${W}
|
|
1585
|
-
使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${W}`}}}}}var NJ=kK();import*as L1 from"node:fs/promises";import*as E1 from"node:path";async function TJ($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:W,storagePath:X}=Z,U=X??Q2(W??C());if(!X){let H=await yK($,W??C(),J,Y);if(H)return H}let Q;try{Q=(await L1.readdir(U)).filter((O)=>O.endsWith(".jsonl")&&!O.startsWith("agent_")).map((O)=>E1.join(U,O))}catch{return[]}let z=(await Promise.all(Q.map(async(H)=>{try{let O=await L1.stat(H);return{path:H,mtime:O.mtimeMs}}catch{return null}}))).filter((H)=>H!==null).sort((H,O)=>O.mtime-H.mtime).map((H)=>H.path),K=[],G=Y?$:$.toLowerCase();for(let H of z){if(K.length>=J)break;let O=E1.basename(H,".jsonl"),q=await vK(H,G,Y,O);if(K.push(...q),K.length>=J){K.length=J;break}}return K}async function yK($,Z,J,Y){try{let{syncAll:W}=await import("./chunk-
|
|
1585
|
+
使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${W}`}}}}}var NJ=kK();import*as L1 from"node:fs/promises";import*as E1 from"node:path";async function TJ($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:W,storagePath:X}=Z,U=X??Q2(W??C());if(!X){let H=await yK($,W??C(),J,Y);if(H)return H}let Q;try{Q=(await L1.readdir(U)).filter((O)=>O.endsWith(".jsonl")&&!O.startsWith("agent_")).map((O)=>E1.join(U,O))}catch{return[]}let z=(await Promise.all(Q.map(async(H)=>{try{let O=await L1.stat(H);return{path:H,mtime:O.mtimeMs}}catch{return null}}))).filter((H)=>H!==null).sort((H,O)=>O.mtime-H.mtime).map((H)=>H.path),K=[],G=Y?$:$.toLowerCase();for(let H of z){if(K.length>=J)break;let O=E1.basename(H,".jsonl"),q=await vK(H,G,Y,O);if(K.push(...q),K.length>=J){K.length=J;break}}return K}async function yK($,Z,J,Y){try{let{syncAll:W}=await import("./chunk-j0p54tqt.js"),X=await jJ();if(!X)return null;let{SessionService:U}=await import("./chunk-1w83z8j0.js");await W(X,U.projectionDeriverForSearch());let Q=E1.resolve(Z),V=MJ(X,$,Q,J*4),z=Y?$:$.toLowerCase(),K=[];for(let G of V){if(G.role!=="user"&&G.role!=="assistant")continue;let H=u4(G.text,z,Y,G.session_id,G.role,G.timestamp??void 0,0);if(H)K.push(H);if(K.length>=J)break}return K}catch{return null}}async function vK($,Z,J,Y){try{let W=await L1.readFile($,"utf8"),U=W.split(`
|
|
1586
1586
|
`).flatMap((G,H)=>{if(!G.trim())return[];try{return[{event:JSON.parse(G),index:H}]}catch{return[]}});if(!U.some(({event:G})=>G.type==="session_created"))return IK(U,Z,J,Y);let V=new Map(U.flatMap(({event:G,index:H})=>typeof G.id==="string"?[[G.id,H+1]]:[])),z=bJ(AJ(W,$)),K=new Map;for(let G of z){if(G.type==="message_created"&&(G.data.role==="user"||G.data.role==="assistant"))K.set(G.data.messageId,{role:G.data.role,content:[],timestamp:G.timestamp,lineNumber:V.get(G.id)??0});if(G.type==="part_created"&&G.data.partType==="text"){let H=K.get(G.data.messageId),O=G.data.payload.text;if(H&&typeof O==="string")H.content.push(O)}}return[...K.values()].flatMap((G)=>{let H=u4(G.content.join(" "),Z,J,Y,G.role,G.timestamp,G.lineNumber);return H?[H]:[]})}catch{return[]}}function IK($,Z,J,Y){return $.flatMap(({event:W,index:X})=>{if(W.type!=="message")return[];let U=W.message;if(U?.role!=="user"&&U?.role!=="assistant"||!U.content)return[];let Q=typeof U.content==="string"?U.content:Array.isArray(U.content)?U.content.filter((z)=>typeof z==="object"&&z!==null&&z.type==="text"&&typeof z.text==="string").map((z)=>z.text).join(" "):"",V=u4(Q,Z,J,Y,U.role,typeof W.timestamp==="string"?W.timestamp:void 0,X+1);return V?[V]:[]})}function u4($,Z,J,Y,W,X,U){if(!$)return;let Q=J?$:$.toLowerCase();if(!Q.includes(Z))return;let V=Q.indexOf(Z),z=Math.max(0,V-80),K=Math.min($.length,V+Z.length+80);return{sessionId:Y,role:W,content:(z>0?"...":"")+$.slice(z,K).replace(/\n/g," ")+(K<$.length?"...":""),timestamp:X,lineNumber:U}}function CJ($){if($.length===0)return"没有找到匹配的历史记录";let Z=[`**找到 ${$.length} 条匹配:**
|
|
1587
1587
|
`];for(let J of $){let Y=J.timestamp?new Date(J.timestamp).toLocaleString("zh-CN",{timeZone:"Asia/Shanghai"}):"?",W=J.role==="user"?"\uD83D\uDC64":"\uD83E\uDD16";Z.push(`${W} \`${J.sessionId.slice(0,8)}\` (${Y})`),Z.push(` ${J.content}`),Z.push("")}return Z.join(`
|
|
1588
1588
|
`)}var xK={name:"search",description:"Search past session transcripts",fullDescription:"搜索历史会话记录,查找过去的对话内容",usage:"/search <keyword>",aliases:["find","history"],category:"Session",examples:['/search 断路器 - 搜索包含"断路器"的历史对话',"/search edit tool - 搜索 edit tool 相关讨论"],async handler($,Z){let J=h(Z);if($.length===0)return J.sendMessage("**用法:** `/search <关键词>`\n\n在历史会话中搜索包含指定关键词的对话"),{success:!0,message:"显示帮助"};let Y=$.join(" ");J.sendMessage(`正在搜索: "${Y}" ...`);try{let W=await TJ(Y,{maxResults:15,projectPath:Z.cwd}),X=CJ(W);return J.sendMessage(X),{success:!0,message:`found ${W.length} results`,data:{matches:W.length}}}catch(W){let X=W instanceof Error?W.message:"未知错误";return J.sendMessage(`搜索失败: ${X}`),{success:!1,error:X}}}},RJ=xK;var hK={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,Z)=>{try{let J=Z.workspaceRoot??Z.cwd;return await X$(J,async(Y)=>{await Y.skills.refresh(),e$(J),await s$(J)}),{success:!0,message:"show_skills_manager",data:{action:"show_skills_manager"}}}catch(J){let Y=`获取 Skills 失败: ${J instanceof Error?J.message:"未知错误"}`;return f().addAssistantMessage(Y),{success:!1,error:Y}}}},PJ=hK;import gK from"node:path";function N5($){if($<1000)return`${$}ms`;let Z=Math.floor($/1000);if(Z<60)return`${Z}s`;let J=Math.floor(Z/60);if(J<60)return`${J}m ${Z%60}s`;return`${Math.floor(J/60)}h ${J%60}m`}function SJ($){switch($){case"running":return"[RUNNING]";case"completed":case"exited":return"[OK]";case"failed":case"error":return"[FAIL]";case"killed":case"cancelled":return"[STOPPED]";default:return"[?]"}}function fJ($,Z){if($.length<=Z)return $;return $.slice(0,Z-3)+"..."}async function mK($,Z){let J=h(Z),Y=$[0],W=a.getInstance(),X=e.getInstance(),U=Z.sessionId??"",Q=Z.sessionId?{sessionId:Z.sessionId,projectPath:gK.resolve(Z.workspaceRoot??Z.cwd)}:void 0;if(Y==="resume"){let O=$[1],q=$.slice(2).join(" ").trim();if(!O||!q)return{success:!1,error:"Usage: /tasks resume <agentId> <prompt>"};if(!Z.subagents)return{success:!1,error:"This surface does not own a subagent runtime"};let B=await Z.subagents.resume(O,q),F=`Resumed \`${O}\` as \`${B.session.id}\` (depth ${B.session.resumeDepth}).`;return J.sendMessage(F),{success:!0,message:F,data:{action:"subagent_resumed",sourceAgentId:O,subagent:B.session}}}if(Y==="clean"){let O=X.cleanupExpiredSessionsForParent(Q??U,0);return J.sendMessage(`已清理 ${O} 个已完成的 Agent 会话`),{success:!0,message:`Cleaned ${O} agent sessions`}}let V=[`**后台任务列表**
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{wa as H}from"./chunk-
|
|
1
|
+
import{wa as H}from"./chunk-qgrq04hb.js";import"./chunk-th4jjfgm.js";import"./chunk-0wxkymqv.js";import{Qd as $,Wd as T}from"./chunk-1je1xw6v.js";import"./chunk-v508x7cg.js";import"./chunk-0j22w4wh.js";import"./chunk-4ke8k0xw.js";import"./chunk-m57w4p91.js";import"./chunk-82htkvz8.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import{wg as k}from"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-t2wgf9tq.js";import"./chunk-2px6hzdc.js";import"./chunk-t8xmh4w2.js";import"./chunk-azw0jckv.js";import"./chunk-jzntxp7f.js";import"./chunk-r9d4mjxj.js";import"./chunk-9q852bsc.js";import"./chunk-wfy851et.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
|
|
2
2
|
blade mcp
|
|
3
3
|
`),console.log(`管理 MCP 服务器
|
|
4
4
|
`),console.log("Commands:"),console.log(" blade mcp add <name> <commandOrUrl> [args...] 添加 MCP 服务器"),console.log(" blade mcp remove <name> 删除 MCP 服务器 [aliases: rm]"),console.log(" blade mcp list 列出所有 MCP 服务器并检查健康状态 [aliases: ls]"),console.log(" blade mcp get <name> 获取服务器详情"),console.log(" blade mcp login <name> 登录远程 MCP OAuth"),console.log(" blade mcp logout <name> 清除远程 MCP OAuth 凭证"),console.log(` blade mcp add-json <name> <json> 从 JSON 字符串添加服务器
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{f as T,g as W,h as X,i as Y}from"./chunk-
|
|
1
|
+
import{f as T,g as W,h as X,i as Y}from"./chunk-93tvxmqg.js";import"./chunk-9hchc346.js";import"./chunk-rm9hbew3.js";import"./chunk-s77sbxr7.js";import"./chunk-ahg9vjb6.js";import"./chunk-byqxaa9v.js";import"./chunk-d3ttqmyt.js";import"./chunk-qgrq04hb.js";import"./chunk-92x15fzx.js";import"./chunk-nx31fkkf.js";import"./chunk-th4jjfgm.js";import"./chunk-97aywyzn.js";import"./chunk-0wxkymqv.js";import"./chunk-mtphps19.js";import{qd as R}from"./chunk-0vrgrw71.js";import"./chunk-bjqjdw34.js";import{Md as Q}from"./chunk-1je1xw6v.js";import"./chunk-v508x7cg.js";import"./chunk-0j22w4wh.js";import"./chunk-zdnk7qtn.js";import"./chunk-wrfay5r3.js";import"./chunk-yn51162x.js";import"./chunk-fcv8b6ny.js";import"./chunk-axtzde5k.js";import"./chunk-hat9v5c5.js";import"./chunk-cdy9efgm.js";import"./chunk-zvz2cnt4.js";import"./chunk-4ke8k0xw.js";import"./chunk-m57w4p91.js";import"./chunk-82htkvz8.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-t2wgf9tq.js";import"./chunk-2px6hzdc.js";import"./chunk-t8xmh4w2.js";import{jh as M}from"./chunk-azw0jckv.js";import"./chunk-jzntxp7f.js";import"./chunk-r9d4mjxj.js";import"./chunk-9q852bsc.js";import"./chunk-wfy851et.js";import m from"chalk";import K from"open";var A=`
|
|
2
2
|
____ _ _
|
|
3
3
|
| __ )| | __ _ __| | ___
|
|
4
4
|
| _ \\| |/ _\` |/ _\` |/ _ \\
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{gg as F}from"./chunk-
|
|
1
|
+
import{gg as F}from"./chunk-82htkvz8.js";import{ah as D,bh as E}from"./chunk-2px6hzdc.js";import G from"node:path";function A(b){if(Array.isArray(b))return b.map((q)=>A(q));if(b!==null&&typeof b==="object"&&Object.getPrototypeOf(b)===Object.prototype)return Object.fromEntries(Object.entries(b).map(([q,w])=>[q,A(w)]));return b}function H(b){return A(b)}function I(b,q){let w=new D(q?.credentials??E().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=G.resolve(b),x=F.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...H(q),...J,...K},B=I(z);return x.validateConfig(z,B),{projectRoot:w,config:z,catalog:B}}function T(b){let q=H(b.config);return{projectRoot:G.resolve(b.projectRoot),config:q,catalog:I(q,b.catalog)}}
|
|
2
2
|
export{H as ke,Q as le,T as me};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{ja as F,la as L}from"./chunk-
|
|
1
|
+
import{ja as F,la as L}from"./chunk-d3ttqmyt.js";import{Dc as $,Fc as B,Nc as Q}from"./chunk-97aywyzn.js";import{Je as y}from"./chunk-axtzde5k.js";import{wg as V}from"./chunk-k0pa8874.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{ld as a,md as b,nd as c}from"./chunk-2428hhvj.js";import"./chunk-s7jsadnc.js";import"./chunk-1je1xw6v.js";import"./chunk-v508x7cg.js";import"./chunk-0j22w4wh.js";import"./chunk-zvz2cnt4.js";import"./chunk-82htkvz8.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-t2wgf9tq.js";import"./chunk-2px6hzdc.js";import"./chunk-t8xmh4w2.js";import"./chunk-azw0jckv.js";import"./chunk-jzntxp7f.js";import"./chunk-r9d4mjxj.js";import"./chunk-9q852bsc.js";import"./chunk-wfy851et.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{bd as a,cd as b,dd as c,ed as d,fd as e,gd as f,hd as g,id as h}from"./chunk-
|
|
1
|
+
import{bd as a,cd as b,dd as c,ed as d,fd as e,gd as f,hd as g,id as h}from"./chunk-mtphps19.js";import"./chunk-t2wgf9tq.js";import"./chunk-9q852bsc.js";import"./chunk-wfy851et.js";export{d as syncSession,e as syncAll,h as searchProjectionText,c as resetProjectionDbCache,f as removeSessionFromProjection,g as rebuildProjectionIndex,b as getProjectionDb,a as getIndexDbPath};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./chunk-
|
|
1
|
+
import"./chunk-wfy851et.js";var d={command:"install [target]",describe:"Install Blade native build. Use [target] to specify version (stable, latest, or specific version)",builder:(b)=>{return b.positional("target",{describe:"Version to install",type:"string",default:"stable",choices:["stable","latest"]}).option("force",{type:"boolean",describe:"Force reinstall",default:!1}).example([["$0 install","Install stable version"],["$0 install latest","Install latest version"],["$0 install --force","Force reinstall stable version"]])},handler:async(b)=>{console.log(`Installing Blade ${b.target}...`);try{if(b.force)console.log("Force reinstall enabled");console.log("Downloading..."),console.log("Installing..."),console.log("Installation completed successfully")}catch(c){console.error(`Error: Installation failed: ${c instanceof Error?c.message:"未知错误"}`),process.exit(1)}}};export{d as installCommands};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{rh as C,sh as I}from"./chunk-r9d4mjxj.js";import{Bh as _}from"./chunk-9q852bsc.js";import{createHash as S}from"node:crypto";import{constants as A,promises as B}from"node:fs";import N from"node:os";import F from"node:path";import{Mutex as w}from"async-mutex";import{LRUCache as k}from"lru-cache";import E from"write-file-atomic";var X=1,j=65536,T=1048576,z=100,R=64;function t(q){return q.state==="trusted"||q.state==="not_required"}function K(q){return q!==null&&typeof q==="object"&&!Array.isArray(q)}function V(q,Q=2048){return q.length<=Q?q:`${q.slice(0,Q-1)}…`}function M(q){if(typeof q!=="string"||!q.trim())return;try{let Q=new URL(q);return V(`${Q.origin}${Q.pathname}`)}catch{return V(q)}}function D(q){return Array.isArray(q)?q.filter((Q)=>typeof Q==="string"):[]}function m(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.type==="string"?$.type:"unknown",G=typeof $.command==="string"?$.command:void 0,J=D($.args),L=H==="stdio"?V([G,...J].filter(Boolean).join(" ")):M($.url);return{kind:"mcp",name:`${Q} (${H})`,...L?{target:L}:{}}})}function g(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.command==="string"?V($.command):void 0,G=K($.extensionToLanguage)?Object.keys($.extensionToLanguage).slice(0,12).join(", "):"unknown extensions";return{kind:"lsp",name:`${Q} (${G})`,...H?{target:H}:{}}})}function P(q){if(!Array.isArray(q))return[];return q.slice(0,z).flatMap((Q)=>{if(!K(Q))return[];let Z=typeof Q.id==="string"?Q.id:"unnamed",$=typeof Q.provider==="string"?Q.provider:"unknown",H=typeof Q.model==="string"?Q.model:"unknown",G=K(Q.overrides)?Q.overrides:{},J=M(G.baseUrl);return[{kind:"model",name:`${Z}: ${$}/${H}`,...J?{target:J}:{}}]})}function y(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.wireApi==="string"?$.wireApi:"unknown",G=M($.baseUrl);return{kind:"model",name:`${Q} (${H})`,...G?{target:G}:{}}})}function f(q){if(!K(q))return[];let Q=[];for(let Z of["allow","ask","deny"])for(let $ of D(q[Z]).slice(0,z))Q.push({kind:"permission",name:`${Z}: ${V($,512)}`});return Q}function h(q){let Q=[...m(q.mcpServers),...g(q.lspServers),...P(q.models),...y(q.modelProviders),...f(q.permissions)];if(K(q.env))for(let Z of Object.keys(q.env).slice(0,z))Q.push({kind:"environment",name:Z});if(typeof q.permissionMode==="string")Q.push({kind:"permission",name:`permissionMode: ${q.permissionMode}`});return Q}function v(q){return q!=="hooks"&&q!=="disableAllHooks"}function l(q){return S("sha256").update(q).digest("hex")}function p(q,Q){let Z=F.relative(q,Q);return Z===""||!Z.startsWith(`..${F.sep}`)&&Z!==".."&&!F.isAbsolute(Z)}class x{storeDir;static instance=null;mutex=new w;statusCache=new k({max:R});constructor(q=F.join(_(),"workspace-trust")){this.storeDir=q}static getInstance(){if(!x.instance)x.instance=new x;return x.instance}static resetInstance(){x.instance=null}async getStatus(q){let Q=await C(q),Z;try{Z=await this.discoverSensitiveSources(Q.projectPath)}catch(Y){let O={...Q,state:"error",sensitiveSources:0,sources:[],decision:"undecided",error:Y instanceof Error?Y.message:"Workspace trust review failed"};return this.cacheStatus(q,O),O}if(Z.length===0){let Y={...Q,state:"not_required",sensitiveSources:0,sources:Z,decision:"undecided"};return this.cacheStatus(q,Y),Y}let $;try{$=await this.readDecisions()}catch(Y){let O={...Q,state:"error",sensitiveSources:Z.length,sources:Z,decision:"undecided",error:Y instanceof Error?Y.message:"Workspace trust store is unavailable"};return this.cacheStatus(q,O),O}let H=$.filter((Y)=>p(Y.path,Q.trustRoot)),G=Math.max(-1,...H.map((Y)=>Y.path.split(F.sep).length)),J=H.filter((Y)=>Y.path.split(F.sep).length===G),L=J.length>0&&J.every((Y)=>Y.trusted),U=J[0],b=U?.path===Q.trustRoot,W={...Q,state:L?"trusted":"untrusted",sensitiveSources:Z.length,sources:Z,decision:U?b?U.trusted?"trusted":"untrusted":"inherited":"undecided",...U?.decidedAt?{decidedAt:U.decidedAt}:{},...!b&&U?.path?{inheritedFrom:U.path}:{}};return this.cacheStatus(q,W),W}cacheStatus(q,Q){this.statusCache.set(F.resolve(q),Q),this.statusCache.set(Q.projectPath,Q)}getCachedStatus(q){return this.statusCache.get(F.resolve(q))}isTrustedCached(q){return this.getCachedStatus(q)?.state==="trusted"}getCacheStats(){return{capacity:R,entries:this.statusCache.size}}async trust(q){return this.recordDecision(q,!0)}async revoke(q){return this.recordDecision(q,!1)}async recordDecision(q,Q){return this.mutex.runExclusive(async()=>{await I(q);let Z=await C(q);await this.assertSafeTrustRoot(Z);let $={version:X,path:Z.trustRoot,trusted:Q,decidedAt:new Date().toISOString()};return await this.writeDecision($),this.statusCache.clear(),this.getStatus(q)})}async assertSafeTrustRoot(q){let Q=F.parse(q.trustRoot).root,Z=await B.realpath(N.homedir()).catch(()=>F.resolve(N.homedir()));if(!F.isAbsolute(q.trustRoot)||q.trustRoot===Q||q.trustRoot===Z)throw Error("Refusing to trust the filesystem root or user home directory")}async discoverSensitiveSources(q){let Q=[],Z=await this.reviewPackageScripts(q);if(Z)Q.push(Z);for(let[$,H]of[[".blade/config.json","config"],[".blade/settings.json","settings"],[".blade/settings.local.json","settings"]]){let G=await this.reviewConfigFile(q,$,H);if(G)Q.push(G)}for(let $ of[".blade/plugins",".claude/plugins"]){let H=await this.reviewResourceDirectory(q,$,"plugins","plugin");if(H)Q.push(H)}for(let $ of[".blade/commands",".claude/commands"]){let H=await this.reviewResourceDirectory(q,$,"commands","command");if(H)Q.push(H)}for(let[$,H,G]of[[".blade/skills","skills","skill"],[".claude/skills","skills","skill"],[".blade/agents","agents","agent"],[".claude/agents","agents","agent"]]){let J=await this.reviewResourceDirectory(q,$,H,G);if(J)Q.push(J)}for(let $ of["CLAUDE.md","AGENTS.md","BLADE.md"]){let H=await this.reviewInstructionFile(q,$);if(H)Q.push(H)}return Q}async reviewPackageScripts(q){let Q=F.join(q,"package.json"),Z;try{Z=await B.stat(Q)}catch(J){if(J.code==="ENOENT")return;throw J}if(!Z.isFile())return;if(Z.size>T)throw Error("package.json exceeds the 1 MiB workspace review limit");let $;try{$=JSON.parse(await B.readFile(Q,"utf8"))}catch{return{path:"package.json",kind:"package",keys:[],effects:[],warning:"Invalid package.json; project scripts will remain blocked"}}if(!K($)||!K($.scripts))return;let H=$.scripts,G=Object.keys(H).filter((J)=>typeof H[J]==="string").sort().slice(0,z);if(G.length===0)return;return{path:"package.json",kind:"package",keys:G,effects:G.map((J)=>({kind:"command",name:`package script: ${J}`}))}}async reviewInstructionFile(q,Q){try{if(!(await B.stat(F.join(q,Q))).isFile())return}catch(Z){if(Z.code==="ENOENT")return;throw Z}return{path:Q,kind:"instructions",keys:[Q],effects:[{kind:"instruction",name:Q}]}}async reviewConfigFile(q,Q,Z){let $=F.join(q,Q),H;try{H=await B.stat($)}catch(b){if(b.code==="ENOENT")return;throw b}if(!H.isFile())return;if(H.size>T)throw Error(`${Q} exceeds the 1 MiB workspace review limit`);let G;try{G=JSON.parse(await B.readFile($,"utf8"))}catch{return{path:Q,kind:Z,keys:[],effects:[],warning:"Invalid JSON; the file will remain blocked"}}if(!K(G))return{path:Q,kind:Z,keys:[],effects:[],warning:"Configuration root is not an object"};let J=Object.keys(G).filter(v).sort();if(J.length===0)return;let L=h(G),U=new Set(["mcpServers","lspServers","models","modelProviders","permissions","env","permissionMode"]);for(let b of J)if(!U.has(b))L.push({kind:"configuration",name:b});return{path:Q,kind:Z,keys:J,effects:L}}async reviewResourceDirectory(q,Q,Z,$){let H=F.join(q,Q),G;try{G=await B.readdir(H,{withFileTypes:!0})}catch(L){if(L.code==="ENOENT")return;throw L}let J=G.filter((L)=>Z==="plugins"||Z==="skills"?L.isDirectory()||L.isSymbolicLink():L.isFile()||L.isDirectory()||L.isSymbolicLink()).slice(0,z);if(J.length===0)return;return{path:Q,kind:Z,keys:J.map((L)=>L.name),effects:J.map((L)=>({kind:$,name:L.name}))}}async readDecisions(){let q;try{q=await B.lstat(this.storeDir)}catch($){if($.code==="ENOENT")return[];throw $}if(!q.isDirectory()||q.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&q.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((q.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700");let Q=await B.readdir(this.storeDir,{withFileTypes:!0}),Z=[];for(let $ of Q){if(!$.name.endsWith(".json"))continue;if(!$.isFile())throw Error("Workspace trust store entries must be regular files");Z.push(await this.readDecision(F.join(this.storeDir,$.name)))}return Z}async readDecision(q){let Q;try{Q=await B.open(q,A.O_RDONLY|A.O_NOFOLLOW)}catch{throw Error("Workspace trust decision must be a regular file")}try{let Z=await Q.stat();if(!Z.isFile()||Z.size>j)throw Error("Workspace trust decision is invalid");if(process.getuid&&Z.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((Z.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600");let $=JSON.parse(await Q.readFile("utf8"));if(!K($)||$.version!==X||typeof $.path!=="string"||!F.isAbsolute($.path)||typeof $.trusted!=="boolean"||typeof $.decidedAt!=="string"||!Number.isFinite(Date.parse($.decidedAt))||Object.keys($).some((H)=>H!=="version"&&H!=="path"&&H!=="trusted"&&H!=="decidedAt"))throw Error("Workspace trust decision schema is invalid");return{version:X,path:$.path,trusted:$.trusted,decidedAt:$.decidedAt}}finally{await Q.close()}}async writeDecision(q){await this.ensureStoreDirectoryForWrite();let Q=F.join(this.storeDir,`${l(q.path)}.json`);try{let Z=await B.lstat(Q);if(!Z.isFile()||Z.isSymbolicLink())throw Error("Workspace trust decision must be a regular file");if(process.getuid&&Z.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((Z.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600")}catch(Z){if(Z.code!=="ENOENT")throw Z}await E(Q,`${JSON.stringify(q,null,2)}
|
|
2
|
+
`,{mode:384}),await B.chmod(Q,384)}async ensureStoreDirectoryForWrite(){try{let q=await B.lstat(this.storeDir);if(!q.isDirectory()||q.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&q.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((q.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700")}catch(q){if(q.code!=="ENOENT")throw q;await B.mkdir(this.storeDir,{recursive:!0,mode:448}),await B.chmod(this.storeDir,448)}}}
|
|
3
|
+
export{R as oh,t as ph,x as qh};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Xg as r}from"./chunk-
|
|
1
|
+
import{Xg as r}from"./chunk-t2wgf9tq.js";import{Bh as u,Ch as i,th as d,vh as x,xh as j}from"./chunk-9q852bsc.js";import{Dh as y}from"./chunk-wfy851et.js";import{stat as a}from"node:fs/promises";import k from"node:path";import*as U from"node:path";var e=50,__=100,E_=new Set(["queued","running","completed","failed","cancelled","interrupted"]),R_=new Set(["high","medium","low"]),W_=/^[A-Za-z0-9_-]+$/,$_=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;function H_(_){return typeof _==="string"&&$_.test(_)&&Number.isFinite(Date.parse(_))}function v(_){return typeof _==="string"&&U.isAbsolute(_)}function M_(_){return Buffer.from(JSON.stringify(_),"utf8").toString("base64url")}function Q_(_){try{if(!W_.test(_))throw Error("invalid");let E=Buffer.from(_,"base64url").toString("utf8");if(Buffer.from(E,"utf8").toString("base64url")!==_)throw Error("invalid");let R=JSON.parse(E);if(R.version!==1||typeof R.includeSubagents!=="boolean"||R.archived!==void 0&&typeof R.archived!=="boolean"||!(R.cwd===null||v(R.cwd))||!H_(R.lastMessageTime)||!v(R.projectPath)||!x(R.sessionId))throw Error("invalid");return{version:1,cwd:R.cwd===null?null:U.resolve(R.cwd),includeSubagents:R.includeSubagents,archived:R.archived??!1,lastMessageTime:R.lastMessageTime,projectPath:U.resolve(R.projectPath),sessionId:R.sessionId}}catch{throw Error("Invalid session cursor")}}function J(_){let E="";for(let R=0;R<_.length;R+=1)E+=_.charCodeAt(R).toString(16).padStart(4,"0");return E}function V_(_){if(!_.cursor)return;let E=Q_(_.cursor);if(E.cwd!==_.cwd||E.includeSubagents!==_.includeSubagents||(E.archived??!1)!==_.archived)throw Error("Session cursor scope does not match this query");return E}function O_(_={}){let{cwd:E,cursor:R,limit:W,includeSubagents:$=!1,archived:H=!1}=_;if(E!==void 0&&!U.isAbsolute(E))throw Error("Session catalog cwd must be absolute");let M=W===void 0?e:W;if(!Number.isInteger(M)||M<1||M>__)throw Error("Session catalog limit must be an integer from 1 to 100");return{cwd:E===void 0?null:U.resolve(E),cursor:R??void 0,limit:M,includeSubagents:$,archived:H}}function N_(_={}){let E=c(_.taskStatus,E_,"task status"),R=c(_.taskPriority,R_,"task priority"),W=S(_.taskDueAfter,"taskDueAfter"),$=S(_.taskDueBefore,"taskDueBefore");return X_(W,$),{...E?{taskStatuses:E}:{},...R?{taskPriorities:R}:{},...W?{taskDueAfter:W}:{},...$?{taskDueBefore:$}:{}}}function c(_,E,R){if(_===void 0)return;let W=Array.isArray(_)?_:[_];if(W.length===0)return;let $=new Set;for(let H of W){if(typeof H!=="string"||!E.has(H))throw Error(`Invalid session ${R} filter`);$.add(H)}return[...$].sort()}function S(_,E){if(_===void 0)return;if(typeof _!=="string"||!Number.isFinite(Date.parse(_)))throw Error(`Invalid session ${E} filter`);return new Date(_).toISOString()}function X_(_,E){if(_!==void 0&&E!==void 0&&_>E)throw Error("Session task due range is inverted")}function Y_(_,E){if(_.lastMessageTime>E.lastMessageTime)return-1;if(_.lastMessageTime<E.lastMessageTime)return 1;if(_.projectPath<E.projectPath)return-1;if(_.projectPath>E.projectPath)return 1;if(_.sessionId<E.sessionId)return-1;if(_.sessionId>E.sessionId)return 1;return 0}function f_(_,E){let R=[..._],W=V_(E);if(W)R=R.filter((M)=>Y_(M,{sessionId:W.sessionId,projectPath:W.projectPath,lastMessageTime:W.lastMessageTime})>0);let $=R.slice(0,E.limit);if($.length===0||R.length<=$.length)return{sessions:$};let H=$[$.length-1];return{sessions:$,nextCursor:M_({version:1,cwd:E.cwd,includeSubagents:E.includeSubagents,archived:E.archived,lastMessageTime:H.lastMessageTime,projectPath:H.projectPath,sessionId:H.sessionId})}}function G_(_){return _.type==="message_created"||_.type==="token_budget_handoff_recorded"||_.type==="part_created"||_.type==="part_updated"||_.type==="turn_started"||_.type==="turn_completed"||_.type==="turn_aborted"||_.type==="interaction_requested"||_.type==="interaction_responded"||_.type==="interaction_recovered"||_.type==="review_started"||_.type==="review_completed"}function O(_){return _.type==="message_created"&&_.data.role==="user"&&(_.data.inboxMessageId!==void 0||_.data.parentMessageId===void 0)}function N(_,E){let R=_.find((W)=>O(W)&&W.data.messageId===E);if(!R)throw Error(`Rewind checkpoint not found: ${E}`);return{messageId:E,preview:m(_,E),createdAt:R.data.createdAt}}function m(_,E){let R=_.flatMap((W)=>{if(W.type!=="part_created"||W.data.messageId!==E)return[];if(W.data.partType==="text"){let $=W.data.payload;return typeof $.text==="string"?[$.text]:[]}if(W.data.partType==="image")return["[Image]"];return[]}).join("").trim();if(R.length<=160)return R;return`${R.slice(0,160)}...`}function h(_,E){N(_,E);let R=_.findIndex((M)=>M.type==="message_created"&&M.data.messageId===E),W=_[R],$=W?.type==="message_created"?W.data.inboxMessageId:void 0,H=new Set(_.flatMap((M)=>M.type==="turn_started"&&$&&M.data.inputMessageIds?.includes($)?[M.data.turnId]:[]));return _.filter((M,Q)=>{if((M.type==="turn_started"||M.type==="turn_completed"||M.type==="turn_aborted")&&H.has(M.data.turnId))return!1;return Q<R||!G_(M)})}function D(_){let E=[];for(let R of _){if(R.type!=="session_rewound"){E.push(R);continue}if(N(E,R.data.targetMessageId),R.data.mode!=="code")E=h(E,R.data.targetMessageId)}return E}function j_(_){let E=D(_);return E.filter(O).map((R)=>({messageId:R.data.messageId,preview:m(E,R.data.messageId),createdAt:R.data.createdAt})).reverse()}function u_(_,E){let R=D(_),W=N(R,E),$=R.findIndex((M)=>M.type==="message_created"&&M.data.messageId===E),H=R.slice($);return{checkpoint:W,projectedEntries:h(R,E),removedTurns:H.filter(O).length,snapshotMessageIds:H.flatMap((M)=>M.type==="part_created"&&M.data.partType==="tool_call"?[M.data.partId]:[])}}import*as I from"node:fs";import{createReadStream as T_}from"node:fs";import*as X from"node:fs/promises";import*as f from"node:path";import{createInterface as Z_}from"node:readline";var b=65536;function w(_){let E=_.data;if(E===null||typeof E!=="object"||Array.isArray(E))throw Error("Session event data must be a JSON object");return JSON.stringify(_)}function g_(_,E,R){let W=_.trim();if(!W)return;try{return JSON.parse(W)}catch($){throw Error(`Invalid session JSONL in ${R} at line ${E}`,{cause:$})}}function z(_,E="session transcript"){let R=_.split(`
|
|
2
2
|
`),W=!_.endsWith(`
|
|
3
3
|
`),$=[];for(let[H,M]of R.entries())try{let Q=g_(M,H+1,E);if(Q){if(typeof Q.seq!=="number")Q.seq=$.length+1;$.push(Q)}}catch(Q){if(W&&H===R.length-1)break;throw Q}return $}class G{static appendQueues=new Map;filePath;constructor(_){this.filePath=_}static maxSeq(_){let E=0;for(let R of _)if(typeof R.seq==="number"&&R.seq>E)E=R.seq;return E}static stampSeqFrom(_,E){let R=E;return _.map((W)=>{if(typeof W.seq==="number"){if(W.seq>R)R=W.seq;return W}return R+=1,{...W,seq:R}})}static stampSeq(_,E){return G.stampSeqFrom(_,G.maxSeq(E))}async append(_){try{let[E]=await this.appendEntries([_]);return E}catch(E){throw console.error(`[JSONLStore] 追加写入失败: ${this.filePath}`,E),E}}async appendBatch(_){try{return await this.appendEntries(_)}catch(E){throw console.error(`[JSONLStore] 批量追加写入失败: ${this.filePath}`,E),E}}async appendEntries(_){if(_.length===0)return[];return this.enqueue(async()=>{await X.mkdir(f.dirname(this.filePath),{recursive:!0,mode:493});let E=await X.open(this.filePath,"a+",384);try{let R=await this.repairIncompleteTail(E),W=await this.readTailSeq(E),$=G.stampSeqFrom(_,W),H=`${$.map(w).join(`
|
|
4
4
|
`)}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b,c,d,e}from"./chunk-be30r8an.js";import"./chunk-azw0jckv.js";import"./chunk-wfy851et.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{s as Pz,t as xz}from"./chunk-
|
|
1
|
+
import{s as Pz,t as xz}from"./chunk-s77sbxr7.js";import{u as E}from"./chunk-ahg9vjb6.js";import{A as Hz,v as Nz,w as $z,x as Qz,y as Wz,z as Yz}from"./chunk-byqxaa9v.js";import{E as N,N as e,Q as zz,R as Jz,V as Zz,ja as jz,ka as Xz,la as Dz,ma as Lz}from"./chunk-d3ttqmyt.js";import{wa as qz}from"./chunk-qgrq04hb.js";import"./chunk-92x15fzx.js";import{db as n,pb as t,yb as s}from"./chunk-nx31fkkf.js";import{Hb as M}from"./chunk-th4jjfgm.js";import{Ac as a,Cc as x,Fc as o,Kc as R,Nc as F,_b as m,ic as d,jc as v,oc as l,rc as i,tc as r,zc as k}from"./chunk-97aywyzn.js";import"./chunk-0wxkymqv.js";import"./chunk-mtphps19.js";import{qd as Ez}from"./chunk-0vrgrw71.js";import"./chunk-bjqjdw34.js";import{Ld as _z,Md as Oz}from"./chunk-1je1xw6v.js";import"./chunk-v508x7cg.js";import{Xd as I}from"./chunk-0j22w4wh.js";import{$d as p}from"./chunk-zdnk7qtn.js";import"./chunk-wrfay5r3.js";import{ie as Az}from"./chunk-yn51162x.js";import"./chunk-fcv8b6ny.js";import"./chunk-axtzde5k.js";import"./chunk-hat9v5c5.js";import{Te as Rz}from"./chunk-cdy9efgm.js";import"./chunk-zvz2cnt4.js";import"./chunk-4ke8k0xw.js";import"./chunk-m57w4p91.js";import{Lf as wz,Of as Kz}from"./chunk-82htkvz8.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import{qg as h,rg as c,sg as S}from"./chunk-xz6y0w4n.js";import{wg as Fz}from"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import{Xg as T}from"./chunk-t2wgf9tq.js";import"./chunk-2px6hzdc.js";import{ch as Uz,fh as Vz}from"./chunk-t8xmh4w2.js";import"./chunk-azw0jckv.js";import"./chunk-jzntxp7f.js";import"./chunk-r9d4mjxj.js";import"./chunk-9q852bsc.js";import"./chunk-wfy851et.js";import{Readable as uz,Writable as gz}from"node:stream";import*as b from"@agentclientprotocol/sdk";import Gz from"node:path";import{PROTOCOL_VERSION as Cz,RequestError as fz}from"@agentclientprotocol/sdk";import{RequestError as yz}from"@agentclientprotocol/sdk";import{nanoid as y}from"nanoid";var B=T("Agent");function g(z){if(!z)return{};return Object.fromEntries(z.map((Z)=>[Z.name,Z.value]))}function hz(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:g(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:g("headers"in z?z.headers:void 0)};return null}function Sz(z){let Z={};for(let J of z){let Y=hz(J);if(Y)Z[J.name]=Y}return Z}function Bz(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 Mz(z){let Z=a(z.metadata);return Z?[{type:"text",text:k(Z)}]:Bz(z.content)}function kz(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
|
|
2
2
|
`)}function Iz(z){if(!p(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...d("capacity"),resource:z.resource}}class P{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingPromptCompletion=null;pendingUserShell=null;pendingUserShellCompletion=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 Hz({maxPendingItems:$z,maxPendingBytes:Qz,writeTimeoutMs:Wz,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([F.loadSession(this.id,this.cwd),F.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 F.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 Zz.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(B.debug(`[AcpSession ${this.id}] Initializing...`),await F.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),N.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd,async(W)=>{await this.sendUpdateAndWait(W)}),B.debug(`[AcpSession ${this.id}] ACP service context initialized`),await s.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?Sz(this.options.mcpServers):void 0,J=N.getInstance().getTerminalService(this.id);if(this.runtime=await e.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:(X)=>Q.onOutput?.("stdout",X)});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 E.recoverInterrupted(this.cwd,this.id,this.runtime))await this.refreshPersistedMessages();this.agent=await this.createAgent(),await Xz(this.cwd),B.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=n.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!=="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(!r(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 Mz(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);B.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{B.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 X=!1,D,G=(U)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:U.id,status:U.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:U.result?.message||U.result?.error||`Subagent ${U.status}`}}]})},L=this.runtime.resumeSubagent({agentId:Q,prompt:j,onCompleted:(U)=>{if(X)G(U);else D=U}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L.session.id,status:"in_progress",title:`Resuming ${L.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${L.source.id} at depth ${L.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),X=!0,D)G(D);return L}},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,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Q,j,X)},complete:async(Q,j,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Q,j,X)},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()}},codeReview:{run:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let X=await E.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:Q,signal:j,onEvent:(L)=>{if(L.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L.toolCall.id,status:"in_progress",title:`Review: ${L.toolCall.function.name}`,content:[],kind:this.mapToolKind(L.toolKind)});else if(L.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:L.toolCall.id,status:L.result.success?"completed":"failed",content:[]})}}),D=await X.completion,G=(await E.list(this.cwd,this.id)).find((L)=>L.start.reviewId===X.reviewId);if(!G)throw Error(`Review not found: ${X.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:X.reviewId,status:D.status,findings:D.findings.length,content:m(G.start,D)}}},signal:Z,acp:{sendMessage:(Q)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}})},sendToolStart:(Q,j,X)=>{let D=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,G=this.mapToolKind(X);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:D,status:"in_progress",title:`${Q}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(j,null,2)}}],kind:G})},sendToolResult:(Q,j)=>{if(j.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:j.summary}})}}},Y=await Dz(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 F.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){return B.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 sendAvailableCommands(){try{let z=Lz(this.cwd,this.runtime?.getAgentResources()),Z=["model","permissions","theme","config","exit","ide"],Y=z.filter((H)=>!Z.includes(H.name)).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}});B.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map((H)=>H.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Y}),B.info(`[AcpSession ${this.id}] Sent ${Y.length} available commands`)}catch(z){B.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((L)=>L.outputSchema)?.outputSchema:void 0),Q;if(W!==void 0)Q=o(W).schema;if(H.trimStart().startsWith("!")){if(Q)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(H)}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 L=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!L.accepted)throw Error(L.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(B.debug(`[AcpSession ${this.id}] Queued steering for active turn (${L.queued})`),L.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let j=new AbortController,X=!1,D,G=new Promise((L)=>{D=L});this.pendingPrompt=j,this.pendingPromptCompletion=G;try{if(B.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),jz(H)){if(Q)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(H,j.signal)}let L={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.contextMessages],signal:j.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($)}}},U=await t(this.agent.chatStream(Y,L,{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 A=this.mapToolKind($.toolKind),w=`Executing ${O}`;if(O==="Task"&&"function"in V)try{let q=JSON.parse(V.function.arguments),K=q.resume_from??q.resume;if(typeof K==="string")w=`Resuming ${String(q.subagent_type||"subagent")} from ${K}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:V.id,status:"in_progress",title:w,content:[],kind:A});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,A=[],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;A.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))A.push({type:"diff",path:w.file_path,oldText:w.oldContent,newText:w.newContent??null});else{let K=V.function.name,Tz=Jz(i(zz(K,O),l));A.push({type:"content",content:{type:"text",text:Tz}})}if(V.function.name==="Task"&&(w?.verificationVerdict==="pass"||w?.verificationVerdict==="fail"||w?.verificationVerdict==="partial"))A.unshift({type:"content",content:{type:"text",text:`Verification result: ${w.verificationVerdict.toUpperCase()}`}});let q=O.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:q,content:A});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{Lb as m2}from"./chunk-th4jjfgm.js";import{Cc as f0,Ec as R6,Fc as O1,Gc as C6,Mb as $$,Nc as R$,Tb as sJ,Ub as tJ,Vb as G6,Wb as O6,ac as eJ,bc as d2,cc as c2,dc as j6,ec as N1,fc as i2,gc as l2,hc as U1,kc as kJ,sc as i$}from"./chunk-1z9k5dmz.js";import{Sc as z0,Vc as dJ,Wc as _0}from"./chunk-f7yfcw8s.js";import{Xd as j2}from"./chunk-0j22w4wh.js";import{Yd as p2,Zd as c0,_d as M2,be as g2,ce as h6,ee as xJ}from"./chunk-q919ypcz.js";import{Oe as l0,Pe as R0,Se as u2}from"./chunk-hat9v5c5.js";import{$e as V$}from"./chunk-qm5c9wew.js";import{jg as Q2}from"./chunk-h0ft81a3.js";import{wg as J0}from"./chunk-k0pa8874.js";import{Xg as y0}from"./chunk-d808m826.js";import{jh as aJ}from"./chunk-y9d9nqnn.js";import{Bh as oJ,th as j$,vh as yJ,wh as D0,xh as G1,zh as nJ}from"./chunk-8wea3qty.js";import{Ch as NZ}from"./chunk-k6shq7rk.js";function Q$($){return $.role==="system"&&Array.isArray($.content)}function X$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class X1{systemMessages;_contextualSystemMessages;_history;_pending=[];context;constructor($,J){this.context=$;let Z=$.messages.find(Q$);if(this._contextualSystemMessages=$.messages.filter(X$),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!Q$(W)&&!X$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!X$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(Q$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((J)=>J.id===$.id))return;this._history.push($)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((J)=>!Q$(J)&&!X$(J))}restoreDurableHistory($){this._contextualSystemMessages=$.filter(X$),this._history=$.filter((J)=>!Q$(J)&&!X$(J)),this._pending=[],this.syncContextualSystemMessages()}removeMessages($){this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages()}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function ZJ($){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 WJ($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function YJ($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import e0 from"node:path";var J8=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"]),Z8=/^(LD_.+|DYLD_.+|PATH)$/,KJ=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function k$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],K=W.match(KJ);if(!K)break;let H=K[1];if(!J8.has(H))break;J=Y}return J}function g4($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],K=W.match(KJ);if(!K)break;let H=K[1];if(Z8.test(H))break;J=Y}return J}var W8=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function a1($){let J=$,Z=!0;while(Z){Z=!1;for(let W of W8){let Y=J.match(W);if(Y){J=J.slice(Y[0].length),Z=!0;break}}if(J.startsWith("-- "))J=J.slice(3),Z=!0}return J}function M$($){let J=[],Z="",W=!1,Y=!1,K=!1;for(let H=0;H<$.length;H++){let X=$[H];if(K){Z+=X,K=!1;continue}if(X==="\\"&&!W){Z+=X,K=!0;continue}if(X==="'"&&!Y){W=!W,Z+=X;continue}if(X==='"'&&!W){Y=!Y,Z+=X;continue}if(W||Y){Z+=X;continue}if(X==="|"){if(H+1<$.length&&$[H+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",H++;continue}return null}if(X===">"||X==="<")return null;if(X==="&"&&H+1<$.length&&$[H+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",H++;continue}if(X==="&")return null;if(X===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=X}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function HJ($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let K=$[Y];if(W){W=!1;continue}if(K==="\\"&&!J){W=!0;continue}if(K==="'"&&!Z){J=!J;continue}if(K==='"'&&!J){Z=!Z;continue}if(J)continue;if(K==="$"){let H=$[Y+1];if(H&&/[A-Za-z_@*#?!$0-9({]/.test(H))return!0}if(K==="`")return!0;if(Z)continue;if(K==="|")return!0;if(K===">"||K==="<")return!0;if(K==="{"){let H=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(H)||/^\{[^}]*\.\.[^}]*\}/.test(H))return!0}}return!1}function t0($){let J=[],Z="",W=!1,Y=!1,K=!1;for(let H=0;H<$.length;H++){let X=$[H];if(K){Z+=X,K=!1;continue}if(X==="\\"&&!W){if(K=!0,Y){let Q=$[H+1];if(Q&&'$`"\\'.includes(Q))continue;Z+=X,K=!1}continue}if(X==="'"&&!Y){W=!W;continue}if(X==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(X)){if(Z)J.push(Z),Z="";continue}Z+=X}if(Z)J.push(Z);return J}var Y8=new Set(["npm","pnpm","yarn","bun"]),XJ=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),K8=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),H8=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function X8($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function QJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function Q8($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=t0(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let K=Y[1];if(!K||K==="-")return;let H=e0.isAbsolute(K)?e0.resolve(K):e0.resolve(Z,K);if(!$$.isWithinWorkspace(H,Z))return;return W[2]?.trim()||void 0}function z8($){let J=[],Z=!1,W=!1,Y=!1;for(let K=0;K<$.length;K++){let H=$[K];if(Y){Y=!1;continue}if(H==="\\"&&!Z){Y=!0;continue}if(H==="'"&&!W){Z=!Z;continue}if(H==='"'&&!Z){W=!W;continue}if(H!=="|"||Z||W)continue;if($[K+1]==="|")return;J.push(K)}return J}function V8($){let J=t0($),[Z,W,Y]=J;if(Z!=="head"&&Z!=="tail")return!1;if(J.length===1)return!0;let K=(H)=>H!==void 0&&/^[1-9]\d{0,4}$/.test(H);if(J.length===2)return W?.startsWith("--lines=")&&K(W.slice(8))||W?.startsWith("-")&&K(W.slice(1));return J.length===3&&(W==="-n"||W==="--lines")&&K(Y)}function B8($){let J=QJ($.replace(H8,"").trim()),Z=z8(J);if(!Z)return;if(Z.length===0)return zJ(J);if(Z.length!==1)return;let W=Z[0];if(W===void 0)return;let Y=QJ(J.slice(0,W).trim()),K=J.slice(W+1).trim();if(!Y||!V8(K))return;return zJ(Y)}function zJ($){let Z=M$($)?.at(-1);if(!Z)return $;let W=t0(Z),[Y,K]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&K==="vitest")||W.some((X)=>X==="--configLoader"||X.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function z$($,J){let Z=B8($);if(!Z)return!1;let W=k$(Z),Y=M$(W);if(!Y||HJ(W)||/[\r\n]/.test(W))return!1;let K=Y.length===1?Y[0]:Q8(W,Y,J);if(!K)return!1;let H=t0(K);if(H.length===0||H.some((D)=>[...K8].some((j)=>D===j||D.startsWith(`${j}=`))))return!1;let[X,Q,z]=H;if(Y8.has(X??""))return X8(Q==="run"?z:Q)||Q==="--test";if((X==="npx"||X==="bunx")&&XJ.has(Q??""))return!0;if(XJ.has(X??""))return!0;if(X==="node"&&Q==="--test")return!0;if(X==="go"&&["build","test","vet"].includes(Q??""))return!0;return X==="cargo"&&["build","check","clippy","test"].includes(Q??"")}function i4($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!e0.isAbsolute($);let Z=e0.isAbsolute($)?e0.resolve($):e0.resolve(J,$);return $$.isWithinWorkspace(Z,J)}var s1=y0("Agent"),D8=3;function t1($,J,Z){if($!=="length")return{action:"none"};if(J>=D8)return{action:"truncated"};if(ZJ(Z)==="stop")return s1.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var j8=[/:\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],w8=/```[\s\S]{50,}```/,VJ="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",U8=2;function e1($,J,Z=!0){if(!$||J>=U8)return{action:"none"};if(!Z&&w8.test($))return{action:"retry",prompt:VJ};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(j8.some((H)=>H.test(W)))return{action:"retry",prompt:VJ};return{action:"none"}}var L8=[/\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}(?:测试|单测|集成测试|检查|构建)/],BJ={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},q8={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},G8="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.",O8="Required verification did not run successfully before the retry limit.",F8=3;function jJ($,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&&z$(Z.metadata.command,W)){$.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes(J))return;let Y=Z.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let K of Y)if(typeof K==="string"&&z$(K,W))$.add(K)}function $6($,J,Z){if(!$||!L8.some((Q)=>Q.test($)))return{action:"none"};let W=Object.keys(BJ).filter((Q)=>BJ[Q].test($)),Y=[...J],K=W.filter((Q)=>!Y.some((z)=>q8[Q].test(z)));if(W.length>0?K.length===0:Y.some((Q)=>z$(Q)))return{action:"none"};if(Z>=F8)return{action:"fail",message:O8};let X=W.length>1&&K.length>0?` Missing successful verification categories: ${K.join(", ")}.`:"";return{action:"retry",prompt:`${G8}${X}`}}var N8=[/\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|子代理|子智能体)/],wJ=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function UJ($){return typeof $==="string"&&wJ.some((J)=>J.test($))}var y8=[/\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|子代理)/],P8=[/\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 _8($){if(typeof $!=="string")return;if(P8.some((J)=>J.test($)))return"multiple-allowed";return y8.some((J)=>J.test($))?"required":void 0}function z1($){for(let J of $){let Z=_8(J);if(Z!==void 0)return Z==="required"}return!1}var A8="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.",b8="Required delegation did not complete before the retry limit.",f8=3;function LJ($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((H)=>H.trim()).filter(Boolean),Y=z1(W),K=!1;if(!Y)for(let H of W){if(wJ.some((X)=>X.test(H)))break;if(N8.some((X)=>X.test(H))){K=!0;break}}if(W.length===0||!Y&&!K||J.has("Task"))return{action:"none"};if(Z>=f8)return{action:"fail",message:b8};return{action:"retry",prompt:A8}}var T8=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],E8=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],S8=[/\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 qJ($){return S8.reduce((J,Z)=>J.replace(Z," "),$)}function V1($){if(typeof $!=="string")return!1;let J=qJ($);return T8.some((Z)=>Z.test(J))}var x8="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.",k8="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.",M8="Required worktree lifecycle did not complete before the retry limit.",h8=3;function GJ($,J,Z){if(!$)return{action:"none"};let W=qJ($);if(!V1(W))return{action:"none"};let Y=E8.some((H)=>H.test(W));if(J.has("TaskWorktree"))return{action:"none"};let K=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!K)return{action:"none"};if(Z>=h8)return{action:"fail",message:M8};return{action:"retry",tool:K,prompt:K==="EnterWorktree"?x8:k8}}var DJ=30000;async function J6($){try{let Z=V$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??J0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((K)=>{W=setTimeout(()=>K("timeout"),DJ)});try{let K=await Promise.race([Z,Y]);if(K==="timeout")return s1.warn(`[Loop] Stop hook 超时 (${DJ}ms),按 shouldStop: true 处理`),{action:"stop"};let H=K;if(!H.shouldStop)return{action:"continue",reason:H.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return s1.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function R8($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var C8=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function I8($){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 v8($){let J=$;for(let Q of C8)J=J.replace(Q," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:Z;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let K=Y.slice(0,60),H=K.lastIndexOf(" ");return`${(H>36?K.slice(0,H):K).trimEnd()}…`}function OJ($){return v8(I8($))}import{EventEmitter as p8}from"events";import FJ from"node:path";function Z6($){if(yJ($.sessionId),!FJ.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:FJ.resolve($.projectPath)}}function NJ($){let J=Z6($);return JSON.stringify([J.projectPath,J.sessionId])}function W5($,J){return NJ($)===NJ(J)}class B$ extends p8{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!B$.instance)B$.instance=new B$;return B$.instance}publish($,J,Z,W){let Y=Z6($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:J,...W!==void 0?{seq:W}:{},properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var h$=B$.getInstance();var u0=y0("Agent"),B1=new Set;async function g8($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(B1.has(Z))return;if(B1.size>=5000)B1.clear();B1.add(Z);try{let W=$.workspaceRoot,Y=await R$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let K=OJ(J);if(!K)return;await R$.updateSessionMetadata(Z,Y.projectPath,{title:K}),h$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:K})}catch(W){u0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var W6=`<turn_aborted>
|
|
1
|
+
import{Lb as m2}from"./chunk-th4jjfgm.js";import{Cc as f0,Ec as R6,Fc as O1,Gc as C6,Mb as $$,Nc as R$,Tb as sJ,Ub as tJ,Vb as G6,Wb as O6,ac as eJ,bc as d2,cc as c2,dc as j6,ec as N1,fc as i2,gc as l2,hc as U1,kc as kJ,sc as i$}from"./chunk-97aywyzn.js";import{Sc as z0,Vc as dJ,Wc as _0}from"./chunk-mtphps19.js";import{Xd as j2}from"./chunk-0j22w4wh.js";import{Yd as p2,Zd as c0,_d as M2,be as g2,ce as h6,ee as xJ}from"./chunk-zdnk7qtn.js";import{Oe as l0,Pe as R0,Se as u2}from"./chunk-hat9v5c5.js";import{$e as V$}from"./chunk-4ke8k0xw.js";import{jg as Q2}from"./chunk-h0ft81a3.js";import{wg as J0}from"./chunk-k0pa8874.js";import{Xg as y0}from"./chunk-t2wgf9tq.js";import{jh as aJ}from"./chunk-azw0jckv.js";import{Ah as nJ,Ch as oJ,uh as j$,wh as yJ,xh as D0,yh as G1}from"./chunk-9q852bsc.js";import{Dh as NZ}from"./chunk-wfy851et.js";function Q$($){return $.role==="system"&&Array.isArray($.content)}function X$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class X1{systemMessages;_contextualSystemMessages;_history;_pending=[];context;constructor($,J){this.context=$;let Z=$.messages.find(Q$);if(this._contextualSystemMessages=$.messages.filter(X$),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!Q$(W)&&!X$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!X$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(Q$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((J)=>J.id===$.id))return;this._history.push($)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((J)=>!Q$(J)&&!X$(J))}restoreDurableHistory($){this._contextualSystemMessages=$.filter(X$),this._history=$.filter((J)=>!Q$(J)&&!X$(J)),this._pending=[],this.syncContextualSystemMessages()}removeMessages($){this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages()}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function ZJ($){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 WJ($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function YJ($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import e0 from"node:path";var J8=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"]),Z8=/^(LD_.+|DYLD_.+|PATH)$/,KJ=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function k$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],K=W.match(KJ);if(!K)break;let H=K[1];if(!J8.has(H))break;J=Y}return J}function g4($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],K=W.match(KJ);if(!K)break;let H=K[1];if(Z8.test(H))break;J=Y}return J}var W8=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function a1($){let J=$,Z=!0;while(Z){Z=!1;for(let W of W8){let Y=J.match(W);if(Y){J=J.slice(Y[0].length),Z=!0;break}}if(J.startsWith("-- "))J=J.slice(3),Z=!0}return J}function M$($){let J=[],Z="",W=!1,Y=!1,K=!1;for(let H=0;H<$.length;H++){let X=$[H];if(K){Z+=X,K=!1;continue}if(X==="\\"&&!W){Z+=X,K=!0;continue}if(X==="'"&&!Y){W=!W,Z+=X;continue}if(X==='"'&&!W){Y=!Y,Z+=X;continue}if(W||Y){Z+=X;continue}if(X==="|"){if(H+1<$.length&&$[H+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",H++;continue}return null}if(X===">"||X==="<")return null;if(X==="&"&&H+1<$.length&&$[H+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",H++;continue}if(X==="&")return null;if(X===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=X}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function HJ($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let K=$[Y];if(W){W=!1;continue}if(K==="\\"&&!J){W=!0;continue}if(K==="'"&&!Z){J=!J;continue}if(K==='"'&&!J){Z=!Z;continue}if(J)continue;if(K==="$"){let H=$[Y+1];if(H&&/[A-Za-z_@*#?!$0-9({]/.test(H))return!0}if(K==="`")return!0;if(Z)continue;if(K==="|")return!0;if(K===">"||K==="<")return!0;if(K==="{"){let H=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(H)||/^\{[^}]*\.\.[^}]*\}/.test(H))return!0}}return!1}function t0($){let J=[],Z="",W=!1,Y=!1,K=!1;for(let H=0;H<$.length;H++){let X=$[H];if(K){Z+=X,K=!1;continue}if(X==="\\"&&!W){if(K=!0,Y){let Q=$[H+1];if(Q&&'$`"\\'.includes(Q))continue;Z+=X,K=!1}continue}if(X==="'"&&!Y){W=!W;continue}if(X==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(X)){if(Z)J.push(Z),Z="";continue}Z+=X}if(Z)J.push(Z);return J}var Y8=new Set(["npm","pnpm","yarn","bun"]),XJ=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),K8=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),H8=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function X8($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function QJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function Q8($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=t0(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let K=Y[1];if(!K||K==="-")return;let H=e0.isAbsolute(K)?e0.resolve(K):e0.resolve(Z,K);if(!$$.isWithinWorkspace(H,Z))return;return W[2]?.trim()||void 0}function z8($){let J=[],Z=!1,W=!1,Y=!1;for(let K=0;K<$.length;K++){let H=$[K];if(Y){Y=!1;continue}if(H==="\\"&&!Z){Y=!0;continue}if(H==="'"&&!W){Z=!Z;continue}if(H==='"'&&!Z){W=!W;continue}if(H!=="|"||Z||W)continue;if($[K+1]==="|")return;J.push(K)}return J}function V8($){let J=t0($),[Z,W,Y]=J;if(Z!=="head"&&Z!=="tail")return!1;if(J.length===1)return!0;let K=(H)=>H!==void 0&&/^[1-9]\d{0,4}$/.test(H);if(J.length===2)return W?.startsWith("--lines=")&&K(W.slice(8))||W?.startsWith("-")&&K(W.slice(1));return J.length===3&&(W==="-n"||W==="--lines")&&K(Y)}function B8($){let J=QJ($.replace(H8,"").trim()),Z=z8(J);if(!Z)return;if(Z.length===0)return zJ(J);if(Z.length!==1)return;let W=Z[0];if(W===void 0)return;let Y=QJ(J.slice(0,W).trim()),K=J.slice(W+1).trim();if(!Y||!V8(K))return;return zJ(Y)}function zJ($){let Z=M$($)?.at(-1);if(!Z)return $;let W=t0(Z),[Y,K]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&K==="vitest")||W.some((X)=>X==="--configLoader"||X.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function z$($,J){let Z=B8($);if(!Z)return!1;let W=k$(Z),Y=M$(W);if(!Y||HJ(W)||/[\r\n]/.test(W))return!1;let K=Y.length===1?Y[0]:Q8(W,Y,J);if(!K)return!1;let H=t0(K);if(H.length===0||H.some((D)=>[...K8].some((j)=>D===j||D.startsWith(`${j}=`))))return!1;let[X,Q,z]=H;if(Y8.has(X??""))return X8(Q==="run"?z:Q)||Q==="--test";if((X==="npx"||X==="bunx")&&XJ.has(Q??""))return!0;if(XJ.has(X??""))return!0;if(X==="node"&&Q==="--test")return!0;if(X==="go"&&["build","test","vet"].includes(Q??""))return!0;return X==="cargo"&&["build","check","clippy","test"].includes(Q??"")}function i4($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!e0.isAbsolute($);let Z=e0.isAbsolute($)?e0.resolve($):e0.resolve(J,$);return $$.isWithinWorkspace(Z,J)}var s1=y0("Agent"),D8=3;function t1($,J,Z){if($!=="length")return{action:"none"};if(J>=D8)return{action:"truncated"};if(ZJ(Z)==="stop")return s1.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var j8=[/:\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],w8=/```[\s\S]{50,}```/,VJ="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",U8=2;function e1($,J,Z=!0){if(!$||J>=U8)return{action:"none"};if(!Z&&w8.test($))return{action:"retry",prompt:VJ};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(j8.some((H)=>H.test(W)))return{action:"retry",prompt:VJ};return{action:"none"}}var L8=[/\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}(?:测试|单测|集成测试|检查|构建)/],BJ={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},q8={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},G8="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.",O8="Required verification did not run successfully before the retry limit.",F8=3;function jJ($,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&&z$(Z.metadata.command,W)){$.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes(J))return;let Y=Z.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let K of Y)if(typeof K==="string"&&z$(K,W))$.add(K)}function $6($,J,Z){if(!$||!L8.some((Q)=>Q.test($)))return{action:"none"};let W=Object.keys(BJ).filter((Q)=>BJ[Q].test($)),Y=[...J],K=W.filter((Q)=>!Y.some((z)=>q8[Q].test(z)));if(W.length>0?K.length===0:Y.some((Q)=>z$(Q)))return{action:"none"};if(Z>=F8)return{action:"fail",message:O8};let X=W.length>1&&K.length>0?` Missing successful verification categories: ${K.join(", ")}.`:"";return{action:"retry",prompt:`${G8}${X}`}}var N8=[/\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|子代理|子智能体)/],wJ=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function UJ($){return typeof $==="string"&&wJ.some((J)=>J.test($))}var y8=[/\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|子代理)/],P8=[/\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 _8($){if(typeof $!=="string")return;if(P8.some((J)=>J.test($)))return"multiple-allowed";return y8.some((J)=>J.test($))?"required":void 0}function z1($){for(let J of $){let Z=_8(J);if(Z!==void 0)return Z==="required"}return!1}var A8="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.",b8="Required delegation did not complete before the retry limit.",f8=3;function LJ($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((H)=>H.trim()).filter(Boolean),Y=z1(W),K=!1;if(!Y)for(let H of W){if(wJ.some((X)=>X.test(H)))break;if(N8.some((X)=>X.test(H))){K=!0;break}}if(W.length===0||!Y&&!K||J.has("Task"))return{action:"none"};if(Z>=f8)return{action:"fail",message:b8};return{action:"retry",prompt:A8}}var T8=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],E8=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],S8=[/\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 qJ($){return S8.reduce((J,Z)=>J.replace(Z," "),$)}function V1($){if(typeof $!=="string")return!1;let J=qJ($);return T8.some((Z)=>Z.test(J))}var x8="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.",k8="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.",M8="Required worktree lifecycle did not complete before the retry limit.",h8=3;function GJ($,J,Z){if(!$)return{action:"none"};let W=qJ($);if(!V1(W))return{action:"none"};let Y=E8.some((H)=>H.test(W));if(J.has("TaskWorktree"))return{action:"none"};let K=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!K)return{action:"none"};if(Z>=h8)return{action:"fail",message:M8};return{action:"retry",tool:K,prompt:K==="EnterWorktree"?x8:k8}}var DJ=30000;async function J6($){try{let Z=V$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??J0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((K)=>{W=setTimeout(()=>K("timeout"),DJ)});try{let K=await Promise.race([Z,Y]);if(K==="timeout")return s1.warn(`[Loop] Stop hook 超时 (${DJ}ms),按 shouldStop: true 处理`),{action:"stop"};let H=K;if(!H.shouldStop)return{action:"continue",reason:H.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return s1.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function R8($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var C8=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function I8($){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 v8($){let J=$;for(let Q of C8)J=J.replace(Q," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:Z;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let K=Y.slice(0,60),H=K.lastIndexOf(" ");return`${(H>36?K.slice(0,H):K).trimEnd()}…`}function OJ($){return v8(I8($))}import{EventEmitter as p8}from"events";import FJ from"node:path";function Z6($){if(yJ($.sessionId),!FJ.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:FJ.resolve($.projectPath)}}function NJ($){let J=Z6($);return JSON.stringify([J.projectPath,J.sessionId])}function W5($,J){return NJ($)===NJ(J)}class B$ extends p8{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!B$.instance)B$.instance=new B$;return B$.instance}publish($,J,Z,W){let Y=Z6($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:J,...W!==void 0?{seq:W}:{},properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var h$=B$.getInstance();var u0=y0("Agent"),B1=new Set;async function g8($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(B1.has(Z))return;if(B1.size>=5000)B1.clear();B1.add(Z);try{let W=$.workspaceRoot,Y=await R$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let K=OJ(J);if(!K)return;await R$.updateSessionMetadata(Z,Y.projectPath,{title:K}),h$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:K})}catch(W){u0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var W6=`<turn_aborted>
|
|
2
2
|
The previous turn was interrupted. Commands or tool calls may have partially completed; inspect the workspace and running processes before retrying.
|
|
3
3
|
</turn_aborted>`,J$="Tool execution was blocked because its durable call record could not be committed. No tool side effect was started.",PJ="Tool execution completed, but its durable result record could not be committed. Further model and tool execution was stopped. The operation may have completed; inspect external state before retrying.";class D$ extends Error{phase;constructor($,J){super($==="user_message"?"Conversation input could not be committed. No further model request was started.":"Model output could not be committed. The run was stopped before any further model request or successful completion.",J);this.phase=$;this.name="DurableConversationPersistenceError"}}function Z$($){return $.executionEngine?.getContextManager()}async function h0($,J,Z,W=null,Y,K={}){let H=K.required??$.executionEngine!==void 0;try{let X=Z$($),Q=typeof Z==="string"?Z.trim()!=="":Z.some((z)=>z.type==="text"?z.text.trim()!=="":!0);if(X&&J.sessionId&&Q){let z=await X.saveMessage(J.sessionId,"user",Z,W,Y,J.subagentInfo);if(H&&!z)throw Error("Durable user-message commit returned no identity");if(Y?.clientVisible!==!1)g8(J,Z);return z}if(H&&J.sessionId&&Q)throw Error("Durable user-message storage is unavailable")}catch(X){if(u0.warn("[Loop] 保存用户消息失败:",X),H)throw new D$("user_message",{cause:X})}return null}async function P0($,J,Z,W,Y,K,H={}){let X=H.required??$.executionEngine!==void 0;try{let Q=Z$($),z=Boolean(Z.trim()||Y?.trim());if(Q&&J.sessionId&&z){let D=await Q.saveMessage(J.sessionId,"assistant",Z,W,K,J.subagentInfo,Y);if(X&&!D)throw Error("Durable assistant-message commit returned no identity");return D}if(X&&J.sessionId&&z)throw Error("Durable assistant-message storage is unavailable")}catch(Q){if(u0.warn("[Loop] 保存助手消息失败:",Q),X)throw new D$("assistant_message",{cause:Q})}return null}async function _J($,J,Z){try{let W=Z$($);if(W&&J.sessionId)return await W.saveMessage(J.sessionId,"system",W6,Z,void 0,J.subagentInfo)}catch(W){u0.warn("[Loop] 保存中断边界失败:",W)}return null}async function AJ($,J,Z,W,Y){try{let K=Z$($);if(!K||!J.sessionId||Z.length===0)return null;return await K.saveMessage(J.sessionId,"system",`<contextual-project-instructions-ref count="${Z.length}" />`,Y,{contextualProjectRules:!0,ruleReferences:JSON.parse(JSON.stringify(Z.map((H)=>({...H})))),triggerPaths:[...W]},J.subagentInfo)}catch(K){u0.warn("[Loop] 保存 contextual project rules provenance 失败:",K)}return null}async function Y6($,J,Z,W,Y,K={}){try{let H=Z$($);if(H&&J.sessionId){let X=await H.saveToolUse(J.sessionId,Z,W,Y,J.subagentInfo,K.providerToolCallId);if(K.required&&!X)throw Error("Durable tool-use commit returned no identity");return X}if(K.required&&J.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(H){if(u0.warn("[Loop] 保存工具调用失败:",H),K.required)throw H}return null}async function D1($,J,Z,W,Y,K,H,X,Q,z={}){try{let D=Z$($);if(D&&J.sessionId){let j=await D.saveToolResult(J.sessionId,Z,W,Y,K,H,J.subagentInfo,X,Q);if(z.required&&!j)throw Error("Durable tool-result commit returned no identity");return j}if(z.required&&J.sessionId)throw Error("Durable tool-result storage is unavailable")}catch(D){if(u0.warn("[Loop] 保存工具结果失败:",D),z.required)throw D}return null}async function C$($,J,Z,W,Y={}){try{let K=Z$($);if(K&&J.sessionId){let H=await K.saveCompaction(J.sessionId,Z,W,null);if(Y.required&&!H)throw Error("Compaction checkpoint commit returned no identity");return H||null}if(Y.required&&J.sessionId)throw Error("Compaction checkpoint storage is unavailable")}catch(K){if(u0.warn("[Loop] 保存压缩数据失败:",K),Y.required)throw K}return null}async function H0($){let{deps:J,context:Z,state:W,assistantContent:Y,assistantReasoningContent:K,lastMessageUuid:H,controlPrompt:X,controlMetadata:Q}=$;W.appendAssistant({role:"assistant",content:Y,reasoningContent:K});let z=H,D=await P0(J,Z,Y,z,K);if(D)z=D;if(X!==void 0){let j={role:"user",content:X};if(Q)j.metadata=Q;W.appendControl("user",j);let B=await h0(J,Z,j.content,z,Q);if(B)z=B}return z}import{createHash as r2}from"node:crypto";import{promises as a8}from"node:fs";import s8 from"node:path";import{nanoid as d0}from"nanoid";import*as r from"node:fs/promises";import*as W$ from"node:path";var bJ={enabled:!0,maxIndexLines:200};var u8="memory",fJ="MEMORY.md";class K6{memoryDir;config;initialized=!1;constructor($,J,Z){if(Z)this.memoryDir=Z;else{let W=j$($);this.memoryDir=W$.join(W,u8)}this.config={...bJ,...J}}async initialize(){if(this.initialized)return;await r.mkdir(this.memoryDir,{recursive:!0}),this.initialized=!0}async loadIndex(){if(!this.config.enabled)return null;await this.initialize();let $=W$.join(this.memoryDir,fJ);try{let J=await r.readFile($,"utf-8");if(!J.trim())return null;let Z=J.split(`
|
|
4
4
|
`),Y=Z.slice(0,this.config.maxIndexLines).join(`
|
|
@@ -80,7 +80,7 @@ Full output saved to: ${X}`}catch{return`${J}
|
|
|
80
80
|
|
|
81
81
|
${Y}`}}import xZ from"node:path";import{nanoid as kZ}from"nanoid";import*as G0 from"node:fs/promises";import*as cJ from"node:path";import{Mutex as LZ}from"async-mutex";import qZ from"write-file-atomic";var uJ=120,B6=128;function g$($){if(!Array.isArray($)||$.length>120||!$.every((J)=>typeof J==="string"&&J.length>0&&J.length<=128))return;return[...new Set($)]}function UZ($){if(!$||typeof $!=="object"||Array.isArray($))return[];if(!("recovery"in $)||!$.recovery)return[];let J=$.recovery;if(typeof J!=="object"||Array.isArray(J))return[];if(!("version"in J)||J.version!==1||!("inputMessageIds"in J)||!("hadSuccessfulToolResult"in J)||typeof J.hadSuccessfulToolResult!=="boolean"||!("emptyFinalCorrectionSpent"in J)||typeof J.emptyFinalCorrectionSpent!=="boolean"||!("acknowledgedInputMessageIds"in $))return[];let Z=g$(J.inputMessageIds),W=g$($.acknowledgedInputMessageIds);if(!Z||!W)return[];let Y=new Set(Z);return W.filter((K)=>Y.has(K))}function L1($,J){let Z=$[J];if(Z?.type!=="turn_aborted")return[];let W=UZ(Z.data);if(W.length===0)return[];let Y=-1;for(let H=J-1;H>=0;H--){let X=$[H];if(X.type==="turn_started"){if(X.data.turnId!==Z.data.turnId)return[];Y=H;break}if(X.type==="turn_completed"||X.type==="turn_aborted")return[]}if(Y<0)return[];let K=new Set;for(let H=Y+1;H<J;H++){let X=$[H];if(X.type!=="message_created"||X.data.role!=="user")continue;let Q=X.data.metadata,z=X.data.inboxMessageId!==void 0?X.data.inboxMessageId:Q!==null&&typeof Q==="object"&&!Array.isArray(Q)?Q.inboxMessageId:void 0;if(typeof z==="string"&&z.length>0&&z.length<=128)K.add(z)}return W.filter((H)=>K.has(H))}var q1=1,u$=8388608;function mJ($,J){let Z={version:q1,sessionId:$,messages:J.map(({recovered:W,...Y})=>Y)};return`${JSON.stringify(Z)}
|
|
82
82
|
`}function D6($,J){return $ instanceof Error&&"code"in $&&$.code===J}function GZ($){if(typeof $==="string")return!0;if(!Array.isArray($))return!1;return $.every((J)=>{if(!J||typeof J!=="object"||!("type"in J))return!1;if(J.type==="text")return"text"in J&&typeof J.text==="string";return J.type==="image_url"&&"image_url"in J&&typeof J.image_url==="object"&&J.image_url!==null&&"url"in J.image_url&&typeof J.image_url.url==="string"})}function OZ($,J,Z){let W;try{W=JSON.parse($)}catch(K){throw Error(`Invalid steering inbox JSON: ${J}`,{cause:K})}if(!W||typeof W!=="object"||!("version"in W)||W.version!==q1||!("sessionId"in W)||W.sessionId!==Z||!("messages"in W)||!Array.isArray(W.messages))throw Error(`Invalid steering inbox record: ${J}`);let Y=W.messages.map((K)=>{if(!K||typeof K!=="object"||!("id"in K)||typeof K.id!=="string"||!("content"in K)||!GZ(K.content)||!("queuedAt"in K)||typeof K.queuedAt!=="number"||"persisted"in K&&typeof K.persisted!=="boolean"||"origin"in K&&K.origin!=="user"&&K.origin!=="background_subagent"||"metadata"in K&&(K.metadata===null||typeof K.metadata!=="object"||Array.isArray(K.metadata))||"outputSchema"in K&&K.outputSchema!==void 0&&(!K.outputSchema||typeof K.outputSchema!=="object"||Array.isArray(K.outputSchema)))throw Error(`Invalid steering inbox message: ${J}`);let H="outputSchema"in K&&K.outputSchema!==void 0?O1(K.outputSchema).schema:void 0;return{id:K.id,content:K.content,queuedAt:K.queuedAt,..."persisted"in K&&K.persisted===!0?{persisted:!0}:{},..."origin"in K&&K.origin?{origin:K.origin}:{},..."metadata"in K&&K.metadata?{metadata:JSON.parse(JSON.stringify(K.metadata))}:{},...H?{outputSchema:H}:{}}});return{version:q1,sessionId:Z,messages:Y}}function FZ($){return new Set($.flatMap((J,Z)=>{if(J.type==="inbox_acknowledged")return J.data.messageIds;if(J.type==="turn_aborted")return L1($,Z);return[]}))}class F1{workspaceRoot;sessionId;filePath;mutex=new LZ;messages=[];constructor($,J,Z){this.workspaceRoot=$;this.sessionId=J;this.filePath=Z}static async open($,J){let Z=new F1($,J,G1($,J));return await Z.loadAndReconcile(),Z}async enqueue($,J){return this.mutex.runExclusive(async()=>{if(J&&!J(this.messages))return!1;let Z=[...this.messages,{...$,recovered:!1}],W=mJ(this.sessionId,Z);if(Buffer.byteLength(W)>u$)return!1;return await this.persist(Z,W),this.messages=Z,!0})}async acknowledge($){if($.length===0)return;let J=new Set($);await this.mutex.runExclusive(async()=>{let Z=this.messages.filter((W)=>!J.has(W.id));this.messages=Z,await this.persist(Z)})}list(){return this.messages.map(($)=>({...$,content:typeof $.content==="string"?$.content:$.content.map((J)=>J.type==="text"?{...J}:{...J,image_url:{...J.image_url}}),...$.outputSchema?{outputSchema:JSON.parse(JSON.stringify($.outputSchema))}:{},...$.metadata?{metadata:JSON.parse(JSON.stringify($.metadata))}:{}}))}count(){return this.messages.length}recoveredCount(){return this.messages.filter(($)=>$.recovered).length}async loadAndReconcile(){await this.mutex.runExclusive(async()=>{let $={version:q1,sessionId:this.sessionId,messages:[]};try{if((await G0.stat(this.filePath)).size>u$)throw Error(`Steering inbox exceeds ${u$} bytes: ${this.filePath}`);await G0.chmod(this.filePath,384),$=OZ(await G0.readFile(this.filePath,"utf8"),this.filePath,this.sessionId)}catch(Y){if(!D6(Y,"ENOENT"))throw Y}let J=D0(this.workspaceRoot,this.sessionId),Z=new Set;try{Z=FZ(dJ(await G0.readFile(J,"utf8"),J))}catch(Y){if(!D6(Y,"ENOENT"))throw Y}let W=$.messages.filter((Y)=>!Z.has(Y.id)).map((Y)=>({...Y,recovered:!0}));if(this.messages=W,W.length!==$.messages.length)await this.persist(W)})}async persist($,J){if(await G0.mkdir(cJ.dirname(this.filePath),{recursive:!0,mode:448}),$.length===0){await G0.unlink(this.filePath).catch((W)=>{if(!D6(W,"ENOENT"))throw W});return}let Z=J??mJ(this.sessionId,$);if(Buffer.byteLength(Z)>u$)throw Error(`Steering inbox exceeds ${u$} bytes: ${this.filePath}`);await qZ(this.filePath,Z,{encoding:"utf8",mode:384,fsync:!0})}}import*as b0 from"node:fs/promises";import*as $2 from"node:path";import{nanoid as e}from"nanoid";var iJ=256;class X0{sessionId;projectPath;static instances=new Map;store;subscribers=new Set;highestSeq=0;constructor($,J){this.sessionId=$;this.projectPath=J;this.store=new _0(D0(J,$))}static for($,J){let Z=`${J}\x00${$}`,W=X0.instances.get(Z);if(!W)W=new X0($,J),X0.instances.set(Z,W),X0.pruneIdleInstances(Z);else X0.instances.delete(Z),X0.instances.set(Z,W);return W}static release($,J){X0.instances.delete(`${J}\x00${$}`)}static pruneIdleInstances($){if(X0.instances.size<=iJ)return;for(let[J,Z]of X0.instances){if(J===$||Z.subscribers.size>0)continue;if(X0.instances.delete(J),X0.instances.size<=iJ)return}}get lastSeq(){return this.highestSeq}async commit($){let J=await this.store.append($);return this.record(J),J}async commitBatch($){if($.length===0)return[];let J=await this.store.appendBatch($);for(let Z of J)this.record(Z);return J}async commitValidated($){let J=await this.store.appendValidated($);return this.record(J),J}async commitValidatedBatch($){let J=await this.store.appendValidatedBatch($);for(let Z of J)this.record(Z);return J}emitDelta($){for(let J of this.subscribers)J.onDelta?.($);h$.publish({sessionId:this.sessionId,projectPath:this.projectPath},"delta",{delta:$})}subscribe($,J){if(this.subscribers.add($),J?.fromSeq!==void 0)this.replay($,J.fromSeq);return()=>{this.subscribers.delete($),X0.pruneIdleInstances()}}async replay($,J){let Z=await this.store.readFromSeq(J);for(let W of Z){if(j6(W))continue;await $.onCommitted(W)}}record($){if(typeof $.seq==="number"&&$.seq>this.highestSeq)this.highestSeq=$.seq;if(j6($))return;for(let J of this.subscribers){let Z=J.onCommitted($);if(Z)Promise.resolve(Z).catch(()=>{return})}h$.publish({sessionId:this.sessionId,projectPath:this.projectPath},`committed.${$.type}`,{event:$},$.seq)}}function L$($){let J=null,Z=null;for(let W of $){if(W.type==="turn_started"){J=W.data;continue}if(W.type==="turn_completed")Z={type:"turn_completed",data:W.data};else if(W.type==="turn_aborted")Z={type:"turn_aborted",data:W.data};else continue;if(J?.turnId===Z.data.turnId)J=null}return{active:J,lastTerminal:Z}}class A0 extends Error{}var yZ="Tool execution was interrupted by a process restart. The operation may have partially completed. Inspect the workspace, running processes, and external state before deciding whether to retry it.";function w6($,J){let Z=$.findLastIndex((W)=>W.type==="turn_started"&&W.data.turnId===J);if(Z<0)return!1;return $.slice(Z+1).some((W)=>{if(W.type!=="message_created"||W.data.role!=="user")return!1;let Y=W.data.metadata;return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)&&Y.clientVisible===!1&&Y.emptyFinalCorrection===!0})}function lJ($,J){let Z=$.findLastIndex((Y)=>Y.type==="turn_started"&&Y.data.turnId===J);if(Z<0)return[];let W=[];for(let Y of $.slice(Z+1)){if(Y.type==="turn_started"&&Y.data.turnId!==J||(Y.type==="turn_completed"||Y.type==="turn_aborted")&&Y.data.turnId===J)break;if(Y.type!=="message_created"||Y.data.role!=="user")continue;let K=Y.data.metadata,H=Y.data.inboxMessageId!==void 0?Y.data.inboxMessageId:K!==null&&typeof K==="object"&&!Array.isArray(K)?K.inboxMessageId:void 0;if(typeof H==="string"&&H.length>0&&H.length<=B6)W.push(H)}return[...new Set(W)]}function J2($){if(!$||typeof $!=="object"||Array.isArray($))return;if(!("version"in $)||$.version!==1)return;let J="inputMessageIds"in $?g$($.inputMessageIds):void 0;if(!J||!("hadSuccessfulToolResult"in $)||typeof $.hadSuccessfulToolResult!=="boolean"||!("emptyFinalCorrectionSpent"in $)||typeof $.emptyFinalCorrectionSpent!=="boolean")return;return{inputMessageIds:J,hadSuccessfulToolResult:$.hadSuccessfulToolResult,emptyFinalCorrectionSpent:$.emptyFinalCorrectionSpent}}function Z2($){return new Set($.flatMap((J,Z)=>{if(J.type==="inbox_acknowledged")return J.data.messageIds;if(J.type==="turn_aborted")return L1($,Z);return[]}))}function W2($,J,Z=[]){let W=J2(J.data.recovery);if(!W)return;let Y=Z2($);for(let H of Z)Y.add(H);let K=W.inputMessageIds.filter((H)=>!Y.has(H));if(K.length===0)return;return{turnId:J.data.turnId,outcome:"aborted",inputMessageIds:K,hadSuccessfulToolResult:W.hadSuccessfulToolResult,emptyFinalCorrectionSpent:W.emptyFinalCorrectionSpent}}function U6($){for(let J=$.length-1;J>=0;J--){let Z=$[J];if(Z.type!=="turn_aborted")continue;let W=W2($,Z);if(W)return W}return}var PZ=1e4,_Z=1e5,AZ=2592000000,rJ=128,bZ=1e6;function fZ($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(typeof J.goalId!=="string"||J.goalId.length===0||J.goalId.length>rJ||typeof J.verificationAttempt!=="number"||!Number.isSafeInteger(J.verificationAttempt)||J.verificationAttempt<1||J.verificationAttempt>bZ||typeof J.verifierSessionId!=="string"||J.verifierSessionId.length===0||J.verifierSessionId.length>rJ||typeof J.evidenceSha256!=="string"||!/^[a-f0-9]{64}$/.test(J.evidenceSha256)||typeof J.goalUpdatedAt!=="string"||!Number.isFinite(Date.parse(J.goalUpdatedAt)))return;return{goalId:J.goalId,verificationAttempt:J.verificationAttempt,verifierSessionId:J.verifierSessionId,evidenceSha256:J.evidenceSha256,goalUpdatedAt:J.goalUpdatedAt}}function Y2($,J){let Z=$.data.metadata;if(!Z||typeof Z!=="object"||Array.isArray(Z))return;let W=Z.turnFinalization;if(!W||typeof W!=="object"||Array.isArray(W))return;let Y=W,K=Y.turnId,H=Y.inputMessageIds,X=Y.turnsCount,Q=Y.toolCallsCount,z=Y.durationMs,D=Array.isArray(H)?H.filter((B)=>typeof B==="string"&&B.length>0&&B.length<=B6):[];if(typeof K!=="string"||K.length===0||K.length>128||J!==void 0&&K!==J||!Array.isArray(H)||H.length>uJ||D.length!==H.length||typeof X!=="number"||!Number.isSafeInteger(X)||X<0||X>PZ||typeof Q!=="number"||!Number.isSafeInteger(Q)||Q<0||Q>_Z||typeof z!=="number"||!Number.isSafeInteger(z)||z<0||z>AZ)return;let j;if("goalFinalization"in Y){if(j=fZ(Y.goalFinalization),!j)return}return{turnId:K,inputMessageIds:[...new Set(D)],turnsCount:X,toolCallsCount:Q,durationMs:z,...j?{goalFinalization:j}:{}}}function TZ($,J){let Z=$.findLastIndex((W)=>W.type==="turn_started"&&W.data.turnId===J);if(Z<0)return;for(let W=$.length-1;W>Z;W--){let Y=$[W];if(Y?.type!=="message_created")continue;let K=Y2(Y,J);if(K)return K}return}function EZ($){for(let J=$.length-1;J>=0;J--){let Z=$[J];if(Z?.type!=="message_created")continue;let W=Y2(Z);if(!W?.goalFinalization)continue;if(!$.slice(0,J).some((K)=>K.type==="turn_started"&&K.data.turnId===W.turnId))continue;return{turnId:W.turnId,finalization:W}}return}function m$($,J){let Z=J?$.findLastIndex((Q)=>Q.type==="turn_started"&&Q.data.turnId===J):-1;if(J&&Z<0)return{all:[],orphaned:[],hadSuccessfulResult:!1};let W=new Map,Y=new Set,K=new Set,H=new Set;for(let Q of $.slice(Z+1)){if(Q.type==="interaction_requested"){H.add(Q.data.toolCallId);continue}if(Q.type!=="part_created")continue;let z=Q.data.payload&&typeof Q.data.payload==="object"&&!Array.isArray(Q.data.payload)?Q.data.payload:{},D=typeof z.toolCallId==="string"?z.toolCallId:Q.data.partId;if(Q.data.partType==="tool_call")W.set(D,{toolCallId:D,messageId:Q.data.messageId,toolName:typeof z.toolName==="string"?z.toolName:"unknown",input:z.input??null});else if(Q.data.partType==="tool_result"){if(Y.add(D),Y.add(Q.data.partId),Y.add(Q.data.messageId),W.has(D)&&z.error===null)K.add(D)}}let X=[...W.values()];return{all:X,orphaned:X.filter((Q)=>!Y.has(Q.toolCallId)&&!H.has(Q.toolCallId)),hadSuccessfulResult:X.some((Q)=>K.has(Q.toolCallId))}}class i0{projectPath;maxSessions;version;constructor($=J0(),J=100,Z=aJ()){this.projectPath=$,this.maxSessions=J,this.version=Z}createEvent($,J,Z){return{id:e(),sessionId:J,projectPath:this.projectPath,timestamp:new Date().toISOString(),type:$,cwd:this.projectPath,gitBranch:nJ(this.projectPath),version:this.version,data:Z}}log($){return X0.for($,this.projectPath)}async ensureSessionCreated($,J){let Z=D0(this.projectPath,$);if((await new _0(Z).readAll()).length>0)return;let K=new Date().toISOString(),H={sessionId:$,rootId:J?.parentSessionId??$,parentId:J?.parentSessionId,relationType:J?"subagent":void 0,resumedFrom:J?.resumedFrom,rootAgentId:J?.rootAgentId,resumeDepth:J?.resumeDepth,title:void 0,status:"running",taskStatus:J?"running":"queued",taskFailure:null,agentType:J?.subagentType,model:void 0,permission:void 0,createdAt:K,updatedAt:K},X=this.createEvent("session_created",$,H);await this.log($).commit(X)}buildCompactionMetadata($){let J={trigger:$.trigger,preTokens:$.preTokens};if($.reason)J.reason=$.reason;if($.strategy)J.strategy=$.strategy;if($.postTokens!==void 0)J.postTokens=$.postTokens;if($.filesIncluded)J.filesIncluded=$.filesIncluded;if($.replacementMessages)J.checkpointVersion=sJ;return J}async initialize(){try{let $=j$(this.projectPath);await b0.mkdir($,{recursive:!0,mode:493}),console.log(`[PersistentStore] 初始化存储目录: ${$}`)}catch($){console.warn("[PersistentStore] 无法创建持久化存储目录:",$)}}async saveMessage($,J,Z,W=null,Y,K,H){try{await this.ensureSessionCreated($,K);let X=new Date().toISOString(),Q=e(),z={messageId:Q,role:J,parentMessageId:W??void 0,inboxMessageId:Y?.inboxMessageId,createdAt:X,model:Y?.model,usage:Y?.usage,metadata:Y?JSON.parse(JSON.stringify(Y)):void 0},D=this.createEvent("message_created",$,z),j=J==="assistant"&&H?.trim()?[this.createEvent("part_created",$,{partId:e(),messageId:Q,partType:"reasoning",payload:{text:H},createdAt:X})]:[],B=typeof Z==="string"?[this.createEvent("part_created",$,{partId:e(),messageId:Q,partType:"text",payload:{text:Z},createdAt:X})]:Z.map((w)=>this.createEvent("part_created",$,{partId:e(),messageId:Q,partType:w.type==="text"?"text":"image",payload:w.type==="text"?{text:w.text}:{mimeType:SZ(w.image_url.url)??"image/png",dataUrl:w.image_url.url},createdAt:X}));return await this.log($).commitBatch([D,...j,...B]),Q}catch(X){throw console.error(`[PersistentStore] 保存消息失败 (session: ${$}):`,X),X}}async acknowledgeInboxMessages($,J){if(J.length===0)return;await this.ensureSessionCreated($);let Z=new Date().toISOString();await this.log($).commit(this.createEvent("inbox_acknowledged",$,{messageIds:[...J],acknowledgedAt:Z}))}async persistBackgroundSubagentCompletion($,J){if(J.inboxMessageId!==`background-subagent-completion:${J.childSessionId}`)return{eligible:!1,acknowledged:!1,persisted:!1};await this.ensureSessionCreated($);let Z={eligible:!1,acknowledged:!1,persisted:!1};return await this.log($).commitValidatedBatch((W)=>{let Y=z0(W),K=Y.some((B)=>B.type==="inbox_acknowledged"&&B.data.messageIds.includes(J.inboxMessageId)),H=Y.find((B)=>B.type==="message_created"&&B.data.inboxMessageId===J.inboxMessageId),X=Y.findLast((B)=>{if(B.type!=="part_created"||B.data.partType!=="tool_call"||!B.data.payload||typeof B.data.payload!=="object"||Array.isArray(B.data.payload))return!1;let w=B.data.payload;if(w.toolName!=="Task"||!w.input||typeof w.input!=="object"||Array.isArray(w.input))return!1;let P=w.input,k=P.resume_from??P.resume;return P.run_in_background===!0&&P.subagent_session_id===J.childSessionId&&P.description===J.subagentRef.subagentDescription&&(P.subagent_type===void 0||P.subagent_type===J.subagentRef.subagentType)&&(P.resume_from===void 0||P.resume===void 0||P.resume_from===P.resume)&&(k===void 0?J.subagentRef.subagentResumedFrom===void 0:k===J.subagentRef.subagentResumedFrom)});if(!X)return Z={eligible:!1,acknowledged:K,persisted:!1,...H?{messageId:H.data.messageId}:{}},[];if(K)return Z={eligible:!0,acknowledged:!0,persisted:!1,...H?{messageId:H.data.messageId}:{}},[];let Q=Y.find((B)=>B.type==="part_created"&&B.data.partType==="subtask_ref"&&B.data.payload!==null&&typeof B.data.payload==="object"&&!Array.isArray(B.data.payload)&&B.data.payload.childSessionId===J.childSessionId&&B.data.payload.status===J.subagentRef.subagentStatus);if(H&&Q)return Z={eligible:!0,acknowledged:!1,persisted:!1,messageId:H.data.messageId},[];let z=new Date().toISOString(),D=H?.data.messageId??e(),j=[];if(!H){let B={messageId:D,role:"user",inboxMessageId:J.inboxMessageId,createdAt:z,metadata:JSON.parse(JSON.stringify(J.metadata))};j.push(this.createEvent("message_created",$,B)),j.push(this.createEvent("part_created",$,{partId:e(),messageId:D,partType:"text",payload:{text:J.content},createdAt:z}))}if(!Q){let B=Y.findLast((P)=>P.type==="part_created"&&P.data.partType==="subtask_ref"&&P.data.messageId===X.data.messageId&&P.data.payload!==null&&typeof P.data.payload==="object"&&!Array.isArray(P.data.payload)&&P.data.payload.childSessionId===J.childSessionId),w=B?.data.payload&&typeof B.data.payload==="object"&&!Array.isArray(B.data.payload)?B.data.payload:void 0;j.push(this.createEvent("part_created",$,{partId:e(),messageId:X.data.messageId,partType:"subtask_ref",payload:{childSessionId:J.subagentRef.subagentSessionId,agentType:J.subagentRef.subagentType,description:J.subagentRef.subagentDescription??"",status:J.subagentRef.subagentStatus,summary:J.subagentRef.subagentSummary??"",resumedFrom:J.subagentRef.subagentResumedFrom??null,rootAgentId:J.subagentRef.subagentRootId??J.subagentRef.subagentSessionId,resumeDepth:J.subagentRef.subagentResumeDepth??0,verificationVerdict:J.subagentRef.verificationVerdict??null,startedAt:typeof w?.startedAt==="string"?w.startedAt:z,finishedAt:z},createdAt:z}))}return Z={eligible:!0,acknowledged:!1,persisted:j.length>0,messageId:D},j}),Z}async saveTurnStart($,J){await this.ensureSessionCreated($);try{await this.log($).commitValidated((Z)=>{let W=z0(Z);if(W.some((K)=>K.type==="turn_started"&&K.data.turnId===J.turnId))throw new A0;let Y=L$(W).active;if(Y)throw Error(`Session already has an active turn: ${Y.turnId}`);return this.createEvent("turn_started",$,J)})}catch(Z){if(!(Z instanceof A0))throw Z}}async saveTurnCompletion($,J,Z=[]){await this.ensureSessionCreated($);try{await this.log($).commitValidatedBatch((W)=>{let Y=z0(W),K=new Set(Y.flatMap((z)=>z.type==="inbox_acknowledged"?z.data.messageIds:[])),H=[...new Set(Z)].filter((z)=>!K.has(z)),X=Y.findLast((z)=>(z.type==="turn_completed"||z.type==="turn_aborted")&&z.data.turnId===J.turnId);if(X){if(X.type==="turn_aborted"||H.length===0)throw new A0;return[this.createEvent("inbox_acknowledged",$,{messageIds:H,acknowledgedAt:J.completedAt})]}let Q=L$(Y).active;if(!Q||Q.turnId!==J.turnId)throw Error(`Turn is not active: ${J.turnId}`);return[...H.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:H,acknowledgedAt:J.completedAt})]:[],this.createEvent("turn_completed",$,J)]})}catch(W){if(!(W instanceof A0))throw W}}async saveTurnAbort($,J,Z={}){let W=Z.acknowledgeInputMessageIds??[],Y=g$(W);if(!Y)throw Error("Invalid turn abort acknowledgement input message IDs");let K=Y;await this.ensureSessionCreated($);let H,X=[];try{await this.log($).commitValidatedBatch((Q)=>{let z=z0(Q),D=Z2(z),j=z.findLast((S)=>(S.type==="turn_completed"||S.type==="turn_aborted")&&S.data.turnId===J.turnId);if(j){if(j.type==="turn_completed")throw H=void 0,X=[],new A0;let S=J2(j.data.recovery),O0=S?K.filter((T0)=>S.inputMessageIds.includes(T0)):[],r$=O0.filter((T0)=>!D.has(T0));if(X=O0,H=W2(z,j,O0),r$.length===0)throw new A0;return[this.createEvent("inbox_acknowledged",$,{messageIds:r$,acknowledgedAt:J.abortedAt})]}let B=L$(z).active;if(!B||B.turnId!==J.turnId)throw Error(`Turn is not active: ${J.turnId}`);let w=m$(z,B.turnId),P=lJ(z,B.turnId),k=U6(z),h=new Set(J.recovery?.inputMessageIds??[]),b=k?k.inputMessageIds.filter((S)=>h.has(S)):[],E=[...new Set([...P,...b])],T={version:1,inputMessageIds:E,hadSuccessfulToolResult:w.hadSuccessfulResult||J.recovery?.hadSuccessfulToolResult===!0,emptyFinalCorrectionSpent:w6(z,B.turnId)||J.recovery?.emptyFinalCorrectionSpent===!0};H={turnId:J.turnId,outcome:"aborted",inputMessageIds:T.inputMessageIds,hadSuccessfulToolResult:T.hadSuccessfulToolResult,emptyFinalCorrectionSpent:T.emptyFinalCorrectionSpent};let v=K.filter((S)=>E.includes(S)),p=v.filter((S)=>!D.has(S));X=v;let q=new Set(D);for(let S of v)q.add(S);let R=T.inputMessageIds.filter((S)=>!q.has(S));H=R.length>0?{turnId:J.turnId,outcome:"aborted",inputMessageIds:R,hadSuccessfulToolResult:T.hadSuccessfulToolResult,emptyFinalCorrectionSpent:T.emptyFinalCorrectionSpent}:void 0;let{acknowledgedInputMessageIds:g,...B0}=J;return[this.createEvent("turn_aborted",$,{...B0,...v.length>0?{acknowledgedInputMessageIds:v}:{},recovery:T}),...p.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:p,acknowledgedAt:J.abortedAt})]:[]]})}catch(Q){if(!(Q instanceof A0))throw Q}return{...H?{recovery:H}:{},acknowledgedInputMessageIds:X}}async loadInterruptedToolCalls($){let J=await this.loadEvents($);if(!J)return[];let Z=z0(J),W=L$(Z).active;return W?m$(Z,W.turnId).orphaned.map((Y)=>({...Y,input:structuredClone(Y.input)})):[]}async loadBackgroundTaskChildIds($){let J=await this.loadEvents($);if(!J)return new Set;let Z=z0(J).flatMap((W)=>{if(W.type!=="part_created"||W.data.partType!=="tool_call"||!W.data.payload||typeof W.data.payload!=="object"||Array.isArray(W.data.payload))return[];let Y=W.data.payload;if(Y.toolName!=="Task"||!Y.input||typeof Y.input!=="object"||Array.isArray(Y.input))return[];let K=Y.input;return K.run_in_background===!0&&typeof K.subagent_session_id==="string"?[K.subagent_session_id]:[]});return new Set(Z)}async recoverInterruptedTurn($,J={}){await this.ensureSessionCreated($);let Z;try{await this.log($).commitValidatedBatch((W)=>{let Y=z0(W),K=L$(Y).active,H=m$(Y);if(!K&&H.orphaned.length===0){if(Z=U6(Y),Z)return[];throw new A0}let X=K?TZ(Y,K.turnId):void 0;if(K&&X&&H.orphaned.length===0){let T=m$(Y,K.turnId);Z={turnId:K.turnId,outcome:"completed",inputMessageIds:X.inputMessageIds,hadSuccessfulToolResult:T.hadSuccessfulResult,emptyFinalCorrectionSpent:w6(Y,K.turnId),finalization:X};let v=new Set(Y.flatMap((R)=>R.type==="inbox_acknowledged"?R.data.messageIds:[])),p=X.inputMessageIds.filter((R)=>!v.has(R)),q=new Date().toISOString();return[...p.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:p,acknowledgedAt:q})]:[],this.createEvent("turn_completed",$,{turnId:K.turnId,completedAt:q,turnsCount:X.turnsCount,toolCallsCount:X.toolCallsCount,durationMs:X.durationMs})]}let Q=K?m$(Y,K.turnId):void 0,z=Q?.orphaned.some((T)=>{let v=J.adoptedToolResults?.get(T.toolCallId);return v?.toolCallId===T.toolCallId&&v.toolName===T.toolName&&v.error===void 0})??!1,D=new Set(K?.inputMessageIds??[]),j=K?U6(Y):void 0,B=j?j.inputMessageIds.filter((T)=>D.has(T)):[],w=B.length>0,P=K?lJ(Y,K.turnId):[];Z=K?{turnId:K.turnId,outcome:"aborted",inputMessageIds:[...new Set([...P,...B])],hadSuccessfulToolResult:(Q?.hadSuccessfulResult??!1)||z||w&&j?.hadSuccessfulToolResult===!0,emptyFinalCorrectionSpent:w6(Y,K.turnId)||w&&j?.emptyFinalCorrectionSpent===!0}:void 0;let k=K?Q?.all.length??0:0,h=new Date().toISOString(),b=K?Date.parse(K.startedAt):Number.NaN,E=H.orphaned.flatMap((T)=>{let v=J.adoptedToolResults?.get(T.toolCallId),p=v?.toolCallId===T.toolCallId&&v.toolName===T.toolName?v:void 0,q=this.createEvent("part_created",$,{partId:T.toolCallId,messageId:p?T.messageId:T.toolCallId,partType:"tool_result",payload:p?{toolCallId:T.toolCallId,toolName:T.toolName,output:p.output,error:p.error??null,...p.metadata===void 0?{}:{metadata:p.metadata}}:{toolCallId:T.toolCallId,toolName:T.toolName,output:null,error:yZ,metadata:{processRestartRecovery:!0,sideEffectsUncertain:!0}},createdAt:h});if(!p?.subagentRef)return[q];let R=p.subagentRef;return[q,this.createEvent("part_created",$,{partId:e(),messageId:T.messageId,partType:"subtask_ref",payload:{childSessionId:R.subagentSessionId,agentType:R.subagentType,description:R.subagentDescription??"",status:R.subagentStatus,summary:R.subagentSummary??"",resumedFrom:R.subagentResumedFrom??null,rootAgentId:R.subagentRootId??R.subagentSessionId,resumeDepth:R.subagentResumeDepth??0,verificationVerdict:R.verificationVerdict??null,startedAt:h,finishedAt:h},createdAt:h})]});return K?[...E,this.createEvent("turn_aborted",$,{turnId:K.turnId,cause:"process_restart",abortedAt:h,turnsCount:0,toolCallsCount:k,durationMs:Number.isFinite(b)?Math.max(0,Date.now()-b):0,recovery:Z?{version:1,inputMessageIds:Z.inputMessageIds,hadSuccessfulToolResult:Z.hadSuccessfulToolResult,emptyFinalCorrectionSpent:Z.emptyFinalCorrectionSpent}:void 0})]:E})}catch(W){if(!(W instanceof A0))throw W}return Z}async loadLatestGoalFinalization($){let J=await this.loadEvents($);return J?EZ(J):void 0}async saveInteractionRequest($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(Z.some((Y)=>Y.type==="interaction_requested"&&Y.data.requestId===J.requestId))throw Error(`Interaction request already exists: ${J.requestId}`);return this.createEvent("interaction_requested",$,J)})}async saveInteractionResponse($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((K)=>K.type==="interaction_requested"&&K.data.requestId===J.requestId))throw Error(`Interaction request not found: ${J.requestId}`);if(Z.some((K)=>K.type==="interaction_responded"&&K.data.requestId===J.requestId))throw Error(`Interaction already responded: ${J.requestId}`);return this.createEvent("interaction_responded",$,J)})}async saveInteractionRecovery($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((K)=>K.type==="interaction_responded"&&K.data.requestId===J.requestId))throw Error(`Interaction response not found: ${J.requestId}`);if(Z.some((K)=>K.type==="interaction_recovered"&&K.data.requestId===J.requestId))throw Error(`Interaction already recovered: ${J.requestId}`);return this.createEvent("interaction_recovered",$,J)})}async saveReviewStart($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(Z.some((K)=>K.type==="review_started"&&K.data.reviewId===J.reviewId))throw Error(`Review already exists: ${J.reviewId}`);if(Z.some((K)=>K.type==="review_started"&&!Z.some((H)=>H.type==="review_completed"&&H.data.reviewId===K.data.reviewId)))throw Error("Session already has an active review");return this.createEvent("review_started",$,J)})}async saveReviewCompletion($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((K)=>K.type==="review_started"&&K.data.reviewId===J.reviewId))throw Error(`Review not found: ${J.reviewId}`);if(Z.some((K)=>K.type==="review_completed"&&K.data.reviewId===J.reviewId))throw Error(`Review already completed: ${J.reviewId}`);return this.createEvent("review_completed",$,J)})}async saveToolUse($,J,Z,W=null,Y,K){try{if(K!==void 0&&(K.length===0||K.length>512))throw Error("Provider tool call identity must contain 1-512 characters");await this.ensureSessionCreated($,Y);let H=new Date().toISOString(),X=W??e(),Q=[];if(!W){let j={messageId:X,role:"assistant",parentMessageId:void 0,createdAt:H};Q.push(this.createEvent("message_created",$,j))}let z=K??e(),D={partId:z,messageId:X,partType:"tool_call",payload:{toolCallId:z,toolName:J,input:Z},createdAt:H};if(Q.push(this.createEvent("part_created",$,D)),J==="Task"&&Z&&typeof Z==="object"){let j=Z,B=typeof j.subagent_session_id==="string"?j.subagent_session_id:void 0,w=typeof j.subagent_type==="string"?j.subagent_type:void 0;if(B&&w){let P={partId:e(),messageId:X,partType:"subtask_ref",payload:{childSessionId:B,agentType:w,status:"running",summary:typeof j.description==="string"?j.description:"",startedAt:H},createdAt:H};Q.push(this.createEvent("part_created",$,P))}}return await this.log($).commitBatch(Q),z}catch(H){throw console.error(`[PersistentStore] 保存工具调用失败 (session: ${$}):`,H),H}}async saveToolResult($,J,Z,W,Y=null,K,H,X,Q){try{await this.ensureSessionCreated($,H);let z=new Date().toISOString(),D=Y??e();return await this.log($).commitValidatedBatch((j)=>{let B=X?.subagentStatus==="running"?z0(j).findLast((E)=>E.type==="part_created"&&E.data.partType==="subtask_ref"&&E.data.payload!==null&&typeof E.data.payload==="object"&&!Array.isArray(E.data.payload)&&E.data.payload.childSessionId===X.subagentSessionId&&(E.data.payload.status==="completed"||E.data.payload.status==="failed"||E.data.payload.status==="cancelled")):void 0,w=B?.data.payload,P=Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:{},k=w?{...P,subagentSessionId:w.childSessionId,subagentType:w.agentType,description:w.description,subagentStatus:w.status,subagentSummary:w.summary,subagentResumedFrom:w.resumedFrom,subagentRootId:w.rootAgentId,subagentResumeDepth:w.resumeDepth,verificationVerdict:w.verificationVerdict}:Q,h=[];if(!Y){let E={messageId:D,role:"assistant",parentMessageId:void 0,createdAt:z};h.push(this.createEvent("message_created",$,E))}let b={partId:J,messageId:D,partType:"tool_result",payload:{toolCallId:J,toolName:Z,output:W,error:K??null,...k===void 0?{}:{metadata:k}},createdAt:z};if(h.push(this.createEvent("part_created",$,b)),X&&!B){let E=X.subagentStatus==="running"?null:z,T={partId:e(),messageId:D,partType:"subtask_ref",payload:{childSessionId:X.subagentSessionId,agentType:X.subagentType,description:X.subagentDescription??"",status:X.subagentStatus,summary:X.subagentSummary??"",resumedFrom:X.subagentResumedFrom??null,rootAgentId:X.subagentRootId??X.subagentSessionId,resumeDepth:X.subagentResumeDepth??0,verificationVerdict:X.verificationVerdict??null,startedAt:z,finishedAt:E},createdAt:z};h.push(this.createEvent("part_created",$,T))}return h}),J}catch(z){throw console.error(`[PersistentStore] 保存工具结果失败 (session: ${$}):`,z),z}}async saveCompaction($,J,Z,W=null){try{await this.ensureSessionCreated($);let Y=new Date().toISOString(),K=e(),H={messageId:K,role:"system",parentMessageId:W??void 0,createdAt:Y},X=this.buildCompactionMetadata(Z),Q={partId:e(),messageId:K,partType:"summary",payload:{text:J,metadata:X,...Z.replacementMessages?{replacementMessages:tJ(Z.replacementMessages)}:{}},createdAt:Y},z=[this.createEvent("message_created",$,H),this.createEvent("part_created",$,Q)];return await this.log($).commitBatch(z),K}catch(Y){throw console.error(`[PersistentStore] 保存压缩失败 (session: ${$}):`,Y),Y}}async recordTokenBudgetHandoff($,J){await this.ensureSessionCreated($);let Z=N1([]),W=await this.log($).commitValidatedBatch((K)=>{if(Z=N1(z0(K)),Z.kind!=="none")return[];let H=new Date().toISOString();return[this.createEvent("token_budget_handoff_recorded",$,{...J,messageId:`${eJ}${e()}`,createdAt:H})]});if(Z.kind==="valid")return{outcome:"existing",event:Z.event};if(Z.kind==="suppressed")return{outcome:"suppressed",recordId:Z.recordId};if(W.length!==1)throw Error("Token budget handoff commit produced an impossible result");let Y=N1(W);if(Y.kind!=="valid")throw Error("Token budget handoff commit produced an invalid event");return{outcome:"created",event:Y.event}}async initSession($,J){await this.ensureSessionCreated($,J)}async loadEvents($){try{let J=D0(this.projectPath,$),W=await new _0(J).readAll();return W.length>0?z0(W):null}catch{return null}}async loadSession($){try{let J=D0(this.projectPath,$),Z=new _0(J),W=z0(await Z.readAll());if(W.length===0)return null;let Y=W.find((K)=>K.type==="session_created");return{sessionId:$,userId:void 0,preferences:{},configuration:{},startTime:new Date(Y?.timestamp??W[0].timestamp).getTime()}}catch{return null}}async loadConversation($){try{let J=D0(this.projectPath,$),Z=new _0(J),W=z0(await Z.readAll());if(W.length===0)return null;let Y=new Map;for(let Q of W){if(Q.type==="message_created")Y.set(Q.data.messageId,{id:Q.data.messageId,role:Q.data.role,content:"",timestamp:new Date(Q.timestamp).getTime()});if(Q.type==="part_created"&&Q.data.partType==="text"){let z=Y.get(Q.data.messageId);if(z){let D=Q.data.payload;z.content=D.text??""}}if(Q.type==="part_created"&&Q.data.partType==="image"){let z=Y.get(Q.data.messageId);if(z)z.content=z.content?`${z.content}
|
|
83
|
-
[Image]`:"[Image]"}}let K=Array.from(Y.values()),H=W[W.length-1],X=new Date(H.timestamp).getTime();return{messages:K,topics:[],lastActivity:X}}catch{return null}}async listSessions(){try{let $=j$(this.projectPath);return(await b0.readdir($)).filter((Z)=>Z.endsWith(".jsonl")).map((Z)=>Z.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){try{let J=D0(this.projectPath,$),Z=new _0(J);if(!(await Z.getStats()).exists)return null;let Y=await Z.readAll();if(Y.length===0)return null;let K=z0(Y),H=Y[Y.length-1],X=K.filter((Q)=>Q.type==="message_created"&&["user","assistant"].includes(Q.data.role)).length;return{sessionId:$,lastActivity:new Date(H.timestamp).getTime(),messageCount:X,topics:[]}}catch{return null}}async deleteSession($){try{let J=D0(this.projectPath,$);await new _0(J).delete(),await b0.unlink(G1(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W});try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-
|
|
83
|
+
[Image]`:"[Image]"}}let K=Array.from(Y.values()),H=W[W.length-1],X=new Date(H.timestamp).getTime();return{messages:K,topics:[],lastActivity:X}}catch{return null}}async listSessions(){try{let $=j$(this.projectPath);return(await b0.readdir($)).filter((Z)=>Z.endsWith(".jsonl")).map((Z)=>Z.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){try{let J=D0(this.projectPath,$),Z=new _0(J);if(!(await Z.getStats()).exists)return null;let Y=await Z.readAll();if(Y.length===0)return null;let K=z0(Y),H=Y[Y.length-1],X=K.filter((Q)=>Q.type==="message_created"&&["user","assistant"].includes(Q.data.role)).length;return{sessionId:$,lastActivity:new Date(H.timestamp).getTime(),messageCount:X,topics:[]}}catch{return null}}async deleteSession($){try{let J=D0(this.projectPath,$);await new _0(J).delete(),await b0.unlink(G1(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W});try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-j0p54tqt.js"),K=await W();if(K)Y(K,$,this.projectPath)}catch{}}catch(J){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,J)}}async cleanupOldSessions(){try{let $=await this.listSessions();if($.length<=this.maxSessions)return;let W=(await Promise.all($.map((Y)=>this.getSessionSummary(Y)))).filter((Y)=>Y!==null).sort((Y,K)=>K.lastActivity-Y.lastActivity).slice(this.maxSessions).map((Y)=>Y.sessionId);await Promise.all(W.map((Y)=>this.deleteSession(Y))),console.log(`[PersistentStore] 已清理 ${W.length} 个旧会话`)}catch($){console.error("[PersistentStore] 清理旧会话失败:",$)}}async getStorageStats(){try{let $=await this.listSessions(),J=0;for(let Z of $){let W=D0(this.projectPath,Z),K=await new _0(W).getStats();J+=K.size}return{totalSessions:$.length,totalSize:J,projectPath:this.projectPath}}catch{return{totalSessions:0,totalSize:0,projectPath:this.projectPath}}}async checkStorageHealth(){try{let $=j$(this.projectPath);await b0.mkdir($,{recursive:!0,mode:493});let J=$2.join($,".health-check");return await b0.writeFile(J,"test","utf-8"),await b0.unlink(J),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return oJ()}}function SZ($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}var K2=131072,L6=new Q2;function q6($,J){return`${xZ.resolve($)}\x00${J}`}function F6($,J){let Z=JSON.stringify($);if(Z===void 0)throw Error(`${J} is not JSON serializable`);if(Buffer.byteLength(Z,"utf8")>K2)throw Error(`${J} exceeds ${K2} bytes`);return JSON.parse(Z)}function H2($){if($.type==="askUserQuestion")return"question";if($.type==="mcpElicitation")return"elicitation";if($.type==="permission"||$.type==="mcpSampling")return"permission";return}function MZ($,J){return JSON.stringify($)===JSON.stringify(J)}function hZ($,J){if($.request.interactionType!=="elicitation")return F6(J,"Interaction response");return F6({approved:J.approved,...J.reason?{reason:J.reason}:{},...J.elicitation?{elicitation:{action:J.elicitation.action}}:{},...J.openExternalUrl?{openExternalUrl:!0}:{}},"Interaction response")}function X2($){let J=$.request.details;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid durable interaction details: ${$.request.requestId}`);return J}function RZ($){let J=$.response?.response;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid durable interaction response: ${$.request.requestId}`);return J}function CZ($){if(!$.answers||Object.keys($.answers).length===0)return"No structured answers were provided.";return Object.entries($.answers).map(([J,Z])=>{let W=Array.isArray(Z)?Z.join(", "):Z;return`${J}: ${W}`}).join(`
|
|
84
84
|
`)}function IZ($,J){let{request:Z}=$;if(Z.interactionType==="question"){let H=CZ(J);return{toolOutput:`User answers:
|
|
85
85
|
${H}`,inbox:`The process restarted while waiting for a structured answer. The recovered user response is:
|
|
86
86
|
${H}
|