blade-code 0.10.149 → 0.10.150
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-zdcgpzgz.js → chunk-01framym.js} +1 -1
- package/dist/{chunk-jcg4svv3.js → chunk-0ktd3vpk.js} +1 -1
- package/dist/chunk-25zrctsh.js +1 -0
- package/dist/{chunk-e5pvmhhs.js → chunk-2zzsyaf4.js} +1 -1
- package/dist/{chunk-65jy1c1k.js → chunk-3hgb942q.js} +1 -1
- package/dist/{chunk-gd9exvss.js → chunk-3rv3fnwr.js} +1 -1
- package/dist/{chunk-54b7jvep.js → chunk-3tvkp2yd.js} +1 -1
- package/dist/{chunk-aqd9968c.js → chunk-6hb0pjmk.js} +1 -1
- package/dist/{chunk-rzww3v93.js → chunk-8gg7zddg.js} +1 -1
- package/dist/{chunk-sjwcb0k3.js → chunk-8s93p05b.js} +1 -1
- package/dist/{chunk-9kny1pt0.js → chunk-9a0cy4z7.js} +1 -1
- package/dist/{chunk-wnpefg32.js → chunk-ahz3sskk.js} +1 -1
- package/dist/{chunk-mgsx0924.js → chunk-cxenrejk.js} +1 -1
- package/dist/chunk-cz77x04v.js +2 -0
- package/dist/{chunk-werp5mqq.js → chunk-d1navt68.js} +3 -3
- package/dist/{chunk-np4bf72v.js → chunk-d9q5dn00.js} +1 -1
- package/dist/{chunk-x9nwnxn4.js → chunk-ddxpgrcv.js} +1 -1
- package/dist/{chunk-3xgtg3as.js → chunk-dxtbv0v7.js} +1 -1
- package/dist/{chunk-025n9zx5.js → chunk-f71j03pq.js} +1 -1
- package/dist/{chunk-me2hnf3w.js → chunk-fkbnsn0a.js} +1 -1
- package/dist/{chunk-q2nn2q0k.js → chunk-ghqvews8.js} +1 -1
- package/dist/{chunk-31w757yv.js → chunk-h8s11k0r.js} +1 -1
- package/dist/{chunk-dmabzqdr.js → chunk-k5m9yj9n.js} +1 -1
- package/dist/{chunk-c24a0tp1.js → chunk-mhb3gg9s.js} +1 -1
- package/dist/{chunk-zy74vwq5.js → chunk-mmcjckwx.js} +1 -1
- package/dist/{chunk-bvc7de7r.js → chunk-mpexy01a.js} +1 -1
- package/dist/{chunk-chgadcwj.js → chunk-q5gcqckt.js} +1 -1
- package/dist/{chunk-fqvrg0em.js → chunk-q8erftv7.js} +1 -1
- package/dist/{chunk-qe07x202.js → chunk-qf6vf457.js} +1 -1
- package/dist/chunk-qypjj8rk.js +1 -0
- package/dist/{chunk-wqn310gf.js → chunk-rxc6mazk.js} +1 -1
- package/dist/{chunk-rn61n450.js → chunk-s1cs5ga0.js} +1 -1
- package/dist/{chunk-90brj5hd.js → chunk-sxvhv62s.js} +1 -1
- package/dist/{chunk-3259ae0w.js → chunk-vj50xf5c.js} +1 -1
- package/dist/{chunk-3fkq5g0t.js → chunk-wkjdgbnx.js} +1 -1
- package/dist/{chunk-mttsbvty.js → chunk-wv8dy886.js} +1 -1
- package/dist/{chunk-s0y338js.js → chunk-xtbcwn9q.js} +1 -1
- package/dist/{chunk-hyp6c0dv.js → chunk-zyxfdewk.js} +2 -2
- package/package.json +1 -1
- package/dist/chunk-72kmnfbn.js +0 -1
- package/dist/chunk-dj9s9ga7.js +0 -2
- package/dist/chunk-jqsepsdx.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Fa as z3}from"./chunk-qm0j4szw.js";import{Ia as T,Ja as $$,Oa as Vz,Pa as RY,Qa as e0}from"./chunk-
|
|
1
|
+
import{Fa as z3}from"./chunk-qm0j4szw.js";import{Ia as T,Ja as $$,Oa as Vz,Pa as RY,Qa as e0}from"./chunk-6hb0pjmk.js";import{Ra as Y5,Ua as pZ,Ya as tZ,Za as UX,_a as HX,ab as rz,cb as nz,db as A9,vb as az}from"./chunk-e12xrg41.js";import{Ab as D2,Bb as BY,Cb as x1,Db as a7,Eb as KY,Fb as $Y,Gb as DY,Hb as qY,Ib as WQ,Kb as JX,Mb as W0,Ob as _2,Rb as p4,Tb as _Z,Ub as l4,Vb as i4,Xb as AJ,Yb as R$,cc as aX,dc as G8,ec as sX,fc as ZX,hc as u1,ic as SX,nc as iY,qc as rY,wb as s5,xb as h7,yb as J1,zb as c7}from"./chunk-mhb3gg9s.js";import{$c as M1,Ac as T1,Bc as ZJ,Cc as _0,Dc as S2,Ec as N1,Fc as S6,Gc as f9,Hc as m4,Ic as c4,Jc as JY,Kc as YY,Lc as CX,Mc as X3,Md as W8,Nc as A1,Oc as Y3,Od as f0,Pc as i8,Pd as b$,Qc as $1,Rc as Z1,Sc as l2,Tc as p2,Uc as i2,Vc as g6,Wc as u6,Wd as Jz,Xc as d2,Xd as VX,Yc as H3,Zc as m2,_c as r8,_d as lY,ad as e1,bd as c2,cd as $2,dd as Z2,de as fX,ed as d6,ee as PX,fd as J2,gd as m6,ge as s,hd as c6,id as k$,jd as p6,kd as O3,ld as r2,md as l6,nd as i6,od as r6,pd as n6,qd as N3,rd as b3,td as j3,wc as v$,xc as MX,yc as r3,zc as k3}from"./chunk-f71j03pq.js";import{he as l,ie as BQ,je as GQ,ke as IJ,me as F2}from"./chunk-9xbwtjac.js";import{Fe as P9,Ge as J$,He as q2,Ie as $9,Je as TX,Ke as RX,Te as ez,ef as $W,oe as oz,re as tz}from"./chunk-3a217980.js";import{Af as NJ,Bf as LJ}from"./chunk-wzqcea6x.js";import{Nf as r4,Of as q0,Pf as d,Sf as j0,Tf as P4,Uf as L2,Vf as G1,Wf as CZ,Xf as R1,Yf as cY,bg as B2}from"./chunk-mpexy01a.js";import{cg as d1}from"./chunk-7xhw74hk.js";import{gg as jZ,hg as pY,mg as dY,ng as mX,og as S4}from"./chunk-z2k08r1h.js";import{pg as nZ}from"./chunk-w6qfbea8.js";import{sg as m0,tg as O1}from"./chunk-shb7g2vr.js";import{ug as tX}from"./chunk-7wcxjbyg.js";import{wg as LX,xg as OX,yg as NX,zg as bX}from"./chunk-01framym.js";import{$g as AX,Ag as I4,Bg as h4,Cg as g4,Eg as u4,Fg as d4,Gg as _1,Hg as FQ,Jg as I$,Kg as j$,Lg as G$,Mg as $5,Ng as W2,Og as H8,Pg as l1,Qg as i1,Rg as EX,Vg as J9,Xg as c0,Yg as f$,_g as k4,ah as kX}from"./chunk-h8s11k0r.js";import{ch as D1,eh as T$,fh as O4}from"./chunk-3kszepm6.js";import{gh as d3,hh as z2,ih as m3,jh as s2,kh as c3,lh as p3,mh as Z4,nh as $4,oh as l3,ph as i3,qh as e6}from"./chunk-wcps5gjm.js";import{rh as _z,th as jX,uh as z8,vh as bJ}from"./chunk-vbjgcn49.js";import{xh as L9,zh as x0}from"./chunk-wv8dy886.js";import{Ah as E6,Bh as R9,Ch as A6,Dh as r1}from"./chunk-3y2x6fb6.js";import{Ci as PY,Di as SY,Ei as kY,Fh as XJ,Fi as vY,Gi as AZ,Hi as yY,Ii as B1,Ji as xY,Kh as zJ,Ki as IY,Li as hY,Mh as D9,Ni as t3,Pi as yX,Qi as _X,Rh as Wz,Ri as B0,Vh as WJ,Xh as qX,Zh as UY,_h as HY,pi as h1,si as e7}from"./chunk-9a0cy4z7.js";import{Ui as L$}from"./chunk-kv458q06.js";import{Wi as eQ,Yi as $X}from"./chunk-5v0jcyea.js";import{$i as X4,bj as C}from"./chunk-2f8d0km4.js";import{Dj as e,Fj as a6,Gj as X2,Hj as K,Ij as R3,Jj as P,Kj as u}from"./chunk-2mk914vk.js";import{Oj as wX,Pj as FX}from"./chunk-j8hbddjp.js";import{Qj as Oz,Tj as wz}from"./chunk-4cdk4mds.js";import{Xj as Ez}from"./chunk-s1cs5ga0.js";import{bk as vX,ck as a0}from"./chunk-rvs364rz.js";import{Bk as E$,Gk as u3,fk as t,gk as N$,hk as D$,ik as t1,jk as o9,kk as u2,lk as X$,mk as t7,pk as I6,yk as P6}from"./chunk-4wx5sya5.js";import{Mk as Y$}from"./chunk-eg3ms291.js";import{randomUUID as M8}from"crypto";import{randomUUID as _W}from"node:crypto";var KW=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);
|
|
@@ -859,7 +859,7 @@ ${A0}
|
|
|
859
859
|
</approved-plan>
|
|
860
860
|
|
|
861
861
|
IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof O==="string")S$=O+j6;else S$=[...O,{type:"text",text:j6}]}v=yield*this.runLoop(S$,b,{...x,inputMessageId:void 0})}if(!this.sessionRuntime||!I)return v;let p=await this.sessionRuntime.recordGoalProgress({tokens:v.metadata?.tokensUsed??0,elapsedMs:v.metadata?.duration??0,...k?{goalId:k.goalId,objective:k.objective,turnId:I.id}:{},executionHostFailureCategory:v.metadata?.executionHostFailureCategory,prematureStopPattern:v.success?VY(v.finalMessage):void 0});if(p)yield{kind:"goal_updated",goal:p};if(!v.success||b.signal?.aborted){if(p=await this.sessionRuntime.pauseActiveGoal(b.signal?.aborted?"goal paused after user cancellation":v.error?.message??"goal paused after turn failure"),p)yield{kind:"goal_updated",goal:p}}if(v.success&&!b.signal?.aborted&&h<20)await this.sessionRuntime.waitForBackgroundSubagentFollowUp(I,b.signal);let n=v.success&&!b.signal?.aborted&&h<20,p0=XG(v);if(R=await this.sessionRuntime.finishTurn(I,{continuePending:n,...p0?{acknowledgeInput:!0}:{},outcome:v.success&&!b.signal?.aborted?{status:"completed",turnsCount:v.metadata?.turnsCount??0,toolCallsCount:v.metadata?.toolCallsCount??0,durationMs:v.metadata?.duration??0}:{status:"aborted",cause:b.signal?.aborted?"cancelled":"failed",turnsCount:v.metadata?.turnsCount??0,toolCallsCount:v.metadata?.toolCallsCount??0,durationMs:v.metadata?.duration??0}}),R){h++,N=!0,M=!1,j=null,O="",o=void 0,A="",S=void 0,E=Z0(),yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:$0(),queue:await this.sessionRuntime.getFollowUpQueueSnapshot()};continue}if(yield{kind:"follow_up_queue_changed",queue:await this.sessionRuntime.getFollowUpQueueSnapshot()},!v.success||b.signal?.aborted)return v;if(p=await this.sessionRuntime.getGoal(),!p||p.status!=="active"&&p.status!=="verifying")return v;let J0=await this.sessionRuntime.prepareGoalContinuation(p);if(!J0.ok){if(J0.goal)yield{kind:"goal_updated",goal:J0.goal};return{success:!1,error:{type:"goal_frontier_unavailable",message:J0.error.message},metadata:{turnsCount:v.metadata?.turnsCount??0,toolCallsCount:v.metadata?.toolCallsCount??0,duration:v.metadata?.duration??0}}}let h0=await this.sessionRuntime.beginGoalTurn(J0.goal);if(!h0)return v;j=h0.goal,q={...J0,goal:h0.goal},R=h0.handle,N=!1,M=!0,O=S5(j),o=void 0,E=void 0,yield{kind:"goal_frontier_updated",goal:j,frontier:J0.frontier,tasks:J0.tasks},yield{kind:"goal_continuation_started",goal:j,continuation:j.continuationCount,...j.prematureStop?{prematureStopPattern:j.prematureStop.pattern,prematureStopCount:j.prematureStop.consecutiveCount}:{}},yield{kind:"goal_updated",goal:j}}}finally{if(this.sessionRuntime&&R)await this.sessionRuntime.finishTurn(R)}}let _=typeof H==="string"?H:H.filter((O)=>O.type==="text").map((O)=>O.text).join(`
|
|
862
|
-
`),L={id:this.generateTaskId(),type:"simple",prompt:_};return{success:!0,finalMessage:(await this.executeTask(L)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-wqn310gf.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){a.debug("Processing Plan mode message...");let{prompt:Y}=await Y1({...Z.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:Z.workspaceRoot||C()},mode:"plan",includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:Z.executionRoot??Z.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...Z.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}}),Q;if(typeof $==="string")Q=t2($);else{let X=$.filter((z)=>z.type==="text");if(X.length>0){let z=X[0];Q=$.map((W)=>W===z?{type:"text",text:t2(z.text)}:W)}else Q=[{type:"text",text:t2("")},...$]}return yield*this.executeLoop(Q,Z,J,Y)}async*runLoop($,Z,J){a.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z);return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await Y1({...$.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:$.workspaceRoot||C()},replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:$.executionRoot??$.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...$.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let Q=this.buildLoopDependencies();return rY(Q,$,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)}},Q=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,X=J.error===void 0,z=J.output,W={success:X,llmContent:typeof z==="string"||z!==null&&typeof z==="object"?z:z===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(z),...J.error?{error:{type:"execution_error",message:J.error}}:{},...Q?{metadata:Q}:{}},V=[{kind:"tool_result",toolCall:Y,result:W}],U=iY(Y,W);if(U)V.push(U);return V})}takeStartupRecoveryEvents(){let $=this.sessionRuntime?.getTurnRecoveryAssessment(),Z=$?.state==="requires_attention"?$:this.sessionRuntime?.takeStartupTurnRecoveryAssessment(),J=Z&&Z.state!=="none"?[{kind:"turn_recovery",assessment:Z}]:[];return J.push(...this.takeStartupAdoptedToolResultEvents()),J}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=$,a.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((Q)=>!$.includes(Q.name));for(let Q of Y)Z.unregister(Q.name);a.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);a.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){a.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){a.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await Y1({...this.sessionRuntime?.isRemoteWorkspace()?{workspaceAccess:"none"}:{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(),...this.sessionRuntime?.isRemoteWorkspace()?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot},...this.sessionRuntime?{environmentOptions:{...u1,workingDirectory:this.sessionRuntime.executionRoot}}:{}});if(J.prompt)this.log("系统提示配置验证成功"),a.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await v4({sessionId:"default",configDir:t(),workspaceRoot:C(),resourceRoot:C(),agentResources:this.agentResources});a.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;a.debug(`Builtin tools registered: ${Z} tools`),a.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw a.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await z4({workspaceRoot:C(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){a.debug("No MCP servers configured");return}let Z=e0.createIsolated({artifactWriter:new o2(`legacy-${QG()}`)});this.legacyMcpRegistry=Z;for(let[X,z]of Object.entries($))try{a.debug(`Connecting to MCP server: ${X}`),await Z.registerServer(X,z),a.debug(`MCP server "${X}" connected`)}catch(W){a.warn(`Warning: MCP server "${X}" connection failed:`,W)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(Y6(Z));let Q=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:Q.revision,reason:"snapshot",replace:!0,instructions:Q.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)a.debug(`Registered ${Y.tools.length} MCP tools`),a.debug(`[MCP Tools] ${Y.tools.map((X)=>X.name).join(", ")}`)}catch($){a.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await c0(C());if(this.agentResources=k4($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)a.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else a.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;a.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{if(Y.name==="ReadPromptArtifact")return!0;return Z.some((Q)=>{if(Q===Y.name)return!0;let X=Q.match(/^(\w+)\(.*\)$/);if(X&&X[1]===Y.name)return!0;return!1})});return a.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)a.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(`
|
|
862
|
+
`),L={id:this.generateTaskId(),type:"simple",prompt:_};return{success:!0,finalMessage:(await this.executeTask(L)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-rxc6mazk.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){a.debug("Processing Plan mode message...");let{prompt:Y}=await Y1({...Z.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:Z.workspaceRoot||C()},mode:"plan",includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:Z.executionRoot??Z.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...Z.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}}),Q;if(typeof $==="string")Q=t2($);else{let X=$.filter((z)=>z.type==="text");if(X.length>0){let z=X[0];Q=$.map((W)=>W===z?{type:"text",text:t2(z.text)}:W)}else Q=[{type:"text",text:t2("")},...$]}return yield*this.executeLoop(Q,Z,J,Y)}async*runLoop($,Z,J){a.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z);return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await Y1({...$.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:$.workspaceRoot||C()},replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:$.executionRoot??$.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...$.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let Q=this.buildLoopDependencies();return rY(Q,$,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)}},Q=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,X=J.error===void 0,z=J.output,W={success:X,llmContent:typeof z==="string"||z!==null&&typeof z==="object"?z:z===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(z),...J.error?{error:{type:"execution_error",message:J.error}}:{},...Q?{metadata:Q}:{}},V=[{kind:"tool_result",toolCall:Y,result:W}],U=iY(Y,W);if(U)V.push(U);return V})}takeStartupRecoveryEvents(){let $=this.sessionRuntime?.getTurnRecoveryAssessment(),Z=$?.state==="requires_attention"?$:this.sessionRuntime?.takeStartupTurnRecoveryAssessment(),J=Z&&Z.state!=="none"?[{kind:"turn_recovery",assessment:Z}]:[];return J.push(...this.takeStartupAdoptedToolResultEvents()),J}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=$,a.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((Q)=>!$.includes(Q.name));for(let Q of Y)Z.unregister(Q.name);a.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);a.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){a.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){a.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await Y1({...this.sessionRuntime?.isRemoteWorkspace()?{workspaceAccess:"none"}:{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(),...this.sessionRuntime?.isRemoteWorkspace()?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot},...this.sessionRuntime?{environmentOptions:{...u1,workingDirectory:this.sessionRuntime.executionRoot}}:{}});if(J.prompt)this.log("系统提示配置验证成功"),a.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await v4({sessionId:"default",configDir:t(),workspaceRoot:C(),resourceRoot:C(),agentResources:this.agentResources});a.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;a.debug(`Builtin tools registered: ${Z} tools`),a.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw a.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await z4({workspaceRoot:C(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){a.debug("No MCP servers configured");return}let Z=e0.createIsolated({artifactWriter:new o2(`legacy-${QG()}`)});this.legacyMcpRegistry=Z;for(let[X,z]of Object.entries($))try{a.debug(`Connecting to MCP server: ${X}`),await Z.registerServer(X,z),a.debug(`MCP server "${X}" connected`)}catch(W){a.warn(`Warning: MCP server "${X}" connection failed:`,W)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(Y6(Z));let Q=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:Q.revision,reason:"snapshot",replace:!0,instructions:Q.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)a.debug(`Registered ${Y.tools.length} MCP tools`),a.debug(`[MCP Tools] ${Y.tools.map((X)=>X.name).join(", ")}`)}catch($){a.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await c0(C());if(this.agentResources=k4($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)a.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else a.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;a.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{if(Y.name==="ReadPromptArtifact")return!0;return Z.some((Q)=>{if(Q===Y.name)return!0;let X=Q.match(/^(\w+)\(.*\)$/);if(X&&X[1]===Y.name)return!0;return!1})});return a.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)a.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(`
|
|
863
863
|
`);try{let Y=await this.attachmentCollector.collect(J);if(Y.length===0)return $;a.debug(`Processed ${Y.length} @ file mentions in multimodal message`);let Q=this.buildAttachmentText(Y);if(!Q)return $;return[...$,{type:"text",text:Q}]}catch(Y){return a.error("Failed to process @ mentions in multimodal message:",Y),$}}buildAttachmentText($){let Z=[],J=[];for(let Q of $)if(Q.type==="file"){let X=Q.metadata?.lineRange?` (lines ${Q.metadata.lineRange.start}${Q.metadata.lineRange.end?`-${Q.metadata.lineRange.end}`:""})`:"";Z.push(`<file path="${Q.path}"${X?` range="${X}"`:""}>`,Q.content,"</file>")}else if(Q.type==="directory")Z.push(`<directory path="${Q.path}">`,Q.content,"</directory>");else if(Q.type==="error")J.push(`- @${Q.path}: ${Q.error}`);let Y="";if(Z.length>0)Y+=`
|
|
864
864
|
|
|
865
865
|
<system-reminder>
|
|
@@ -1675,7 +1675,7 @@ ${J}
|
|
|
1675
1675
|
`)),{success:!0,message:"Schedules listed",content:V.join(`
|
|
1676
1676
|
`)}}case"create":{let W=aw(X);if("error"in W)return Y.sendMessage(`创建失败:${W.error}`),{success:!1,error:W.error};let V={prompt:W.prompt,projectPath:z,trigger:W.trigger,isolation:"worktree",permissionMode:"default",enabled:!0};try{let U=await $.create(V),H=U.nextRunAt?new Date(U.nextRunAt).toLocaleString():"(无)";return Y.sendMessage(`[OK] 已创建定时任务 \`${U.id}\`
|
|
1677
1677
|
${A9(U.trigger)} · 下次运行: ${H}`),{success:!0,message:`Schedule ${U.id} created`}}catch(U){let H=U instanceof Error?U.message:String(U);return Y.sendMessage(`创建失败:${H}`),{success:!1,error:H}}}case"remove":case"rm":{let W=X[0];if(!W)return Y.sendMessage("用法:/schedule remove <id>"),{success:!1,error:"Missing schedule id"};let V=await $.remove(W);return Y.sendMessage(V?`[OK] 已删除 \`${W}\``:`未找到 \`${W}\``),{success:V,message:V?"Removed":"Not found"}}case"enable":case"disable":{let W=X[0];if(!W)return Y.sendMessage(`用法:/schedule ${Q} <id>`),{success:!1,error:"Missing schedule id"};let V=await $.setEnabled(W,Q==="enable");return Y.sendMessage(V?`[OK] 已${Q==="enable"?"启用":"停用"} \`${W}\``:`未找到 \`${W}\``),{success:Boolean(V),message:V?"Updated":"Not found"}}case"run":{let W=X[0];if(!W)return Y.sendMessage("用法:/schedule run <id>"),{success:!1,error:"Missing schedule id"};try{return await sw(W),Y.sendMessage(`[OK] 已触发 \`${W}\``),{success:!0,message:"Schedule triggered"}}catch(V){let U=V instanceof Error?V.message:String(V);return Y.sendMessage(`运行失败:${U}`),{success:!1,error:U}}}default:return Y.sendMessage(`未知子命令: ${Q}
|
|
1678
|
-
使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Q}`}}}}}var sz=ow();import*as f2 from"node:fs/promises";import*as P2 from"node:path";async function ZW($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:Q,storagePath:X}=Z,z=X??P6(Q??C());if(!X){let G=await tw($,Q??C(),J,Y);if(G)return G}let W;try{W=(await f2.readdir(z)).filter((D)=>D.endsWith(".jsonl")&&!D.startsWith("agent_")).map((D)=>P2.join(z,D))}catch{return[]}let U=(await Promise.all(W.map(async(G)=>{try{let D=await f2.stat(G);return{path:G,mtime:D.mtimeMs}}catch{return null}}))).filter((G)=>G!==null).sort((G,D)=>D.mtime-G.mtime).map((G)=>G.path),H=[],B=Y?$:$.toLowerCase();for(let G of U){if(H.length>=J)break;let D=P2.basename(G,".jsonl"),w=await ew(G,B,Y,D);if(H.push(...w),H.length>=J){H.length=J;break}}return H}async function tw($,Z,J,Y){try{let{syncAll:Q}=await import("./chunk-87xebr2g.js"),X=await ez();if(!X)return null;let{SessionService:z}=await import("./chunk-
|
|
1678
|
+
使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Q}`}}}}}var sz=ow();import*as f2 from"node:fs/promises";import*as P2 from"node:path";async function ZW($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:Q,storagePath:X}=Z,z=X??P6(Q??C());if(!X){let G=await tw($,Q??C(),J,Y);if(G)return G}let W;try{W=(await f2.readdir(z)).filter((D)=>D.endsWith(".jsonl")&&!D.startsWith("agent_")).map((D)=>P2.join(z,D))}catch{return[]}let U=(await Promise.all(W.map(async(G)=>{try{let D=await f2.stat(G);return{path:G,mtime:D.mtimeMs}}catch{return null}}))).filter((G)=>G!==null).sort((G,D)=>D.mtime-G.mtime).map((G)=>G.path),H=[],B=Y?$:$.toLowerCase();for(let G of U){if(H.length>=J)break;let D=P2.basename(G,".jsonl"),w=await ew(G,B,Y,D);if(H.push(...w),H.length>=J){H.length=J;break}}return H}async function tw($,Z,J,Y){try{let{syncAll:Q}=await import("./chunk-87xebr2g.js"),X=await ez();if(!X)return null;let{SessionService:z}=await import("./chunk-d9q5dn00.js");await Q(X,z.projectionDeriverForSearch());let W=P2.resolve(Z),V=$W(X,$,W,J*4),U=Y?$:$.toLowerCase(),H=[];for(let B of V){if(B.role!=="user"&&B.role!=="assistant")continue;let G=M9(B.text,U,Y,B.session_id,B.role,B.timestamp??void 0,0);if(G)H.push(G);if(H.length>=J)break}return H}catch{return null}}async function ew($,Z,J,Y){try{let Q=await f2.readFile($,"utf8"),z=Q.split(`
|
|
1679
1679
|
`).flatMap((B,G)=>{if(!B.trim())return[];try{return[{event:JSON.parse(B),index:G}]}catch{return[]}});if(!z.some(({event:B})=>B.type==="session_created"))return $F(z,Z,J,Y);let V=new Map(z.flatMap(({event:B,index:G})=>typeof B.id==="string"?[[B.id,G+1]]:[])),U=oz(tz(Q,$)),H=new Map;for(let B of U){if(B.type==="message_created"&&(B.data.role==="user"||B.data.role==="assistant"))H.set(B.data.messageId,{role:B.data.role,content:[],timestamp:B.timestamp,lineNumber:V.get(B.id)??0});if(B.type==="part_created"&&B.data.partType==="text"){let G=H.get(B.data.messageId),D=B.data.payload.text;if(G&&typeof D==="string")G.content.push(D)}}return[...H.values()].flatMap((B)=>{let G=M9(B.content.join(" "),Z,J,Y,B.role,B.timestamp,B.lineNumber);return G?[G]:[]})}catch{return[]}}function $F($,Z,J,Y){return $.flatMap(({event:Q,index:X})=>{if(Q.type!=="message")return[];let z=Q.message;if(z?.role!=="user"&&z?.role!=="assistant"||!z.content)return[];let W=typeof z.content==="string"?z.content:Array.isArray(z.content)?z.content.filter((U)=>typeof U==="object"&&U!==null&&U.type==="text"&&typeof U.text==="string").map((U)=>U.text).join(" "):"",V=M9(W,Z,J,Y,z.role,typeof Q.timestamp==="string"?Q.timestamp:void 0,X+1);return V?[V]:[]})}function M9($,Z,J,Y,Q,X,z){if(!$)return;let W=J?$:$.toLowerCase();if(!W.includes(Z))return;let V=W.indexOf(Z),U=Math.max(0,V-80),H=Math.min($.length,V+Z.length+80);return{sessionId:Y,role:Q,content:(U>0?"...":"")+$.slice(U,H).replace(/\n/g," ")+(H<$.length?"...":""),timestamp:X,lineNumber:z}}function JW($){if($.length===0)return"没有找到匹配的历史记录";let Z=[`**找到 ${$.length} 条匹配:**
|
|
1680
1680
|
`];for(let J of $){let Y=J.timestamp?new Date(J.timestamp).toLocaleString("zh-CN",{timeZone:"Asia/Shanghai"}):"?",Q=J.role==="user"?"\uD83D\uDC64":"\uD83E\uDD16";Z.push(`${Q} \`${J.sessionId.slice(0,8)}\` (${Y})`),Z.push(` ${J.content}`),Z.push("")}return Z.join(`
|
|
1681
1681
|
`)}var ZF={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=c(Z);if($.length===0)return J.sendMessage("**用法:** `/search <关键词>`\n\n在历史会话中搜索包含指定关键词的对话"),{success:!0,message:"显示帮助"};let Y=$.join(" ");J.sendMessage(`正在搜索: "${Y}" ...`);try{let Q=await ZW(Y,{maxResults:15,projectPath:Z.cwd}),X=JW(Q);return J.sendMessage(X),{success:!0,message:`found ${Q.length} results`,data:{matches:Q.length}}}catch(Q){let X=Q instanceof Error?Q.message:"未知错误";return J.sendMessage(`搜索失败: ${X}`),{success:!1,error:X}}}},YW=ZF;var JF={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,Z)=>{try{let J=Z.workspaceRoot??Z.cwd;return await f$(J,async(Y)=>{await Y.skills.refresh(),i1(J),await l1(J)}),{success:!0,message:"show_skills_manager",data:{action:"show_skills_manager"}}}catch(J){let Y=`获取 Skills 失败: ${J instanceof Error?J.message:"未知错误"}`;return d().addAssistantMessage(Y),{success:!1,error:Y}}}},QW=JF;import YF from"node:path";function O8($){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 XW($){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 zW($,Z){if($.length<=Z)return $;return $.slice(0,Z-3)+"..."}async function QF($,Z){let J=c(Z),Y=$[0],Q=Y0.getInstance(),X=D0.getInstance(),z=Z.sessionId??"",W=Z.sessionId?{sessionId:Z.sessionId,projectPath:YF.resolve(Z.workspaceRoot??Z.cwd)}:void 0;if(Y==="resume"){let D=$[1],w=$.slice(2).join(" ").trim();if(!D||!w)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 q=await Z.subagents.resume(D,w),_=`Resumed \`${D}\` as \`${q.session.id}\` (depth ${q.session.resumeDepth}).`;return J.sendMessage(_),{success:!0,message:_,data:{action:"subagent_resumed",sourceAgentId:D,subagent:q.session}}}if(Y==="clean"){let D=X.cleanupExpiredSessionsForParent(W??z,0);return J.sendMessage(`已清理 ${D} 个已完成的 Agent 会话`),{success:!0,message:`Cleaned ${D} agent sessions`}}let V=[`**后台任务列表**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ae as a,be as b,ce as c,de as d,ee as e,fe as f,ge as g}from"./chunk-
|
|
1
|
+
import{ae as a,be as b,ce as c,de as d,ee as e,fe as f,ge as g}from"./chunk-f71j03pq.js";import"./chunk-9xbwtjac.js";import"./chunk-3a217980.js";import"./chunk-mh9nqbwa.js";import"./chunk-7wcxjbyg.js";import"./chunk-vbjgcn49.js";import"./chunk-3y2x6fb6.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-2mk914vk.js";import"./chunk-4cdk4mds.js";import"./chunk-s1cs5ga0.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";export{b as __setSessionSnapshotIOForTesting,c as __resetSessionSnapshotIOForTesting,g as SessionService,d as SessionMissingCreationError,e as SessionArchivedError,f as SessionArchiveConflictError,a as STALE_EMPTY_SESSION_AGE_MS};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{e as r2,f as e2,g as W3,h as i0,i as _3}from"./chunk-
|
|
1
|
+
import{e as r2,f as e2,g as W3,h as i0,i as _3}from"./chunk-q5gcqckt.js";import{j as d1}from"./chunk-zj1g4nbq.js";import{v as v0,w as M2}from"./chunk-2zzsyaf4.js";import{A as E0,x as A2,y as T2,z as b2}from"./chunk-qf6vf457.js";import{B as F2,C as O$,D as $$,E as Q$,F as J0,G as Z$}from"./chunk-ghqvews8.js";import{$ as W2,Da as T3,J as Q2,K as m1,L as A3,O as Z2,P as a0,Q as C4,R as g1,S as b$,T as w4,U as Y2,V as X0,W as N2,X as X2,Y as Y$,Z as z1,aa as H4,ba as B0,ca as L0,fa as T1,ga as b1,ha as m3,ia as _2,ja as K2,ka as m2,la as h2,ma as y2,na as g2,oa as p2,pa as v2,qa as u2,ra as d2,sa as l2,va as s2,ya as c3}from"./chunk-d1navt68.js";import{Ka as F$,Qa as hO}from"./chunk-6hb0pjmk.js";import{Ta as V2,Va as z2,Wa as G2,Xa as U2,bb as O4,eb as j3,fb as f4,gb as w2,hb as H2,ib as I3,jb as R3,kb as P4,lb as q3,mb as P0,nb as $3,ob as Q3,pb as Z3,qb as B2,rb as D2,sb as L2,tb as x2,ub as t4,vb as v4}from"./chunk-e12xrg41.js";import{Jb as yO,Kb as n,Mb as P,Nb as J2,Yb as F4,gc as f0}from"./chunk-mhb3gg9s.js";import{rc as B4}from"./chunk-wm896gnx.js";import{$c as K1,Bd as s$,Ld as B1,Md as C0,Rc as c$,Td as M1,Ud as D4,Vd as A1,Xd as d0,Yc as a$,Zc as U4,_c as o$,_d as W4,ad as n$,dd as X4,de as $2,ee as _4,fe as K4,ge as v,qd as t$}from"./chunk-f71j03pq.js";import{Ee as r$,Le as e$,Me as O2}from"./chunk-3a217980.js";import{ff as Y3,jf as N3,kf as X3,lf as V3,mf as z3,nf as E4,of as G3,pf as U3}from"./chunk-mh9nqbwa.js";import{Of as P3,Sf as LO,Wf as D$,bg as lO}from"./chunk-mpexy01a.js";import{cg as y1}from"./chunk-7xhw74hk.js";import{vg as l$}from"./chunk-7wcxjbyg.js";import{xg as k1}from"./chunk-01framym.js";import{Gg as k3,Ig as w3,Lg as k2,Pg as U1,Qg as W1,Ug as O5,Xg as eO,Yg as _1,ah as p4}from"./chunk-h8s11k0r.js";import{th as L$,uh as i$}from"./chunk-vbjgcn49.js";import{yh as U$,zh as p0}from"./chunk-wv8dy886.js";import{Mi as W$,Rh as K$,Ri as G1,fi as h$,ii as y$,ki as g$,li as p$,mi as A$,ni as T$,oi as s4,ui as v$,xi as u$,zi as d$}from"./chunk-9a0cy4z7.js";import{Ui as z4}from"./chunk-kv458q06.js";import{Wi as v1,Zi as G4}from"./chunk-5v0jcyea.js";import{bj as YO}from"./chunk-2f8d0km4.js";import{Dj as $O,Fj as y,Hj as z,Ij as iO,Kj as JO}from"./chunk-2mk914vk.js";import{Pj as I0}from"./chunk-j8hbddjp.js";import{Rj as H$,Sj as k$,Uj as B$,Vj as m$}from"./chunk-4cdk4mds.js";import{Xj as g0}from"./chunk-s1cs5ga0.js";import{ck as g4}from"./chunk-rvs364rz.js";import{Bk as C1,Jk as X$,fk as p1,zk as WO}from"./chunk-4wx5sya5.js";import{Mk as m4}from"./chunk-eg3ms291.js";var c6={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function a6(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{existsSync as u4,readFileSync as R1}from"node:fs";import{createServer as x6}from"node:http";import{networkInterfaces as M6}from"node:os";import{dirname as A6,extname as T6,join as T0}from"node:path";import{fileURLToPath as b6}from"node:url";import{brotliCompressSync as j6,gzipSync as I6,constants as R6}from"node:zlib";import{Hono as q6}from"hono";import{cors as E6}from"hono/cors";import{WebSocketServer as S6}from"ws";var y0=$O("Service"),F5=30000,w5=new Set(["completed","failed","cancelled","interrupted"]);class $4{dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor(O){this.dispatch=O.dispatch,this.store=O.store??t4.getInstance(),this.tickMs=O.tickMs??F5}start(){if(this.timer)return;y0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=P.subscribe((O)=>{if(O.type!=="task.status")return;let $=O.properties.taskStatus;if(typeof $!=="string"||!w5.has($))return;this.recordTerminalStatus(O.sessionId,$,typeof O.properties.taskStatusReason==="string"?O.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,y0.info("[TaskScheduler] Stopped scheduler tick loop")}async tick(O=new Date){if(this.ticking)return;this.ticking=!0;try{let $=await this.store.list();for(let Q of $)await this.evaluate(Q,O)}catch($){y0.warn("[TaskScheduler] Tick failed:",$)}finally{this.ticking=!1}}async evaluate(O,$){if(!O.enabled)return;if(this.inFlight.has(O.id))return;if(O.expiresAt&&new Date(O.expiresAt).getTime()<=$.getTime()){await this.store.update(O.id,{enabled:!1,nextRunAt:null}),y0.info(`[TaskScheduler] Schedule ${O.id} expired; disabled`);return}if(!O.nextRunAt)return;if(!(new Date(O.nextRunAt).getTime()<=$.getTime()))return;await this.fire(O,$)}async fire(O,$=new Date,Q={}){if(this.inFlight.has(O.id))throw Error(`Schedule ${O.id} is already dispatching`);this.inFlight.add(O.id);let Z=$.toISOString();try{let J=await this.dispatch({prompt:O.prompt,title:O.title??H5(O),sourceProjectPath:O.projectPath,isolation:O.dispatch.isolation??"worktree",permissionMode:O.dispatch.permissionMode??"default",modelId:O.dispatch.modelId,reasoningEffort:O.dispatch.reasoningEffort,serviceTier:O.dispatch.serviceTier,responseVerbosity:O.dispatch.responseVerbosity,communicationStyle:O.dispatch.communicationStyle}),N=O.trigger.kind==="once"?null:Q.manual?O.nextRunAt?new Date(O.nextRunAt):null:O4(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:Z,lastRunSessionId:J.session.sessionId,lastStatus:J.status,lastError:void 0,runCount:O.runCount+1,nextRunAt:N?N.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled}),P.publish({sessionId:J.session.sessionId,projectPath:O.projectPath},"schedule.fired",{scheduleId:O.id,firedAt:Z,sessionId:J.session.sessionId,runId:J.runId,status:J.status}),y0.info(`[TaskScheduler] Fired schedule ${O.id} -> session ${J.session.sessionId} (${J.status})`)}catch(J){let N=J instanceof Error?J.message:String(J);y0.warn(`[TaskScheduler] Schedule ${O.id} dispatch failed:`,J);let X=O.trigger.kind==="once"?null:Q.manual?O.nextRunAt?new Date(O.nextRunAt):null:O4(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:Z,lastStatus:"error",lastError:N,nextRunAt:X?X.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled})}finally{this.inFlight.delete(O.id)}}async recordTerminalStatus(O,$,Q){let J=(await this.store.list()).find((N)=>N.lastRunSessionId===O);if(!J)return;await this.store.update(J.id,{lastStatus:$,...Q?{lastError:Q}:{lastError:void 0}})}}function H5(O){return`Scheduled: ${O.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class zO extends Error{code;statusCode;details;constructor(O,$,Q=500,Z){super($);this.code=O;this.statusCode=Q;this.details=Z;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class c extends zO{constructor(O,$){super("NOT_FOUND",$?`${O} not found: ${$}`:`${O} not found`,404)}}class w extends zO{constructor(O){super("BAD_REQUEST",O,400)}}class l extends zO{constructor(O){super("CONFLICT",O,409)}}class nO extends zO{constructor(O,$){super("TOO_MANY_REQUESTS",O,429,$)}}class DO extends zO{constructor(O="Server is shutting down"){super("SERVICE_UNAVAILABLE",O,503)}}class E1 extends zO{constructor(O){super("SESSION_WORKSPACE_UNAVAILABLE","This session workspace is no longer available",409,{reason:O})}}class mO extends zO{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class ZO extends zO{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var $8=z.Object({error:z.Object({code:z.String(),message:z.String(),details:z.Optional(z.Record(z.String(),z.Unknown()))})});import{Hono as B5}from"hono";var Q4=$O("Service"),D5=z.Object({updates:z.Record(z.String(),z.Any()),options:z.Optional(z.Object({scope:z.Optional(JO(["local","project","global"])),immediate:z.Optional(z.Boolean())}))});function L5(O){return{currentModelId:O.currentModelId,permissionMode:O.permissionMode,language:O.language,codeTheme:O.codeTheme,uiTheme:O.uiTheme,autoSaveSessions:O.autoSaveSessions,notifyBuild:O.notifyBuild,notifyErrors:O.notifyErrors,notifySounds:O.notifySounds,privacyTelemetry:O.privacyTelemetry,privacyCrash:O.privacyCrash,agentTeamsEnabled:O.agentTeamsEnabled===!0,communicationStyle:O.communicationStyle,maxConcurrentTasks:O.maxConcurrentTasks,maxQueuedTasks:O.maxQueuedTasks,maxQueuedTaskBytes:O.maxQueuedTaskBytes,maxResidentSessionRuntimes:O.maxResidentSessionRuntimes,sessionRuntimeIdleMs:O.sessionRuntimeIdleMs,maxResidentSessionProjections:O.maxResidentSessionProjections,sessionProjectionIdleMs:O.sessionProjectionIdleMs}}var r4=()=>{let O=new B5;return O.get("/",async($)=>{try{let Q=LO();return $.json(Q?L5(Q):{})}catch(Q){return Q4.error("[ConfigRoutes] Failed to get config:",Q),$.json({})}}),O.put("/",async($)=>{try{let Q=await $.req.json(),Z=y(D5,Q);if(!Z.success)throw new w("Invalid config update format");let{updates:J,options:N}=Z.data;return await lO().updateConfig(J,N),$.json({success:!0,updates:J})}catch(Q){if(Q instanceof s4)throw new w(Q.message);throw Q4.error("[ConfigRoutes] Failed to update config:",Q),Q}}),O.get("/permissions",async($)=>{try{let Q=LO();return $.json(Q?.permissions||{})}catch(Q){return Q4.error("[ConfigRoutes] Failed to get permissions:",Q),$.json({})}}),O};import{Hono as x5}from"hono";import{streamSSE as M5}from"hono/streaming";function e4(O){let $="";if(O.id!==void 0)$+=`id: ${O.id}
|
|
2
2
|
`;if(O.event!==void 0)$+=`event: ${O.event}
|
|
3
3
|
`;for(let Q of O.data.split(/\r\n|\r|\n/))$+=`data: ${Q}
|
|
4
4
|
`;if(O.retry!==void 0)$+=`retry: ${O.retry}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{k as o}from"./chunk-
|
|
1
|
+
import{k as o}from"./chunk-cz77x04v.js";import"./chunk-s1cs5ga0.js";import"./chunk-eg3ms291.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Ae as A0,Be as B1,Ce as H1,Ee as d2,Le as i2,Me as C0,Te as p_,Ve as N1,Xe as r2,Ye as o2,Ze as q1,_e as a2,ne as u2,oe as e,pe as h2,qe as Z1,re as l2,se as m,te as G1,ue as c2,ve as p2,we as V1,xe as L1,ye as n2,ze as U1}from"./chunk-3a217980.js";import{ug as o_}from"./chunk-7wcxjbyg.js";import{rh as a_}from"./chunk-vbjgcn49.js";import{Vi as v2,Wi as P2,Xi as x_,Yi as Q0,Zi as w_}from"./chunk-5v0jcyea.js";import{bj as f1}from"./chunk-2f8d0km4.js";import{Dj as H0}from"./chunk-2mk914vk.js";import{Qj as i_,Tj as r_}from"./chunk-4cdk4mds.js";import{Xj as __}from"./chunk-
|
|
1
|
+
import{Ae as A0,Be as B1,Ce as H1,Ee as d2,Le as i2,Me as C0,Te as p_,Ve as N1,Xe as r2,Ye as o2,Ze as q1,_e as a2,ne as u2,oe as e,pe as h2,qe as Z1,re as l2,se as m,te as G1,ue as c2,ve as p2,we as V1,xe as L1,ye as n2,ze as U1}from"./chunk-3a217980.js";import{ug as o_}from"./chunk-7wcxjbyg.js";import{rh as a_}from"./chunk-vbjgcn49.js";import{Vi as v2,Wi as P2,Xi as x_,Yi as Q0,Zi as w_}from"./chunk-5v0jcyea.js";import{bj as f1}from"./chunk-2f8d0km4.js";import{Dj as H0}from"./chunk-2mk914vk.js";import{Qj as i_,Tj as r_}from"./chunk-4cdk4mds.js";import{Xj as __}from"./chunk-s1cs5ga0.js";import{Ak as c_,Bk as A,Ck as P,Dk as S,Ek as E1,Fk as F1,Gk as M_,Hk as z1,Ik as b1,Jk as q_,fk as h,pk as o,qk as p,rk as S2,sk as n,tk as d,uk as I2,vk as K0,wk as Y1,xk as m2,yk as K_,zk as M0}from"./chunk-4wx5sya5.js";import{readdir as b_,readFile as V_,rm as f_,stat as E0}from"node:fs/promises";import*as N from"node:path";import{nanoid as I}from"nanoid";import{createHash as F4,randomUUID as z4}from"node:crypto";import*as W_ from"node:fs/promises";import*as W0 from"node:path";import D4 from"proper-lockfile";function cX(_){return Object.freeze({kind:"local",root:_})}function pX(_,X){let $=o(X);if(p($.collisionIdentity)!==_)throw Error("ACP remote workspace durable state is invalid");return Object.freeze({kind:"acp-remote",root:_,descriptor:$})}function nX(_,X){return _.kind==="acp-remote"?`${_.kind}\x00${_.root}\x00${_.descriptor.exactIdentity}\x00${X}`:`${_.kind}\x00${_.root}\x00${X}`}async function H_(_,X){if(_.kind==="local")return X(K_(_.root));return n(_.root,($)=>X(String($),$))}async function dX(_,X,$){return H_(_,(W,J)=>$(J?{storageRoot:W,transcriptPath:S(J,X),inboxPath:F1(J,X),goalPath:z1(J,X),remoteScope:J}:{storageRoot:W,transcriptPath:P(_.root,X),inboxPath:E1(_.root,X),goalPath:M_(_.root,X)}))}import{execFileSync as T4}from"node:child_process";import{createHash as C4}from"node:crypto";import{readFileSync as K4}from"node:fs";var M4=/^[a-f0-9]{64}$/;function D1(_){if(!_||typeof _!=="object")return!1;let X=_;return(X.platform==="linux"||X.platform==="darwin"||X.platform==="win32")&&typeof X.fingerprint==="string"&&M4.test(X.fingerprint)}var R1={readFile:(_)=>K4(_,"utf8"),execFile:(_,X)=>T4(_,X,{encoding:"utf8",timeout:_==="powershell.exe"?3000:2000,windowsHide:!0})},A4=(_)=>{try{return process.kill(_,0),!0}catch(X){return X instanceof Error&&"code"in X&&X.code==="EPERM"}};function x0(_,X){return{platform:_,fingerprint:C4("sha256").update(`${_}\x00${X}`).digest("hex")}}function E4(_,X){let $=X.readFile(`/proc/${_}/stat`).trim(),W=$.lastIndexOf(")");if(W<0)throw Error("Invalid /proc process stat");let O=$.slice(W+2).split(/\s+/)[19];if(!O||!/^\d+$/.test(O))throw Error("Missing process start ticks");return O}function m_(_,X=process.platform,$=R1){if(!Number.isInteger(_)||_<=1)return;try{if(X==="linux")return x0(X,E4(_,$));if(X==="darwin"){let W=$.execFile("ps",["-o","lstart=","-p",String(_)]).trim();return W?x0(X,W):void 0}if(X==="win32"){let W=`(Get-CimInstance Win32_Process -Filter "ProcessId = ${_}").CreationDate.ToUniversalTime().ToString('O')`,J=$.execFile("powershell.exe",["-NoProfile","-NonInteractive","-Command",W]).trim();return J?x0(X,J):void 0}}catch{return}return}function tX(_,X){return m_(_,X.platform)?.fingerprint===X.fingerprint}function sX(_,X,$=R1,W=A4){if(!Number.isInteger(_)||_<=1)return!1;let J=m_(_,X.platform,$);if(J)return J.fingerprint===X.fingerprint;return!W(_)}var j1=1;function R4(_,X){let $=F4("sha256").update(X).digest("hex");return W0.join(K_(_),".locks",`${$}.lock`)}function R_(_,X){return _ instanceof Error&&"code"in _&&_.code===X}async function k0(_){try{let X=JSON.parse(await W_.readFile(_,"utf8"));if(X.version!==j1||typeof X.sessionId!=="string"||typeof X.ownerId!=="string"||!Number.isInteger(X.pid)||(X.pid??0)<=0||X.processIdentity!==void 0&&!D1(X.processIdentity)||typeof X.acquiredAt!=="string")return;return X}catch(X){if(R_(X,"ENOENT")||X instanceof SyntaxError)return;throw X}}async function w1(_){let X=await k0(_);if(X)return X;return await new Promise(($)=>setTimeout($,10)),k0(_)}function w4(_){try{return process.kill(_,0),!0}catch(X){return!R_(X,"ESRCH")}}async function x1(_,X){let $;try{return $=await W_.open(_,"wx",384),await $.writeFile(`${JSON.stringify(X)}
|
|
2
2
|
`,"utf8"),!0}catch(W){if(R_(W,"EEXIST"))return!1;if($)await W_.unlink(_).catch(()=>{return});throw W}finally{await $?.close().catch(()=>{return})}}class $_ extends Error{code="BLADE_SESSION_IN_USE";constructor(_){super(_?`Session is already active in another Blade process (PID ${_}). Stop that process or choose a different session.`:"Session is already active in another Blade process. Stop that process or choose a different session.");this.name="SessionInUseError"}}async function k1(_,X,$=!1){let W,J;try{J=await D4.lock(_,{realpath:!1,retries:$?{retries:50,minTimeout:10,maxTimeout:100,factor:1.2}:0,onCompromised:(Q)=>{W=Q}})}catch(Q){if(R_(Q,"ELOCKED"))throw new $_;throw Q}let O=()=>{if(W)throw W};try{O();let Q=await X(O);return O(),Q}finally{await J()}}class u{filePath;record;stateStorage;released=!1;constructor(_,X,$){this.filePath=_;this.record=X;this.stateStorage=$}static async acquireForStorage(_,X){if(X.kind==="local")return u.acquire(_,X.root);return H_(X,($,W)=>{if(!W||$!==X.root)throw Error("ACP remote session lease scope is invalid");return u.acquireRemote(_,W,X)})}static async acquire(_,X=f1()){return u.acquireAtPath(_,R4(X,_))}static async acquireRemote(_,X,$){let W=b1(X,_);try{await d(X,W)}catch(O){if(O.code!=="ENOENT")throw O}let J=await u.acquireAtPath(_,W);try{return await d(X,W),new u(W,J.record,$)}catch(O){throw await J.release(),O}}static async acquireAtPath(_,X){return await W_.mkdir(W0.dirname(X),{recursive:!0,mode:448}),k1(X,async($)=>{let W={version:j1,sessionId:_,ownerId:z4(),pid:process.pid,processIdentity:m_(process.pid),acquiredAt:new Date().toISOString()};if($(),await x1(X,W))return new u(X,W);let J=await w1(X);if(!J||J.sessionId!==_)throw new $_;if(w4(J.pid)){let O=J.processIdentity?m_(J.pid,J.processIdentity.platform):void 0;if(!O||O.fingerprint===J.processIdentity?.fingerprint)throw new $_(J.pid)}if($(),await W_.unlink(X).catch((O)=>{if(!R_(O,"ENOENT"))throw O}),$(),await x1(X,W))return new u(X,W);throw new $_((await w1(X))?.pid)})}async release(){if(this.released)return;let _=()=>k1(this.filePath,async(X)=>{if((await k0(this.filePath))?.ownerId!==this.record.ownerId)return;X(),await W_.unlink(this.filePath).catch((W)=>{if(!R_(W,"ENOENT"))throw W})},!0);if(this.stateStorage?.kind==="acp-remote")await H_(this.stateStorage,_);else await _();this.released=!0}}import{createHash as O0}from"node:crypto";import{constants as A_,promises as O_}from"node:fs";import G_ from"node:path";import{Mutex as x4}from"async-mutex";var y1=128,g1=67108864,k4=24576,S1=65536,f0=1,h1=/^[a-f0-9]{64}$/,b4=/^[a-f0-9]{64}\.txt$/,l1=64,f4=new Set(["EBUSY","EAGAIN","EMFILE","ENFILE"]),Y0=`
|
|
3
3
|
|
|
4
4
|
...[middle omitted; read the private prompt artifact for the complete request]...
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$j as f,Wj as a,Xj as b,Yj as c,Zj as d,_j as e}from"./chunk-
|
|
1
|
+
import{$j as f,Wj as a,Xj as b,Yj as c,Zj as d,_j as e}from"./chunk-s1cs5ga0.js";import"./chunk-eg3ms291.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{V as I}from"./chunk-
|
|
1
|
+
import{V as I}from"./chunk-d1navt68.js";import{ge as M}from"./chunk-f71j03pq.js";import P from"node:path";function w(s){let a=s.replace(/\s+/g," ").trim();return a.length<=72?a:`${a.slice(0,69)}...`}function W(s){let a=s.replace(/\s+/g," ").trim();return a.length<=500?a:`${a.slice(0,497)}...`}function A(s){return`task/${s.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class C{static async createSessionTask(s){if(!s.prompt.trim())throw Error("Task prompt must not be blank");if(!P.isAbsolute(s.sourceProjectPath))throw Error("Task source project path must be absolute");let a=P.resolve(s.sourceProjectPath),t;try{return t=s.isolation==="worktree"?await I.enter({sessionId:s.sessionId,workspaceRoot:a,name:A(s.sessionId)}):void 0,{metadata:await M.createSessionMetadata(s.sessionId,t?.workspaceRoot??a,{title:s.title?.trim()||w(s.prompt),taskPromptSummary:W(s.prompt),taskPriority:s.taskPriority,taskKind:s.taskKind,taskDueAt:s.taskDueAt,taskDispatch:s.dispatch,taskModelId:s.dispatch?.modelId,selectedModelId:s.dispatch?.modelId,permissionMode:s.dispatch?.permissionMode,reasoningEffort:s.dispatch?.reasoningEffort,serviceTier:s.dispatch?.serviceTier,responseVerbosity:s.dispatch?.responseVerbosity,communicationStyle:s.dispatch?.communicationStyle,communicationStyleDigest:s.dispatch?.communicationStyleDigest,projectInstructionsDigest:s.dispatch?.projectInstructionsDigest,taskRetriedFrom:s.retriedFrom,taskIsolation:s.isolation,taskSourceProjectPath:a,taskWorktree:t}),taskWorktree:t}}catch(k){if(t)await I.exit({sessionId:s.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw k}}}var $=256,V=8388608,x=30000;class i extends Error{kind;pendingItems;pendingBytes;constructor(s,a,t){super(a,t);this.kind=s;this.name="BoundedSerialEgressError",this.pendingItems=t?.pendingItems,this.pendingBytes=t?.pendingBytes}}function T(s){s.catch(()=>{return})}class K{options;pending=[];flushWaiters=[];pendingBytes=0;nextSequence=0;completedSequence=0;draining=!1;closed=!1;failure;activeWriteAbort;activeWriteStop;activeWriteTimeout;constructor(s){this.options=s;if(this.assertPositiveInteger(s.maxPendingItems,"maxPendingItems"),this.assertPositiveInteger(s.maxPendingBytes,"maxPendingBytes"),this.assertPositiveInteger(s.writeTimeoutMs,"writeTimeoutMs"),s.signal?.addEventListener("abort",this.handleAbort,{once:!0}),s.signal?.aborted)this.handleAbort()}offer(s){if(this.closed)return{accepted:!1,error:this.failure??new i("closed","Egress is already closed")};let a;try{a=this.options.sizeOf(s)}catch(h){return this.rejectAdmission(new i("invalid_size","Egress size calculation failed",{cause:h}))}if(!Number.isSafeInteger(a)||a<0)return this.rejectAdmission(new i("invalid_size","Egress size must be a non-negative safe integer"));if(a>this.options.maxPendingBytes)return this.rejectAdmission(new i("oversized",`Egress value requires ${a} bytes; limit is ${this.options.maxPendingBytes}`));if(this.pending.length>=this.options.maxPendingItems||this.pendingBytes+a>this.options.maxPendingBytes)return this.rejectAdmission(new i("overflow",`Egress pending limit exceeded (${this.pending.length} items, ${this.pendingBytes} bytes)`));let t,k,c=new Promise((h,m)=>{t=h,k=m});return T(c),this.nextSequence+=1,this.pending.push({value:s,bytes:a,sequence:this.nextSequence,resolve:t,reject:k,completion:c}),this.pendingBytes+=a,this.startDrain(),{accepted:!0,completion:c}}flush(){if(this.failure){let c=Promise.reject(this.failure);return T(c),c}let s=this.nextSequence;if(s<=this.completedSequence)return Promise.resolve();let a,t,k=new Promise((c,h)=>{a=c,t=h});return T(k),this.flushWaiters.push({targetSequence:s,resolve:a,reject:t}),k}close(s){let a=s instanceof i?s:new i("closed","Egress was closed",{cause:s});this.fail(a)}stats(){return{closed:this.closed,pendingItems:this.pending.length,pendingBytes:this.pendingBytes}}handleAbort=()=>{this.fail(new i("aborted","Egress was aborted",{cause:this.options.signal?.reason}))};rejectAdmission(s){return this.fail(s),{accepted:!1,error:s}}startDrain(){if(this.draining||this.closed)return;this.draining=!0;let s=this.drain();T(s)}async drain(){try{while(!this.closed){let s=this.pending[0];if(!s)return;try{await this.writeOne(s.value)}catch(a){this.fail(this.normalizeWriteError(a));return}if(this.closed||this.pending[0]!==s)return;this.pending.shift(),this.pendingBytes-=s.bytes,this.completedSequence=s.sequence,s.resolve(),this.settleFlushWaiters()}}finally{if(this.draining=!1,!this.closed&&this.pending.length>0)this.startDrain()}}async writeOne(s){let a=new AbortController;this.activeWriteAbort=a;let t,k,c=new Promise((S,f)=>{k=f});T(c),this.activeWriteStop=k;let h=Promise.resolve().then(()=>this.options.write(s,a.signal));T(h);let m=new Promise((S,f)=>{t=setTimeout(()=>{let D=new i("write_timeout",`Egress write timed out after ${this.options.writeTimeoutMs}ms`);a.abort(D),f(D)},this.options.writeTimeoutMs),this.activeWriteTimeout=t});T(m);try{await Promise.race([h,m,c])}finally{if(t!==void 0)clearTimeout(t);if(this.activeWriteTimeout===t)this.activeWriteTimeout=void 0;if(this.activeWriteAbort===a)this.activeWriteAbort=void 0;if(this.activeWriteStop===k)this.activeWriteStop=void 0}}normalizeWriteError(s){if(s instanceof i)return s;return new i("write_failed","Egress write failed",{cause:s})}fail(s){if(this.closed)return;if(s.pendingItems??=this.pending.length,s.pendingBytes??=this.pendingBytes,this.closed=!0,this.failure=s,this.options.signal?.removeEventListener("abort",this.handleAbort),this.activeWriteTimeout!==void 0)clearTimeout(this.activeWriteTimeout),this.activeWriteTimeout=void 0;this.activeWriteAbort?.abort(s),this.activeWriteStop?.(s),this.activeWriteAbort=void 0,this.activeWriteStop=void 0;let a=this.pending.splice(0);this.pendingBytes=0;for(let t of a)t.reject(s);for(let t of this.flushWaiters.splice(0))t.reject(s);try{this.options.onFailure?.(s)}catch{}}settleFlushWaiters(){for(let s=0;s<this.flushWaiters.length;){let a=this.flushWaiters[s];if(a.targetSequence>this.completedSequence){s+=1;continue}this.flushWaiters.splice(s,1),a.resolve()}}assertPositiveInteger(s,a){if(!Number.isSafeInteger(s)||s<=0)throw RangeError(`${a} must be a positive safe integer`)}}
|
|
2
2
|
export{C as B,$ as C,V as D,x as E,i as F,K as G};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{bh as A1,ch as L0,dh as M1}from"./chunk-3kszepm6.js";import{jh as v0}from"./chunk-wcps5gjm.js";import{sh as SO,th as F1}from"./chunk-vbjgcn49.js";import{wh as x1}from"./chunk-06hkf59s.js";import{xh as A0,zh as J0}from"./chunk-
|
|
1
|
+
import{bh as A1,ch as L0,dh as M1}from"./chunk-3kszepm6.js";import{jh as v0}from"./chunk-wcps5gjm.js";import{sh as SO,th as F1}from"./chunk-vbjgcn49.js";import{wh as x1}from"./chunk-06hkf59s.js";import{xh as A0,zh as J0}from"./chunk-wv8dy886.js";import{Mi as z0,Ni as WO,Ri as b0}from"./chunk-9a0cy4z7.js";import{bj as M}from"./chunk-2f8d0km4.js";import{Dj as P,Ej as S,Fj as u,Hj as L,Kj as l1}from"./chunk-2mk914vk.js";import{Xj as c0}from"./chunk-s1cs5ga0.js";import{ck as N}from"./chunk-rvs364rz.js";import{zk as qO}from"./chunk-4wx5sya5.js";import N0 from"node:path";import YO from"node:path";import y0 from"node:fs";import W0 from"node:os";import E from"node:path";import pO from"yaml";var V1=2000,j1=50,B1=1000,X4={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:V1},findings:{type:"array",maxItems:j1,items:{type:"string",minLength:1,maxLength:B1}}},required:["verdict","summary","findings"],additionalProperties:!1};function U1(O,$){let Q=O.trim().replaceAll(/\s+/g," ");if($)Q=Q.replaceAll($,".");return Q.replace(/\bBearer\s+[^\s"'`]+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted-key]").replace(/\b(api(?:[_-]?|\s+)key|access(?:[_-]?|\s+)token|authorization|cookie|password|passwd|refresh(?:[_-]?|\s+)token|secret|session(?:[_-]?|\s+)token)\b(\s*[:=]\s*)([^\s,;]+)/gi,"$1$2[redacted]")}function kO(O){if(O.length<=v0)return O;let $=" [verification feedback truncated]",Q=O.slice(0,v0-$.length);if(/[\uD800-\uDBFF]$/.test(Q))Q=Q.slice(0,-1);return Q.trimEnd()+$}function S1(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O;if($.verdict!=="pass"&&$.verdict!=="fail"&&$.verdict!=="partial"||typeof $.summary!=="string"||!$.summary.trim()||$.summary.length>V1||!Array.isArray($.findings)||$.findings.length>j1||!$.findings.every((Q)=>typeof Q==="string"&&Q.trim().length>0&&Q.length<=B1))return;return{verdict:$.verdict,summary:$.summary.trim(),findings:$.findings.map((Q)=>Q.trim())}}function H4(O,$){let Q=S1(O);if(!Q)return;let Z=U1(Q.summary,$),J=Q.findings.map((K)=>U1(K,$));return kO([Z,J.length>0?`Findings:
|
|
2
2
|
${J.map((K)=>`- ${K}`).join(`
|
|
3
3
|
`)}`:""].filter(Boolean).join(`
|
|
4
4
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{wg as a,xg as b,yg as c,zg as d}from"./chunk-
|
|
1
|
+
import{wg as a,xg as b,yg as c,zg as d}from"./chunk-01framym.js";import"./chunk-9a0cy4z7.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-s1cs5ga0.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,d as createProcessModelResources,a as cloneWorkspaceModelConfig};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{vc as H8}from"./chunk-wm896gnx.js";import{$d as P6,Ac as p1,Cc as X$,Dd as f2,Ed as j8,Fd as z8,Gd as Z6,Hd as r1,Id as B8,Jd as U8,Kd as u1,Od as uJ,Xd as I0,Zd as N6,_d as m1,ge as J1,sd as G2,ud as F2,vd as L2,wc as U$,wd as Q6,xd as K6,yc as B$,zc as q2}from"./chunk-025n9zx5.js";import{le as X8}from"./chunk-9xbwtjac.js";import{De as w1,oe as D0,re as W2,se as C$}from"./chunk-3a217980.js";import{cg as M2}from"./chunk-7xhw74hk.js";import{dg as Q8,eg as c0,fg as $8,gg as xJ,ig as I1,jg as A6,kg as vJ,lg as CJ,og as IJ}from"./chunk-z2k08r1h.js";import{bh as Z$,ch as l0,fh as K8}from"./chunk-3kszepm6.js";import{kh as d2,oh as aJ}from"./chunk-wcps5gjm.js";import{zh as b$}from"./chunk-mttsbvty.js";import{Ui as R$}from"./chunk-kv458q06.js";import{bj as z0}from"./chunk-2f8d0km4.js";import{Dj as b0}from"./chunk-2mk914vk.js";import{Xj as D2}from"./chunk-rn61n450.js";import{Bk as zJ,Ck as i1,Ek as B2,Jk as U2,Kk as w2,fk as z2,uk as Q2,vk as K2,yk as Y1}from"./chunk-4wx5sya5.js";import{Mk as vZ}from"./chunk-eg3ms291.js";function y$($){return $.role==="system"&&Array.isArray($.content)}function P$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class T1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,Z){this.context=$;let J=$.messages.find(y$);if(this._contextualSystemMessages=$.messages.filter(P$),J)this.systemMessages=[J,...this._contextualSystemMessages];else if(Z)this.systemMessages=[{role:"system",content:[{type:"text",text:Z,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!y$(W)&&!P$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}get contextRevision(){return this._contextRevision}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!P$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(y$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,Z){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(Z)}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((Z)=>Z.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((Z)=>!y$(Z)&&!P$(Z)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(P$),this._history=$.filter((Z)=>!y$(Z)&&!P$(Z)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let Z=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages(),this._history.length!==Z[0]||this._pending.length!==Z[1]||this._contextualSystemMessages.length!==Z[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function l6($){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 i6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function r6($,Z,J){return{...$,usage:$.usage+Z,lastOutputDelta:Z,consecutiveContinuations:J?$.consecutiveContinuations+1:0}}import K$ from"node:path";var P8=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"]),y8=/^(LD_.+|DYLD_.+|PATH)$/,n6=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function s$($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],V=W.match(n6);if(!V)break;let Q=V[1];if(!P8.has(Q))break;Z=Y}return Z}function v5($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],V=W.match(n6);if(!V)break;let Q=V[1];if(y8.test(Q))break;Z=Y}return Z}var _8=[/^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 _Z($){let Z=$,J=!0;while(J){J=!1;for(let W of _8){let Y=Z.match(W);if(Y){Z=Z.slice(Y[0].length),J=!0;break}}if(Z.startsWith("-- "))Z=Z.slice(3),J=!0}return Z}function t$($){let Z=[],J="",W=!1,Y=!1,V=!1;for(let Q=0;Q<$.length;Q++){let K=$[Q];if(V){J+=K,V=!1;continue}if(K==="\\"&&!W){J+=K,V=!0;continue}if(K==="'"&&!Y){W=!W,J+=K;continue}if(K==='"'&&!W){Y=!Y,J+=K;continue}if(W||Y){J+=K;continue}if(K==="|"){if(Q+1<$.length&&$[Q+1]==="|"){if(J.trim())Z.push(J.trim());J="",Q++;continue}return null}if(K===">"||K==="<")return null;if(K==="&"&&Q+1<$.length&&$[Q+1]==="&"){if(J.trim())Z.push(J.trim());J="",Q++;continue}if(K==="&")return null;if(K===";"){if(J.trim())Z.push(J.trim());J="";continue}J+=K}if(J.trim())Z.push(J.trim());return Z.length>0?Z:null}function o6($){let Z=!1,J=!1,W=!1;for(let Y=0;Y<$.length;Y++){let V=$[Y];if(W){W=!1;continue}if(V==="\\"&&!Z){W=!0;continue}if(V==="'"&&!J){Z=!Z;continue}if(V==='"'&&!Z){J=!J;continue}if(Z)continue;if(V==="$"){let Q=$[Y+1];if(Q&&/[A-Za-z_@*#?!$0-9({]/.test(Q))return!0}if(V==="`")return!0;if(J)continue;if(V==="|")return!0;if(V===">"||V==="<")return!0;if(V==="{"){let Q=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(Q)||/^\{[^}]*\.\.[^}]*\}/.test(Q))return!0}}return!1}function Q$($){let Z=[],J="",W=!1,Y=!1,V=!1;for(let Q=0;Q<$.length;Q++){let K=$[Q];if(V){J+=K,V=!1;continue}if(K==="\\"&&!W){if(V=!0,Y){let X=$[Q+1];if(X&&'$`"\\'.includes(X))continue;J+=K,V=!1}continue}if(K==="'"&&!Y){W=!W;continue}if(K==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(K)){if(J)Z.push(J),J="";continue}J+=K}if(J)Z.push(J);return Z}var b8=new Set(["npm","pnpm","yarn","bun"]),a6=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),E8=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),S8=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function R8($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function s6($){return $.replace(/\s+2>&1\s*$/,"").trim()}function T8($,Z,J){if(!J||Z.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=Q$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let V=Y[1];if(!V||V==="-")return;let Q=K$.isAbsolute(V)?K$.resolve(V):K$.resolve(J,V);if(!X$.isWithinWorkspace(Q,J))return;return W[2]?.trim()||void 0}function M8($){let Z=[],J=!1,W=!1,Y=!1;for(let V=0;V<$.length;V++){let Q=$[V];if(Y){Y=!1;continue}if(Q==="\\"&&!J){Y=!0;continue}if(Q==="'"&&!W){J=!J;continue}if(Q==='"'&&!J){W=!W;continue}if(Q!=="|"||J||W)continue;if($[V+1]==="|")return;Z.push(V)}return Z}function k8($){let Z=Q$($),[J,W,Y]=Z;if(J!=="head"&&J!=="tail")return!1;if(Z.length===1)return!0;let V=(Q)=>Q!==void 0&&/^[1-9]\d{0,4}$/.test(Q);if(Z.length===2)return W?.startsWith("--lines=")&&V(W.slice(8))||W?.startsWith("-")&&V(W.slice(1));return Z.length===3&&(W==="-n"||W==="--lines")&&V(Y)}function h8($){let Z=s6($.replace(S8,"").trim()),J=M8(Z);if(!J)return;if(J.length===0)return t6(Z);if(J.length!==1)return;let W=J[0];if(W===void 0)return;let Y=s6(Z.slice(0,W).trim()),V=Z.slice(W+1).trim();if(!Y||!k8(V))return;return t6(Y)}function t6($){let J=t$($)?.at(-1);if(!J)return $;let W=Q$(J),[Y,V]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&V==="vitest")||W.some((K)=>K==="--configLoader"||K.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function _$($,Z){let J=h8($);if(!J)return!1;let W=s$(J),Y=t$(W);if(!Y||o6(W)||/[\r\n]/.test(W))return!1;let V=Y.length===1?Y[0]:T8(W,Y,Z);if(!V)return!1;let Q=Q$(V);if(Q.length===0||Q.some((z)=>[...E8].some((B)=>z===B||z.startsWith(`${B}=`))))return!1;let[K,X,H]=Q;if(b8.has(K??""))return R8(X==="run"?H:X)||X==="--test";if((K==="npx"||K==="bunx")&&a6.has(X??""))return!0;if(a6.has(K??""))return!0;if(K==="node"&&X==="--test")return!0;if(K==="go"&&["build","test","vet"].includes(X??""))return!0;return K==="cargo"&&["build","check","clippy","test"].includes(X??"")}function p5($,Z){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!Z)return!K$.isAbsolute($);let J=K$.isAbsolute($)?K$.resolve($):K$.resolve(Z,$);return X$.isWithinWorkspace(J,Z)}var bZ=b0("Agent"),x8=3;function EZ($,Z,J){if($!=="length")return{action:"none"};if(Z>=x8)return{action:"truncated"};if(l6(J)==="stop")return bZ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var v8=[/:\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],C8=/```[\s\S]{50,}```/,e6="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",I8=2;function SZ($,Z,J=!0){if(!$||Z>=I8)return{action:"none"};if(!J&&C8.test($))return{action:"retry",prompt:e6};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(v8.some((Q)=>Q.test(W)))return{action:"retry",prompt:e6};return{action:"none"}}var u8=[/\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}(?:测试|单测|集成测试|检查|构建)/],$J={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},g8={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},p8="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.",d8="Required verification did not run successfully before the retry limit.",m8=3;function JJ($,Z,J,W){if(!J.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(Z)){$.clear();return}if(Z==="Bash"&&typeof J.metadata?.command==="string"&&J.metadata.exit_code===0&&_$(J.metadata.command,W)){$.add(J.metadata.command);return}if(!["Task","TaskOutput"].includes(Z))return;let Y=J.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let V of Y)if(typeof V==="string"&&_$(V,W))$.add(V)}function RZ($,Z,J){if(!$||!u8.some((X)=>X.test($)))return{action:"none"};let W=Object.keys($J).filter((X)=>$J[X].test($)),Y=[...Z],V=W.filter((X)=>!Y.some((H)=>g8[X].test(H)));if(W.length>0?V.length===0:Y.some((X)=>_$(X)))return{action:"none"};if(J>=m8)return{action:"fail",message:d8};let K=W.length>1&&V.length>0?` Missing successful verification categories: ${V.join(", ")}.`:"";return{action:"retry",prompt:`${p8}${K}`}}var c8=[/\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 YJ($){return typeof $==="string"&&WJ.some((Z)=>Z.test($))}var l8=[/\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|子代理)/],i8=[/\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 r8($){if(typeof $!=="string")return;if(i8.some((Z)=>Z.test($)))return"multiple-allowed";return l8.some((Z)=>Z.test($))?"required":void 0}function $1($){for(let Z of $){let J=r8(Z);if(J!==void 0)return J==="required"}return!1}var n8="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.",o8="Required delegation did not complete before the retry limit.",a8=3;function VJ($,Z,J){let W=(typeof $==="string"?[$]:$??[]).map((Q)=>Q.trim()).filter(Boolean),Y=$1(W),V=!1;if(!Y)for(let Q of W){if(WJ.some((K)=>K.test(Q)))break;if(c8.some((K)=>K.test(Q))){V=!0;break}}if(W.length===0||!Y&&!V||Z.has("Task"))return{action:"none"};if(J>=a8)return{action:"fail",message:o8};return{action:"retry",prompt:n8}}var s8=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],t8=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],e8=[/\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 e8.reduce((Z,J)=>Z.replace(J," "),$)}function M1($){if(typeof $!=="string")return!1;let Z=QJ($);return s8.some((J)=>J.test(Z))}var $9="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.",Z9="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.",J9="Required worktree lifecycle did not complete before the retry limit.",W9=3;function KJ($,Z,J){if(!$)return{action:"none"};let W=QJ($);if(!M1(W))return{action:"none"};let Y=t8.some((Q)=>Q.test(W));if(Z.has("TaskWorktree"))return{action:"none"};let V=!Z.has("EnterWorktree")?"EnterWorktree":Y&&!Z.has("ExitWorktree")?"ExitWorktree":void 0;if(!V)return{action:"none"};if(J>=W9)return{action:"fail",message:J9};return{action:"retry",tool:V,prompt:V==="EnterWorktree"?$9:Z9}}var ZJ=30000;async function TZ($){try{let J=b$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??z0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((V)=>{W=setTimeout(()=>V("timeout"),ZJ)});try{let V=await Promise.race([J,Y]);if(V==="timeout")return bZ.warn(`[Loop] Stop hook 超时 (${ZJ}ms),按 shouldStop: true 处理`),{action:"stop"};let Q=V;if(!Q.shouldStop)return{action:"continue",reason:Q.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(Z){return bZ.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}async function Y9($,Z){let J;while(!(J=await $.next()).done)if(Z)await Z(J.value);return J.value}var V9=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function Q9($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((Z)=>{if(typeof Z==="string")return Z;if(Z&&typeof Z==="object"&&"text"in Z){let J=Z.text;return typeof J==="string"?J:""}return""}).join(" ");return""}function K9($){let Z=$;for(let X of V9)Z=Z.replace(X," ");Z=Z.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let J=Z.replace(/\s+/g," ").trim();if(!J)return"";let W=J.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:J;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let V=Y.slice(0,60),Q=V.lastIndexOf(" ");return`${(Q>36?V.slice(0,Q):V).trimEnd()}…`}function XJ($){return K9(Q9($))}import{EventEmitter as X9}from"events";import HJ from"node:path";function MZ($){if(zJ($.sessionId),!HJ.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:HJ.resolve($.projectPath)}}function jJ($){let Z=MZ($);return JSON.stringify([Z.projectPath,Z.sessionId])}function $3($,Z){return jJ($)===jJ(Z)}class E$ extends X9{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!E$.instance)E$.instance=new E$;return E$.instance}publish($,Z,J,W){let Y=MZ($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:Z,...W!==void 0?{seq:W}:{},properties:J})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var Z1=E$.getInstance();var s0=b0("Agent"),k1=new Set;async function H9($,Z){let J=$.sessionId;if(!J||$.subagentInfo)return;if(k1.has(J))return;if(k1.size>=5000)k1.clear();k1.add(J);try{let W=$.workspaceRoot,Y=await J1.findSessionMetadata(J,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let V=XJ(Z);if(!V)return;await J1.updateSessionMetadata(J,Y.projectPath,{title:V}),Z1.publish({sessionId:J,projectPath:Y.projectPath},"session.updated",{title:V})}catch(W){s0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var kZ=`<turn_aborted>
|
|
1
|
+
import{vc as H8}from"./chunk-wm896gnx.js";import{$d as P6,Ac as p1,Cc as X$,Dd as f2,Ed as j8,Fd as z8,Gd as Z6,Hd as r1,Id as B8,Jd as U8,Kd as u1,Od as uJ,Xd as I0,Zd as N6,_d as m1,ge as J1,sd as G2,ud as F2,vd as L2,wc as U$,wd as Q6,xd as K6,yc as B$,zc as q2}from"./chunk-f71j03pq.js";import{le as X8}from"./chunk-9xbwtjac.js";import{De as w1,oe as D0,re as W2,se as C$}from"./chunk-3a217980.js";import{cg as M2}from"./chunk-7xhw74hk.js";import{dg as Q8,eg as c0,fg as $8,gg as xJ,ig as I1,jg as A6,kg as vJ,lg as CJ,og as IJ}from"./chunk-z2k08r1h.js";import{bh as Z$,ch as l0,fh as K8}from"./chunk-3kszepm6.js";import{kh as d2,oh as aJ}from"./chunk-wcps5gjm.js";import{zh as b$}from"./chunk-wv8dy886.js";import{Ui as R$}from"./chunk-kv458q06.js";import{bj as z0}from"./chunk-2f8d0km4.js";import{Dj as b0}from"./chunk-2mk914vk.js";import{Xj as D2}from"./chunk-s1cs5ga0.js";import{Bk as zJ,Ck as i1,Ek as B2,Jk as U2,Kk as w2,fk as z2,uk as Q2,vk as K2,yk as Y1}from"./chunk-4wx5sya5.js";import{Mk as vZ}from"./chunk-eg3ms291.js";function y$($){return $.role==="system"&&Array.isArray($.content)}function P$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class T1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,Z){this.context=$;let J=$.messages.find(y$);if(this._contextualSystemMessages=$.messages.filter(P$),J)this.systemMessages=[J,...this._contextualSystemMessages];else if(Z)this.systemMessages=[{role:"system",content:[{type:"text",text:Z,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!y$(W)&&!P$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}get contextRevision(){return this._contextRevision}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!P$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(y$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,Z){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(Z)}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((Z)=>Z.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((Z)=>!y$(Z)&&!P$(Z)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(P$),this._history=$.filter((Z)=>!y$(Z)&&!P$(Z)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let Z=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages(),this._history.length!==Z[0]||this._pending.length!==Z[1]||this._contextualSystemMessages.length!==Z[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function l6($){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 i6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function r6($,Z,J){return{...$,usage:$.usage+Z,lastOutputDelta:Z,consecutiveContinuations:J?$.consecutiveContinuations+1:0}}import K$ from"node:path";var P8=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"]),y8=/^(LD_.+|DYLD_.+|PATH)$/,n6=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function s$($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],V=W.match(n6);if(!V)break;let Q=V[1];if(!P8.has(Q))break;Z=Y}return Z}function v5($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],V=W.match(n6);if(!V)break;let Q=V[1];if(y8.test(Q))break;Z=Y}return Z}var _8=[/^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 _Z($){let Z=$,J=!0;while(J){J=!1;for(let W of _8){let Y=Z.match(W);if(Y){Z=Z.slice(Y[0].length),J=!0;break}}if(Z.startsWith("-- "))Z=Z.slice(3),J=!0}return Z}function t$($){let Z=[],J="",W=!1,Y=!1,V=!1;for(let Q=0;Q<$.length;Q++){let K=$[Q];if(V){J+=K,V=!1;continue}if(K==="\\"&&!W){J+=K,V=!0;continue}if(K==="'"&&!Y){W=!W,J+=K;continue}if(K==='"'&&!W){Y=!Y,J+=K;continue}if(W||Y){J+=K;continue}if(K==="|"){if(Q+1<$.length&&$[Q+1]==="|"){if(J.trim())Z.push(J.trim());J="",Q++;continue}return null}if(K===">"||K==="<")return null;if(K==="&"&&Q+1<$.length&&$[Q+1]==="&"){if(J.trim())Z.push(J.trim());J="",Q++;continue}if(K==="&")return null;if(K===";"){if(J.trim())Z.push(J.trim());J="";continue}J+=K}if(J.trim())Z.push(J.trim());return Z.length>0?Z:null}function o6($){let Z=!1,J=!1,W=!1;for(let Y=0;Y<$.length;Y++){let V=$[Y];if(W){W=!1;continue}if(V==="\\"&&!Z){W=!0;continue}if(V==="'"&&!J){Z=!Z;continue}if(V==='"'&&!Z){J=!J;continue}if(Z)continue;if(V==="$"){let Q=$[Y+1];if(Q&&/[A-Za-z_@*#?!$0-9({]/.test(Q))return!0}if(V==="`")return!0;if(J)continue;if(V==="|")return!0;if(V===">"||V==="<")return!0;if(V==="{"){let Q=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(Q)||/^\{[^}]*\.\.[^}]*\}/.test(Q))return!0}}return!1}function Q$($){let Z=[],J="",W=!1,Y=!1,V=!1;for(let Q=0;Q<$.length;Q++){let K=$[Q];if(V){J+=K,V=!1;continue}if(K==="\\"&&!W){if(V=!0,Y){let X=$[Q+1];if(X&&'$`"\\'.includes(X))continue;J+=K,V=!1}continue}if(K==="'"&&!Y){W=!W;continue}if(K==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(K)){if(J)Z.push(J),J="";continue}J+=K}if(J)Z.push(J);return Z}var b8=new Set(["npm","pnpm","yarn","bun"]),a6=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),E8=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),S8=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function R8($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function s6($){return $.replace(/\s+2>&1\s*$/,"").trim()}function T8($,Z,J){if(!J||Z.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=Q$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let V=Y[1];if(!V||V==="-")return;let Q=K$.isAbsolute(V)?K$.resolve(V):K$.resolve(J,V);if(!X$.isWithinWorkspace(Q,J))return;return W[2]?.trim()||void 0}function M8($){let Z=[],J=!1,W=!1,Y=!1;for(let V=0;V<$.length;V++){let Q=$[V];if(Y){Y=!1;continue}if(Q==="\\"&&!J){Y=!0;continue}if(Q==="'"&&!W){J=!J;continue}if(Q==='"'&&!J){W=!W;continue}if(Q!=="|"||J||W)continue;if($[V+1]==="|")return;Z.push(V)}return Z}function k8($){let Z=Q$($),[J,W,Y]=Z;if(J!=="head"&&J!=="tail")return!1;if(Z.length===1)return!0;let V=(Q)=>Q!==void 0&&/^[1-9]\d{0,4}$/.test(Q);if(Z.length===2)return W?.startsWith("--lines=")&&V(W.slice(8))||W?.startsWith("-")&&V(W.slice(1));return Z.length===3&&(W==="-n"||W==="--lines")&&V(Y)}function h8($){let Z=s6($.replace(S8,"").trim()),J=M8(Z);if(!J)return;if(J.length===0)return t6(Z);if(J.length!==1)return;let W=J[0];if(W===void 0)return;let Y=s6(Z.slice(0,W).trim()),V=Z.slice(W+1).trim();if(!Y||!k8(V))return;return t6(Y)}function t6($){let J=t$($)?.at(-1);if(!J)return $;let W=Q$(J),[Y,V]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&V==="vitest")||W.some((K)=>K==="--configLoader"||K.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function _$($,Z){let J=h8($);if(!J)return!1;let W=s$(J),Y=t$(W);if(!Y||o6(W)||/[\r\n]/.test(W))return!1;let V=Y.length===1?Y[0]:T8(W,Y,Z);if(!V)return!1;let Q=Q$(V);if(Q.length===0||Q.some((z)=>[...E8].some((B)=>z===B||z.startsWith(`${B}=`))))return!1;let[K,X,H]=Q;if(b8.has(K??""))return R8(X==="run"?H:X)||X==="--test";if((K==="npx"||K==="bunx")&&a6.has(X??""))return!0;if(a6.has(K??""))return!0;if(K==="node"&&X==="--test")return!0;if(K==="go"&&["build","test","vet"].includes(X??""))return!0;return K==="cargo"&&["build","check","clippy","test"].includes(X??"")}function p5($,Z){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!Z)return!K$.isAbsolute($);let J=K$.isAbsolute($)?K$.resolve($):K$.resolve(Z,$);return X$.isWithinWorkspace(J,Z)}var bZ=b0("Agent"),x8=3;function EZ($,Z,J){if($!=="length")return{action:"none"};if(Z>=x8)return{action:"truncated"};if(l6(J)==="stop")return bZ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var v8=[/:\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],C8=/```[\s\S]{50,}```/,e6="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",I8=2;function SZ($,Z,J=!0){if(!$||Z>=I8)return{action:"none"};if(!J&&C8.test($))return{action:"retry",prompt:e6};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(v8.some((Q)=>Q.test(W)))return{action:"retry",prompt:e6};return{action:"none"}}var u8=[/\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}(?:测试|单测|集成测试|检查|构建)/],$J={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},g8={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},p8="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.",d8="Required verification did not run successfully before the retry limit.",m8=3;function JJ($,Z,J,W){if(!J.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(Z)){$.clear();return}if(Z==="Bash"&&typeof J.metadata?.command==="string"&&J.metadata.exit_code===0&&_$(J.metadata.command,W)){$.add(J.metadata.command);return}if(!["Task","TaskOutput"].includes(Z))return;let Y=J.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let V of Y)if(typeof V==="string"&&_$(V,W))$.add(V)}function RZ($,Z,J){if(!$||!u8.some((X)=>X.test($)))return{action:"none"};let W=Object.keys($J).filter((X)=>$J[X].test($)),Y=[...Z],V=W.filter((X)=>!Y.some((H)=>g8[X].test(H)));if(W.length>0?V.length===0:Y.some((X)=>_$(X)))return{action:"none"};if(J>=m8)return{action:"fail",message:d8};let K=W.length>1&&V.length>0?` Missing successful verification categories: ${V.join(", ")}.`:"";return{action:"retry",prompt:`${p8}${K}`}}var c8=[/\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 YJ($){return typeof $==="string"&&WJ.some((Z)=>Z.test($))}var l8=[/\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|子代理)/],i8=[/\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 r8($){if(typeof $!=="string")return;if(i8.some((Z)=>Z.test($)))return"multiple-allowed";return l8.some((Z)=>Z.test($))?"required":void 0}function $1($){for(let Z of $){let J=r8(Z);if(J!==void 0)return J==="required"}return!1}var n8="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.",o8="Required delegation did not complete before the retry limit.",a8=3;function VJ($,Z,J){let W=(typeof $==="string"?[$]:$??[]).map((Q)=>Q.trim()).filter(Boolean),Y=$1(W),V=!1;if(!Y)for(let Q of W){if(WJ.some((K)=>K.test(Q)))break;if(c8.some((K)=>K.test(Q))){V=!0;break}}if(W.length===0||!Y&&!V||Z.has("Task"))return{action:"none"};if(J>=a8)return{action:"fail",message:o8};return{action:"retry",prompt:n8}}var s8=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],t8=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],e8=[/\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 e8.reduce((Z,J)=>Z.replace(J," "),$)}function M1($){if(typeof $!=="string")return!1;let Z=QJ($);return s8.some((J)=>J.test(Z))}var $9="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.",Z9="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.",J9="Required worktree lifecycle did not complete before the retry limit.",W9=3;function KJ($,Z,J){if(!$)return{action:"none"};let W=QJ($);if(!M1(W))return{action:"none"};let Y=t8.some((Q)=>Q.test(W));if(Z.has("TaskWorktree"))return{action:"none"};let V=!Z.has("EnterWorktree")?"EnterWorktree":Y&&!Z.has("ExitWorktree")?"ExitWorktree":void 0;if(!V)return{action:"none"};if(J>=W9)return{action:"fail",message:J9};return{action:"retry",tool:V,prompt:V==="EnterWorktree"?$9:Z9}}var ZJ=30000;async function TZ($){try{let J=b$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??z0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((V)=>{W=setTimeout(()=>V("timeout"),ZJ)});try{let V=await Promise.race([J,Y]);if(V==="timeout")return bZ.warn(`[Loop] Stop hook 超时 (${ZJ}ms),按 shouldStop: true 处理`),{action:"stop"};let Q=V;if(!Q.shouldStop)return{action:"continue",reason:Q.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(Z){return bZ.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}async function Y9($,Z){let J;while(!(J=await $.next()).done)if(Z)await Z(J.value);return J.value}var V9=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function Q9($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((Z)=>{if(typeof Z==="string")return Z;if(Z&&typeof Z==="object"&&"text"in Z){let J=Z.text;return typeof J==="string"?J:""}return""}).join(" ");return""}function K9($){let Z=$;for(let X of V9)Z=Z.replace(X," ");Z=Z.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let J=Z.replace(/\s+/g," ").trim();if(!J)return"";let W=J.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:J;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let V=Y.slice(0,60),Q=V.lastIndexOf(" ");return`${(Q>36?V.slice(0,Q):V).trimEnd()}…`}function XJ($){return K9(Q9($))}import{EventEmitter as X9}from"events";import HJ from"node:path";function MZ($){if(zJ($.sessionId),!HJ.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:HJ.resolve($.projectPath)}}function jJ($){let Z=MZ($);return JSON.stringify([Z.projectPath,Z.sessionId])}function $3($,Z){return jJ($)===jJ(Z)}class E$ extends X9{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!E$.instance)E$.instance=new E$;return E$.instance}publish($,Z,J,W){let Y=MZ($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:Z,...W!==void 0?{seq:W}:{},properties:J})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var Z1=E$.getInstance();var s0=b0("Agent"),k1=new Set;async function H9($,Z){let J=$.sessionId;if(!J||$.subagentInfo)return;if(k1.has(J))return;if(k1.size>=5000)k1.clear();k1.add(J);try{let W=$.workspaceRoot,Y=await J1.findSessionMetadata(J,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let V=XJ(Z);if(!V)return;await J1.updateSessionMetadata(J,Y.projectPath,{title:V}),Z1.publish({sessionId:J,projectPath:Y.projectPath},"session.updated",{title:V})}catch(W){s0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var kZ=`<turn_aborted>
|
|
2
2
|
The previous turn was interrupted. Commands or tool calls may have partially completed; inspect the workspace and running processes before retrying.
|
|
3
3
|
</turn_aborted>`,H$="Tool execution was blocked because its durable call record could not be committed. No tool side effect was started.",BJ="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 S$ extends Error{phase;constructor($,Z){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.",Z);this.phase=$;this.name="DurableConversationPersistenceError"}}function j$($){return $.executionEngine?.getContextManager()}async function m0($,Z,J,W=null,Y,V={}){let Q=V.required??$.executionEngine!==void 0;try{let K=j$($),X=typeof J==="string"?J.trim()!=="":J.some((H)=>H.type==="text"?H.text.trim()!=="":!0);if(K&&Z.sessionId&&X){let H=await K.saveMessage(Z.sessionId,"user",J,W,Y,Z.subagentInfo);if(Q&&!H)throw Error("Durable user-message commit returned no identity");if(Y?.clientVisible!==!1)H9(Z,J);return H}if(Q&&Z.sessionId&&X)throw Error("Durable user-message storage is unavailable")}catch(K){if(s0.warn("[Loop] 保存用户消息失败:",K),Q)throw new S$("user_message",{cause:K})}return null}async function x0($,Z,J,W,Y,V,Q={}){let K=Q.required??$.executionEngine!==void 0;try{let X=j$($),H=Boolean(J.trim()||Y?.trim());if(X&&Z.sessionId&&H){let z=await X.saveMessage(Z.sessionId,"assistant",J,W,V,Z.subagentInfo,Y);if(K&&!z)throw Error("Durable assistant-message commit returned no identity");return z}if(K&&Z.sessionId&&H)throw Error("Durable assistant-message storage is unavailable")}catch(X){if(s0.warn("[Loop] 保存助手消息失败:",X),K)throw new S$("assistant_message",{cause:X})}return null}async function UJ($,Z,J){try{let W=j$($);if(W&&Z.sessionId)return await W.saveMessage(Z.sessionId,"system",kZ,J,void 0,Z.subagentInfo)}catch(W){s0.warn("[Loop] 保存中断边界失败:",W)}return null}async function wJ($,Z,J,W,Y){try{let V=j$($);if(!V||!Z.sessionId||J.length===0)return null;return await V.saveMessage(Z.sessionId,"system",`<contextual-project-instructions-ref count="${J.length}" />`,Y,{contextualProjectRules:!0,ruleReferences:JSON.parse(JSON.stringify(J.map((Q)=>({...Q})))),triggerPaths:[...W]},Z.subagentInfo)}catch(V){s0.warn("[Loop] 保存 contextual project rules provenance 失败:",V)}return null}async function hZ($,Z,J,W,Y,V={}){try{let Q=j$($);if(Q&&Z.sessionId){let K=await Q.saveToolUse(Z.sessionId,J,W,Y,Z.subagentInfo,V.providerToolCallId);if(V.required&&!K)throw Error("Durable tool-use commit returned no identity");return K}if(V.required&&Z.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(Q){if(s0.warn("[Loop] 保存工具调用失败:",Q),V.required)throw Q}return null}async function h1($,Z,J,W,Y,V,Q,K,X,H={}){try{let z=j$($);if(z&&Z.sessionId){let B=await z.saveToolResult(Z.sessionId,J,W,Y,V,Q,Z.subagentInfo,K,X);if(H.required&&!B)throw Error("Durable tool-result commit returned no identity");return B}if(H.required&&Z.sessionId)throw Error("Durable tool-result storage is unavailable")}catch(z){if(s0.warn("[Loop] 保存工具结果失败:",z),H.required)throw z}return null}async function W1($,Z,J,W,Y={}){try{let V=j$($);if(V&&Z.sessionId){let Q=await V.saveCompaction(Z.sessionId,J,W,null);if(Y.required&&!Q)throw Error("Compaction checkpoint commit returned no identity");return Q||null}if(Y.required&&Z.sessionId)throw Error("Compaction checkpoint storage is unavailable")}catch(V){if(s0.warn("[Loop] 保存压缩数据失败:",V),Y.required)throw V}return null}async function f0($){let{deps:Z,context:J,state:W,assistantContent:Y,assistantReasoningContent:V,lastMessageUuid:Q,controlPrompt:K,controlMetadata:X}=$;W.appendAssistant({role:"assistant",content:Y,reasoningContent:V});let H=Q,z=await x0(Z,J,Y,H,V);if(z)H=z;if(K!==void 0){let B={role:"user",content:K};if(X)B.metadata=X;W.appendControl("user",B);let j=await m0(Z,J,B.content,H,X);if(j)H=j}return H}import{createHash as y6}from"node:crypto";import{promises as C9}from"node:fs";import I9 from"node:path";import{nanoid as e0}from"nanoid";import*as t from"node:fs/promises";import*as t0 from"node:path";import qJ from"write-file-atomic";var DJ={enabled:!0,maxIndexLines:200};var j9="memory",xZ="MEMORY.md",CZ="<!-- blade:auto-memory-topics:start -->",x1="<!-- blade:auto-memory-topics:end -->",z9={realpath:!1,retries:{retries:5,factor:1.2,minTimeout:20,maxTimeout:100,randomize:!0}},B9=new R$,GJ;function LJ($){return $.trim().replace(/\s+/g," ")}function U9($){return LJ($.replace(/^- \[\d{4}-\d{2}-\d{2}\] /,""))}function w9($){return[CZ,"## Auto-consolidated topics",...$.map((Z)=>`- [${Z}](${Z}.md)`),x1].join(`
|
|
4
4
|
`)}function D9($,Z){let J=w9(Z),W=$.indexOf(CZ),Y=$.indexOf(x1,Math.max(0,W));if(W>=0&&Y>=W)return $.slice(0,W)+J+$.slice(Y+x1.length);if(!$)return`${J}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Xj as d,Zj as h}from"./chunk-
|
|
1
|
+
import{Xj as d,Zj as h}from"./chunk-s1cs5ga0.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"max-queued-task-bytes":{alias:["maxQueuedTaskBytes"],type:"number",describe:"Maximum retained bytes across queued top-level tasks",group:"AI Options:",default:void 0},"max-resident-session-runtimes":{alias:["maxResidentSessionRuntimes"],type:"number",describe:"Maximum initialized Session runtimes resident in this process",group:"AI Options:",default:void 0},"session-runtime-idle-ms":{alias:["sessionRuntimeIdleMs"],type:"number",describe:"Idle time before an evictable Web Session runtime is evicted",group:"AI Options:",default:void 0},"max-resident-session-projections":{alias:["maxResidentSessionProjections"],type:"number",describe:"Maximum resident Session projections retained in this process",group:"AI Options:",default:void 0},"session-projection-idle-ms":{alias:["sessionProjectionIdleMs"],type:"number",describe:"Idle time before an evictable Session projection is evicted",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
|
|
2
2
|
export{q as qf,w as rf};
|