blade-code 0.10.78 → 0.10.80
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-n60hs2m0.js → chunk-03n2qfqm.js} +1 -1
- package/dist/{chunk-3bmsp8yv.js → chunk-0fs8vp48.js} +2 -2
- package/dist/{chunk-s3r32avd.js → chunk-1mjh959m.js} +1 -1
- package/dist/{chunk-tqjpaaa0.js → chunk-26h77cn2.js} +1 -1
- package/dist/{chunk-3cbfykzb.js → chunk-2baq1mf4.js} +1 -1
- package/dist/{chunk-fdcn0thm.js → chunk-483qnmqm.js} +1 -1
- package/dist/{chunk-5m8x01n9.js → chunk-4n3yf5n8.js} +1 -1
- package/dist/{chunk-w1zk41np.js → chunk-4vyfj372.js} +1 -1
- package/dist/{chunk-jswmz4fk.js → chunk-4ywbj4bb.js} +1 -1
- package/dist/{chunk-1j4smrfy.js → chunk-5f243y5p.js} +1 -1
- package/dist/{chunk-g6fw4y71.js → chunk-6fzzhspt.js} +1 -1
- package/dist/{chunk-vkz1vhbp.js → chunk-7k24492x.js} +1 -1
- package/dist/{chunk-tzq6155m.js → chunk-8ts93ywy.js} +20 -20
- package/dist/chunk-9y9bhhfx.js +169 -0
- package/dist/{chunk-wbap76bk.js → chunk-bexfrjpn.js} +1 -1
- package/dist/{chunk-96ye1aqq.js → chunk-crfbw7dj.js} +2 -2
- package/dist/{chunk-89yq5n68.js → chunk-dgg07z93.js} +1 -1
- package/dist/{chunk-s56p9w29.js → chunk-dkdapvdp.js} +1 -1
- package/dist/{chunk-ezs65v1m.js → chunk-dpk3yatp.js} +2 -2
- package/dist/{chunk-nmh9b40p.js → chunk-e9a1br9y.js} +1 -1
- package/dist/{chunk-m7xfm75q.js → chunk-f44wasww.js} +1 -1
- package/dist/{chunk-fyd1v6c0.js → chunk-fa7cygpw.js} +1 -1
- package/dist/{chunk-0vr244p2.js → chunk-g8swjz81.js} +1 -1
- package/dist/{chunk-72mk2y5d.js → chunk-gh91rrzh.js} +1 -1
- package/dist/{chunk-7az90ak3.js → chunk-hwtayzyn.js} +1 -1
- package/dist/{chunk-nykkq8c2.js → chunk-j5zq828f.js} +1 -1
- package/dist/{chunk-gwbanhxq.js → chunk-j9ysfhj9.js} +8 -6
- package/dist/{chunk-m4avjqx5.js → chunk-jscpxfwd.js} +1 -1
- package/dist/{chunk-03k5c0e3.js → chunk-jtmzdxbf.js} +1 -1
- package/dist/{chunk-m3vqjtz7.js → chunk-k80skq6e.js} +1 -1
- package/dist/{chunk-szhzvb57.js → chunk-pfdzgcza.js} +1 -1
- package/dist/chunk-rs3mp90v.js +1 -0
- package/dist/{chunk-wy9c9jj6.js → chunk-v1eakd9c.js} +1 -1
- package/dist/chunk-xhqvdrap.js +6 -0
- package/dist/{chunk-16wxxkev.js → chunk-y7fhg1gb.js} +1 -1
- package/dist/{chunk-d4z4kpvk.js → chunk-yr9mex38.js} +1 -1
- package/dist/chunk-zbrb26d5.js +1 -0
- package/package.json +1 -1
- package/dist/chunk-91w5bqyx.js +0 -1
- package/dist/chunk-9vrtjw9f.js +0 -1
- package/dist/chunk-bxks9zbr.js +0 -168
- package/dist/chunk-yd7bc0cm.js +0 -6
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{f as T,g as W,h as X,i as Y}from"./chunk-
|
|
1
|
+
import{f as T,g as W,h as X,i as Y}from"./chunk-crfbw7dj.js";import"./chunk-1mc7nfb4.js";import"./chunk-shq0pkxq.js";import"./chunk-2baq1mf4.js";import"./chunk-4ywbj4bb.js";import"./chunk-483qnmqm.js";import"./chunk-j9ysfhj9.js";import"./chunk-1mjh959m.js";import"./chunk-ky9q53m7.js";import"./chunk-9y9bhhfx.js";import"./chunk-r8wbvxn7.js";import"./chunk-8ts93ywy.js";import"./chunk-skw3b17a.js";import"./chunk-jwx10h5z.js";import{yd as R}from"./chunk-e9a1br9y.js";import"./chunk-h3w814js.js";import{Ud as Q}from"./chunk-y7fhg1gb.js";import"./chunk-v508x7cg.js";import"./chunk-c9e0fbyh.js";import"./chunk-seamt0j3.js";import"./chunk-33bpwkyk.js";import"./chunk-mygw13zd.js";import"./chunk-4n3yf5n8.js";import"./chunk-yr9mex38.js";import"./chunk-jzvbjn6e.js";import"./chunk-7nx0pzfk.js";import"./chunk-b9nhnzaj.js";import"./chunk-4vyfj372.js";import"./chunk-zkhb55jz.js";import"./chunk-jscpxfwd.js";import"./chunk-pfvgkexe.js";import"./chunk-qxn5bg5k.js";import"./chunk-reakyamv.js";import"./chunk-0141jad7.js";import"./chunk-eeb2945p.js";import"./chunk-b9vm7gns.js";import"./chunk-5nezhmnq.js";import"./chunk-h6a0nct6.js";import{Ch as M}from"./chunk-f44wasww.js";import"./chunk-0a0sj79a.js";import"./chunk-sj0k8cdf.js";import"./chunk-0ra945vt.js";import"./chunk-h0fh3j9w.js";import m from"chalk";import K from"open";var A=`
|
|
2
2
|
____ _ _
|
|
3
3
|
| __ )| | __ _ __| | ___
|
|
4
4
|
| _ \\| |/ _\` |/ _\` |/ _ \\
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$d as n,Od as a,Pd as b,Qd as c,Rd as d,Sd as e,Td as f,Ud as g,Vd as h,Wd as i,Xd as j,Yd as k,Zd as l,_d as m,ae as o,be as p,ce as q}from"./chunk-
|
|
1
|
+
import{$d as n,Od as a,Pd as b,Qd as c,Rd as d,Sd as e,Td as f,Ud as g,Vd as h,Wd as i,Xd as j,Yd as k,Zd as l,_d as m,ae as o,be as p,ce as q}from"./chunk-y7fhg1gb.js";import"./chunk-v508x7cg.js";import"./chunk-c9e0fbyh.js";import"./chunk-jscpxfwd.js";import"./chunk-pfvgkexe.js";import"./chunk-qxn5bg5k.js";import"./chunk-reakyamv.js";import"./chunk-0141jad7.js";import"./chunk-eeb2945p.js";import"./chunk-b9vm7gns.js";import"./chunk-5nezhmnq.js";import"./chunk-h6a0nct6.js";import"./chunk-f44wasww.js";import"./chunk-0a0sj79a.js";import"./chunk-sj0k8cdf.js";import"./chunk-0ra945vt.js";import"./chunk-h0fh3j9w.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{s as yz,t as hz}from"./chunk-
|
|
1
|
+
import{s as yz,t as hz}from"./chunk-2baq1mf4.js";import{u as b}from"./chunk-4ywbj4bb.js";import{A as Bz,v as Tz,w as jz,x as Xz,y as Dz,z as Lz}from"./chunk-483qnmqm.js";import{E as N,L as Zz,M as $z,Q as Qz,T as Wz,U as Yz,Y as Hz,ma as Gz,na as Fz,oa as Uz,pa as Vz}from"./chunk-j9ysfhj9.js";import{za as bz}from"./chunk-1mjh959m.js";import{Ba as Jz}from"./chunk-ky9q53m7.js";import{Eb as zz,jb as s,vb as e}from"./chunk-9y9bhhfx.js";import{Pb as k}from"./chunk-r8wbvxn7.js";import{Bc as o,Hc as I,Ic as n,Kc as x,Nc as t,Sc as P,Vc as F,gc as v,qc as l,rc as i,wc as r,zc as a}from"./chunk-8ts93ywy.js";import"./chunk-skw3b17a.js";import"./chunk-jwx10h5z.js";import{yd as Sz}from"./chunk-e9a1br9y.js";import"./chunk-h3w814js.js";import{Td as qz,Ud as Nz}from"./chunk-y7fhg1gb.js";import"./chunk-v508x7cg.js";import{de as C}from"./chunk-c9e0fbyh.js";import{ie as d}from"./chunk-seamt0j3.js";import"./chunk-33bpwkyk.js";import{te as Ez}from"./chunk-mygw13zd.js";import"./chunk-4n3yf5n8.js";import"./chunk-yr9mex38.js";import"./chunk-jzvbjn6e.js";import{jf as xz}from"./chunk-7nx0pzfk.js";import"./chunk-b9nhnzaj.js";import"./chunk-4vyfj372.js";import"./chunk-zkhb55jz.js";import{bg as Rz,eg as Pz}from"./chunk-jscpxfwd.js";import"./chunk-pfvgkexe.js";import"./chunk-qxn5bg5k.js";import{Ig as S,Jg as m,Kg as M}from"./chunk-reakyamv.js";import{Og as _z}from"./chunk-0141jad7.js";import"./chunk-eeb2945p.js";import{oh as T}from"./chunk-b9vm7gns.js";import"./chunk-5nezhmnq.js";import{vh as Oz,yh as Az}from"./chunk-h6a0nct6.js";import"./chunk-f44wasww.js";import"./chunk-0a0sj79a.js";import"./chunk-sj0k8cdf.js";import{Uh as p}from"./chunk-0ra945vt.js";import"./chunk-h0fh3j9w.js";import{Readable as dz,Writable as vz}from"node:stream";import*as y from"@agentclientprotocol/sdk";import Kz from"node:path";import{PROTOCOL_VERSION as pz,RequestError as mz}from"@agentclientprotocol/sdk";import{RequestError as Iz}from"@agentclientprotocol/sdk";import{nanoid as h}from"nanoid";var G=T("Agent");function c(z){if(!z)return{};return Object.fromEntries(z.map((Z)=>[Z.name,Z.value]))}function Cz(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:c(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:c("headers"in z?z.headers:void 0)};return null}function fz(z){let Z={};for(let J of z){let Y=Cz(J);if(Y)Z[J.name]=Y}return Z}function wz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((Z)=>{if(Z.type==="text")return Z.text?[{type:"text",text:Z.text}]:[];let J=Z.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(J);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function uz(z){let Z=n(z.metadata);return Z?[{type:"text",text:I(Z)}]:wz(z.content)}function gz(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
|
|
2
2
|
`)}function cz(z){if(!d(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...l("capacity"),resource:z.resource}}class E{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingPromptCompletion=null;pendingUserShell=null;pendingUserShellCompletion=null;pendingSideConversation=null;pendingSideConversationCompletion=null;pendingResumeRequested=!1;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;destroyFinished=!1;destroyPromise;messages;contextMessages;mode;updateEgress;constructor(z,Z,J,Y,H={}){this.id=z;this.cwd=Z;this.connection=J;this.clientCapabilities=Y;this.options=H;this.messages=[...H.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(H.permissionMode),this.updateEgress=new Bz({maxPendingItems:jz,maxPendingBytes:Xz,writeTimeoutMs:Dz,signal:J.signal,sizeOf:(W)=>Buffer.byteLength(JSON.stringify(W)),write:async(W)=>{await J.sessionUpdate(W)},onFailure:(W)=>this.handleUpdateEgressFailure(W)})}async refreshPersistedMessages(){let[z,Z]=await Promise.all([F.loadSession(this.id,this.cwd),F.loadSessionModelContext(this.id,this.cwd)]);if(z.length>0)this.messages=z;if(Z.length>0)this.contextMessages=Z}async loadModelContextOr(z){let Z=await F.loadSessionModelContext(this.id,this.cwd);return Z.length>0?Z:[...z]}mapPermissionModeToMode(z){switch(z){case"yolo":return"yolo";case"autoEdit":return"auto-edit";case"plan":return"plan";case"default":default:return"default"}}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return Hz.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(G.debug(`[AcpSession ${this.id}] Initializing...`),await F.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),N.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd,async(W)=>{await this.sendUpdateAndWait(W)}),G.debug(`[AcpSession ${this.id}] ACP service context initialized`),await zz.resolvePendingWithHandler(this.cwd,this.id,{requestConfirmation:(W)=>this.requestPermission(W)}))await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let Z=this.options.mcpServers?fz(this.options.mcpServers):void 0,J=N.getInstance().getTerminalService(this.id);if(this.runtime=await Qz.create({sessionId:this.id,workspaceRoot:this.cwd,permissionMode:this.mapModeToPermissionMode(),...Z?{mcpServers:Z}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async(W,Q)=>{let j=await J.execute(W,{cwd:Q.cwd,env:Q.env,timeout:Q.timeoutMs,signal:Q.signal,allowLocalFallback:!1,onOutput:(X)=>Q.onOutput?.("stdout",X)});return{exitCode:j.exitCode,stdout:j.stdout,stderr:j.stderr,...j.error?{error:j.error}:{},timedOut:j.failureKind==="timeout",aborted:j.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),await b.recoverInterrupted(this.cwd,this.id,this.runtime))await this.refreshPersistedMessages();this.agent=await this.createAgent(),await Fz(this.cwd),G.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=s.subscribe((W)=>{if(W.sessionId!==this.id||W.projectPath!==this.cwd)return;if(W.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":W.properties}}),this.schedulePendingResume();return}if(W.type==="task.delivery"){if(!W.properties.taskDelivery||typeof W.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof W.properties.updatedAt==="string"?W.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":W.properties.taskDelivery,...W.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(W.type.startsWith("team.")){let{teamName:Q,messageId:j,content:X}=W.properties,D=W.properties.metadata;if(W.type==="team.message.received"&&typeof Q==="string"&&typeof j==="string"&&typeof X==="string"&&$z(D,{messageId:j,teamName:Q}))(async()=>{let L=await this.runtime?.enqueueSteering(X,{allowBeforeTurn:!0,messageId:j,origin:"team_message",metadata:D});if(!L?.accepted)return;if(await new Zz(Q,p()).markDelivered([j]),L.delivery==="next_turn")this.schedulePendingResume()})().catch((L)=>{G.warn(`[AcpSession ${this.id}] Failed to deliver teammate message`,L)});this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/teamEvent":{type:W.type,...W.properties}}});return}if(W.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof W.properties.updatedAt==="string"?W.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":W.properties.taskStatus,...typeof W.properties.taskStatusReason==="string"?{"blade/taskStatusReason":W.properties.taskStatusReason}:{},...W.properties.taskFailure&&typeof W.properties.taskFailure==="object"?{"blade/taskFailure":W.properties.taskFailure}:{},...typeof W.properties.taskStartedAt==="string"?{"blade/taskStartedAt":W.properties.taskStartedAt}:{},...typeof W.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":W.properties.taskCompletedAt}:{},...W.properties.taskDiffStat&&typeof W.properties.taskDiffStat==="object"?{"blade/taskDiffStat":W.properties.taskDiffStat}:{},...typeof W.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":W.properties.taskQueuePosition}:{},...typeof W.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":W.properties.taskQueueDepth}:{},...typeof W.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":W.properties.taskConcurrencyLimit}:{},...typeof W.properties.taskInFlight==="number"?{"blade/taskInFlight":W.properties.taskInFlight}:{}}})});let H=await this.runtime.getGoal();if(this.runtime.getPendingSteeringCount()>0||H?.status==="active"||H?.status==="verifying")if(this.options.initialMessages===void 0)this.schedulePendingResume();else this.pendingResumeRequested=!0}async replayHistory(){for(let Z of this.messages){if(!this.canSendUpdates())return;if(!o(Z))continue;let J=Z.role==="user"?"user_message_chunk":Z.role==="assistant"?"agent_message_chunk":void 0;if(!J)continue;for(let Y of uz(Z)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:J,content:Y}))return}}let z=await this.runtime?.getGoal();if(z&&!await this.sendUpdateAndWait(this.goalSessionUpdate(z)))return;if(this.pendingResumeRequested)this.schedulePendingResume()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);G.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendAvailableCommands()},500)}async handleSlashCommand(z,Z){try{G.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let J={cwd:this.cwd,surface:"acp",workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.contextMessages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let j=await this.runtime.rewindSession(Q);return this.messages=[...j.messages],this.contextMessages=await this.loadModelContextOr(j.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),j}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async(Q)=>{if(await this.setReasoningEffort(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()}},serviceTier:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()},set:async(Q)=>{if(await this.setServiceTier(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()}},responseVerbosity:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()},set:async(Q)=>{if(await this.setResponseVerbosity(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()}},communicationStyle:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()},set:async(Q)=>{if(await this.setCommunicationStyle(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()}},subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let X=!1,D,L=(B)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:B.id,status:B.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:B.result?.message||B.result?.error||`Subagent ${B.status}`}}]})},U=this.runtime.resumeSubagent({agentId:Q,prompt:j,onCompleted:(B)=>{if(X)L(B);else D=B}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:U.session.id,status:"in_progress",title:`Resuming ${U.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${U.source.id} at depth ${U.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),X=!0,D)L(D);return U}},mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs(Q)},getPrompt:async(Q,j,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Q,j,X)},complete:async(Q,j,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Q,j,X)},listTasks:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks(Q)},getTask:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask(Q)},cancelTask:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Q,j)},getLogs:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Q,j)},setLoggingLevel:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Q,j)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},sideConversation:{ask:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.askSideQuestion(Q,{signal:j})}},codeReview:{run:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let X=await b.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:Q,signal:j,onEvent:(U)=>{if(U.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:U.toolCall.id,status:"in_progress",title:`Review: ${U.toolCall.function.name}`,content:[],kind:this.mapToolKind(U.toolKind)});else if(U.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:U.toolCall.id,status:U.result.success?"completed":"failed",content:[]})}}),D=await X.completion,L=(await b.list(this.cwd,this.id)).find((U)=>U.start.reviewId===X.reviewId);if(!L)throw Error(`Review not found: ${X.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:X.reviewId,status:D.status,findings:D.findings.length,content:v(L.start,D)}}},signal:Z,acp:{sendMessage:(Q)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}})},sendToolStart:(Q,j,X)=>{let D=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,L=this.mapToolKind(X);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:D,status:"in_progress",title:`${Q}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(j,null,2)}}],kind:L})},sendToolResult:(Q,j)=>{if(j.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:j.summary}})}}},Y=await Uz(z,J),H=Y.data?.action;if(H==="start_goal"||H==="resume_goal")this.schedulePendingResume();if(H==="rewind_session"&&Array.isArray(Y.data?.messages))this.messages=[...Y.data.messages],this.contextMessages=await this.loadModelContextOr(Y.data.messages);if((Y.message==="compact_completed"||Y.message==="compact_fallback")&&Y.data?.compactedMessages){this.contextMessages=[...Y.data.compactedMessages];let Q=await F.loadSession(this.id,this.cwd);if(Q.length>0)this.messages=Q}let W=Y.content||Y.message;if(W)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W}});if(Y.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Y.error}`}});return await this.flushUpdates(),{stopReason:Y.success?"end_turn":"cancelled"}}catch(J){if(Z.aborted||J instanceof Error&&J.name==="AbortError")return{stopReason:"cancelled"};return G.error(`[AcpSession ${this.id}] Slash command error:`,J),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${J instanceof Error?J.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async handleSideConversationCommand(z){if(this.pendingSideConversation)throw Error("A side conversation is already running");let Z=new AbortController,J,Y=new Promise((H)=>{J=H});this.pendingSideConversation=Z,this.pendingSideConversationCompletion=Y;try{return await this.handleSlashCommand(z,Z.signal)}catch(H){if(Z.signal.aborted||H instanceof Error&&H.name==="AbortError")return{stopReason:"cancelled"};throw H}finally{if(J(),this.pendingSideConversationCompletion===Y)this.pendingSideConversationCompletion=null;if(this.pendingSideConversation===Z)this.pendingSideConversation=null}}async sendAvailableCommands(){try{let z=Vz(this.cwd,this.runtime?.getAgentResources()),Z=["model","permissions","theme","config","exit","ide"],Y=z.filter((H)=>!Z.includes(H.name)&&(H.name!=="team"||this.runtime?.getConfig().agentTeamsEnabled===!0)).map((H)=>{let W;if(H.usage){let Q=H.usage.replace(/^\/\w+\s*/,"").trim();if(Q)W=Q}if(H.aliases?.length){let Q=`Aliases: ${H.aliases.join(", ")}`;W=W?`${W} | ${Q}`:Q}return{name:H.name,description:H.description,input:W?{hint:W}:void 0}});G.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map((H)=>H.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Y}),G.info(`[AcpSession ${this.id}] Sent ${Y.length} available commands`)}catch(z){G.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,Z={}){if(N.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let J=this.resolvePrompt(z.prompt),Y=J.content,H=J.displayText,W=z._meta?.outputSchema??(Z.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((B)=>B.outputSchema)?.outputSchema:void 0),Q;if(W!==void 0)Q=t(W).schema;if(H.trimStart().startsWith("!")){if(Q)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(H)}let j=Jz(H);if(j){if(Q)throw Error("Output schemas cannot be combined with slash commands");if(Array.isArray(Y)&&Y.some((B)=>B.type==="image_url"))throw Error("Side conversations do not accept image attachments");return this.handleSideConversationCommand(j.question?`/btw ${j.question}`:"/btw")}if(this.pendingPrompt){if(Q)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test(H.trim()))return this.handleSlashCommand(H,this.pendingPrompt.signal);let B=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!B.accepted)throw Error(B.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(G.debug(`[AcpSession ${this.id}] Queued steering for active turn (${B.queued})`),B.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let X=new AbortController,D=!1,L,U=new Promise((B)=>{L=B});this.pendingPrompt=X,this.pendingPromptCompletion=U;try{if(G.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),Gz(H)){if(Q)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(H,X.signal)}let B={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.contextMessages],signal:X.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async($)=>{this.mode=this.mapPermissionModeToMode($),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async($)=>{return this.requestPermission($)}}},A=await e(this.agent.chatStream(Y,B,{pendingInputOnly:Z.pendingInputOnly,goalContinuationOnly:Z.goalContinuationOnly,outputSchema:Q}),async($)=>{switch($.kind){case"content_delta":if(Q)break;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:$.delta}});break;case"tool_start":{let V=$.toolCall,O=V.function.name;if(O===x)break;let R=this.mapToolKind($.toolKind),w=`Executing ${O}`;if(O==="Task"&&"function"in V)try{let q=JSON.parse(V.function.arguments),K=q.resume_from??q.resume;if(typeof K==="string")w=`Resuming ${String(q.subagent_type||"subagent")} from ${K}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:V.id,status:"in_progress",title:w,content:[],kind:R});break}case"tool_progress":{let V=$.toolCall;if(V.function.name===x)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:$.update.message}}]});break}case"tool_result":{let V=$.toolCall;if(V.function.name===x)break;let O=$.result,R=[],w=O.metadata;if(w?.kind==="patch"&&Array.isArray(w.changes))for(let K of w.changes){if(!K||typeof K!=="object"||!("path"in K)||typeof K.path!=="string")continue;R.push({type:"diff",path:K.path,oldText:"oldContent"in K&&typeof K.oldContent==="string"?K.oldContent:null,newText:"newContent"in K&&typeof K.newContent==="string"?K.newContent:null})}else if(w?.kind==="edit"&&typeof w.file_path==="string"&&typeof w.oldContent==="string"&&(typeof w.newContent==="string"||w.newContent===void 0))R.push({type:"diff",path:w.file_path,oldText:w.oldContent,newText:w.newContent??null});else{let K=V.function.name,Mz=Yz(a(Wz(K,O),r));R.push({type:"content",content:{type:"text",text:Mz}})}if(V.function.name==="Task"&&(w?.verificationVerdict==="pass"||w?.verificationVerdict==="fail"||w?.verificationVerdict==="partial"))R.unshift({type:"content",content:{type:"text",text:`Verification result: ${w.verificationVerdict.toUpperCase()}`}});let q=O.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:q,content:R});break}case"structured_output":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify($.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
|
|
3
3
|
`}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${$.contentKind} r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
|
|
4
4
|
`}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${$.revision} (${$.serverName}): ${$.uri}
|
|
@@ -9,7 +9,7 @@ import{s as yz,t as hz}from"./chunk-3cbfykzb.js";import{u as b}from"./chunk-jswm
|
|
|
9
9
|
`}});break;case"project_rules_loaded":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Project rules loaded: ${$.files.length}${$.blockedWrite?" (write retry required)":""}
|
|
10
10
|
`}});break;case"provider_admission":D=$.phase!=="admitted",this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":$.phase!=="admitted"?{phase:$.phase,requestClass:$.requestClass,resource:$.resource,scope:$.scope,...$.reason!==void 0?{reason:$.reason}:{},queuePosition:$.queuePosition,queueDepth:$.queueDepth,inFlight:$.inFlight,limit:$.limit,waitMs:$.waitMs,maxWaitMs:$.maxWaitMs,...$.recoveryRemainingMs!==void 0?{recoveryRemainingMs:$.recoveryRemainingMs}:{}}:null}});break;case"provider_circuit":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerCircuit":{phase:$.phase,reason:$.reason,...$.statusCode!==void 0?{statusCode:$.statusCode}:{},...$.retryAfterMs!==void 0?{retryAfterMs:$.retryAfterMs}:{},...$.nextProbeAt!==void 0?{nextProbeAt:$.nextProbeAt}:{},openDurationMs:$.openDurationMs,...$.sampleCount!==void 0?{sampleCount:$.sampleCount}:{},...$.failureCount!==void 0?{failureCount:$.failureCount}:{},...$.recoveryRemainingMs!==void 0?{recoveryRemainingMs:$.recoveryRemainingMs}:{}}}});break;case"provider_retry":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerRetry":{phase:$.phase,attempt:$.attempt,maxRetries:$.maxRetries,reason:$.reason,...$.statusCode!==void 0?{statusCode:$.statusCode}:{},...$.delayMs!==void 0?{delayMs:$.delayMs}:{},...$.nextRetryAt!==void 0?{nextRetryAt:$.nextRetryAt}:{},...$.mode!==void 0?{mode:$.mode}:{},...$.recoveryBudgetMs!==void 0?{recoveryBudgetMs:$.recoveryBudgetMs}:{},...$.recoveryElapsedMs!==void 0?{recoveryElapsedMs:$.recoveryElapsedMs}:{},...$.recoveryRemainingMs!==void 0?{recoveryRemainingMs:$.recoveryRemainingMs}:{},...$.exhaustedBy!==void 0?{exhaustedBy:$.exhaustedBy}:{}}}});break;case"provider_stall":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerStall":{phase:$.phase,stallCount:$.stallCount,durationMs:$.durationMs,warningAfterMs:$.warningAfterMs,timeoutMs:$.timeoutMs,outputStarted:$.outputStarted}}});break;case"action_stationarity":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/actionStationarity":{phase:$.phase,toolName:$.toolName,runLength:$.runLength,nudgeThreshold:$.nudgeThreshold,haltThreshold:$.haltThreshold,progressAware:$.progressAware}}});break;case"task_update":this.sendPlanUpdate($.tasks);break;case"steering_applied":break;case"follow_up_started":for(let V of $.messages){if(!V.recovered||V.persisted)continue;for(let O of wz(V.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:O})}if($.recovered>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${$.recovered} queued instruction${$.recovered===1?"":"s"} recovered after restart]
|
|
11
11
|
`}});break;case"goal_updated":if($.goal)this.sendUpdate(this.goalSessionUpdate($.goal));if($.goal&&$.goal.status!=="active")this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Goal ${$.goal.status}: ${$.goal.objective}]
|
|
12
|
-
`}});break;case"goal_continuation_started":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/goalContinuation":{goalId:$.goal.goalId,continuation:$.continuation,...$.prematureStopPattern?{prematureStopPattern:$.prematureStopPattern}:{},...$.prematureStopCount!==void 0?{prematureStopCount:$.prematureStopCount}:{}}}});break;case"compaction":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/compaction":{phase:$.phase,...$.reason?{reason:$.reason}:{},...$.strategy?{strategy:$.strategy}:{},...$.outcome?{outcome:$.outcome}:{},...$.preTokens!==void 0?{preTokens:$.preTokens}:{},...$.postTokens!==void 0?{postTokens:$.postTokens}:{},...$.sampleAttempts!==void 0?{sampleAttempts:$.sampleAttempts}:{},...$.inputReductions!==void 0?{inputReductions:$.inputReductions}:{},...$.messagesOmitted!==void 0?{messagesOmitted:$.messagesOmitted}:{},...$.filesOmitted!==void 0?{filesOmitted:$.filesOmitted}:{},...$.failureReason?{failureReason:$.failureReason}:{}}}});break;default:break}if(!await this.flushUpdates())X.abort("acp-egress-failed")});if(!await this.flushUpdates())X.abort("acp-egress-failed");this.contextMessages=[...B.messages];let u=await F.loadSession(this.id,this.cwd);if(this.messages=u.length>0?u:[...B.messages],!A.success){let $=A.error?.type??"unknown",V=A.error?.details??A.error?.message??"Agent execution failed",O=cz(V)??i(V);throw Iz.internalError({failureType:$,taskFailure:{code:O.code,retryable:O.retryable,...O.resource?{resource:O.resource}:{}}},`Agent turn failed (${$})`)}if(X.signal.aborted)return{stopReason:"cancelled"};let g={...A.metadata?.structuredOutput?{structuredOutput:A.metadata.structuredOutput,outputSchemaDigest:A.metadata.structuredOutputSchemaDigest}:{},...A.metadata?.goalCompletionVerified?{goalCompletion:{verified:!0,verdict:A.metadata.goalVerificationVerdict,...A.metadata.goalVerifierSessionId?{verifierSessionId:A.metadata.goalVerifierSessionId}:{},...A.metadata.goalVerificationEvidenceSha256?{evidenceSha256:A.metadata.goalVerificationEvidenceSha256}:{}}}:{}};return{stopReason:"end_turn",...Object.keys(g).length>0?{_meta:g}:{}}}catch(B){if(X.signal.aborted||B instanceof Error&&B.name==="AbortError")return{stopReason:"cancelled"};throw G.error(`[AcpSession ${this.id}] Prompt error:`,B),B}finally{if(D&&!this.destroyed)this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":null}}),await this.flushUpdates();if(L(),this.pendingPromptCompletion===U)this.pendingPromptCompletion=null;if(this.pendingPrompt===X){if(this.pendingPrompt=null,!this.destroyed&&this.pendingResumeRequested)this.schedulePendingResume()}}}async handleUserShellCommand(z){if(!this.runtime)throw Error("Session runtime is unavailable");if(this.pendingUserShell)throw Error("A user shell command is already running");let Z=z.trimStart().slice(1).trim();if(!Z)throw Error("User shell command cannot be empty");let J=new AbortController,Y,H=new Promise((j)=>{Y=j});this.pendingUserShell=J,this.pendingUserShellCompletion=H;let W,Q="";try{let j=await this.runtime.executeUserShellCommand(Z,{signal:J.signal,onEvent:async(D)=>{if(W=D.executionId,D.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:D.executionId,status:"in_progress",title:`! ${D.command}`,content:[],kind:"execute"});return}if(D.type==="output"){Q+=D.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:D.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:D.chunk}}]});return}let L=I(D.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:D.executionId,status:D.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:Q?gz(D.record):L}}]})}}),X={role:"user",content:j.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify(j.record))}};if(this.messages.push(X),this.contextMessages.push(X),j.delivery==="next_turn")this.schedulePendingResume();if(!await this.flushUpdates())return J.abort("acp-egress-failed"),{stopReason:"cancelled"};return{stopReason:j.record.status==="aborted"?"cancelled":"end_turn"}}catch(j){if(W)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:W,status:"failed",content:[{type:"content",content:{type:"text",text:j instanceof Error?j.message:String(j)}}]});if(J.signal.aborted)return{stopReason:"cancelled"};throw j}finally{if(Y(),this.pendingUserShellCompletion===H)this.pendingUserShellCompletion=null;if(this.pendingUserShell===J)this.pendingUserShell=null}}schedulePendingResume(){if(this.destroyed||this.connection.signal.aborted)return;this.pendingResumeRequested=!0,queueMicrotask(()=>{this.resumePendingIfIdle()})}async resumePendingIfIdle(){if(this.destroyed||this.connection.signal.aborted)return;if(this.pendingPrompt||this.pendingUserShell||!this.runtime||!this.agent)return;let z=this.runtime.getPendingSteeringCount()>0,Z=z?null:await this.runtime.getGoal(),J=Z?.status==="active"||Z?.status==="verifying";if(!z&&!J){this.pendingResumeRequested=!1;return}this.pendingResumeRequested=!1,await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:z,goalContinuationOnly:J}).catch((Y)=>{G.error(`[AcpSession ${this.id}] Failed to resume pending input:`,Y)})}cancel(){G.info(`[AcpSession ${this.id}] Cancel requested`),this.pendingResumeRequested=!1;let z=!1;if(this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,z=!0;if(this.pendingUserShell)this.pendingUserShell.abort(),this.pendingUserShell=null,z=!0;if(this.pendingSideConversation)this.pendingSideConversation.abort(),this.pendingSideConversation=null,z=!0;if(!z)G.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(z){let J=["default","auto-edit","yolo","plan"].includes(z)?z:"default",Y=this.mapModeIdToPermissionMode(J);await F.setSessionPermissionMode(this.id,this.cwd,Y),this.mode=J,G.info(`[AcpSession ${this.id}] Mode set to: ${this.mode}`),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})}mapModeToPermissionMode(){return this.mapModeIdToPermissionMode(this.mode)}mapModeIdToPermissionMode(z){switch(z){case"yolo":return"yolo";case"auto-edit":return"autoEdit";case"plan":return"plan";case"default":default:return"default"}}shouldAutoApprove(z){switch(this.mode){case"yolo":return!0;case"auto-edit":return z==="readonly"||z==="write";case"plan":return z==="readonly";case"default":default:return!1}}async setModel(z){if(G.info(`[AcpSession ${this.id}] Model set to: ${z}`),this.pendingPrompt)throw Error("Cannot switch models while a prompt is active");if(!this.agent)throw Error("Session not initialized");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getCurrentModelId();await this.agent.switchModel(z);try{try{await F.updateSessionMetadata(this.id,this.cwd,{selectedModelId:z})}catch(J){if(!(J instanceof P)&&J.code!=="ENOENT")throw J;await F.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:z})}}catch(J){if(Z&&Z!==z)await this.agent.switchModel(Z).catch((Y)=>{G.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,Y)});throw J}}getCurrentModelId(){return this.runtime?.getCurrentModelId()}async setReasoningEffort(z){if(this.pendingPrompt)throw Error("Cannot switch reasoning effort while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getReasoningConfiguration();try{this.runtime.resolveReasoningConfiguration(z)}catch(J){throw Error(J instanceof Error?J.message:"Invalid reasoning effort")}if(Z.selection===z)return;await this.runtime.refresh({reasoningEffort:z});try{try{await F.updateSessionMetadata(this.id,this.cwd,{reasoningEffort:z})}catch(J){if(!(J instanceof P)&&J.code!=="ENOENT")throw J;await F.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),reasoningEffort:z})}}catch(J){throw await this.runtime.refresh({reasoningEffort:Z.selection}),J}}async setServiceTier(z){if(this.pendingPrompt)throw Error("Cannot switch service tier while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getServiceTierConfiguration();try{this.runtime.resolveServiceTierConfiguration(z)}catch(J){throw Error(J instanceof Error?J.message:"Invalid service tier")}if(Z.selection===z)return;await this.runtime.refresh({serviceTier:z});try{try{await F.updateSessionMetadata(this.id,this.cwd,{serviceTier:z})}catch(J){if(!(J instanceof P)&&J.code!=="ENOENT")throw J;await F.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),serviceTier:z})}}catch(J){throw await this.runtime.refresh({serviceTier:Z.selection}),J}}async setResponseVerbosity(z){if(this.pendingPrompt)throw Error("Cannot switch response verbosity while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getResponseVerbosityConfiguration();try{this.runtime.resolveResponseVerbosityConfiguration(z)}catch(J){throw Error(J instanceof Error?J.message:"Invalid response verbosity")}if(Z.selection===z)return;await this.runtime.refresh({responseVerbosity:z});try{try{await F.updateSessionMetadata(this.id,this.cwd,{responseVerbosity:z})}catch(J){if(!(J instanceof P)&&J.code!=="ENOENT")throw J;await F.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),responseVerbosity:z})}}catch(J){throw await this.runtime.refresh({responseVerbosity:Z.selection}),J}}async setCommunicationStyle(z){if(this.pendingPrompt)throw Error("Cannot switch communication style while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getCommunicationStyleConfiguration(),J=this.runtime.resolveCommunicationStyleConfiguration(z);if(J.source!=="built-in"&&!J.contentSha256)throw Error("Custom communication style has no provenance");if(Z.selection===z)return;await this.runtime.refresh({communicationStyle:z});try{try{await F.updateSessionMetadata(this.id,this.cwd,{communicationStyle:z,communicationStyleDigest:J.source==="built-in"?null:J.contentSha256})}catch(Y){if(!(Y instanceof P)&&Y.code!=="ENOENT")throw Y;await F.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:z,...J.source!=="built-in"&&J.contentSha256?{communicationStyleDigest:J.contentSha256}:{}})}}catch(Y){throw await this.runtime.refresh({communicationStyle:Z.selection}),Y}}getModelConfiguration(){if(!this.runtime)return;let z=this.runtime.getConfig();return{currentModelId:this.runtime.getCurrentModelId()??z.currentModelId,models:z.models.map((Z)=>structuredClone(Z)),modelProviders:structuredClone(z.modelProviders),reasoning:this.runtime.getReasoningConfiguration(),serviceTier:this.runtime.getServiceTierConfiguration(),responseVerbosity:this.runtime.getResponseVerbosityConfiguration(),communicationStyle:this.runtime.getCommunicationStyleConfiguration()}}getMode(){return this.mode}isIdleForResidency(){return!this.destroyed&&this.pendingPrompt===null&&this.pendingUserShell===null&&this.pendingSideConversation===null&&(this.runtime?.isIdleForResidency()??!1)}destroy(z={}){if(this.destroyPromise)return this.destroyFinished?Promise.resolve():this.destroyPromise;return this.destroyPromise=this.destroyOwnedResources(z.discardPendingInput===!0).finally(()=>{this.destroyFinished=!0}),this.destroyPromise}async destroyOwnedResources(z){if(this.destroyed=!0,this.updateEgress.close(new Lz("closed","ACP Session was destroyed")),this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let Z=this.agent,J=this.runtime,Y=this.pendingPromptCompletion,H=this.pendingUserShellCompletion,W=this.pendingSideConversationCompletion;this.agent=null,this.runtime=null;let Q,j=async(X)=>{try{await X()}catch(D){Q??=D}};if(await j(()=>this.cancel()),Y)await j(()=>Y);if(H)await j(()=>H);if(W)await j(()=>W);if(z&&Y&&J)await j(()=>J.discardPendingInput());if(Z)await j(()=>Z.destroy());if(J)await j(()=>J.dispose());if(await j(()=>N.destroySession(this.id)),G.debug(`[AcpSession ${this.id}] Destroyed`),Q!==void 0)throw Q}resolvePrompt(z){let Z=[],J=[],Y=0,H=0,W=0,Q=(X)=>{if(J.length>0)J.push({type:"text",text:`
|
|
12
|
+
`}});break;case"goal_continuation_started":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/goalContinuation":{goalId:$.goal.goalId,continuation:$.continuation,...$.prematureStopPattern?{prematureStopPattern:$.prematureStopPattern}:{},...$.prematureStopCount!==void 0?{prematureStopCount:$.prematureStopCount}:{}}}});break;case"compaction":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/compaction":{phase:$.phase,...$.reason?{reason:$.reason}:{},...$.strategy?{strategy:$.strategy}:{},...$.outcome?{outcome:$.outcome}:{},...$.preTokens!==void 0?{preTokens:$.preTokens}:{},...$.postTokens!==void 0?{postTokens:$.postTokens}:{},...$.sampleAttempts!==void 0?{sampleAttempts:$.sampleAttempts}:{},...$.inputReductions!==void 0?{inputReductions:$.inputReductions}:{},...$.messagesOmitted!==void 0?{messagesOmitted:$.messagesOmitted}:{},...$.filesOmitted!==void 0?{filesOmitted:$.filesOmitted}:{},...$.imagesOmitted!==void 0?{imagesOmitted:$.imagesOmitted}:{},...$.failureReason?{failureReason:$.failureReason}:{}}}});break;default:break}if(!await this.flushUpdates())X.abort("acp-egress-failed")});if(!await this.flushUpdates())X.abort("acp-egress-failed");this.contextMessages=[...B.messages];let u=await F.loadSession(this.id,this.cwd);if(this.messages=u.length>0?u:[...B.messages],!A.success){let $=A.error?.type??"unknown",V=A.error?.details??A.error?.message??"Agent execution failed",O=cz(V)??i(V);throw Iz.internalError({failureType:$,taskFailure:{code:O.code,retryable:O.retryable,...O.resource?{resource:O.resource}:{}}},`Agent turn failed (${$})`)}if(X.signal.aborted)return{stopReason:"cancelled"};let g={...A.metadata?.structuredOutput?{structuredOutput:A.metadata.structuredOutput,outputSchemaDigest:A.metadata.structuredOutputSchemaDigest}:{},...A.metadata?.goalCompletionVerified?{goalCompletion:{verified:!0,verdict:A.metadata.goalVerificationVerdict,...A.metadata.goalVerifierSessionId?{verifierSessionId:A.metadata.goalVerifierSessionId}:{},...A.metadata.goalVerificationEvidenceSha256?{evidenceSha256:A.metadata.goalVerificationEvidenceSha256}:{}}}:{}};return{stopReason:"end_turn",...Object.keys(g).length>0?{_meta:g}:{}}}catch(B){if(X.signal.aborted||B instanceof Error&&B.name==="AbortError")return{stopReason:"cancelled"};throw G.error(`[AcpSession ${this.id}] Prompt error:`,B),B}finally{if(D&&!this.destroyed)this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":null}}),await this.flushUpdates();if(L(),this.pendingPromptCompletion===U)this.pendingPromptCompletion=null;if(this.pendingPrompt===X){if(this.pendingPrompt=null,!this.destroyed&&this.pendingResumeRequested)this.schedulePendingResume()}}}async handleUserShellCommand(z){if(!this.runtime)throw Error("Session runtime is unavailable");if(this.pendingUserShell)throw Error("A user shell command is already running");let Z=z.trimStart().slice(1).trim();if(!Z)throw Error("User shell command cannot be empty");let J=new AbortController,Y,H=new Promise((j)=>{Y=j});this.pendingUserShell=J,this.pendingUserShellCompletion=H;let W,Q="";try{let j=await this.runtime.executeUserShellCommand(Z,{signal:J.signal,onEvent:async(D)=>{if(W=D.executionId,D.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:D.executionId,status:"in_progress",title:`! ${D.command}`,content:[],kind:"execute"});return}if(D.type==="output"){Q+=D.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:D.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:D.chunk}}]});return}let L=I(D.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:D.executionId,status:D.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:Q?gz(D.record):L}}]})}}),X={role:"user",content:j.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify(j.record))}};if(this.messages.push(X),this.contextMessages.push(X),j.delivery==="next_turn")this.schedulePendingResume();if(!await this.flushUpdates())return J.abort("acp-egress-failed"),{stopReason:"cancelled"};return{stopReason:j.record.status==="aborted"?"cancelled":"end_turn"}}catch(j){if(W)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:W,status:"failed",content:[{type:"content",content:{type:"text",text:j instanceof Error?j.message:String(j)}}]});if(J.signal.aborted)return{stopReason:"cancelled"};throw j}finally{if(Y(),this.pendingUserShellCompletion===H)this.pendingUserShellCompletion=null;if(this.pendingUserShell===J)this.pendingUserShell=null}}schedulePendingResume(){if(this.destroyed||this.connection.signal.aborted)return;this.pendingResumeRequested=!0,queueMicrotask(()=>{this.resumePendingIfIdle()})}async resumePendingIfIdle(){if(this.destroyed||this.connection.signal.aborted)return;if(this.pendingPrompt||this.pendingUserShell||!this.runtime||!this.agent)return;let z=this.runtime.getPendingSteeringCount()>0,Z=z?null:await this.runtime.getGoal(),J=Z?.status==="active"||Z?.status==="verifying";if(!z&&!J){this.pendingResumeRequested=!1;return}this.pendingResumeRequested=!1,await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:z,goalContinuationOnly:J}).catch((Y)=>{G.error(`[AcpSession ${this.id}] Failed to resume pending input:`,Y)})}cancel(){G.info(`[AcpSession ${this.id}] Cancel requested`),this.pendingResumeRequested=!1;let z=!1;if(this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,z=!0;if(this.pendingUserShell)this.pendingUserShell.abort(),this.pendingUserShell=null,z=!0;if(this.pendingSideConversation)this.pendingSideConversation.abort(),this.pendingSideConversation=null,z=!0;if(!z)G.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(z){let J=["default","auto-edit","yolo","plan"].includes(z)?z:"default",Y=this.mapModeIdToPermissionMode(J);await F.setSessionPermissionMode(this.id,this.cwd,Y),this.mode=J,G.info(`[AcpSession ${this.id}] Mode set to: ${this.mode}`),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})}mapModeToPermissionMode(){return this.mapModeIdToPermissionMode(this.mode)}mapModeIdToPermissionMode(z){switch(z){case"yolo":return"yolo";case"auto-edit":return"autoEdit";case"plan":return"plan";case"default":default:return"default"}}shouldAutoApprove(z){switch(this.mode){case"yolo":return!0;case"auto-edit":return z==="readonly"||z==="write";case"plan":return z==="readonly";case"default":default:return!1}}async setModel(z){if(G.info(`[AcpSession ${this.id}] Model set to: ${z}`),this.pendingPrompt)throw Error("Cannot switch models while a prompt is active");if(!this.agent)throw Error("Session not initialized");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getCurrentModelId();await this.agent.switchModel(z);try{try{await F.updateSessionMetadata(this.id,this.cwd,{selectedModelId:z})}catch(J){if(!(J instanceof P)&&J.code!=="ENOENT")throw J;await F.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:z})}}catch(J){if(Z&&Z!==z)await this.agent.switchModel(Z).catch((Y)=>{G.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,Y)});throw J}}getCurrentModelId(){return this.runtime?.getCurrentModelId()}async setReasoningEffort(z){if(this.pendingPrompt)throw Error("Cannot switch reasoning effort while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getReasoningConfiguration();try{this.runtime.resolveReasoningConfiguration(z)}catch(J){throw Error(J instanceof Error?J.message:"Invalid reasoning effort")}if(Z.selection===z)return;await this.runtime.refresh({reasoningEffort:z});try{try{await F.updateSessionMetadata(this.id,this.cwd,{reasoningEffort:z})}catch(J){if(!(J instanceof P)&&J.code!=="ENOENT")throw J;await F.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),reasoningEffort:z})}}catch(J){throw await this.runtime.refresh({reasoningEffort:Z.selection}),J}}async setServiceTier(z){if(this.pendingPrompt)throw Error("Cannot switch service tier while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getServiceTierConfiguration();try{this.runtime.resolveServiceTierConfiguration(z)}catch(J){throw Error(J instanceof Error?J.message:"Invalid service tier")}if(Z.selection===z)return;await this.runtime.refresh({serviceTier:z});try{try{await F.updateSessionMetadata(this.id,this.cwd,{serviceTier:z})}catch(J){if(!(J instanceof P)&&J.code!=="ENOENT")throw J;await F.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),serviceTier:z})}}catch(J){throw await this.runtime.refresh({serviceTier:Z.selection}),J}}async setResponseVerbosity(z){if(this.pendingPrompt)throw Error("Cannot switch response verbosity while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getResponseVerbosityConfiguration();try{this.runtime.resolveResponseVerbosityConfiguration(z)}catch(J){throw Error(J instanceof Error?J.message:"Invalid response verbosity")}if(Z.selection===z)return;await this.runtime.refresh({responseVerbosity:z});try{try{await F.updateSessionMetadata(this.id,this.cwd,{responseVerbosity:z})}catch(J){if(!(J instanceof P)&&J.code!=="ENOENT")throw J;await F.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),responseVerbosity:z})}}catch(J){throw await this.runtime.refresh({responseVerbosity:Z.selection}),J}}async setCommunicationStyle(z){if(this.pendingPrompt)throw Error("Cannot switch communication style while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getCommunicationStyleConfiguration(),J=this.runtime.resolveCommunicationStyleConfiguration(z);if(J.source!=="built-in"&&!J.contentSha256)throw Error("Custom communication style has no provenance");if(Z.selection===z)return;await this.runtime.refresh({communicationStyle:z});try{try{await F.updateSessionMetadata(this.id,this.cwd,{communicationStyle:z,communicationStyleDigest:J.source==="built-in"?null:J.contentSha256})}catch(Y){if(!(Y instanceof P)&&Y.code!=="ENOENT")throw Y;await F.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:z,...J.source!=="built-in"&&J.contentSha256?{communicationStyleDigest:J.contentSha256}:{}})}}catch(Y){throw await this.runtime.refresh({communicationStyle:Z.selection}),Y}}getModelConfiguration(){if(!this.runtime)return;let z=this.runtime.getConfig();return{currentModelId:this.runtime.getCurrentModelId()??z.currentModelId,models:z.models.map((Z)=>structuredClone(Z)),modelProviders:structuredClone(z.modelProviders),reasoning:this.runtime.getReasoningConfiguration(),serviceTier:this.runtime.getServiceTierConfiguration(),responseVerbosity:this.runtime.getResponseVerbosityConfiguration(),communicationStyle:this.runtime.getCommunicationStyleConfiguration()}}getMode(){return this.mode}isIdleForResidency(){return!this.destroyed&&this.pendingPrompt===null&&this.pendingUserShell===null&&this.pendingSideConversation===null&&(this.runtime?.isIdleForResidency()??!1)}destroy(z={}){if(this.destroyPromise)return this.destroyFinished?Promise.resolve():this.destroyPromise;return this.destroyPromise=this.destroyOwnedResources(z.discardPendingInput===!0).finally(()=>{this.destroyFinished=!0}),this.destroyPromise}async destroyOwnedResources(z){if(this.destroyed=!0,this.updateEgress.close(new Lz("closed","ACP Session was destroyed")),this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let Z=this.agent,J=this.runtime,Y=this.pendingPromptCompletion,H=this.pendingUserShellCompletion,W=this.pendingSideConversationCompletion;this.agent=null,this.runtime=null;let Q,j=async(X)=>{try{await X()}catch(D){Q??=D}};if(await j(()=>this.cancel()),Y)await j(()=>Y);if(H)await j(()=>H);if(W)await j(()=>W);if(z&&Y&&J)await j(()=>J.discardPendingInput());if(Z)await j(()=>Z.destroy());if(J)await j(()=>J.dispose());if(await j(()=>N.destroySession(this.id)),G.debug(`[AcpSession ${this.id}] Destroyed`),Q!==void 0)throw Q}resolvePrompt(z){let Z=[],J=[],Y=0,H=0,W=0,Q=(X)=>{if(J.length>0)J.push({type:"text",text:`
|
|
13
13
|
`}),W+=1;if(J.push(X),X.type==="text")W+=X.text.length};for(let X of z)if(X.type==="text")Z.push(X.text),Q({type:"text",text:X.text});else if(X.type==="image"){let D=`data:${X.mimeType};base64,${X.data}`;Y+=1,H+=D.length,Z.push(`[Image: ${X.mimeType}]`),Q({type:"image_url",image_url:{url:D}})}else if(X.type==="resource"){let D=X.resource;if("text"in D){let L=`<file path="${D.uri}">
|
|
14
14
|
${D.text}
|
|
15
15
|
</file>`;Z.push(L),Q({type:"text",text:L})}}else if(X.type==="resource_link"){let D=`[Resource: ${X.uri}]`;Z.push(D),Q({type:"text",text:D})}if(Y>S)throw Error(`ACP prompt contains more than ${S} images`);if(H>m)throw Error("ACP prompt images exceed the 5 MiB limit");if(W>M)throw Error(`ACP prompt text exceeds ${M} characters`);let j=Z.join(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Pd as N}from"./chunk-
|
|
1
|
+
import{Pd as N}from"./chunk-y7fhg1gb.js";import{rf as $}from"./chunk-4vyfj372.js";import{Og as _}from"./chunk-0141jad7.js";import{mh as Y,oh as Z}from"./chunk-b9vm7gns.js";function X(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?1004l"),process.stdout.write("\x1B[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var z=Z("Service");function E(b){switch(b){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class B{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!B.instance)B.instance=new B;return B.instance}initialize(){if(this.initialized){z.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}process.on("uncaughtException",(b)=>{this.handleFatalError("uncaughtException",b)}),process.on("unhandledRejection",(b)=>{let q=b instanceof Error?b:Error(String(b));this.handleFatalError("unhandledRejection",q)}),process.on("SIGTERM",()=>{z.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)z.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else z.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
|
|
2
2
|
再按一次 Ctrl+C 退出
|
|
3
3
|
`)}),this.initialized=!0,z.debug("[GracefulShutdown] 全局错误处理器已初始化")}registerCleanup(b){return this.cleanupHandlers.push(b),z.debug(`[GracefulShutdown] 注册清理函数,当前共 ${this.cleanupHandlers.length} 个`),()=>{let q=this.cleanupHandlers.indexOf(b);if(q!==-1)this.cleanupHandlers.splice(q,1),z.debug(`[GracefulShutdown] 取消注册清理函数,剩余 ${this.cleanupHandlers.length} 个`)}}handleFatalError(b,q){if(this.isShuttingDown){console.error(`[GracefulShutdown] 退出过程中发生额外错误 (${b}):`,q);return}if(console.error(""),console.error("═".repeat(60)),console.error(`Uncaught error (${b})`),console.error("═".repeat(60)),console.error(""),console.error("错误信息:",q.message),console.error(""),q.stack)console.error("堆栈跟踪:"),console.error(q.stack);console.error(""),console.error("═".repeat(60)),console.error(""),this.shutdown(b,1)}async shutdown(b,q=0){if(this.isShuttingDown){z.debug("[GracefulShutdown] 已在退出过程中,跳过重复退出");return}this.isShuttingDown=!0;try{N().command.actions.abort("process-shutdown")}catch(A){z.warn("[GracefulShutdown] Failed to abort the active command",A)}z.info(`[GracefulShutdown] 开始优雅退出 (原因: ${b})`);let Q=setTimeout(()=>{X(),process.exit(q)},5000);Q.unref?.();let U=4000,K;try{await Promise.race([this.runCleanupHandlers(),new Promise((A,J)=>{K=setTimeout(()=>{J(Error(`清理超时 (${U}ms)`))},U),K.unref?.()})])}catch(A){console.error("[GracefulShutdown] 清理过程中发生错误:",A)}finally{if(K)clearTimeout(K)}try{let A=$.getInstance(),J=N(),V=J.session?.sessionId||"unknown",W=J.session?.workspaceRoot||_();if(A.isEnabled(W,V)){let v=J.config?.config?.permissionMode||"default";await A.executeSessionEndHooks(E(b),{projectDir:W,sessionId:V,permissionMode:v})}}catch(A){console.error("[GracefulShutdown] SessionEnd hooks 执行失败:",A)}try{await Y()}catch{}clearTimeout(Q),X(),setTimeout(()=>{process.exit(q)},100)}async runCleanupHandlers(){let b=[...this.cleanupHandlers].reverse();for(let q of b)try{let F=q();if(F instanceof Promise)await F}catch(F){console.error("[GracefulShutdown] 清理函数执行失败:",F)}}isExiting(){return this.isShuttingDown}reset(){this.isShuttingDown=!1,this.cleanupHandlers=[],this.initialized=!1}}var O=()=>{return B.getInstance()},y=(b)=>{return O().registerCleanup(b)},j=()=>{O().initialize()},C=(b=0)=>{O().shutdown("normal",b)};
|
|
4
4
|
export{O as xd,y as yd,j as zd,C as Ad};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{readFileSync as l}from"node:fs";import{dirname as o,join as u}from"node:path";import{fileURLToPath as a}from"node:url";var e={name:"blade-code",version:"0.10.
|
|
1
|
+
import{readFileSync as l}from"node:fs";import{dirname as o,join as u}from"node:path";import{fileURLToPath as a}from"node:url";var e={name:"blade-code",version:"0.10.80",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts --project='!performance' && vitest run --config vitest.config.ts --project=performance","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:real-api":"node scripts/test.js realApi","test:real-api:qualification":"node scripts/test.js realApiQualification","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","browser:install":"playwright install chromium","browser:check":"node scripts/run-bun.js run scripts/browser-check.ts","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","qualify:local":"node scripts/run-bun.js run scripts/qualify.ts local","qualify:production":"node scripts/run-bun.js run scripts/qualify.ts production","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/qualify.ts production","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",prepack:"node scripts/run-bun.js run build",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",repository:{type:"git",url:"git+https://github.com/echoVic/blade-code.git"},homepage:"https://github.com/echoVic/blade-code#readme",bugs:{url:"https://github.com/echoVic/blade-code/issues"},engines:{node:">=22.19.0"},optionalDependencies:{"@vscode/ripgrep":"^1.18.0","better-sqlite3":"^11.8.1","bun-pty":"^0.4.8","node-pty":"1.1.0"},dependencies:{"@agentclientprotocol/sdk":"^1.3.0","@anthropic-ai/sandbox-runtime":"0.0.67","@earendil-works/pi-ai":"0.84.2","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.30.0",ahooks:"^3.9.7",ajv:"^8.17.1","ansi-escapes":"^7.3.0","async-mutex":"^0.5.0",axios:"^1.19.0",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.5.0","gray-matter":"^4.0.3",hono:"^4.13.0",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.18.1",lowlight:"^3.3.0","lru-cache":"^11.5.2",nanoid:"^5.1.6",open:"^10.1.2",picomatch:"^4.0.5","proper-lockfile":"^4.1.2",react:"19.2.4","react-dom":"19.2.4",semver:"^7.8.5","string-width":"^8.2.2",typebox:"1.3.10",undici:"^7.16.0","vscode-jsonrpc":"8.2.1","vscode-languageserver-protocol":"3.17.5","vscode-languageserver-types":"3.17.5","write-file-atomic":"^7.0.0",ws:"^8.21.2",yaml:"^2.9.0",yargs:"^18.1.0",zustand:"^5.0.14"},devDependencies:{"@biomejs/biome":"2.5.7","@types/bun":"^1.3.14","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.3","@types/proper-lockfile":"^4.1.4","@types/react":"19.2.10","@types/react-dom":"19.2.3","@types/semver":"^7.8.0","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.18.1","@types/yargs":"^17.0.35","@vitest/coverage-v8":"^4.1.10",jsdom:"^26.0.0",playwright:"1.62.1",typescript:"^5.9.2",vitest:"^4.1.10"}};var s;function r(){if(s)return s;let i=o(a(import.meta.url));for(let n=0;n<5;n++){try{let t=JSON.parse(l(u(i,"package.json"),"utf8"));if(t.name===e.name&&typeof t.version==="string"&&typeof t.description==="string")return s=t,s}catch{}i=o(i)}return s={name:e.name,version:process.env.BLADE_VERSION??e.version,description:e.description},s}function y(){return{...r()}}function p(){return r().version}function v(){return r().name}function g(){return r().description}function f(){return`v${p()}`}function w(){return`v${p()} © 2025 Blade Code`}
|
|
2
2
|
export{y as Bh,p as Ch,v as Dh,g as Eh,f as Fh,w as Gh};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Bh as a,Ch as b,Dh as c,Eh as d,Fh as e,Gh as f}from"./chunk-
|
|
1
|
+
import{Bh as a,Ch as b,Dh as c,Eh as d,Fh as e,Gh as f}from"./chunk-f44wasww.js";import"./chunk-h0fh3j9w.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Pc as a,Qc as b,Rc as c,Sc as d,Tc as e,Uc as f,Vc as g}from"./chunk-
|
|
1
|
+
import{Pc as a,Qc as b,Rc as c,Sc as d,Tc as e,Uc as f,Vc as g}from"./chunk-8ts93ywy.js";import"./chunk-skw3b17a.js";import"./chunk-jwx10h5z.js";import"./chunk-mygw13zd.js";import"./chunk-7nx0pzfk.js";import"./chunk-zkhb55jz.js";import"./chunk-reakyamv.js";import"./chunk-0141jad7.js";import"./chunk-b9vm7gns.js";import"./chunk-h6a0nct6.js";import"./chunk-f44wasww.js";import"./chunk-0ra945vt.js";import"./chunk-h0fh3j9w.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{m as R,n as c,o as g,p as d,q as m,r as l}from"./chunk-
|
|
1
|
+
import{m as R,n as c,o as g,p as d,q as m,r as l}from"./chunk-7k24492x.js";import{Q as M,Y as y}from"./chunk-j9ysfhj9.js";import"./chunk-1mjh959m.js";import"./chunk-ky9q53m7.js";import{Eb as A,vb as h}from"./chunk-9y9bhhfx.js";import"./chunk-r8wbvxn7.js";import{Hc as w,Vc as U}from"./chunk-8ts93ywy.js";import"./chunk-skw3b17a.js";import"./chunk-jwx10h5z.js";import{rd as C}from"./chunk-26h77cn2.js";import{td as I,ud as S,vd as v}from"./chunk-pfdzgcza.js";import{wd as O}from"./chunk-jdb2mwbn.js";import"./chunk-h3w814js.js";import{Td as P}from"./chunk-y7fhg1gb.js";import"./chunk-v508x7cg.js";import"./chunk-c9e0fbyh.js";import"./chunk-seamt0j3.js";import"./chunk-33bpwkyk.js";import"./chunk-mygw13zd.js";import"./chunk-4n3yf5n8.js";import"./chunk-yr9mex38.js";import"./chunk-jzvbjn6e.js";import"./chunk-7nx0pzfk.js";import"./chunk-b9nhnzaj.js";import"./chunk-4vyfj372.js";import"./chunk-zkhb55jz.js";import"./chunk-jscpxfwd.js";import{Ag as F}from"./chunk-pfvgkexe.js";import"./chunk-qxn5bg5k.js";import"./chunk-reakyamv.js";import{Og as z}from"./chunk-0141jad7.js";import"./chunk-eeb2945p.js";import"./chunk-b9vm7gns.js";import"./chunk-5nezhmnq.js";import"./chunk-h6a0nct6.js";import"./chunk-f44wasww.js";import"./chunk-0a0sj79a.js";import"./chunk-sj0k8cdf.js";import"./chunk-0ra945vt.js";import"./chunk-h0fh3j9w.js";import p from"yargs";import{hideBin as e}from"yargs/helpers";var s=new Set(Object.values(F));function t(j){if(j&&s.has(j))return j;return}function x(j){if(j.options.outputFormat==="json")j.io.stdout.write(`${JSON.stringify({response:j.response,...j.structuredOutput?{structured_output:j.structuredOutput,output_schema_digest:j.structuredOutputSchemaDigest}:{},input:j.requestInput,model:j.options.model,timestamp:new Date().toISOString()},null,2)}
|
|
2
2
|
`);else if(j.options.outputFormat==="stream-json")j.io.stdout.write(`${JSON.stringify(j.structuredOutput?{type:"structured_output",output:j.structuredOutput,schema_digest:j.structuredOutputSchemaDigest}:{type:"response",content:j.response})}
|
|
3
3
|
`);else j.io.stdout.write(`${j.response}
|
|
4
4
|
`)}function i(j){return j.command("* [message]","Print response and exit (useful for pipes)",(B)=>B.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(B)=>{if(!B.p)return;let q=await n(B);process.exit(q)})}async function n(j,B=process){let q;try{await R();let _=j.forkSession!==!0&&(j.continue===!0||typeof j.resume==="string"&&j.resume.length>0)?await g({message:j.message,_:j._}):await c({message:j.message,_:j._,defaultMessage:"Hello"}),J=_===void 0,T=J?{mode:"agent",content:""}:await d(_);if(T.mode==="output"){if(T.content)B.stdout.write(`${T.content}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Qe as a,Re as b,Se as c,Te as d,Ue as e,Ve as f,We as g,Xe as h,Ye as i,Ze as j}from"./chunk-
|
|
1
|
+
import{Qe as a,Re as b,Se as c,Te as d,Ue as e,Ve as f,We as g,Xe as h,Ye as i,Ze as j}from"./chunk-yr9mex38.js";import"./chunk-jzvbjn6e.js";import"./chunk-7nx0pzfk.js";import"./chunk-b9nhnzaj.js";import"./chunk-4vyfj372.js";import"./chunk-zkhb55jz.js";import"./chunk-jscpxfwd.js";import"./chunk-pfvgkexe.js";import"./chunk-qxn5bg5k.js";import"./chunk-reakyamv.js";import"./chunk-0141jad7.js";import"./chunk-eeb2945p.js";import"./chunk-b9vm7gns.js";import"./chunk-5nezhmnq.js";import"./chunk-h6a0nct6.js";import"./chunk-f44wasww.js";import"./chunk-0a0sj79a.js";import"./chunk-sj0k8cdf.js";import"./chunk-0ra945vt.js";import"./chunk-h0fh3j9w.js";export{g as withWorkspaceAgentResources,i as snapshotWorkspaceAgentResources,f as resolveWorkspaceAgentResources,j as resetWorkspaceAgentResources,d as refreshWorkspaceCommunicationStyles,h as getWorkspaceAgentResourceCacheStats,e as configureInvocationPluginDirs,c as WorkspaceAgentResourceCapacityError,a as MAX_RESIDENT_WORKSPACE_AGENT_RESOURCES,b as MAX_ACTIVE_WORKSPACE_AGENT_RESOURCES};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as RY,c as MY,d as TY}from"./chunk-
|
|
1
|
+
import{b as RY,c as MY,d as TY}from"./chunk-6fzzhspt.js";import{j as DJ,k as VJ}from"./chunk-1mc7nfb4.js";import{u as s2}from"./chunk-4ywbj4bb.js";import{B as c6,D as gY,F as OQ,G as XQ,H as v6,L as A6,M as P6,Q as j1,S as e4,T as $6,W as y6,Y as z2,Z as nJ,_ as tJ,ba as sJ,ca as eJ,ga as L4,ha as $9,ja as t6,ka as s6,la as mY,ma as O6,oa as z6,qa as x6}from"./chunk-j9ysfhj9.js";import{ua as qJ,va as OJ,wa as zJ,za as EY}from"./chunk-1mjh959m.js";import{Ba as b6}from"./chunk-ky9q53m7.js";import{Eb as QQ,ib as L6,jb as B6,vb as w6}from"./chunk-9y9bhhfx.js";import{Pb as W2}from"./chunk-r8wbvxn7.js";import{Gc as Y6,Hc as $Q,Ic as Z6,Kc as d2,Sc as O2,Vc as C0,gc as _6,uc as t4,zc as s4}from"./chunk-8ts93ywy.js";import"./chunk-skw3b17a.js";import"./chunk-jwx10h5z.js";import{wd as PY}from"./chunk-jdb2mwbn.js";import{Ad as C1,xd as H2,yd as e2}from"./chunk-e9a1br9y.js";import"./chunk-h3w814js.js";import{Ed as k$,Fd as a0,Gd as Q$,Hd as jQ,Id as g$,Jd as r2,Kd as v9,Ld as Q4,Md as MJ,Nd as D9,Od as V$,Pd as l0,Qd as jY,Rd as o0,Sd as AY,Td as D8,Ud as N2,Xd as U6,ce as p0}from"./chunk-y7fhg1gb.js";import"./chunk-v508x7cg.js";import"./chunk-c9e0fbyh.js";import"./chunk-seamt0j3.js";import{se as J4}from"./chunk-33bpwkyk.js";import"./chunk-mygw13zd.js";import"./chunk-4n3yf5n8.js";import{Ee as Q8,He as _Y,Me as iJ,Ve as hY}from"./chunk-yr9mex38.js";import"./chunk-jzvbjn6e.js";import"./chunk-7nx0pzfk.js";import"./chunk-b9nhnzaj.js";import{pf as gQ,rf as q1}from"./chunk-4vyfj372.js";import"./chunk-zkhb55jz.js";import{tg as DY,yg as oJ,zg as VY}from"./chunk-jscpxfwd.js";import"./chunk-pfvgkexe.js";import"./chunk-qxn5bg5k.js";import{Ig as m$,Jg as a2,Kg as mQ}from"./chunk-reakyamv.js";import{Og as d0}from"./chunk-0141jad7.js";import"./chunk-eeb2945p.js";import{lh as vY,oh as t1}from"./chunk-b9vm7gns.js";import{qh as kJ,rh as SJ,uh as h1}from"./chunk-5nezhmnq.js";import"./chunk-h6a0nct6.js";import{Gh as bJ}from"./chunk-f44wasww.js";import{Jh as F4}from"./chunk-0a0sj79a.js";import"./chunk-sj0k8cdf.js";import{Uh as e8}from"./chunk-0ra945vt.js";import{Wh as EQ}from"./chunk-h0fh3j9w.js";import{useMemoizedFn as u8}from"ahooks";import{useEffect as S7,useState as l8}from"react";import{useMemoizedFn as s0}from"ahooks";import{Box as z$}from"ink";import{useEffect as _$,useMemo as R7,useRef as p8}from"react";import{useShallow as uY}from"zustand/react/shallow";import{useStore as xY}from"zustand";function t($){return xY(V$,$)}var lY=[],j$=()=>t(($)=>$.session.sessionId),T1=()=>t(($)=>$.session.workspaceRoot),B4=()=>t(($)=>$.session.messages),w4=()=>t(($)=>$.session.clearCount),b4=()=>t(($)=>$.session.isCompacting),A4=()=>t(($)=>$.session.tokenUsage.estimatedCostUsd),P4=()=>t(($)=>{let{totalInputTokens:Q,cacheReadTokens:Y,cacheWriteTokens:J}=$.session.tokenUsage;return L4({totalInputTokens:Q,cacheReadTokens:Y,cacheWriteTokens:J}).hitRate}),y4=()=>t(($)=>$.session.providerCircuit),R4=()=>t(($)=>$.session.providerAdmission),M4=()=>t(($)=>$.session.providerRetry),T4=()=>t(($)=>$.session.providerStall),C4=()=>t(($)=>$.session.actionStationarity),i1=()=>t(($)=>$.session.actions),I4=()=>t(($)=>{let{inputTokens:Q,maxContextTokens:Y}=$.session.tokenUsage;if(Y<=0)return 100;let J=Math.max(0,100-Q/Y*100);return Math.round(J)}),f4=()=>t(($)=>$.app.initializationStatus),k4=()=>t(($)=>$.app.initializationError),D2=()=>t(($)=>$.app.activeModal),S4=()=>t(($)=>$.app.tasks),v4=()=>t(($)=>$.app.modelEditorTarget),D4=()=>t(($)=>$.app.sessionSelectorData),V4=()=>t(($)=>$.app.awaitingSecondCtrlC),n1=()=>t(($)=>$.app.actions),V2=()=>t(($)=>$.app.sideConversation),j4=()=>t(($)=>$.app.teams),j2=()=>t(($)=>$.app.initializationStatus==="ready"),h4=()=>t(($)=>$.app.tasks.length>0),h$=()=>t(($)=>$.config.config?.permissionMode||"default"),E4=()=>t(($)=>$.config.config?.models??lY),h2=()=>t(($)=>{let Q=$.config.config;if(!Q)return;let Y=Q.currentModelId;return Q.models.find((Z)=>Z.id===Y)??Q.models[0]}),E2=()=>t(($)=>$.config.config?.currentModelId),g4=()=>t(($)=>$.config.config?.agentTeamsEnabled===!0),b0=()=>t(($)=>{return a0.getTheme()}),m4=()=>t(($)=>$.config.config?.codeTheme??"default"),e0=()=>t(($)=>$.focus.currentFocus),p4=()=>t(($)=>$.focus.actions),E$=()=>t(($)=>$.command.isProcessing),c4=()=>t(($)=>$.command.actions),g2=()=>t(($)=>$.command.pendingCommands),x4=()=>t(($)=>$.command.recoveredSteeringCount),m2=()=>t(($)=>$.app.reasoningEffort!=="off"),p2=()=>t(($)=>$.app.reasoningEffort),c2=()=>t(($)=>$.app.serviceTier),x2=()=>t(($)=>$.app.responseVerbosity),u2=()=>t(($)=>$.app.communicationStyle),u4=()=>t(($)=>$.session.currentThinkingContent),l4=()=>t(($)=>$.session.thinkingExpanded),d4=()=>t(($)=>$.session.currentStreamingMessageId),r4=()=>t(uY(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),a4=()=>t(($)=>$.session.finalizingStreamingMessageId),o4=()=>t(($)=>$.session.historyExpanded),i4=()=>t(($)=>$.session.expandedMessageCount);import{useMemoizedFn as s1}from"ahooks";import{useEffect as c$,useRef as s8}from"react";function dY($){if(!($ instanceof Error))return"未知错误";let J=$.lastError??$;if(J.responseBody)try{let K=JSON.parse(J.responseBody)?.error?.message;if(K){let U=J.statusCode?` (HTTP ${J.statusCode})`:"";return`${K}${U}`}}catch{}let Z=$.message.match(/Last error:\s*(.+)$/);if(Z)return Z[1];return $.message}function rY($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function aY($){if(!($ instanceof Error))return!1;let Q=$.message;return Q.includes("can only concatenate str")||Q.includes("image_url")||Q.includes("multimodal")||Q.includes("vision")||Q.includes("does not support images")}function l2($){let Q=rY($),Y=aY($),J;if(Y)J="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else J=dY($);return{displayMessage:J,isAbort:Q,isVisionNotSupported:Y}}import{appendFileSync as oY,mkdirSync as iY,writeFileSync as nY}from"node:fs";import tY from"node:os";import a8 from"node:path";var n4=null;function sY(){let $=process.env.BLADE_STORAGE_ROOT||a8.join(tY.homedir(),".blade");return a8.join($,"logs","stream-debug.log")}function eY($){if(n4===$)return;let Q=a8.dirname($);iY(Q,{recursive:!0,mode:493}),nY($,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
|
|
2
2
|
`),n4=$}function o8($,Q,Y){try{let J=sY();eY(J);let Z=new Date().toISOString(),X=Y?` | ${JSON.stringify(Y)}`:"",K=`[${Z}] [${$}] ${Q}${X}
|
|
3
3
|
`;oY(J,K)}catch{}}var q2=t1("UI");function Q6($,Q){let Y=!1;return(J)=>{switch(J.kind){case"content_delta":if(Y||$.signal.aborted)break;Q.contentDeltaCount++,Q.contentDeltaTotalLen+=J.delta.length,o8("loopEventHandler","onContentDelta",{callCount:Q.contentDeltaCount,deltaLen:J.delta.length,totalLen:Q.contentDeltaTotalLen}),$.streamingBuffer.batchAppendContent(J.delta);break;case"thinking_delta":if(Y||$.signal.aborted)break;if($.thinkingModeEnabled)$.streamingBuffer.batchAppendThinking(J.delta);break;case"stream_end":{if($.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),q2.debug("[loopEventHandler] stream_end",{contentDeltaCount:Q.contentDeltaCount,contentDeltaTotalLen:Q.contentDeltaTotalLen,streamFinalized:Y,signalAborted:$.signal.aborted}),o8("loopEventHandler","onStreamEnd",{contentDeltaCallCount:Q.contentDeltaCount,contentDeltaTotalLen:Q.contentDeltaTotalLen,streamFinalized:Y,signalAborted:$.signal.aborted}),Y||$.signal.aborted){Y=!0;break}let{extraContent:Z,extraThinking:X}=$.streamingBuffer.drainPendingBuffers(),K=$.getStreamingMessageId();if(K){if(Z)g$(K,Z);r2(K)}$.sessionActions.finalizeStreamingMessage(Z,X),Y=!0;break}case"model_fallback":Y=!0,$.sessionActions.setProviderAdmission(null),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),$.streamingBuffer.resetStreamingBuffers(),$.sessionActions.discardStreamingMessage(),$.sessionActions.setCurrentThinkingContent(null);break;case"provider_admission":{let{kind:Z,...X}=J;$.sessionActions.setProviderAdmission(J.phase==="queued"?X:null);break}case"provider_circuit":{let{kind:Z,...X}=J;$.sessionActions.setProviderCircuit(J.phase==="closed"?null:X);break}case"provider_retry":{let{kind:Z,...X}=J;$.sessionActions.setProviderRetry(J.phase==="recovered"?null:X);break}case"provider_stall":{let{kind:Z,...X}=J;$.sessionActions.setProviderStall(J.phase==="detected"?X:null);break}case"action_stationarity":{let{kind:Z,...X}=J;$.sessionActions.setActionStationarity(J.phase==="recovered"?null:X);break}case"tool_start":{let Z=J.toolCall;if(!("function"in Z))break;if(Z.function.name===d2)break;if(q2.debug("[loopEventHandler] tool_start",{toolName:Z.function.name,toolKind:J.toolKind}),["TaskCreate","TaskUpdate","TaskList"].includes(Z.function.name))break;try{let X=JSON.parse(Z.function.arguments),K=e4(Z.function.name,X);$.sessionActions.addToolMessage(K,{toolCallId:Z.id,toolName:Z.function.name,phase:"start",summary:K,params:X})}catch(X){q2.error("[loopEventHandler] onToolStart error:",X)}break}case"tool_progress":{let Z=J.toolCall;if(!("function"in Z))break;if(Z.function.name===d2)break;let X=J.update.total!==void 0?` ${Math.max(0,Math.min(100,Math.round((J.update.progress??0)/J.update.total*100)))}%`:"",K=`${Z.function.name}${X}: ${J.update.message}`;$.sessionActions.addToolMessage(K,{toolCallId:Z.id,toolName:Z.function.name,phase:"progress",summary:K,...J.update.admission?{admission:J.update.admission}:{}});break}case"tool_result":{let Z=J.toolCall;if(!("function"in Z))break;if(Z.function.name===d2)break;q2.debug("[loopEventHandler] tool_result",{toolName:Z.function.name,success:J.result.success});let X=s4($6(Z.function.name,J.result),t4);$.sessionActions.addToolMessage(X.summary,{toolCallId:Z.id,toolName:Z.function.name,phase:"complete",summary:X.summary,detail:X.detail});break}case"structured_output":$.sessionActions.replaceLastAssistantMessage(JSON.stringify(J.output,null,2));break;case"token_usage":$.sessionActions.updateTokenUsage(J.usage);break;case"compaction":if($.sessionActions.setCompacting(J.phase==="start"),J.phase==="end"){if($.sessionActions.resetContextUsage(),J.outcome!=="failed")Q.compactionCount=(Q.compactionCount??0)+1}break;case"turn_start":q2.debug("[loopEventHandler] turn_start",{turn:J.turn,maxTurns:J.maxTurns}),$.sessionActions.updateTokenUsage({turnCount:J.turn}),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),Y=!1;break;case"task_update":$.appActions.setTasks(J.tasks);break;case"mcp_catalog_changed":{let Z=`MCP catalog r${J.revision}: +${J.added.length} -${J.removed.length} ~${J.updated.length}`;$.sessionActions.addToolMessage(Z,{toolName:"MCP Catalog",phase:"complete",summary:Z,detail:[J.added.length>0?`Added: ${J.added.join(", ")}`:"",J.removed.length>0?`Removed: ${J.removed.join(", ")}`:"",J.updated.length>0?`Updated: ${J.updated.join(", ")}`:""].filter(Boolean).join(`
|
|
4
4
|
`)});break}case"mcp_content_changed":{let Z=`MCP ${J.contentKind} r${J.revision}: +${J.added.length} -${J.removed.length} ~${J.updated.length}`;$.sessionActions.addToolMessage(Z,{toolName:"MCP Content",phase:"complete",summary:Z,detail:[J.added.length>0?`Added: ${J.added.join(", ")}`:"",J.removed.length>0?`Removed: ${J.removed.join(", ")}`:"",J.updated.length>0?`Updated: ${J.updated.join(", ")}`:""].filter(Boolean).join(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{ra as R,sa as m0,xa as Q3,ya as h9,za as u0}from"./chunk-
|
|
1
|
+
import{ra as R,sa as m0,xa as Q3,ya as h9,za as u0}from"./chunk-1mjh959m.js";import{Aa as W6,Ca as c3,Ea as l3,Fa as QZ,Xa as i3}from"./chunk-ky9q53m7.js";import{$a as a$,Bb as v5,Cb as aJ,Db as FJ,Fb as Z2,Gb as fJ,Lb as Z7,Ob as J7,Ya as b$,Za as F1,_a as b9,ab as H9,bb as j9,cb as F9,db as M9,eb as C9,fb as B7,jb as W0,lb as $5,ob as O5,qb as K4,rb as F5,sb as D5,ub as Q8,vb as Q$}from"./chunk-9y9bhhfx.js";import{Cc as GZ,Dc as d0,Ec as D1,Fc as TJ,Gc as RJ,Jc as Z3,Nc as $7,Sc as PJ,Tc as SJ,Ub as O0,Vb as f1,Vc as r,Wb as m$,Xb as N2,Yb as KZ,Zb as K5,_b as G5,rc as P5,sc as L0,tc as $$}from"./chunk-8ts93ywy.js";import{Wc as x,Xc as E7,Yc as w7,Zc as t$}from"./chunk-skw3b17a.js";import{_c as n3,bd as a3,kd as o3,qd as t3}from"./chunk-jwx10h5z.js";import{Bd as J8,Cd as $8}from"./chunk-h3w814js.js";import{Od as B5,Pd as H0,Qd as f,Td as B0,Ud as Z5,Vd as B1,Wd as P$,Xd as E4,Yd as i$,Zd as s9,ce as G1}from"./chunk-y7fhg1gb.js";import{de as $1}from"./chunk-c9e0fbyh.js";import{ie as e9,je as o9,oe as dJ,pe as J5}from"./chunk-seamt0j3.js";import{re as P0,se as g$}from"./chunk-33bpwkyk.js";import{te as tJ}from"./chunk-mygw13zd.js";import{ve as bJ,we as AJ,xe as jJ}from"./chunk-4n3yf5n8.js";import{Ae as z5,Ce as V5,De as H5,Ee as I$,Fe as M7,He as K$,Ie as Z$,Je as a0,Ke as Z6,Le as H1,Me as k5,Ne as W1,Oe as X1,Pe as CJ,Te as g4,Ve as S0,We as U$,Ye as Y5,Ze as kJ,ye as Q5,ze as U5}from"./chunk-yr9mex38.js";import{$e as f$,bf as X$,cf as c2,df as NZ,ef as bZ,ff as g1,gf as AZ,hf as jZ,if as M2}from"./chunk-jzvbjn6e.js";import{jf as B3,lf as MJ,mf as R5,nf as Y8}from"./chunk-7nx0pzfk.js";import{pf as $Z,rf as j0}from"./chunk-4vyfj372.js";import{sf as F2,tf as HZ,uf as D2,vf as U1}from"./chunk-zkhb55jz.js";import{$f as O9,Cf as dZ,Ef as a4,Jf as X3,Nf as pZ,Pf as LJ,Rf as w9,Sf as N9,Yf as s$,jg as u9,kg as m9,lg as d9,mg as p9,ng as q4,og as c9,pg as R$,qg as l9,rg as i9,sg as r9,ug as PZ,wg as vJ,xf as mZ,xg as NJ,yg as Q0}from"./chunk-jscpxfwd.js";import{Bg as N$}from"./chunk-pfvgkexe.js";import{Cg as j2,Dg as t5,Eg as O,Fg as S7,Gg as S,Hg as m}from"./chunk-qxn5bg5k.js";import{Jg as GJ,Kg as OJ}from"./chunk-reakyamv.js";import{Mg as f2,Og as T}from"./chunk-0141jad7.js";import{oh as l}from"./chunk-b9vm7gns.js";import{th as EJ,uh as wJ}from"./chunk-5nezhmnq.js";import{vh as q3,yh as F3}from"./chunk-h6a0nct6.js";import{Ch as N3}from"./chunk-f44wasww.js";import{Ih as yJ,Jh as v0}from"./chunk-0a0sj79a.js";import{Nh as w2,Ph as C$,Rh as qJ,Sh as wZ,Uh as e}from"./chunk-0ra945vt.js";import{Wh as t0}from"./chunk-h0fh3j9w.js";import{randomUUID as a5}from"crypto";import{randomUUID as BY}from"node:crypto";var KY=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);
|
|
@@ -816,7 +816,7 @@ ${n}
|
|
|
816
816
|
</approved-plan>
|
|
817
817
|
|
|
818
818
|
IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof G==="string")s=G+y;else s=[...G,{type:"text",text:y}]}P=yield*this.runLoop(s,F,{...C,inputMessageId:void 0})}if(!this.sessionRuntime||!b)return P;let k=await this.sessionRuntime.recordGoalProgress({tokens:P.metadata?.tokensUsed??0,elapsedMs:P.metadata?.duration??0,prematureStopPattern:P.success?E9(P.finalMessage):void 0});if(k)yield{kind:"goal_updated",goal:k};if(!P.success||F.signal?.aborted){if(k=await this.sessionRuntime.pauseActiveGoal(F.signal?.aborted?"goal paused after user cancellation":P.error?.message??"goal paused after turn failure"),k)yield{kind:"goal_updated",goal:k}}if(P.success&&!F.signal?.aborted&&w<20)await this.sessionRuntime.waitForBackgroundSubagentFollowUp(b,F.signal);let a=P.success&&!F.signal?.aborted&&w<20,g=uQ(P);if(N=await this.sessionRuntime.finishTurn(b,{continuePending:a,...g?{acknowledgeInput:!0}:{},outcome:P.success&&!F.signal?.aborted?{status:"completed",turnsCount:P.metadata?.turnsCount??0,toolCallsCount:P.metadata?.toolCallsCount??0,durationMs:P.metadata?.duration??0}:{status:"aborted",cause:F.signal?.aborted?"cancelled":"failed",turnsCount:P.metadata?.turnsCount??0,toolCallsCount:P.metadata?.toolCallsCount??0,durationMs:P.metadata?.duration??0}}),N){w++,B=!0,D=!1,L=null,G="",q=void 0,_=M(),yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:A()};continue}if(!P.success||F.signal?.aborted)return P;if(k=await this.sessionRuntime.getGoal(),!k||k.status!=="active"&&k.status!=="verifying")return P;if(L=await this.sessionRuntime.beginGoalContinuation(),!L)return P;N=await this.sessionRuntime.beginTurn("goal"),B=!1,D=!0,G=C6(L),q=void 0,_=void 0,yield{kind:"goal_continuation_started",goal:L,continuation:L.continuationCount,...L.prematureStop?{prematureStopPattern:L.prematureStop.pattern,prematureStopCount:L.prematureStop.consecutiveCount}:{}},yield{kind:"goal_updated",goal:L}}}finally{if(this.sessionRuntime&&N)await this.sessionRuntime.finishTurn(N)}}let V=typeof U==="string"?U:U.filter((G)=>G.type==="text").map((G)=>G.text).join(`
|
|
819
|
-
`),H={id:this.generateTaskId(),type:"simple",prompt:V};return{success:!0,finalMessage:(await this.executeTask(H)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-
|
|
819
|
+
`),H={id:this.generateTaskId(),type:"simple",prompt:V};return{success:!0,finalMessage:(await this.executeTask(H)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-v1eakd9c.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){p.debug("Processing Plan mode message...");let{prompt:Y}=await A$({projectPath:Z.workspaceRoot||T(),mode:"plan",includeEnvironment:!0,environmentOptions:Z2,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot}),W;if(typeof $==="string")W=d1($);else{let X=$.filter((Q)=>Q.type==="text");if(X.length>0){let Q=X[0];W=$.map((U)=>U===Q?{type:"text",text:d1(Q.text)}:U)}else W=[{type:"text",text:d1("")},...$]}return yield*this.executeLoop(W,Z,J,Y)}async*runLoop($,Z,J){p.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z.workspaceRoot||T());return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await A$({projectPath:$,replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:Z2,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let W=this.buildLoopDependencies();return J7(W,$,Z,J,Y)}takeStartupAdoptedToolResultEvents(){return(this.sessionRuntime?.takeStartupAdoptedToolResults()??[]).flatMap(({call:Z,result:J})=>{let Y={id:Z.toolCallId,type:"function",function:{name:Z.toolName,arguments:JSON.stringify(Z.input)}},W=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,X=J.error===void 0,Q=J.output,U={success:X,llmContent:typeof Q==="string"||Q!==null&&typeof Q==="object"?Q:Q===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(Q),...J.error?{error:{type:"execution_error",message:J.error}}:{},...W?{metadata:W}:{}},z=[{kind:"tool_result",toolCall:Y,result:U}],V=Z7(Y,U);if(V)z.push(V);return z})}buildLoopDependencies(){return{chatService:this.chatService,toolExecutor:this.toolExecutor,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,p.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($),staticProjectRules:this.sessionRuntime?.getStaticProjectRules(),hydrateProjectRules:this.sessionRuntime?($)=>this.sessionRuntime.hydrateProjectRules($):void 0,resolveContextualProjectRules:this.sessionRuntime?($,Z,J,Y)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,Y):void 0}}async chatWithSystem($,Z){if(!this.isInitialized)throw Error("Agent未初始化");let J=[{role:"system",content:$},{role:"user",content:Z}];return(await this.chatService.chat(J)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.toolExecutor?this.toolExecutor.getRegistry().getAll():[]}getToolRegistry(){return this.toolExecutor.getRegistry()}applyToolWhitelist($){let Z=this.toolExecutor.getRegistry(),Y=Z.getAll().filter((W)=>!$.includes(W.name));for(let W of Y)Z.unregister(W.name);p.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let Y of Z.getAll())if(J.has(Y.name))Z.unregister(Y.name);p.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let Y=Z.get(J.kind)||0;Z.set(J.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.name)}}async destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=(async()=>{this.log("销毁Agent..."),await this.activeOperations.shutdown("agent-destroy");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}})(),this.destroyPromise}syncRuntimeState(){if(!this.sessionRuntime)return;this.chatService=this.sessionRuntime.getChatService(),this.executionEngine=this.sessionRuntime.getExecutionEngine(),this.attachmentCollector=this.sessionRuntime.getAttachmentCollector(),this.currentModelId=this.sessionRuntime.getCurrentModelId(),this.currentModelMaxContextTokens=this.sessionRuntime.getCurrentModelMaxContextTokens()}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}log($,Z){p.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){p.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await A$({projectPath:this.sessionRuntime?.workspaceRoot??T(),replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot});if(J.prompt)this.log("系统提示配置验证成功"),p.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await W5({sessionId:"default",configDir:e(),workspaceRoot:T(),resourceRoot:T(),agentResources:this.agentResources});p.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;p.debug(`Builtin tools registered: ${Z} tools`),p.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw p.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await k2({workspaceRoot:T(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){p.debug("No MCP servers configured");return}let Z=u0.createIsolated({artifactWriter:new m1(`legacy-${gQ()}`)});this.legacyMcpRegistry=Z;for(let[X,Q]of Object.entries($))try{p.debug(`Connecting to MCP server: ${X}`),await Z.registerServer(X,Q),p.debug(`MCP server "${X}" connected`)}catch(U){p.warn(`Warning: MCP server "${X}" connection failed:`,U)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(r1(Z));let W=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:W.revision,reason:"snapshot",replace:!0,instructions:W.instructions,removed:[]}),Z.on("catalogChanged",(X)=>{J.replaceMcpTools(X.tools,X)}),Z.on("contentCatalogChanged",(X)=>{J.queueMcpContentChange(X)}),Z.on("resourceUpdated",(X)=>{J.queueMcpResourceUpdated(X)}),Z.on("connectionLifecycleChanged",(X)=>{J.queueMcpConnectionChange(X)}),Z.on("log",(X)=>{J.queueMcpLog(X)}),Z.on("instructionsChanged",(X)=>{J.queueMcpInstructionsChange({revision:X.revision,reason:X.reason,replace:!1,instructions:X.action==="added"&&X.instruction?[{serverName:X.serverName,...X.instruction}]:[],removed:X.action==="removed"?[X.serverName]:[]})}),Y.tools.length>0)p.debug(`Registered ${Y.tools.length} MCP tools`),p.debug(`[MCP Tools] ${Y.tools.map((X)=>X.name).join(", ")}`)}catch($){p.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await S0(T());if(this.agentResources=Y5($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)p.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else p.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;p.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{return Z.some((W)=>{if(W===Y.name)return!0;let X=W.match(/^(\w+)\(.*\)$/);if(X&&X[1]===Y.name)return!0;return!1})});return p.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)p.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let Z=[];for(let Y of $)if(Y.type==="text")Z.push(Y.text);if(Z.length===0)return $;let J=Z.join(`
|
|
820
820
|
`);try{let Y=await this.attachmentCollector.collect(J);if(Y.length===0)return $;p.debug(`Processed ${Y.length} @ file mentions in multimodal message`);let W=this.buildAttachmentText(Y);if(!W)return $;return[...$,{type:"text",text:W}]}catch(Y){return p.error("Failed to process @ mentions in multimodal message:",Y),$}}buildAttachmentText($){let Z=[],J=[];for(let W of $)if(W.type==="file"){let X=W.metadata?.lineRange?` (lines ${W.metadata.lineRange.start}${W.metadata.lineRange.end?`-${W.metadata.lineRange.end}`:""})`:"";Z.push(`<file path="${W.path}"${X?` range="${X}"`:""}>`,W.content,"</file>")}else if(W.type==="directory")Z.push(`<directory path="${W.path}">`,W.content,"</directory>");else if(W.type==="error")J.push(`- @${W.path}: ${W.error}`);let Y="";if(Z.length>0)Y+=`
|
|
821
821
|
|
|
822
822
|
<system-reminder>
|
|
@@ -1118,29 +1118,31 @@ ${Y.response}`,data:{action:"show_side_conversation",question:J,response:Y.respo
|
|
|
1118
1118
|
• Token 数量: ${V.toLocaleString()}
|
|
1119
1119
|
• Token 限制: ${K.toLocaleString()}
|
|
1120
1120
|
• 使用率: ${G}%`),V<K*0.5)return J.sendMessage(`提示: 当前 token 使用率较低(${G}%),可以暂时不压缩。
|
|
1121
|
-
系统会在达到 80% 时自动触发压缩。`),{success:!0,message:"无需压缩"};J.sendMessage("**正在压缩上下文...**");let F=await aJ.compact(z,{trigger:"manual",modelName:W.model,modelProvider:W.provider,maxContextTokens:K,apiKey:H.chat.apiKey,baseURL:H.chat.baseUrl,workspaceRoot:Z.workspaceRoot??Z.cwd,sessionId:U});if(U)await new t1({projectPath:Z.workspaceRoot??Z.cwd}).saveCompaction(U,F.summary,{trigger:"manual",reason:"manual",strategy:F.success?"llm":"fallback",preTokens:F.preTokens,postTokens:F.postTokens,sampleAttempts:F.sampleAttempts,inputReductions:F.inputReductions,messagesOmitted:F.messagesOmitted,filesOmitted:F.filesOmitted,failureReason:F.failureReason,filesIncluded:F.filesIncluded,replacementMessages:F.compactedMessages},null),console.log("[/compact] 压缩数据已保存到 JSONL");if(F.success){let B=`[OK] **压缩完成!**
|
|
1121
|
+
系统会在达到 80% 时自动触发压缩。`),{success:!0,message:"无需压缩"};J.sendMessage("**正在压缩上下文...**");let F=await aJ.compact(z,{trigger:"manual",modelName:W.model,modelProvider:W.provider,maxContextTokens:K,apiKey:H.chat.apiKey,baseURL:H.chat.baseUrl,workspaceRoot:Z.workspaceRoot??Z.cwd,sessionId:U});if(U)await new t1({projectPath:Z.workspaceRoot??Z.cwd}).saveCompaction(U,F.summary,{trigger:"manual",reason:"manual",strategy:F.success?"llm":"fallback",preTokens:F.preTokens,postTokens:F.postTokens,sampleAttempts:F.sampleAttempts,inputReductions:F.inputReductions,messagesOmitted:F.messagesOmitted,filesOmitted:F.filesOmitted,imagesOmitted:F.imagesOmitted,failureReason:F.failureReason,filesIncluded:F.filesIncluded,replacementMessages:F.compactedMessages},null),console.log("[/compact] 压缩数据已保存到 JSONL");if(F.success){let B=`[OK] **压缩完成!**
|
|
1122
1122
|
|
|
1123
1123
|
**Token 变化**
|
|
1124
1124
|
• 压缩前: ${F.preTokens.toLocaleString()} tokens
|
|
1125
1125
|
• 压缩后: ${F.postTokens.toLocaleString()} tokens
|
|
1126
1126
|
• 摘要尝试: ${F.sampleAttempts??0}
|
|
1127
1127
|
• 输入缩减: ${F.inputReductions??0}
|
|
1128
|
+
• 省略图片: ${F.imagesOmitted??0}
|
|
1128
1129
|
• 压缩率: ${((1-F.postTokens/F.preTokens)*100).toFixed(1)}%`;if(F.filesIncluded.length>0)B+=`
|
|
1129
1130
|
|
|
1130
1131
|
**包含文件** (${F.filesIncluded.length})`,F.filesIncluded.forEach((D,_)=>{B+=`
|
|
1131
1132
|
${_+1}. ${D}`});return B+=`
|
|
1132
1133
|
|
|
1133
|
-
对话历史已压缩,但完整记录仍保存在会话文件中。`,J.sendMessage(B),{success:!0,message:"compact_completed",data:{compactedMessages:F.compactedMessages,boundaryMessage:F.boundaryMessage,summaryMessage:F.summaryMessage,preTokens:F.preTokens,postTokens:F.postTokens,filesIncluded:F.filesIncluded,usage:F.usage,maxContextTokens:K}}}else return J.sendMessage(`[WARN] **压缩使用降级策略**
|
|
1134
|
+
对话历史已压缩,但完整记录仍保存在会话文件中。`,J.sendMessage(B),{success:!0,message:"compact_completed",data:{compactedMessages:F.compactedMessages,boundaryMessage:F.boundaryMessage,summaryMessage:F.summaryMessage,preTokens:F.preTokens,postTokens:F.postTokens,filesIncluded:F.filesIncluded,usage:F.usage,sampleAttempts:F.sampleAttempts,inputReductions:F.inputReductions,messagesOmitted:F.messagesOmitted,filesOmitted:F.filesOmitted,imagesOmitted:F.imagesOmitted,maxContextTokens:K}}}else return J.sendMessage(`[WARN] **压缩使用降级策略**
|
|
1134
1135
|
|
|
1135
1136
|
**Token 变化**
|
|
1136
1137
|
• 压缩前: ${F.preTokens.toLocaleString()} tokens
|
|
1137
1138
|
• 压缩后: ${F.postTokens.toLocaleString()} tokens
|
|
1138
1139
|
• 摘要尝试: ${F.sampleAttempts??0}
|
|
1139
1140
|
• 输入缩减: ${F.inputReductions??0}
|
|
1141
|
+
• 省略图片: ${F.imagesOmitted??0}
|
|
1140
1142
|
|
|
1141
1143
|
由于压缩过程出现错误,已使用简单截断策略。
|
|
1142
1144
|
失败分类: ${F.failureReason??"deterministic"}
|
|
1143
|
-
错误信息: ${F.error}`),{success:!1,message:"compact_fallback",error:F.error,data:{compactedMessages:F.compactedMessages,boundaryMessage:F.boundaryMessage,summaryMessage:F.summaryMessage,preTokens:F.preTokens,postTokens:F.postTokens,sampleAttempts:F.sampleAttempts,inputReductions:F.inputReductions,messagesOmitted:F.messagesOmitted,filesOmitted:F.filesOmitted,failureReason:F.failureReason}}}catch(Y){let W=Y instanceof Error?Y.message:String(Y);return J.sendMessage(`[FAIL] **压缩失败**: ${W}`),{success:!1,error:W}}}var AV={name:"compact",description:"手动压缩当前会话的上下文",fullDescription:"压缩当前对话历史,生成详细的技术总结,保留最近的消息。压缩后的上下文可以节省 token 使用量,同时保留关键信息。",usage:"/compact",examples:["/compact"],category:"context",handler:bV},oJ=AV;function jV($){return`Reasoning effort: ${$.selection===$.effective?$.selection:`${$.selection} (${$.effective})`}
|
|
1145
|
+
错误信息: ${F.error}`),{success:!1,message:"compact_fallback",error:F.error,data:{compactedMessages:F.compactedMessages,boundaryMessage:F.boundaryMessage,summaryMessage:F.summaryMessage,preTokens:F.preTokens,postTokens:F.postTokens,usage:F.usage,sampleAttempts:F.sampleAttempts,inputReductions:F.inputReductions,messagesOmitted:F.messagesOmitted,filesOmitted:F.filesOmitted,imagesOmitted:F.imagesOmitted,failureReason:F.failureReason,maxContextTokens:K}}}catch(Y){let W=Y instanceof Error?Y.message:String(Y);return J.sendMessage(`[FAIL] **压缩失败**: ${W}`),{success:!1,error:W}}}var AV={name:"compact",description:"手动压缩当前会话的上下文",fullDescription:"压缩当前对话历史,生成详细的技术总结,保留最近的消息。压缩后的上下文可以节省 token 使用量,同时保留关键信息。",usage:"/compact",examples:["/compact"],category:"context",handler:bV},oJ=AV;function jV($){return`Reasoning effort: ${$.selection===$.effective?$.selection:`${$.selection} (${$.effective})`}
|
|
1144
1146
|
Supported: auto, ${$.supported.join(", ")}`}var MV={name:"effort",description:"查看或设置当前 Session 的推理强度",fullDescription:"推理强度由当前 Session 持有并持久化。auto 会按模型能力在 high 附近解析;显式不支持的级别会被拒绝。",usage:"/effort [auto|off|minimal|low|medium|high|xhigh|max]",category:"Session",examples:["/effort","/effort low","/effort auto","/effort off"],async handler($,Z){if(!Z.reasoning)return{success:!1,error:"This surface has no active Session reasoning boundary"};if($.length>1)return{success:!1,error:"Usage: /effort [auto|off|minimal|low|medium|high|xhigh|max]"};let J=$[0]?.toLowerCase();if(J!==void 0&&!tJ(J))return{success:!1,error:`Invalid reasoning effort: ${J}`};try{let Y=J?await Z.reasoning.set(J):await Z.reasoning.get();return{success:!0,message:jV(Y),data:{reasoningEffort:Y.selection,effectiveReasoningEffort:Y.effective,supportedReasoningEfforts:Y.supported}}}catch(Y){return{success:!1,error:Y instanceof Error?Y.message:"Failed to update reasoning effort"}}}},sJ=MV;import{mkdir as CV,open as TV,unlink as RV}from"node:fs/promises";import eJ from"node:os";import j1 from"node:path";function PV($,Z,J){let Y=Z?.trim()||J;if(Y.includes("\x00"))throw Error("Session export path contains a null byte");if(Y==="~")return j1.join(eJ.homedir(),J);if(Y.startsWith(`~${j1.sep}`)||Y.startsWith("~/"))return j1.resolve(eJ.homedir(),Y.slice(2));return j1.resolve($,Y)}async function $3($,Z,J){if(!j1.isAbsolute($))throw Error("Session export cwd must be absolute");let Y=PV($,J,Z.filename);await CV(j1.dirname(Y),{recursive:!0,mode:448});let W,X=!1;try{return W=await TV(Y,"wx",384),X=!0,await W.writeFile(Z.markdown,"utf8"),await W.sync(),Y}catch(Q){if(await W?.close().catch(()=>{return}),W=void 0,X)await RV(Y).catch(()=>{return});if(Q.code==="EEXIST")throw Error(`Session export already exists: ${Y}`);throw Q}finally{await W?.close().catch(()=>{return})}}function SV($){let Z=!1,J=[];for(let Y of $){if(Y==="--reasoning"){Z=!0;continue}if(Y.startsWith("--"))throw Error(`Unknown export option: ${Y}`);J.push(Y)}if(J.length>1)throw Error("Usage: /export [path] [--reasoning]");return{includeReasoning:Z,...J[0]?{outputPath:J[0]}:{}}}var fV={name:"export",description:"Export the current durable conversation as safe Markdown",fullDescription:"将当前完整 durable history 导出为 Markdown。工具活动经过凭证、二进制、宿主路径和体积清理;reasoning 仅在显式 --reasoning 时包含。",usage:"/export [path] [--reasoning]",category:"Session",examples:["/export","/export reports/conversation.md","/export --reasoning"],async handler($,Z){if(!Z.sessionId)return{success:!1,error:"No active session to export"};let J=Z.workspaceRoot??Z.cwd;try{let{includeReasoning:Y,outputPath:W}=SV($),X=await r.exportSessionMarkdown(Z.sessionId,J,{includeReasoning:Y});if(Z.surface==="acp"){if(W)return{success:!1,error:"ACP export does not write host paths; omit the path to receive Markdown"};if(Buffer.byteLength(X.markdown,"utf8")>Z3)return{success:!1,error:"Session export exceeds the ACP inline limit; use the Web export endpoint"};return{success:!0,message:"Session export ready",content:X.markdown,data:{action:"session_exported",filename:X.filename,contentSha256:X.contentSha256,contentBytes:X.contentBytes}}}let Q=await $3(J,X,W);return{success:!0,message:`Saved conversation to ${Q}
|
|
1145
1147
|
SHA-256 ${X.contentSha256}`,data:{action:"session_exported",filePath:Q,filename:X.filename,contentSha256:X.contentSha256,contentBytes:X.contentBytes,redactionCount:X.redactionCount}}}catch(Y){return{success:!1,error:Y instanceof Error?Y.message:"Session export failed"}}}},J3=fV;function kV($){return $.filter((Z)=>Z.relationType!=="subagent")}var yV={name:"fork",description:"Fork a conversation into an independent session branch",fullDescription:"从任意工作区的历史会话创建独立分支。可以指定唯一 sessionId 直接 fork,或不带参数打开会话选择器。",usage:"/fork [sessionId]",category:"Session",examples:["/fork - 打开会话选择器","/fork parent-session - 直接 fork 指定会话"],async handler($,Z){if($.length>1)return{success:!1,error:"Usage: /fork [sessionId]"};try{let J=await r.listSessions({includeSubagents:!1}),Y=kV(J);if($.length===0){if(Y.length===0)return{success:!1,error:"No forkable sessions found"};return{success:!0,data:{action:"select_session",intent:"fork",sessions:Y}}}let W=$[0],X=J.filter((U)=>U.sessionId===W);if(X.length>0&&X.every((U)=>U.relationType==="subagent"))return{success:!1,error:`Cannot fork subagent session: ${W}`};let Q=Y.filter((U)=>U.sessionId===W);if(Q.length===0)return{success:!1,error:`Session not found: ${W}`};if(Q.length>1)return{success:!1,error:`Multiple workspaces contain session ${W}; use /fork to select one`};return{success:!0,data:{action:"activate_session",intent:"fork",session:Q[0]}}}catch(J){return{success:!1,error:J instanceof Error?J.message:"Failed to list sessions"}}}},Y3=yV;function U3($){let Z=Math.floor((Date.now()-$.getTime())/1000);if(Z<60)return`${Z}s ago`;let J=Math.floor(Z/60);if(J<60)return`${J}m ago`;let Y=Math.floor(J/60);if(Y<24)return`${Y}h ago`;return`${Math.floor(Y/24)}d ago`}async function vV($){let Z=u0.getInstance(),J=i$();if(Object.keys(J).length===0){$.sendMessage(`**MCP 服务器状态**
|
|
1146
1148
|
|
|
@@ -1621,7 +1623,7 @@ ${J}
|
|
|
1621
1623
|
`)),{success:!0,message:"Schedules listed",content:z.join(`
|
|
1622
1624
|
`)}}case"create":{let U=qK(X);if("error"in U)return Y.sendMessage(`创建失败:${U.error}`),{success:!1,error:U.error};let z={prompt:U.prompt,projectPath:Q,trigger:U.trigger,isolation:"worktree",permissionMode:"default",enabled:!0};try{let V=await $.create(z),H=V.nextRunAt?new Date(V.nextRunAt).toLocaleString():"(无)";return Y.sendMessage(`[OK] 已创建定时任务 \`${V.id}\`
|
|
1623
1625
|
${QZ(V.trigger)} · 下次运行: ${H}`),{success:!0,message:`Schedule ${V.id} created`}}catch(V){let H=V instanceof Error?V.message:String(V);return Y.sendMessage(`创建失败:${H}`),{success:!1,error:H}}}case"remove":case"rm":{let U=X[0];if(!U)return Y.sendMessage("用法:/schedule remove <id>"),{success:!1,error:"Missing schedule id"};let z=await $.remove(U);return Y.sendMessage(z?`[OK] 已删除 \`${U}\``:`未找到 \`${U}\``),{success:z,message:z?"Removed":"Not found"}}case"enable":case"disable":{let U=X[0];if(!U)return Y.sendMessage(`用法:/schedule ${W} <id>`),{success:!1,error:"Missing schedule id"};let z=await $.setEnabled(U,W==="enable");return Y.sendMessage(z?`[OK] 已${W==="enable"?"启用":"停用"} \`${U}\``:`未找到 \`${U}\``),{success:Boolean(z),message:z?"Updated":"Not found"}}case"run":{let U=X[0];if(!U)return Y.sendMessage("用法:/schedule run <id>"),{success:!1,error:"Missing schedule id"};try{return await LK(U),Y.sendMessage(`[OK] 已触发 \`${U}\``),{success:!0,message:"Schedule triggered"}}catch(z){let V=z instanceof Error?z.message:String(z);return Y.sendMessage(`运行失败:${V}`),{success:!1,error:V}}}default:return Y.sendMessage(`未知子命令: ${W}
|
|
1624
|
-
使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${W}`}}}}}var r3=EK();import*as R1 from"node:fs/promises";import*as P1 from"node:path";async function s3($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:W,storagePath:X}=Z,Q=X??w2(W??T());if(!X){let G=await wK($,W??T(),J,Y);if(G)return G}let U;try{U=(await R1.readdir(Q)).filter((F)=>F.endsWith(".jsonl")&&!F.startsWith("agent_")).map((F)=>P1.join(Q,F))}catch{return[]}let V=(await Promise.all(U.map(async(G)=>{try{let F=await R1.stat(G);return{path:G,mtime:F.mtimeMs}}catch{return null}}))).filter((G)=>G!==null).sort((G,F)=>F.mtime-G.mtime).map((G)=>G.path),H=[],K=Y?$:$.toLowerCase();for(let G of V){if(H.length>=J)break;let F=P1.basename(G,".jsonl"),B=await NK(G,K,Y,F);if(H.push(...B),H.length>=J){H.length=J;break}}return H}async function wK($,Z,J,Y){try{let{syncAll:W}=await import("./chunk-h9xayrwp.js"),X=await o3();if(!X)return null;let{SessionService:Q}=await import("./chunk-
|
|
1626
|
+
使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${W}`}}}}}var r3=EK();import*as R1 from"node:fs/promises";import*as P1 from"node:path";async function s3($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:W,storagePath:X}=Z,Q=X??w2(W??T());if(!X){let G=await wK($,W??T(),J,Y);if(G)return G}let U;try{U=(await R1.readdir(Q)).filter((F)=>F.endsWith(".jsonl")&&!F.startsWith("agent_")).map((F)=>P1.join(Q,F))}catch{return[]}let V=(await Promise.all(U.map(async(G)=>{try{let F=await R1.stat(G);return{path:G,mtime:F.mtimeMs}}catch{return null}}))).filter((G)=>G!==null).sort((G,F)=>F.mtime-G.mtime).map((G)=>G.path),H=[],K=Y?$:$.toLowerCase();for(let G of V){if(H.length>=J)break;let F=P1.basename(G,".jsonl"),B=await NK(G,K,Y,F);if(H.push(...B),H.length>=J){H.length=J;break}}return H}async function wK($,Z,J,Y){try{let{syncAll:W}=await import("./chunk-h9xayrwp.js"),X=await o3();if(!X)return null;let{SessionService:Q}=await import("./chunk-g8swjz81.js");await W(X,Q.projectionDeriverForSearch());let U=P1.resolve(Z),z=t3(X,$,U,J*4),V=Y?$:$.toLowerCase(),H=[];for(let K of z){if(K.role!=="user"&&K.role!=="assistant")continue;let G=UZ(K.text,V,Y,K.session_id,K.role,K.timestamp??void 0,0);if(G)H.push(G);if(H.length>=J)break}return H}catch{return null}}async function NK($,Z,J,Y){try{let W=await R1.readFile($,"utf8"),Q=W.split(`
|
|
1625
1627
|
`).flatMap((K,G)=>{if(!K.trim())return[];try{return[{event:JSON.parse(K),index:G}]}catch{return[]}});if(!Q.some(({event:K})=>K.type==="session_created"))return bK(Q,Z,J,Y);let z=new Map(Q.flatMap(({event:K,index:G})=>typeof K.id==="string"?[[K.id,G+1]]:[])),V=n3(a3(W,$)),H=new Map;for(let K of V){if(K.type==="message_created"&&(K.data.role==="user"||K.data.role==="assistant"))H.set(K.data.messageId,{role:K.data.role,content:[],timestamp:K.timestamp,lineNumber:z.get(K.id)??0});if(K.type==="part_created"&&K.data.partType==="text"){let G=H.get(K.data.messageId),F=K.data.payload.text;if(G&&typeof F==="string")G.content.push(F)}}return[...H.values()].flatMap((K)=>{let G=UZ(K.content.join(" "),Z,J,Y,K.role,K.timestamp,K.lineNumber);return G?[G]:[]})}catch{return[]}}function bK($,Z,J,Y){return $.flatMap(({event:W,index:X})=>{if(W.type!=="message")return[];let Q=W.message;if(Q?.role!=="user"&&Q?.role!=="assistant"||!Q.content)return[];let U=typeof Q.content==="string"?Q.content:Array.isArray(Q.content)?Q.content.filter((V)=>typeof V==="object"&&V!==null&&V.type==="text"&&typeof V.text==="string").map((V)=>V.text).join(" "):"",z=UZ(U,Z,J,Y,Q.role,typeof W.timestamp==="string"?W.timestamp:void 0,X+1);return z?[z]:[]})}function UZ($,Z,J,Y,W,X,Q){if(!$)return;let U=J?$:$.toLowerCase();if(!U.includes(Z))return;let z=U.indexOf(Z),V=Math.max(0,z-80),H=Math.min($.length,z+Z.length+80);return{sessionId:Y,role:W,content:(V>0?"...":"")+$.slice(V,H).replace(/\n/g," ")+(H<$.length?"...":""),timestamp:X,lineNumber:Q}}function e3($){if($.length===0)return"没有找到匹配的历史记录";let Z=[`**找到 ${$.length} 条匹配:**
|
|
1626
1628
|
`];for(let J of $){let Y=J.timestamp?new Date(J.timestamp).toLocaleString("zh-CN",{timeZone:"Asia/Shanghai"}):"?",W=J.role==="user"?"\uD83D\uDC64":"\uD83E\uDD16";Z.push(`${W} \`${J.sessionId.slice(0,8)}\` (${Y})`),Z.push(` ${J.content}`),Z.push("")}return Z.join(`
|
|
1627
1629
|
`)}var AK={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=I(Z);if($.length===0)return J.sendMessage("**用法:** `/search <关键词>`\n\n在历史会话中搜索包含指定关键词的对话"),{success:!0,message:"显示帮助"};let Y=$.join(" ");J.sendMessage(`正在搜索: "${Y}" ...`);try{let W=await s3(Y,{maxResults:15,projectPath:Z.cwd}),X=e3(W);return J.sendMessage(X),{success:!0,message:`found ${W.length} results`,data:{matches:W.length}}}catch(W){let X=W instanceof Error?W.message:"未知错误";return J.sendMessage(`搜索失败: ${X}`),{success:!1,error:X}}}},$Y=AK;var jK={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,Z)=>{try{let J=Z.workspaceRoot??Z.cwd;return await U$(J,async(Y)=>{await Y.skills.refresh(),X1(J),await W1(J)}),{success:!0,message:"show_skills_manager",data:{action:"show_skills_manager"}}}catch(J){let Y=`获取 Skills 失败: ${J instanceof Error?J.message:"未知错误"}`;return f().addAssistantMessage(Y),{success:!1,error:Y}}}},ZY=jK;import MK from"node:path";function p5($){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 JY($){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 YY($,Z){if($.length<=Z)return $;return $.slice(0,Z-3)+"..."}async function CK($,Z){let J=I(Z),Y=$[0],W=o.getInstance(),X=U0.getInstance(),Q=Z.sessionId??"",U=Z.sessionId?{sessionId:Z.sessionId,projectPath:MK.resolve(Z.workspaceRoot??Z.cwd)}:void 0;if(Y==="resume"){let F=$[1],B=$.slice(2).join(" ").trim();if(!F||!B)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 D=await Z.subagents.resume(F,B),_=`Resumed \`${F}\` as \`${D.session.id}\` (depth ${D.session.resumeDepth}).`;return J.sendMessage(_),{success:!0,message:_,data:{action:"subagent_resumed",sourceAgentId:F,subagent:D.session}}}if(Y==="clean"){let F=X.cleanupExpiredSessionsForParent(U??Q,0);return J.sendMessage(`已清理 ${F} 个已完成的 Agent 会话`),{success:!0,message:`Cleaned ${F} agent sessions`}}let z=[`**后台任务列表**
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Bg as Y}from"./chunk-pfvgkexe.js";import{Cg as on,Dg as F,Eg as o}from"./chunk-qxn5bg5k.js";import{Ig as ct,Jg as bt}from"./chunk-reakyamv.js";import{Og as x}from"./chunk-0141jad7.js";import{$g as zt,Pg as Jn,Qg as Xt,Rg as pt,Vg as gt,Wg as kn,Xg as it,Yg as Rt,Zg as Ct,_g as un,ah as Bt,bh as On,ch as Kt,dh as Ut,eh as jn,fh as Ht,gh as Yt,hh as qt,ih as Vt,jh as Qt,kh as Gt}from"./chunk-eeb2945p.js";import{oh as fn}from"./chunk-b9vm7gns.js";import{rh as $t,uh as J}from"./chunk-5nezhmnq.js";import{Ch as Pn,Dh as Ln}from"./chunk-
|
|
1
|
+
import{Bg as Y}from"./chunk-pfvgkexe.js";import{Cg as on,Dg as F,Eg as o}from"./chunk-qxn5bg5k.js";import{Ig as ct,Jg as bt}from"./chunk-reakyamv.js";import{Og as x}from"./chunk-0141jad7.js";import{$g as zt,Pg as Jn,Qg as Xt,Rg as pt,Vg as gt,Wg as kn,Xg as it,Yg as Rt,Zg as Ct,_g as un,ah as Bt,bh as On,ch as Kt,dh as Ut,eh as jn,fh as Ht,gh as Yt,hh as qt,ih as Vt,jh as Qt,kh as Gt}from"./chunk-eeb2945p.js";import{oh as fn}from"./chunk-b9vm7gns.js";import{rh as $t,uh as J}from"./chunk-5nezhmnq.js";import{Ch as Pn,Dh as Ln}from"./chunk-f44wasww.js";import{Jh as h}from"./chunk-0a0sj79a.js";import{Uh as Tn}from"./chunk-0ra945vt.js";var Wt=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function Zt(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function R(n,t="MCP OAuth URL"){let M=new URL(n);if(M.username||M.password)throw Error(`${t} must not contain credentials`);if(M.protocol!=="https:"&&!(M.protocol==="http:"&&Zt(M.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return M}var U=async(n,t)=>{R(n,"MCP OAuth request URL");let M=await fetch(n,{...t,redirect:"manual"});if(M.status>=300&&M.status<400)throw await M.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return M};function k(n){let t=n.oauth;if(!t)return;let M=t;for(let u of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(M[u]!==void 0)throw Error(`MCP OAuth "${u}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(R(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((u)=>u.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let _=t.clientId?.trim();if(_&&_.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let S=t.scopes?.map((u)=>u.trim());if(S){if(S.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(S.some((u)=>!u||u.length>128||!Wt.test(u)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(S).size!==S.length)throw Error("MCP OAuth scopes must not contain duplicates")}let r=t.callbackPort;if(r!==void 0&&(!Number.isInteger(r)||r<1024||r>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,..._?{clientId:_}:{},...S?.length?{scopes:S}:{},...r!==void 0?{callbackPort:r}:{}}}import{randomUUID as v}from"node:crypto";import MM from"node:http";import{auth as cn}from"@modelcontextprotocol/sdk/client/auth.js";import _M from"open";import{createHash as Dt,randomUUID as Jt}from"node:crypto";import{constants as O,promises as L}from"node:fs";import j from"node:path";import kt from"write-file-atomic";var An=1,Ot=1048576,jt=5000,yt=50,Ft=/^[a-f0-9]{64}$/,lt=o.Object({client_id:o.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),vt=o.Object({access_token:o.String({minLength:1,maxLength:65536}),token_type:o.String({minLength:1,maxLength:64}),expires_in:o.Optional(o.Number({minimum:0})),refresh_token:o.Optional(o.String({minLength:1,maxLength:65536})),scope:o.Optional(o.String({maxLength:16384})),id_token:o.Optional(o.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),nM=o.Unsafe({type:"object",properties:{authorizationServerUrl:o.String({format:"uri"}),resourceMetadataUrl:o.Optional(o.String({format:"uri"})),resourceMetadata:o.Optional(o.Unknown()),authorizationServerMetadata:o.Optional(o.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),sn=o.Object({serverUrl:o.String({format:"uri"}),clientId:o.Optional(o.String({minLength:1,maxLength:4096})),clientInformation:o.Optional(lt),tokens:o.Optional(vt),tokenExpiresAt:o.Optional(o.Number({minimum:0})),discoveryState:o.Optional(nM),updatedAt:o.String({format:"date-time"})},{additionalProperties:!1}),En=o.Object({version:o.Literal(An),credentials:o.Record(o.String(),sn)},{additionalProperties:!1});function H(n,t){return n instanceof Error&&"code"in n&&n.code===t}function tM(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return H(t,"EPERM")}}function y(n){return structuredClone(n)}function mn(n){if(Object.keys(n.credentials).some((t)=>!Ft.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function q(n){let t=new URL(n);return t.hash="",t.toString()}function l(n,t,M=[]){return Dt("sha256").update(JSON.stringify({serverUrl:q(n),clientId:t?.trim()||null,scopes:[...M].sort()})).digest("hex")}class I{static locks=new Y;stateRoot;tokenFilePath;constructor(n=Tn()){this.stateRoot=j.join(n,"mcp"),this.tokenFilePath=j.join(this.stateRoot,"oauth-credentials.json")}static coordinationStatsForTests(){return this.locks.getStats()}async getCredential(n){return I.locks.runExclusive(this.tokenFilePath,async()=>{let M=(await this.readStore()).credentials[n];return M?y(M):null})}async updateCredential(n,t){return this.runMutation(async(M)=>{let e=M.credentials[n],_=await t(e?y(e):null);if(_)M.credentials[n]=F(sn,_);else delete M.credentials[n];return _?y(M.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return I.locks.runExclusive(this.tokenFilePath,async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return I.locks.runExclusive(this.tokenFilePath,async()=>{let t=await this.acquireStoreLock();try{let M=await this.readStore(),e=await n(M);return await this.writeStore(M),e}finally{await t()}})}async ensureStateRoot(){await L.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await L.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await L.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>Ot)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await L.readFile(this.tokenFilePath,"utf8")),M=on(En,t);if(!M.success)throw Error("MCP OAuth credential store has an invalid schema");return mn(M.data),M.data}catch(n){if(H(n,"ENOENT"))return{version:An,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=F(En,n);mn(t),await kt(this.tokenFilePath,`${JSON.stringify(t,null,2)}
|
|
2
2
|
`,{mode:384,encoding:"utf8"}),await L.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let n=j.join(this.stateRoot,".oauth-credentials.lock"),t=Jt(),M=Date.now()+jt;while(Date.now()<M)try{let e=await L.open(n,O.O_CREAT|O.O_EXCL|O.O_WRONLY,384);return await e.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:t,createdAt:new Date().toISOString()})}
|
|
3
3
|
`,"utf8"),await e.close(),async()=>{try{if(JSON.parse(await L.readFile(n,"utf8")).token===t)await L.unlink(n)}catch(_){if(!H(_,"ENOENT"))throw _}}}catch(e){if(!H(e,"EEXIST"))throw e;await this.removeDeadLock(n),await new Promise((_)=>setTimeout(_,yt))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(n){let t=await L.lstat(n);if(!t.isFile()||t.isSymbolicLink())throw Error("MCP OAuth credential lock must be a regular file");if(process.getuid&&t.uid!==process.getuid()||(t.mode&511)!==384)throw Error("MCP OAuth credential lock ownership or permissions are invalid");let M=JSON.parse(await L.readFile(n,"utf8"));if(typeof M.pid!=="number"||!Number.isInteger(M.pid)||M.pid<=0)throw Error("MCP OAuth credential lock owner is invalid");if(!tM(M.pid))await L.unlink(n)}}var bn="127.0.0.1",wn=7777,xn="/oauth/callback",eM=300000;class nn extends Error{constructor(n){super(`MCP server "${n}" requires OAuth authorization; run "blade mcp login ${n}" or use the Web MCP panel`);this.name="McpOAuthAuthorizationRequiredError"}}class an extends Error{constructor(n){super(`MCP OAuth credentials are unavailable in this runtime for server "${n}"`);this.name="McpOAuthUnavailableError"}}function rM(n){let t=n?"Authentication complete":"Authentication failed";return`<!doctype html>
|
|
4
4
|
<html lang="en">
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ve as a,we as b,xe as c}from"./chunk-
|
|
1
|
+
import{ve as a,we as b,xe as c}from"./chunk-4n3yf5n8.js";import"./chunk-jscpxfwd.js";import"./chunk-pfvgkexe.js";import"./chunk-qxn5bg5k.js";import"./chunk-reakyamv.js";import"./chunk-0141jad7.js";import"./chunk-eeb2945p.js";import"./chunk-b9vm7gns.js";import"./chunk-5nezhmnq.js";import"./chunk-h6a0nct6.js";import"./chunk-f44wasww.js";import"./chunk-0a0sj79a.js";import"./chunk-sj0k8cdf.js";import"./chunk-0ra945vt.js";import"./chunk-h0fh3j9w.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,a as cloneWorkspaceModelConfig};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{td as a,ud as b,vd as c}from"./chunk-
|
|
1
|
+
import{td as a,ud as b,vd as c}from"./chunk-pfdzgcza.js";import"./chunk-jdb2mwbn.js";import"./chunk-y7fhg1gb.js";import"./chunk-v508x7cg.js";import"./chunk-c9e0fbyh.js";import"./chunk-b9nhnzaj.js";import"./chunk-jscpxfwd.js";import"./chunk-pfvgkexe.js";import"./chunk-qxn5bg5k.js";import"./chunk-reakyamv.js";import"./chunk-0141jad7.js";import"./chunk-eeb2945p.js";import"./chunk-b9vm7gns.js";import"./chunk-5nezhmnq.js";import"./chunk-h6a0nct6.js";import"./chunk-f44wasww.js";import"./chunk-0a0sj79a.js";import"./chunk-sj0k8cdf.js";import"./chunk-0ra945vt.js";import"./chunk-h0fh3j9w.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
|