blade-code 0.10.28 → 0.10.30
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-0pbvrw1c.js → chunk-0prp87ys.js} +1 -1
- package/dist/{chunk-6vfctcqp.js → chunk-0rwz7tm0.js} +1 -1
- package/dist/{chunk-axcaxcgk.js → chunk-1444wfhr.js} +2 -2
- package/dist/{chunk-2ycs4wce.js → chunk-1ggxyyar.js} +1 -1
- package/dist/{chunk-4y6pjd2n.js → chunk-1sswefqp.js} +2 -2
- package/dist/{chunk-t0n90d7w.js → chunk-1zpqxjj7.js} +2 -2
- package/dist/{chunk-stmsk0kz.js → chunk-2d35rmyg.js} +2 -2
- package/dist/chunk-2wdmt91f.js +1 -0
- package/dist/{chunk-0pcwv1h8.js → chunk-37se34rx.js} +1 -1
- package/dist/{chunk-yv2sdpxk.js → chunk-39gb49pv.js} +1 -1
- package/dist/chunk-3y97cpzv.js +1 -0
- package/dist/{chunk-287fabvz.js → chunk-48tz6s0s.js} +2 -2
- package/dist/{chunk-jvtzyba4.js → chunk-4djps7bz.js} +1 -1
- package/dist/{chunk-j9djsqqy.js → chunk-4p9cwr9s.js} +2 -2
- package/dist/{chunk-hbhcj665.js → chunk-4qtb8yf6.js} +2 -2
- package/dist/{chunk-k3wmp1xm.js → chunk-4qyhtrhx.js} +1 -1
- package/dist/chunk-56hphybe.js +1 -0
- package/dist/{chunk-69r9j0ms.js → chunk-5m5nxkfs.js} +1 -1
- package/dist/{chunk-1e9cpchh.js → chunk-64hndcnj.js} +41 -41
- package/dist/{chunk-d6a4qw1m.js → chunk-6h9d9ykg.js} +1 -1
- package/dist/{chunk-sh2kjand.js → chunk-6kc12pma.js} +1 -1
- package/dist/chunk-7brnbdq8.js +10 -0
- package/dist/{chunk-q4fy74fz.js → chunk-7e7zgzag.js} +2 -2
- package/dist/{chunk-9ev9k5bd.js → chunk-82jdnt03.js} +2 -2
- package/dist/{chunk-0xhd2mzm.js → chunk-8gv6hsrf.js} +2 -2
- package/dist/{chunk-tct2ybbh.js → chunk-9mamc250.js} +2 -2
- package/dist/{chunk-1ycv8b9t.js → chunk-9pww3s5m.js} +1 -1
- package/dist/chunk-a5yd0c77.js +1 -0
- package/dist/{chunk-wn60hv0w.js → chunk-b634n0ts.js} +199 -199
- package/dist/{chunk-a1a4351m.js → chunk-btfxa4w8.js} +2 -2
- package/dist/chunk-d38t0wa2.js +6 -0
- package/dist/{chunk-5wkv5g4v.js → chunk-d4327k1v.js} +1 -1
- package/dist/{chunk-djzy4zgc.js → chunk-d9gthet1.js} +2 -2
- package/dist/chunk-e269454y.js +1 -0
- package/dist/{chunk-sjbqm4be.js → chunk-e3qzedvj.js} +2 -2
- package/dist/{chunk-dny4h2gz.js → chunk-ej1z75jf.js} +1 -1
- package/dist/{chunk-p4hf7agx.js → chunk-ekv4hpy8.js} +2 -2
- package/dist/chunk-f90v5vza.js +1 -0
- package/dist/{chunk-dx5996qr.js → chunk-fr3kysfm.js} +1 -1
- package/dist/{chunk-xqapcfw3.js → chunk-gdp6fg4e.js} +1 -1
- package/dist/{chunk-a1ftc84p.js → chunk-h9c7xec5.js} +2 -2
- package/dist/{chunk-6qdwp1t3.js → chunk-hdr8bcxt.js} +1 -1
- package/dist/{chunk-rqvejn8x.js → chunk-heydawsf.js} +2 -2
- package/dist/chunk-j3k3xdac.js +1 -0
- package/dist/{chunk-gpa4y0xk.js → chunk-j7ebts5c.js} +1 -1
- package/dist/{chunk-gbmnbckj.js → chunk-kk071ywk.js} +2 -2
- package/dist/{chunk-cbyewxx4.js → chunk-kkpxmhjv.js} +3 -3
- package/dist/chunk-m3epqvpc.js +1 -0
- package/dist/{chunk-rf3jf275.js → chunk-m8jen593.js} +3 -3
- package/dist/{chunk-8djaj8m7.js → chunk-mbrgz77y.js} +2 -2
- package/dist/chunk-n1byt26d.js +4 -0
- package/dist/{chunk-ecvk8npm.js → chunk-p6s92zj1.js} +1 -1
- package/dist/chunk-pdkj959x.js +1 -0
- package/dist/chunk-pwwm04bc.js +1 -0
- package/dist/chunk-q9ghq6jw.js +204 -0
- package/dist/chunk-qs9wwe8d.js +9 -0
- package/dist/chunk-qv1v32ts.js +22 -0
- package/dist/{chunk-x3dche8v.js → chunk-rezjy4mp.js} +2 -2
- package/dist/{chunk-78bknnzt.js → chunk-rh5g6em4.js} +2 -2
- package/dist/{chunk-70kccy7a.js → chunk-s3zfyy7r.js} +1 -1
- package/dist/chunk-s6rdv601.js +2 -0
- package/dist/chunk-szmm21q9.js +1 -0
- package/dist/{chunk-2gre3vrn.js → chunk-vx8a7e1j.js} +2 -2
- package/dist/{chunk-tdevyej4.js → chunk-vz0zsct0.js} +1 -1
- package/dist/chunk-x96czg8t.js +1 -0
- package/dist/{chunk-p2j0wcca.js → chunk-x9940mcy.js} +2 -2
- package/dist/chunk-xh2c6ycd.js +1 -0
- package/dist/{chunk-taj3qfn3.js → chunk-xr033fd3.js} +1 -1
- package/dist/{chunk-ae7f5mh9.js → chunk-z5eaph4a.js} +1 -1
- package/dist/chunk-ze8rmhs1.js +1 -0
- package/dist/web/assets/{ChatView-BtSSERlQ.js → ChatView-CjEyCR8V.js} +3 -3
- package/dist/web/assets/{CodeBlockHighlighter-CAuanOO0.js → CodeBlockHighlighter-DZxXrhQO.js} +1 -1
- package/dist/web/assets/{FilePreview-BKQ-EBj3.js → FilePreview-8fbolCzV.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-BdYjJ_NM.js → MarkdownRenderer-Bfm5TG2z.js} +3 -3
- package/dist/web/assets/{SettingsModal-CB6hM8fT.js → SettingsModal-KATzS3Iy.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-sSD4B7C_.js → TaskSwitcher-BrfN6F0-.js} +1 -1
- package/dist/web/assets/{TerminalPanel-ZnEoQU6o.js → TerminalPanel-sbqhmFcK.js} +1 -1
- package/dist/web/assets/{index-DtOztVFd.js → index-xB4mFHWl.js} +3 -3
- package/dist/web/index.html +1 -1
- package/package.json +1 -1
- package/dist/chunk-03633tsz.js +0 -10
- package/dist/chunk-1kxz32m6.js +0 -1
- package/dist/chunk-1sregjyz.js +0 -1
- package/dist/chunk-2byq2qja.js +0 -1
- package/dist/chunk-3t5gqr9e.js +0 -1
- package/dist/chunk-6znn1a5v.js +0 -1
- package/dist/chunk-7hjz5jjn.js +0 -9
- package/dist/chunk-8k9ark1n.js +0 -1
- package/dist/chunk-98rbxm1y.js +0 -22
- package/dist/chunk-apq6qqjg.js +0 -204
- package/dist/chunk-br9230a2.js +0 -2
- package/dist/chunk-hb9yjfja.js +0 -1
- package/dist/chunk-jk66yar2.js +0 -1
- package/dist/chunk-k52a3bq6.js +0 -1
- package/dist/chunk-n1qmwjmc.js +0 -1
- package/dist/chunk-p2yb40zk.js +0 -4
- package/dist/chunk-qewf02br.js +0 -1
- package/dist/chunk-qsj712zc.js +0 -1
- package/dist/chunk-ry7226b5.js +0 -6
- package/dist/chunk-x1a5wv45.js +0 -1
- package/dist/chunk-z516a7nx.js +0 -1
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{m as R,n as c,o as g,p as d,q as m,r as l}from"./chunk-n1byt26d.js";import{G as M,M as y}from"./chunk-b634n0ts.js";import"./chunk-1sswefqp.js";import"./chunk-1zpqxjj7.js";import{ab as h,jb as A}from"./chunk-q9ghq6jw.js";import"./chunk-ej1z75jf.js";import{ac as w,oc as U}from"./chunk-x9940mcy.js";import"./chunk-4djps7bz.js";import"./chunk-rezjy4mp.js";import{Kc as C}from"./chunk-btfxa4w8.js";import{Mc as I,Nc as S,Oc as v}from"./chunk-1444wfhr.js";import{Pc as O}from"./chunk-48tz6s0s.js";import"./chunk-d9gthet1.js";import{kd as P}from"./chunk-mbrgz77y.js";import"./chunk-v508x7cg.js";import"./chunk-6kc12pma.js";import"./chunk-4qtb8yf6.js";import"./chunk-4p9cwr9s.js";import"./chunk-vz0zsct0.js";import"./chunk-rh5g6em4.js";import"./chunk-9mamc250.js";import"./chunk-0prp87ys.js";import"./chunk-9pww3s5m.js";import"./chunk-0rwz7tm0.js";import"./chunk-m8jen593.js";import"./chunk-s3zfyy7r.js";import"./chunk-vx8a7e1j.js";import{nf as F}from"./chunk-gdp6fg4e.js";import"./chunk-4qyhtrhx.js";import"./chunk-s6rdv601.js";import{Af as z}from"./chunk-1ggxyyar.js";import"./chunk-ekv4hpy8.js";import"./chunk-8gv6hsrf.js";import"./chunk-5m5nxkfs.js";import"./chunk-7e7zgzag.js";import"./chunk-2d35rmyg.js";import"./chunk-d4327k1v.js";import"./chunk-heydawsf.js";import"./chunk-37se34rx.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
|
+
`);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
|
+
`);else j.io.stdout.write(`${j.response}
|
|
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}
|
|
5
|
+
`);return T.exitCode??0}let K=T.content,V=await m(j),W=K.trimStart().startsWith("!")?K.trimStart().slice(1).trim():void 0;if(W!==void 0&&V)throw Error("Output schemas cannot be combined with user shell commands");let{sessionId:H,messages:a,metadata:D}=await l({sessionId:j.sessionId,continue:j.continue,resume:j.resume,forkSession:j.forkSession,fallbackSessionPrefix:"print"}),X=D?.projectPath??z(),$=t(j.permissionMode)??D?.permissionMode??P()?.permissionMode??"default";await U.setSessionPermissionMode(H,X,$);let E=await A.cancelPendingNonInteractive(X,H)?await U.loadSessionModelContext(H,X):a;q=await M.create({sessionId:H,workspaceRoot:X,modelId:j.model,permissionMode:$,mcpConfig:j.mcpConfig,strictMcpConfig:j.strictMcpConfig,agents:j.agents?O(j.agents):void 0,...E.length>0?{sessionStart:{isResume:!0,resumeSessionId:H}}:{}});let b=J&&q.getPendingSteeringCount()>0,G=J&&!b?await q.getGoal():null,f=G?.status==="active"||G?.status==="verifying",L=J&&!b&&!f?await q.getRecoveredFinalResponse():void 0;if(J&&!b&&!f){if(!L)throw Error("No unfinished turn or active goal to resume");return x({io:B,options:j,response:L.content,requestInput:K,structuredOutput:L.structuredOutput,structuredOutputSchemaDigest:L.structuredOutputSchemaDigest}),0}if(W!==void 0){let Q=await q.executeUserShellCommand(W);if(j.outputFormat==="json")B.stdout.write(`${JSON.stringify(Q,null,2)}
|
|
6
|
+
`);else if(j.outputFormat==="stream-json")B.stdout.write(`${JSON.stringify({type:"user_shell_completed",executionId:Q.executionId,record:Q.record})}
|
|
7
|
+
`);else B.stdout.write(`${w(Q.record)}
|
|
8
|
+
`);return Q.record.status==="completed"?0:Q.record.status==="aborted"?130:Q.record.exitCode??1}let N=await y.createWithRuntime(q,{sessionId:H,systemPrompt:j.systemPrompt,appendSystemPrompt:j.appendSystemPrompt,maxTurns:j.maxTurns,modelId:j.model,permissionMode:$,toolWhitelist:j.allowedTools,toolBlacklist:j.disallowedTools,mcpConfig:j.mcpConfig,strictMcpConfig:j.strictMcpConfig}),k={messages:[...E],userId:"cli-user",sessionId:H,workspaceRoot:X,permissionMode:$},Y=await h(V||J?N.chatStream(K,k,{...V?{outputSchema:V}:{},pendingInputOnly:b,goalContinuationOnly:f}):N.chatStream(K,k));if(!Y.success)throw Error(Y.error?.message??"Agent execution failed");let r=Y.finalMessage||"",u=Y.metadata?.structuredOutput;return x({io:B,options:j,response:r,requestInput:K,structuredOutput:u,structuredOutputSchemaDigest:Y.metadata?.structuredOutputSchemaDigest}),0}catch(Z){return B.stderr.write(`Error: ${Z instanceof Error?Z.message:"未知错误"}
|
|
9
|
+
`),1}finally{await q?.dispose()}}async function _j(){if(process.argv.slice(2).findIndex((q)=>q==="--print"||q==="-p")===-1)return!1;try{let{print:q,"output-format":Z,"include-partial-messages":_,"input-format":J,"system-prompt":T,"append-system-prompt":K,"max-turns":V,...W}=C,H=p(e(process.argv)).scriptName("blade").strict(!1).options(W).middleware([S,I,v]);return i(H),await H.parse(),!0}catch(q){console.error(`Print mode error: ${q instanceof Error?q.message:"未知错误"}`),process.exit(1)}}export{n as runPrint,_j as handlePrintMode};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import{s as E}from"./chunk-h9c7xec5.js";import{t as FJ}from"./chunk-e3qzedvj.js";import{$ as o,G as l,J as i,K as r,M as a,_ as n,aa as t,ba as s,w as A}from"./chunk-b634n0ts.js";import{la as HJ}from"./chunk-1sswefqp.js";import"./chunk-1zpqxjj7.js";import{Na as v,ab as m,jb as d}from"./chunk-q9ghq6jw.js";import{rb as T}from"./chunk-ej1z75jf.js";import{Kb as f,Rb as u,Ub as g,ac as M,bc as c,dc as R,gc as p,lc as _,oc as D}from"./chunk-x9940mcy.js";import"./chunk-4djps7bz.js";import"./chunk-rezjy4mp.js";import"./chunk-d9gthet1.js";import"./chunk-mbrgz77y.js";import"./chunk-v508x7cg.js";import{wd as zJ}from"./chunk-6kc12pma.js";import"./chunk-4qtb8yf6.js";import"./chunk-4p9cwr9s.js";import{Hd as WJ}from"./chunk-vz0zsct0.js";import"./chunk-rh5g6em4.js";import"./chunk-9mamc250.js";import"./chunk-0prp87ys.js";import{me as YJ}from"./chunk-9pww3s5m.js";import"./chunk-0rwz7tm0.js";import"./chunk-m8jen593.js";import"./chunk-s3zfyy7r.js";import"./chunk-vx8a7e1j.js";import"./chunk-gdp6fg4e.js";import"./chunk-4qyhtrhx.js";import{uf as I,vf as S,wf as y}from"./chunk-s6rdv601.js";import{Af as QJ}from"./chunk-1ggxyyar.js";import{Ef as b}from"./chunk-ekv4hpy8.js";import"./chunk-8gv6hsrf.js";import{Lf as ZJ,Of as $J}from"./chunk-5m5nxkfs.js";import"./chunk-7e7zgzag.js";import"./chunk-2d35rmyg.js";import"./chunk-d4327k1v.js";import"./chunk-heydawsf.js";import"./chunk-37se34rx.js";import{Readable as KJ,Writable as UJ}from"node:stream";import*as x from"@agentclientprotocol/sdk";import{PROTOCOL_VERSION as wJ}from"@agentclientprotocol/sdk";import JJ from"node:path";import{RequestError as GJ}from"@agentclientprotocol/sdk";import{nanoid as h}from"nanoid";var G=b("Agent");function C(J){if(!J)return{};return Object.fromEntries(J.map((Z)=>[Z.name,Z.value]))}function DJ(J){if("command"in J)return{type:"stdio",command:J.command,args:J.args,env:C(J.env)};if("url"in J)return{type:J.type,url:J.url,headers:C("headers"in J?J.headers:void 0)};return null}function BJ(J){let Z={};for(let Q of J){let Y=DJ(Q);if(Y)Z[Q.name]=Y}return Z}function e(J){if(typeof J==="string")return J?[{type:"text",text:J}]:[];return J.flatMap((Z)=>{if(Z.type==="text")return Z.text?[{type:"text",text:Z.text}]:[];let Q=Z.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(Q);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function LJ(J){let Z=c(J.metadata);return Z?[{type:"text",text:M(Z)}]:e(J.content)}function VJ(J){return[`Status: ${J.status}`,`Exit code: ${J.exitCode??"null"}`,`Duration: ${(J.durationMs/1000).toFixed(3)} seconds`].join(`
|
|
2
|
+
`)}class O{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingUserShell=null;pendingResumeRequested=!1;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;messages;contextMessages;mode;constructor(J,Z,Q,Y,H={}){this.id=J;this.cwd=Z;this.connection=Q;this.clientCapabilities=Y;this.options=H;this.messages=[...H.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(H.permissionMode)}async refreshPersistedMessages(){let[J,Z]=await Promise.all([D.loadSession(this.id,this.cwd),D.loadSessionModelContext(this.id,this.cwd)]);if(J.length>0)this.messages=J;if(Z.length>0)this.contextMessages=Z}async loadModelContextOr(J){let Z=await D.loadSessionModelContext(this.id,this.cwd);return Z.length>0?Z:[...J]}mapPermissionModeToMode(J){switch(J){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 a.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(G.debug(`[AcpSession ${this.id}] Initializing...`),await D.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),A.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd),G.debug(`[AcpSession ${this.id}] ACP service context initialized`),await d.resolvePendingWithHandler(this.cwd,this.id,{requestConfirmation:(z)=>this.requestPermission(z)}))await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let Z=this.options.mcpServers?BJ(this.options.mcpServers):void 0,Q=A.getInstance().getTerminalService(this.id);if(this.runtime=await l.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(z,$)=>{let F=await Q.execute(z,{cwd:$.cwd,env:$.env,timeout:$.timeoutMs,signal:$.signal,allowLocalFallback:!1,onOutput:(X)=>$.onOutput?.("stdout",X)});return{exitCode:F.exitCode,stdout:F.stdout,stderr:F.stderr,...F.error?{error:F.error}:{},timedOut:F.failureKind==="timeout",aborted:F.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),await E.recoverInterrupted(this.cwd,this.id,this.runtime))await this.refreshPersistedMessages();this.agent=await this.createAgent(),await o(this.cwd),G.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=v.subscribe((z)=>{if(z.sessionId!==this.id||z.projectPath!==this.cwd)return;if(z.type==="task.delivery"){if(!z.properties.taskDelivery||typeof z.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof z.properties.updatedAt==="string"?z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":z.properties.taskDelivery,...z.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(z.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof z.properties.updatedAt==="string"?z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":z.properties.taskStatus,...typeof z.properties.taskStatusReason==="string"?{"blade/taskStatusReason":z.properties.taskStatusReason}:{},...z.properties.taskFailure&&typeof z.properties.taskFailure==="object"?{"blade/taskFailure":z.properties.taskFailure}:{},...typeof z.properties.taskStartedAt==="string"?{"blade/taskStartedAt":z.properties.taskStartedAt}:{},...typeof z.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":z.properties.taskCompletedAt}:{},...z.properties.taskDiffStat&&typeof z.properties.taskDiffStat==="object"?{"blade/taskDiffStat":z.properties.taskDiffStat}:{},...typeof z.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":z.properties.taskQueuePosition}:{},...typeof z.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":z.properties.taskQueueDepth}:{},...typeof z.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":z.properties.taskConcurrencyLimit}:{},...typeof z.properties.taskInFlight==="number"?{"blade/taskInFlight":z.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;let Q=Z.role==="user"?"user_message_chunk":Z.role==="assistant"?"agent_message_chunk":void 0;if(!Q)continue;for(let Y of LJ(Z)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:Q,content:Y}))return}}let J=await this.runtime?.getGoal();if(J&&!await this.sendUpdateAndWait(this.goalSessionUpdate(J)))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(J,Z){try{G.debug(`[AcpSession ${this.id}] Executing slash command: ${J}`);let Q={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($)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let F=await this.runtime.rewindSession($);return this.messages=[...F.messages],this.contextMessages=await this.loadModelContextOr(F.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),F}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async($)=>{if(await this.setReasoningEffort($),!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($)=>{if(await this.setServiceTier($),!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($)=>{if(await this.setResponseVerbosity($),!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($)=>{if(await this.setCommunicationStyle($),!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($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let X=!1,j,B=(W)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:W.id,status:W.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:W.result?.message||W.result?.error||`Subagent ${W.status}`}}]})},L=this.runtime.resumeSubagent({agentId:$,prompt:F,onCompleted:(W)=>{if(X)B(W);else j=W}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L.session.id,status:"in_progress",title:`Resuming ${L.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${L.source.id} at depth ${L.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),X=!0,j)B(j);return L}},mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async($)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs($)},getPrompt:async($,F,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt($,F,X)},complete:async($,F,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument($,F,X)},listTasks:async($)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks($)},getTask:async($)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask($)},cancelTask:async($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask($,F)},getLogs:async($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs($,F)},setLoggingLevel:async($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel($,F)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},codeReview:{run:async($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let X=await E.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:$,signal:F,onEvent:(L)=>{if(L.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L.toolCall.id,status:"in_progress",title:`Review: ${L.toolCall.function.name}`,content:[],kind:this.mapToolKind(L.toolKind)});else if(L.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:L.toolCall.id,status:L.result.success?"completed":"failed",content:[]})}}),j=await X.completion,B=(await E.list(this.cwd,this.id)).find((L)=>L.start.reviewId===X.reviewId);if(!B)throw Error(`Review not found: ${X.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:X.reviewId,status:j.status,findings:j.findings.length,content:f(B.start,j)}}},signal:Z,acp:{sendMessage:($)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$}})},sendToolStart:($,F,X)=>{let j=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,B=this.mapToolKind(X);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:j,status:"in_progress",title:`${$}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(F,null,2)}}],kind:B})},sendToolResult:($,F)=>{if(F.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:F.summary}})}}},Y=await t(J,Q),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 $=await D.loadSession(this.id,this.cwd);if($.length>0)this.messages=$}let z=Y.content||Y.message;if(z)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:z}});if(Y.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Y.error}`}});return{stopReason:Y.success?"end_turn":"cancelled"}}catch(Q){return G.error(`[AcpSession ${this.id}] Slash command error:`,Q),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${Q instanceof Error?Q.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async sendAvailableCommands(){try{let J=s(this.cwd),Z=["model","permissions","theme","config","exit","ide"],Y=J.filter((H)=>!Z.includes(H.name)).map((H)=>{let z;if(H.usage){let $=H.usage.replace(/^\/\w+\s*/,"").trim();if($)z=$}if(H.aliases?.length){let $=`Aliases: ${H.aliases.join(", ")}`;z=z?`${z} | ${$}`:$}return{name:H.name,description:H.description,input:z?{hint:z}: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(J){G.error(`[AcpSession ${this.id}] Failed to send available commands:`,J)}}async prompt(J,Z={}){if(A.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let Q=this.resolvePrompt(J.prompt),Y=Q.content,H=Q.displayText,z=J._meta?.outputSchema??(Z.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((X)=>X.outputSchema)?.outputSchema:void 0),$;if(z!==void 0)$=p(z).schema;if(H.trimStart().startsWith("!")){if($)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(H)}if(this.pendingPrompt){if($)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 X=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!X.accepted)throw Error(X.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 (${X.queued})`),X.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let F=new AbortController;this.pendingPrompt=F;try{if(G.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),n(H)){if($)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(H,F.signal)}let X={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.contextMessages],signal:F.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async(W)=>{this.mode=this.mapPermissionModeToMode(W),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async(W)=>{return this.requestPermission(W)}}},j=await m(this.agent.chatStream(Y,X,{pendingInputOnly:Z.pendingInputOnly,goalContinuationOnly:Z.goalContinuationOnly,outputSchema:$}),async(W)=>{switch(W.kind){case"content_delta":if($)break;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:W.delta}});break;case"tool_start":{let w=W.toolCall,q=w.function.name;if(q===R)break;let N=this.mapToolKind(W.toolKind),V=`Executing ${q}`;if(q==="Task"&&"function"in w)try{let P=JSON.parse(w.function.arguments),K=P.resume_from??P.resume;if(typeof K==="string")V=`Resuming ${String(P.subagent_type||"subagent")} from ${K}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:w.id,status:"in_progress",title:V,content:[],kind:N});break}case"tool_progress":{let w=W.toolCall;if(w.function.name===R)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:w.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:W.update.message}}]});break}case"tool_result":{let w=W.toolCall;if(w.function.name===R)break;let q=W.result,N=[],V=q.metadata;if(V?.kind==="patch"&&Array.isArray(V.changes))for(let K of V.changes){if(!K||typeof K!=="object"||!("path"in K)||typeof K.path!=="string")continue;N.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(V?.kind==="edit"&&typeof V.file_path==="string"&&typeof V.oldContent==="string"&&(typeof V.newContent==="string"||V.newContent===void 0))N.push({type:"diff",path:V.file_path,oldText:V.oldContent,newText:V.newContent??null});else{let K=w.function.name,XJ=r(g(i(K,q),u));N.push({type:"content",content:{type:"text",text:XJ}})}if(w.function.name==="Task"&&(V?.verificationVerdict==="pass"||V?.verificationVerdict==="fail"||V?.verificationVerdict==="partial"))N.unshift({type:"content",content:{type:"text",text:`Verification result: ${V.verificationVerdict.toUpperCase()}`}});let P=q.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:w.id,status:P,content:N});break}case"structured_output":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify(W.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${W.revision} (${W.serverName}): +${W.added.length} -${W.removed.length} ~${W.updated.length}
|
|
3
|
+
`}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${W.contentKind} r${W.revision} (${W.serverName}): +${W.added.length} -${W.removed.length} ~${W.updated.length}
|
|
4
|
+
`}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${W.revision} (${W.serverName}): ${W.uri}
|
|
5
|
+
`}});break;case"mcp_connection_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP connection r${W.revision} (${W.serverName}): ${W.phase} ${W.attempt}/${W.maxAttempts}
|
|
6
|
+
`}});break;case"mcp_log":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP log r${W.revision} (${W.serverName}) ${W.level}${W.logger?` logger=${W.logger}`:""}: ${W.message}
|
|
7
|
+
`}});break;case"mcp_instructions_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP instructions r${W.revision} (${W.serverName}): ${W.action}${W.detailsOmitted?" details-omitted":""}
|
|
8
|
+
`}});break;case"mcp_task_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP task r${W.revision} ${W.taskId} (${W.serverName}/${W.toolName}): ${W.status}${W.hasResult?" result-available":""}
|
|
9
|
+
`}});break;case"project_rules_loaded":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Project rules loaded: ${W.files.length}${W.blockedWrite?" (write retry required)":""}
|
|
10
|
+
`}});break;case"provider_retry":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerRetry":{phase:W.phase,attempt:W.attempt,maxRetries:W.maxRetries,reason:W.reason,...W.statusCode!==void 0?{statusCode:W.statusCode}:{},...W.delayMs!==void 0?{delayMs:W.delayMs}:{},...W.nextRetryAt!==void 0?{nextRetryAt:W.nextRetryAt}:{}}}});break;case"provider_stall":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerStall":{phase:W.phase,stallCount:W.stallCount,durationMs:W.durationMs,warningAfterMs:W.warningAfterMs,timeoutMs:W.timeoutMs,outputStarted:W.outputStarted}}});break;case"action_stationarity":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/actionStationarity":{phase:W.phase,toolName:W.toolName,runLength:W.runLength,nudgeThreshold:W.nudgeThreshold,haltThreshold:W.haltThreshold,progressAware:W.progressAware}}});break;case"task_update":this.sendPlanUpdate(W.tasks);break;case"steering_applied":break;case"follow_up_started":for(let w of W.messages){if(!w.recovered||w.persisted)continue;for(let q of e(w.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:q})}if(W.recovered>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${W.recovered} queued instruction${W.recovered===1?"":"s"} recovered after restart]
|
|
11
|
+
`}});break;case"goal_updated":if(W.goal)this.sendUpdate(this.goalSessionUpdate(W.goal));if(W.goal&&W.goal.status!=="active")this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Goal ${W.goal.status}: ${W.goal.objective}]
|
|
12
|
+
`}});break;case"goal_continuation_started":break;case"compaction":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/compaction":{phase:W.phase,...W.reason?{reason:W.reason}:{},...W.strategy?{strategy:W.strategy}:{},...W.outcome?{outcome:W.outcome}:{},...W.preTokens!==void 0?{preTokens:W.preTokens}:{},...W.postTokens!==void 0?{postTokens:W.postTokens}:{}}}});break;default:break}});this.contextMessages=[...X.messages];let B=await D.loadSession(this.id,this.cwd);if(this.messages=B.length>0?B:[...X.messages],!j.success){let W=j.error?.type??"unknown";throw GJ.internalError({failureType:W},`Agent turn failed (${W})`)}if(F.signal.aborted)return{stopReason:"cancelled"};let L={...j.metadata?.structuredOutput?{structuredOutput:j.metadata.structuredOutput,outputSchemaDigest:j.metadata.structuredOutputSchemaDigest}:{},...j.metadata?.goalCompletionVerified?{goalCompletion:{verified:!0,verdict:j.metadata.goalVerificationVerdict,...j.metadata.goalVerifierSessionId?{verifierSessionId:j.metadata.goalVerifierSessionId}:{},...j.metadata.goalVerificationEvidenceSha256?{evidenceSha256:j.metadata.goalVerificationEvidenceSha256}:{}}}:{}};return{stopReason:"end_turn",...Object.keys(L).length>0?{_meta:L}:{}}}catch(X){if(F.signal.aborted||X instanceof Error&&X.name==="AbortError")return{stopReason:"cancelled"};throw G.error(`[AcpSession ${this.id}] Prompt error:`,X),X}finally{if(this.pendingPrompt===F){if(this.pendingPrompt=null,!this.destroyed&&this.pendingResumeRequested)this.schedulePendingResume()}}}async handleUserShellCommand(J){if(!this.runtime)throw Error("Session runtime is unavailable");if(this.pendingUserShell)throw Error("A user shell command is already running");let Z=J.trimStart().slice(1).trim();if(!Z)throw Error("User shell command cannot be empty");let Q=new AbortController;this.pendingUserShell=Q;let Y,H="";try{let z=await this.runtime.executeUserShellCommand(Z,{signal:Q.signal,onEvent:async(F)=>{if(Y=F.executionId,F.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:F.executionId,status:"in_progress",title:`! ${F.command}`,content:[],kind:"execute"});return}if(F.type==="output"){H+=F.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:F.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:F.chunk}}]});return}let X=M(F.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:F.executionId,status:F.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:H?VJ(F.record):X}}]})}}),$={role:"user",content:z.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify(z.record))}};if(this.messages.push($),this.contextMessages.push($),z.delivery==="next_turn")this.schedulePendingResume();return{stopReason:z.record.status==="aborted"?"cancelled":"end_turn"}}catch(z){if(Y)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Y,status:"failed",content:[{type:"content",content:{type:"text",text:z instanceof Error?z.message:String(z)}}]});if(Q.signal.aborted)return{stopReason:"cancelled"};throw z}finally{if(this.pendingUserShell===Q)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 J=this.runtime.getPendingSteeringCount()>0,Z=J?null:await this.runtime.getGoal(),Q=Z?.status==="active"||Z?.status==="verifying";if(!J&&!Q){this.pendingResumeRequested=!1;return}this.pendingResumeRequested=!1,await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:J,goalContinuationOnly:Q}).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 J=!1;if(this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,J=!0;if(this.pendingUserShell)this.pendingUserShell.abort(),this.pendingUserShell=null,J=!0;if(!J)G.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(J){let Q=["default","auto-edit","yolo","plan"].includes(J)?J:"default",Y=this.mapModeIdToPermissionMode(Q);await D.setSessionPermissionMode(this.id,this.cwd,Y),this.mode=Q,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(J){switch(J){case"yolo":return"yolo";case"auto-edit":return"autoEdit";case"plan":return"plan";case"default":default:return"default"}}shouldAutoApprove(J){switch(this.mode){case"yolo":return!0;case"auto-edit":return J==="readonly"||J==="write";case"plan":return J==="readonly";case"default":default:return!1}}async setModel(J){if(G.info(`[AcpSession ${this.id}] Model set to: ${J}`),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(J);try{try{await D.updateSessionMetadata(this.id,this.cwd,{selectedModelId:J})}catch(Q){if(!(Q instanceof _)&&Q.code!=="ENOENT")throw Q;await D.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:J})}}catch(Q){if(Z&&Z!==J)await this.agent.switchModel(Z).catch((Y)=>{G.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,Y)});throw Q}}getCurrentModelId(){return this.runtime?.getCurrentModelId()}async setReasoningEffort(J){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(J)}catch(Q){throw Error(Q instanceof Error?Q.message:"Invalid reasoning effort")}if(Z.selection===J)return;await this.runtime.refresh({reasoningEffort:J});try{try{await D.updateSessionMetadata(this.id,this.cwd,{reasoningEffort:J})}catch(Q){if(!(Q instanceof _)&&Q.code!=="ENOENT")throw Q;await D.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),reasoningEffort:J})}}catch(Q){throw await this.runtime.refresh({reasoningEffort:Z.selection}),Q}}async setServiceTier(J){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(J)}catch(Q){throw Error(Q instanceof Error?Q.message:"Invalid service tier")}if(Z.selection===J)return;await this.runtime.refresh({serviceTier:J});try{try{await D.updateSessionMetadata(this.id,this.cwd,{serviceTier:J})}catch(Q){if(!(Q instanceof _)&&Q.code!=="ENOENT")throw Q;await D.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),serviceTier:J})}}catch(Q){throw await this.runtime.refresh({serviceTier:Z.selection}),Q}}async setResponseVerbosity(J){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(J)}catch(Q){throw Error(Q instanceof Error?Q.message:"Invalid response verbosity")}if(Z.selection===J)return;await this.runtime.refresh({responseVerbosity:J});try{try{await D.updateSessionMetadata(this.id,this.cwd,{responseVerbosity:J})}catch(Q){if(!(Q instanceof _)&&Q.code!=="ENOENT")throw Q;await D.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),responseVerbosity:J})}}catch(Q){throw await this.runtime.refresh({responseVerbosity:Z.selection}),Q}}async setCommunicationStyle(J){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(),Q=this.runtime.resolveCommunicationStyleConfiguration(J);if(Q.source!=="built-in"&&!Q.contentSha256)throw Error("Custom communication style has no provenance");if(Z.selection===J)return;await this.runtime.refresh({communicationStyle:J});try{try{await D.updateSessionMetadata(this.id,this.cwd,{communicationStyle:J,communicationStyleDigest:Q.source==="built-in"?null:Q.contentSha256})}catch(Y){if(!(Y instanceof _)&&Y.code!=="ENOENT")throw Y;await D.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:J,...Q.source!=="built-in"&&Q.contentSha256?{communicationStyleDigest:Q.contentSha256}:{}})}}catch(Y){throw await this.runtime.refresh({communicationStyle:Z.selection}),Y}}getModelConfiguration(){if(!this.runtime)return;let J=this.runtime.getConfig();return{currentModelId:this.runtime.getCurrentModelId()??J.currentModelId,models:J.models.map((Z)=>structuredClone(Z)),modelProviders:structuredClone(J.modelProviders),reasoning:this.runtime.getReasoningConfiguration(),serviceTier:this.runtime.getServiceTierConfiguration(),responseVerbosity:this.runtime.getResponseVerbosityConfiguration(),communicationStyle:this.runtime.getCommunicationStyleConfiguration()}}getMode(){return this.mode}async destroy(){if(this.destroyed)return;if(this.destroyed=!0,this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let J=this.agent,Z=this.runtime;this.agent=null,this.runtime=null;let Q,Y=async(H)=>{try{await H()}catch(z){Q??=z}};if(await Y(()=>this.cancel()),J)await Y(()=>J.destroy());if(Z)await Y(()=>Z.dispose());if(await Y(()=>A.destroySession(this.id)),G.debug(`[AcpSession ${this.id}] Destroyed`),Q!==void 0)throw Q}resolvePrompt(J){let Z=[],Q=[],Y=0,H=0,z=0,$=(X)=>{if(Q.length>0)Q.push({type:"text",text:`
|
|
13
|
+
`}),z+=1;if(Q.push(X),X.type==="text")z+=X.text.length};for(let X of J)if(X.type==="text")Z.push(X.text),$({type:"text",text:X.text});else if(X.type==="image"){let j=`data:${X.mimeType};base64,${X.data}`;Y+=1,H+=j.length,Z.push(`[Image: ${X.mimeType}]`),$({type:"image_url",image_url:{url:j}})}else if(X.type==="resource"){let j=X.resource;if("text"in j){let B=`<file path="${j.uri}">
|
|
14
|
+
${j.text}
|
|
15
|
+
</file>`;Z.push(B),$({type:"text",text:B})}}else if(X.type==="resource_link"){let j=`[Resource: ${X.uri}]`;Z.push(j),$({type:"text",text:j})}if(Y>I)throw Error(`ACP prompt contains more than ${I} images`);if(H>S)throw Error("ACP prompt images exceed the 5 MiB limit");if(z>y)throw Error(`ACP prompt text exceeds ${y} characters`);let F=Z.join(`
|
|
16
|
+
`);return{content:Y>0?Q:F,displayText:F}}canSendUpdates(){return!this.destroyed&&!this.connection.signal.aborted}async sendUpdateAndWait(J){if(!this.canSendUpdates())return!1;return await this.connection.sessionUpdate({sessionId:this.id,update:J}),this.canSendUpdates()}goalSessionUpdate(J){return{sessionUpdate:"session_info_update",updatedAt:J.updatedAt,_meta:{"blade/goal":{goalId:J.goalId,status:J.status,verificationAttempt:J.completionVerification?.attempt,verificationStatus:J.completionVerification?.status,verifierSessionId:J.completionVerification?.verifierSessionId,verificationEvidenceSha256:J.completionVerification?.evidenceSha256}}}}sendUpdate(J){if(!this.canSendUpdates())return;let Z={sessionId:this.id,update:J};this.connection.sessionUpdate(Z).catch((Q)=>{G.warn(`[AcpSession ${this.id}] Failed to send update:`,Q)})}sendPlanUpdate(J){let Z=J.map((Q)=>({content:Q.subject,priority:Q.priority,status:Q.status}));G.debug(`[AcpSession ${this.id}] Sending plan update with ${Z.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:Z})}async requestPermission(J){let Z=this.pendingPrompt?.signal;if(J.type==="askUserQuestion")return this.requestUserQuestions(J,Z);if(J.type==="mcpElicitation")return this.requestMcpElicitation(J,Z);let Q=J.kind?.toLowerCase()||"execute";if(J.type!=="mcpSampling"&&this.shouldAutoApprove(Q))return G.debug(`[AcpSession ${this.id}] Auto-approving ${Q} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(Q==="write"||Q==="execute"))return G.debug(`[AcpSession ${this.id}] Rejecting ${Q} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};try{let Y=h(),H=[];if(J.message)H.push({type:"content",content:{type:"text",text:J.message}});if(J.details)H.push({type:"content",content:{type:"text",text:J.details}});if(J.risks&&J.risks.length>0)H.push({type:"content",content:{type:"text",text:`Risks:
|
|
17
|
+
- ${J.risks.join(`
|
|
18
|
+
- `)}`}});let z=this.mapToolKind(Q),$={sessionId:this.id,options:J.type==="mcpSampling"?[{optionId:"allow_once",name:"Allow this sampling request",kind:"allow_once"},{optionId:"reject_once",name:"Deny",kind:"reject_once"}]:[{optionId:"allow_once",name:"Allow once",kind:"allow_once"},{optionId:"allow_always",name:"Always allow",kind:"allow_always"},{optionId:"reject_once",name:"Deny once",kind:"reject_once"},{optionId:"reject_always",name:"Always deny",kind:"reject_always"}],toolCall:{toolCallId:Y,status:"pending",title:J.title||"Permission Required",content:H,kind:z}},F=await this.waitForClientInteraction(this.connection.requestPermission($),Z);if(!F)return{approved:!1,reason:T};let X=F.outcome;if(X.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let j=X.optionId;if(j==="allow_always")return{approved:!0,scope:"project"};if(j==="reject_always")return{approved:!1,scope:"project",reason:"User permanently denied the permission request"};let B=j==="allow_once";return{approved:B,scope:"once",reason:B?void 0:"User denied the operation"}}catch(Y){return G.warn(`[AcpSession ${this.id}] Permission request failed:`,Y),{approved:!1,reason:"Permission request failed"}}}async requestUserQuestions(J,Z){let Q=J.questions??[];if(Q.length===0)return{approved:!1,reason:"No structured questions were provided"};if(Q.some((H)=>H.multiSelect))return{approved:!1,reason:"ACP does not support multi-select question responses"};let Y={};try{for(let[H,z]of Q.entries()){let $=z.options.map((B,L)=>`answer:${H}:${L}`),F=`answer:${H}:cancel`,X=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...z.options.map((B,L)=>({optionId:$[L],name:B.label,kind:"allow_once"})),{optionId:F,name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:h(),status:"pending",title:z.header,kind:"think",content:[{type:"content",content:{type:"text",text:[z.question,...z.options.map((B)=>`${B.label}: ${B.description}`)].join(`
|
|
19
|
+
`)}}]}}),Z);if(!X)return{approved:!1,reason:T};if(X.outcome.outcome!=="selected")return{approved:!1,reason:"User cancelled the question prompt"};let j=$.indexOf(X.outcome.optionId);if(j<0)return{approved:!1,reason:"User cancelled the question prompt"};Y[z.header]=z.options[j].label}return{approved:!0,answers:Y}}catch(H){return G.warn(`[AcpSession ${this.id}] Question request failed:`,H),{approved:!1,reason:"Question request failed"}}}async requestMcpElicitation(J,Z){let Q=J.mcpElicitation;if(!Q)return{approved:!1,reason:"MCP elicitation details are missing",elicitation:{action:"cancel"}};try{if(Q.mode==="url"){let H=await this.requestElicitationChoice("MCP external authorization",[Q.message,`Server: ${Q.serverName}`,`Domain: ${Q.domain??"unknown"}`,`URL: ${Q.url??""}`,"Open this URL yourself only if you trust the MCP server."].join(`
|
|
20
|
+
`),[{id:"accept",label:"I will open this URL"},{id:"decline",label:"Decline"}],Z);if(H==="accept")return{approved:!0,elicitation:{action:"accept"}};return{approved:!1,reason:H==="decline"?"User declined URL":"User cancelled",elicitation:{action:H==="decline"?"decline":"cancel"}}}let Y=Object.create(null);for(let H of Q.fields??[]){let z=await this.collectAcpElicitationField(H,Z);if(z.cancelled)return{approved:!1,reason:z.reason,elicitation:{action:"cancel"}};if(z.value!==void 0)Y[H.name]=z.value}return{approved:!0,elicitation:{action:"accept",content:Y}}}catch(Y){return G.warn(`[AcpSession ${this.id}] MCP elicitation failed:`,Y),{approved:!1,reason:"MCP elicitation failed",elicitation:{action:"cancel"}}}}async collectAcpElicitationField(J,Z){if(J.type==="select"||J.type==="boolean"){let Q=J.type==="boolean"?[{id:"true",label:"Yes",value:!0},{id:"false",label:"No",value:!1}]:(J.options??[]).map((z,$)=>({id:`option:${$}`,label:z.label,value:z.value})),Y=await this.requestElicitationChoice(J.title,[J.description,J.required?"Required":"Optional"].filter(Boolean).join(`
|
|
21
|
+
`),[...Q.map((z)=>({id:z.id,label:z.label})),...!J.required?[{id:"skip",label:"Skip"}]:[]],Z);if(Y==="skip")return{cancelled:!1};let H=Q.find((z)=>z.id===Y);if(!H)return{cancelled:!0,reason:"User cancelled MCP elicitation"};return{cancelled:!1,value:H.value}}if(J.defaultValue!==void 0){let Q=await this.requestElicitationChoice(J.title,[J.description,`ACP cannot collect ${J.type} input. Use the server default: ${String(J.defaultValue)}?`].filter(Boolean).join(`
|
|
22
|
+
`),[{id:"default",label:"Use default"},...!J.required?[{id:"skip",label:"Skip"}]:[]],Z);if(Q==="default")return{cancelled:!1,value:J.defaultValue};if(Q==="skip")return{cancelled:!1};return{cancelled:!0,reason:"User cancelled MCP elicitation"}}if(!J.required)return{cancelled:!1};return{cancelled:!0,reason:`ACP cannot collect required ${J.type} field "${J.name}"`}}async requestElicitationChoice(J,Z,Q,Y){let H=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...Q.map((z)=>({optionId:z.id,name:z.label,kind:"allow_once"})),{optionId:"cancel",name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:h(),status:"pending",title:J,kind:"think",content:[{type:"content",content:{type:"text",text:Z}}]}}),Y);return H?.outcome.outcome==="selected"?H.outcome.optionId:void 0}async waitForClientInteraction(J,Z){if(!Z)return J;if(Z.aborted)return;return new Promise((Q,Y)=>{let H=!1,z=(F)=>{if(H)return;H=!0,Z.removeEventListener("abort",$),F()},$=()=>z(()=>Q(void 0));if(Z.addEventListener("abort",$,{once:!0}),Z.aborted)$();J.then((F)=>z(()=>Q(F)),(F)=>z(()=>Y(F)))})}mapToolKind(J){return{readonly:"read",write:"edit",execute:"execute",read:"read",edit:"edit",delete:"delete",move:"move",search:"search",think:"think",fetch:"fetch"}[J||""]||"other"}}var U=b("Agent");class k{connection;sessions=new Map;sessionLoadQueues=new Map;clientCapabilities;destroyed=!1;constructor(J){this.connection=J}async initialize(J){return U.info("[BladeAgent] Initializing ACP connection"),U.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(J.clientCapabilities)}`),this.clientCapabilities=J.clientCapabilities,{protocolVersion:wJ,agentCapabilities:{loadSession:!0,sessionCapabilities:{list:{},fork:{}},promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0}}}}async authenticate(J){return}async newSession(J){this.assertNotDestroyed();let Z=zJ("acp"),Q=J.cwd||QJ(),Y=J._meta?.["blade/taskIsolation"],H=Y==="local"||Y==="worktree"?Y:void 0,z=J._meta?.["blade/taskPrompt"],$=H?await FJ.createSessionTask({sessionId:Z,prompt:typeof z==="string"&&z.trim()?z:"ACP task session",sourceProjectPath:Q,isolation:H}):void 0,F=$?.metadata.projectPath??Q;U.info(`[BladeAgent] Creating new session: ${Z}`),U.debug(`[BladeAgent] Session cwd: ${F}`);let X=new O(Z,F,this.connection,this.clientCapabilities,{mcpServers:J.mcpServers,...$?.taskWorktree?{taskWorktree:$.taskWorktree}:{},...$?.metadata.taskIsolation?{taskIsolation:$.metadata.taskIsolation}:{}});try{await X.initialize(),this.assertNotDestroyed()}catch(j){throw await X.destroy().catch(()=>{return}),j}return this.sessions.set(Z,X),U.info(`[BladeAgent] Session ${Z} created, scheduling available commands update`),X.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Z,$?.metadata,X.getModelConfiguration())}async listSessions(J){if(J.cwd!=null&&!JJ.isAbsolute(J.cwd))throw Error("ACP session list cwd must be absolute");let Z=await D.listSessionPage({cwd:J.cwd??void 0,cursor:J.cursor??void 0,limit:50,includeSubagents:!1});return{sessions:Z.sessions.map((Q)=>({sessionId:Q.sessionId,cwd:Q.projectPath,title:Q.title??null,updatedAt:Q.lastMessageTime,_meta:{"blade/taskStatus":Q.taskStatus,...Q.taskStatusReason?{"blade/taskStatusReason":Q.taskStatusReason}:{},...Q.taskFailure?{"blade/taskFailure":Q.taskFailure}:{},...Q.taskStartedAt?{"blade/taskStartedAt":Q.taskStartedAt}:{},...Q.taskCompletedAt?{"blade/taskCompletedAt":Q.taskCompletedAt}:{},...Q.taskModelId?{"blade/taskModelId":Q.taskModelId}:{},...Q.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...Q.taskRetriedFrom?{"blade/taskRetriedFrom":Q.taskRetriedFrom}:{},...Q.taskDelivery?{"blade/taskDelivery":Q.taskDelivery}:{},...Q.taskIsolation?{"blade/taskIsolation":Q.taskIsolation}:{},...Q.taskSourceProjectPath?{"blade/taskSourceProjectPath":Q.taskSourceProjectPath}:{},...Q.taskWorktreeBranch?{"blade/taskWorktreeBranch":Q.taskWorktreeBranch}:{},...Q.taskBaseCommit?{"blade/taskBaseCommit":Q.taskBaseCommit}:{},...Q.taskDiffStat?{"blade/taskDiffStat":Q.taskDiffStat}:{},...Q.taskQueuePosition?{"blade/taskQueuePosition":Q.taskQueuePosition}:{},...Q.taskQueueDepth!==void 0?{"blade/taskQueueDepth":Q.taskQueueDepth}:{},...Q.taskConcurrencyLimit!==void 0?{"blade/taskConcurrencyLimit":Q.taskConcurrencyLimit}:{}}})),nextCursor:Z.nextCursor}}async unstable_forkSession(J){if(this.assertNotDestroyed(),!JJ.isAbsolute(J.cwd))throw Error("ACP session fork cwd must be absolute");let Z=await D.forkSession(J.sessionId,{sourceProjectPath:J.cwd,targetProjectPath:J.cwd});this.assertNotDestroyed();let Q=new O(Z.sessionId,J.cwd,this.connection,this.clientCapabilities,{initialMessages:Z.messages,permissionMode:Z.metadata.permissionMode,mcpServers:J.mcpServers});try{await Q.initialize(),this.assertNotDestroyed()}catch(Y){throw await Q.destroy().catch(()=>{return}),Y}return this.sessions.set(Z.sessionId,Q),Q.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Z.sessionId,Z.metadata,Q.getModelConfiguration())}async loadSession(J){this.assertNotDestroyed(),U.info(`[BladeAgent] Loading session: ${J.sessionId}`);let Q=(this.sessionLoadQueues.get(J.sessionId)??Promise.resolve()).then(()=>this.replaceSession(J)),Y=Q.then(()=>{return},()=>{return});this.sessionLoadQueues.set(J.sessionId,Y);try{return await Q}finally{if(this.sessionLoadQueues.get(J.sessionId)===Y)this.sessionLoadQueues.delete(J.sessionId)}}async replaceSession(J){this.assertNotDestroyed(),await D.assertSessionWritable(J.sessionId,J.cwd);let Z=this.sessions.get(J.sessionId);if(Z)try{await Z.destroy()}finally{if(this.sessions.get(J.sessionId)===Z)this.sessions.delete(J.sessionId)}let[Q,Y]=await Promise.all([D.loadSession(J.sessionId,J.cwd),D.findSessionMetadata(J.sessionId,J.cwd)]);if(!Y)throw Error(`Session not found: ${J.sessionId}`);let H=new O(J.sessionId,J.cwd,this.connection,this.clientCapabilities,{initialMessages:Q,permissionMode:Y.permissionMode,mcpServers:J.mcpServers});try{await H.initialize(),await H.replayHistory(),this.assertNotDestroyed()}catch(z){throw await H.destroy().catch(()=>{return}),z}return this.sessions.set(J.sessionId,H),H.sendAvailableCommandsDelayed(),this.buildSessionSetup(H.getModelConfiguration(),H.getMode())}buildChildSessionResponse(J,Z,Q){return{sessionId:J,...this.buildSessionSetup(Q,Z?.permissionMode==="autoEdit"?"auto-edit":Z?.permissionMode),...Z?{_meta:{"blade/taskIsolation":Z.taskIsolation,"blade/taskSourceProjectPath":Z.taskSourceProjectPath,"blade/taskProjectPath":Z.projectPath,...Z.taskModelId?{"blade/taskModelId":Z.taskModelId}:{},...Z.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...Z.taskRetriedFrom?{"blade/taskRetriedFrom":Z.taskRetriedFrom}:{},...Z.taskDelivery?{"blade/taskDelivery":Z.taskDelivery}:{},...Z.taskWorktreeBranch?{"blade/taskWorktreeBranch":Z.taskWorktreeBranch}:{},...Z.taskBaseCommit?{"blade/taskBaseCommit":Z.taskBaseCommit}:{}}}:{}}}assertNotDestroyed(){if(this.destroyed)throw Error("BladeAgent is destroyed")}buildSessionSetup(J,Z="default"){let Q=J?.models??[],Y=(J?.currentModelId&&Q.some(($)=>$.id===J.currentModelId)?J.currentModelId:void 0)??Q[0]?.id,H=[{id:"default",name:"Default",description:"Ask for confirmation before all file edits and commands"},{id:"auto-edit",name:"Auto Edit",description:"Auto-approve file edits, ask for shell commands"},{id:"yolo",name:"Full Auto",description:"Auto-approve everything without confirmation"},{id:"plan",name:"Plan Only",description:"Read-only mode, no file changes or commands"}],z=[];if(Q.length>0)z.push({type:"select",id:"model",name:"Model",description:"Active language model",category:"model",currentValue:Y,options:Q.map(($)=>({value:$.id,name:$.displayName??$.model,description:`${J?.modelProviders[$.provider]?.name??$.provider} · ${$.model}`}))});if(J?.reasoning)z.push({type:"select",id:"reasoning_effort",name:"Reasoning effort",description:"Session-owned model reasoning intensity",category:"model",currentValue:J.reasoning.selection,options:[{value:"auto",name:"Auto",description:`Resolve near high for this model (currently ${J.reasoning.effective})`},...J.reasoning.supported.map(($)=>({value:$,name:$[0].toUpperCase()+$.slice(1),description:$==="off"?"Disable model reasoning":`Use ${$} reasoning effort`}))]});if(J?.serviceTier)z.push({type:"select",id:"service_tier",name:"Service tier",description:"Session-owned provider latency and pricing tier",category:"model",currentValue:J.serviceTier.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default tier"},...J.serviceTier.supported.map(($)=>({value:$,name:$[0].toUpperCase()+$.slice(1),description:$==="fast"?"Use the provider priority tier":$==="flex"?"Use the lower-cost flexible tier":"Use the standard provider tier"}))]});if(J?.responseVerbosity)z.push({type:"select",id:"response_verbosity",name:"Response verbosity",description:"Session-owned model response detail",category:"model",currentValue:J.responseVerbosity.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default verbosity"},...J.responseVerbosity.supported.map(($)=>({value:$,name:$[0].toUpperCase()+$.slice(1),description:`Use ${$} response verbosity`}))]});if(J?.communicationStyle)z.push({type:"select",id:"communication_style",name:"Communication style",description:"Session-owned tone and explanatory framing",category:"model",currentValue:J.communicationStyle.selection,options:J.communicationStyle.supported.map(($)=>({value:$.id,name:$.name,description:`${$.description} · ${$.source}`}))});return{modes:{availableModes:H,currentModeId:Z},configOptions:z.length>0?z:void 0}}async prompt(J){let Z=this.sessions.get(J.sessionId);if(!Z)throw Error(`Session not found: ${J.sessionId}`);return Z.prompt(J)}async cancel(J){U.info(`[BladeAgent] Cancel notification received for session: ${J.sessionId}`);let Z=this.sessions.get(J.sessionId);if(Z)U.info("[BladeAgent] Found session, calling session.cancel()"),Z.cancel();else U.warn(`[BladeAgent] Session not found for cancel: ${J.sessionId}`)}async setSessionMode(J){U.info(`[BladeAgent] Setting session mode: ${J.modeId}`);let Z=this.sessions.get(J.sessionId);if(Z)await Z.setMode(J.modeId);return{}}async setSessionConfigOption(J){let Z=this.sessions.get(J.sessionId);if(!Z)throw Error(`Session not found: ${J.sessionId}`);if(J.configId==="model"&&"value"in J&&typeof J.value==="string")U.info(`[BladeAgent] Setting session model: ${J.value}`),await Z.setModel(J.value);else if(J.configId==="reasoning_effort"&&"value"in J&&WJ(J.value))U.info(`[BladeAgent] Setting reasoning effort: ${J.value}`),await Z.setReasoningEffort(J.value);else if(J.configId==="service_tier"&&"value"in J&&$J(J.value))U.info(`[BladeAgent] Setting service tier: ${J.value}`),await Z.setServiceTier(J.value);else if(J.configId==="response_verbosity"&&"value"in J&&ZJ(J.value))U.info(`[BladeAgent] Setting response verbosity: ${J.value}`),await Z.setResponseVerbosity(J.value);else if(J.configId==="communication_style"&&"value"in J&&YJ(J.value))U.info(`[BladeAgent] Setting communication style: ${J.value}`),await Z.setCommunicationStyle(J.value);else throw Error(`Invalid session config option: ${J.configId}`);return{configOptions:this.buildSessionSetup(Z.getModelConfiguration(),Z.getMode()).configOptions??[]}}async destroy(){this.destroyed=!0,await Promise.all([...this.sessionLoadQueues.values()]),this.sessionLoadQueues.clear();let J;for(let Z of this.sessions.values())try{await Z.destroy()}catch(Q){J??=Q}this.sessions.clear();try{await HJ.getInstance().disconnectAll()}catch(Z){J??=Z}if(J!==void 0)throw J}}async function ZQ(){let J=UJ.toWeb(process.stdout),Z=KJ.toWeb(process.stdin),Q=x.ndJsonStream(J,Z);await new x.AgentSideConnection((H)=>new k(H),Q).closed}export{ZQ as runAcpIntegration};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Ef as i}from"./chunk-ekv4hpy8.js";import{$f as C,Zf as o,bg as L,fg as j,gg as n}from"./chunk-heydawsf.js";import{hg as I}from"./chunk-37se34rx.js";import{stat as d}from"node:fs/promises";import B from"node:path";import*as U from"node:path";var s=50,t=100,e=/^[A-Za-z0-9_-]+$/,__=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;function E_(_){return typeof _==="string"&&__.test(_)&&Number.isFinite(Date.parse(_))}function P(_){return typeof _==="string"&&U.isAbsolute(_)}function R_(_){return Buffer.from(JSON.stringify(_),"utf8").toString("base64url")}function W_(_){try{if(!e.test(_))throw Error("invalid");let E=Buffer.from(_,"base64url").toString("utf8");if(Buffer.from(E,"utf8").toString("base64url")!==_)throw Error("invalid");let R=JSON.parse(E);if(R.version!==1||typeof R.includeSubagents!=="boolean"||R.archived!==void 0&&typeof R.archived!=="boolean"||!(R.cwd===null||P(R.cwd))||!E_(R.lastMessageTime)||!P(R.projectPath)||!C(R.sessionId))throw Error("invalid");return{version:1,cwd:R.cwd===null?null:U.resolve(R.cwd),includeSubagents:R.includeSubagents,archived:R.archived??!1,lastMessageTime:R.lastMessageTime,projectPath:U.resolve(R.projectPath),sessionId:R.sessionId}}catch{throw Error("Invalid session cursor")}}function y(_){let E="";for(let R=0;R<_.length;R+=1)E+=_.charCodeAt(R).toString(16).padStart(4,"0");return E}function $_(_){if(!_.cursor)return;let E=W_(_.cursor);if(E.cwd!==_.cwd||E.includeSubagents!==_.includeSubagents||(E.archived??!1)!==_.archived)throw Error("Session cursor scope does not match this query");return E}function z_(_={}){let{cwd:E,cursor:R,limit:W,includeSubagents:$=!1,archived:H=!1}=_;if(E!==void 0&&!U.isAbsolute(E))throw Error("Session catalog cwd must be absolute");let k=W===void 0?s:W;if(!Number.isInteger(k)||k<1||k>t)throw Error("Session catalog limit must be an integer from 1 to 100");return{cwd:E===void 0?null:U.resolve(E),cursor:R??void 0,limit:k,includeSubagents:$,archived:H}}function k_(_,E){if(_.lastMessageTime>E.lastMessageTime)return-1;if(_.lastMessageTime<E.lastMessageTime)return 1;if(_.projectPath<E.projectPath)return-1;if(_.projectPath>E.projectPath)return 1;if(_.sessionId<E.sessionId)return-1;if(_.sessionId>E.sessionId)return 1;return 0}function f_(_,E){let R=[..._],W=$_(E);if(W)R=R.filter((k)=>k_(k,{sessionId:W.sessionId,projectPath:W.projectPath,lastMessageTime:W.lastMessageTime})>0);let $=R.slice(0,E.limit);if($.length===0||R.length<=$.length)return{sessions:$};let H=$[$.length-1];return{sessions:$,nextCursor:R_({version:1,cwd:E.cwd,includeSubagents:E.includeSubagents,archived:E.archived,lastMessageTime:H.lastMessageTime,projectPath:H.projectPath,sessionId:H.sessionId})}}function H_(_){return _.type==="message_created"||_.type==="part_created"||_.type==="part_updated"||_.type==="turn_started"||_.type==="turn_completed"||_.type==="turn_aborted"||_.type==="interaction_requested"||_.type==="interaction_responded"||_.type==="interaction_recovered"||_.type==="review_started"||_.type==="review_completed"}function J(_){return _.type==="message_created"&&_.data.role==="user"&&(_.data.inboxMessageId!==void 0||_.data.parentMessageId===void 0)}function u(_,E){let R=_.find((W)=>J(W)&&W.data.messageId===E);if(!R)throw Error(`Rewind checkpoint not found: ${E}`);return{messageId:E,preview:c(_,E),createdAt:R.data.createdAt}}function c(_,E){let R=_.flatMap((W)=>{if(W.type!=="part_created"||W.data.messageId!==E)return[];if(W.data.partType==="text"){let $=W.data.payload;return typeof $.text==="string"?[$.text]:[]}if(W.data.partType==="image")return["[Image]"];return[]}).join("").trim();if(R.length<=160)return R;return`${R.slice(0,160)}...`}function S(_,E){u(_,E);let R=_.findIndex((k)=>k.type==="message_created"&&k.data.messageId===E),W=_[R],$=W?.type==="message_created"?W.data.inboxMessageId:void 0,H=new Set(_.flatMap((k)=>k.type==="turn_started"&&$&&k.data.inputMessageIds?.includes($)?[k.data.turnId]:[]));return _.filter((k,M)=>{if((k.type==="turn_started"||k.type==="turn_completed"||k.type==="turn_aborted")&&H.has(k.data.turnId))return!1;return M<R||!H_(k)})}function w(_){let E=[];for(let R of _){if(R.type!=="session_rewound"){E.push(R);continue}if(u(E,R.data.targetMessageId),R.data.mode!=="code")E=S(E,R.data.targetMessageId)}return E}function q_(_){let E=w(_);return E.filter(J).map((R)=>({messageId:R.data.messageId,preview:c(E,R.data.messageId),createdAt:R.data.createdAt})).reverse()}function y_(_,E){let R=w(_),W=u(R,E),$=R.findIndex((k)=>k.type==="message_created"&&k.data.messageId===E),H=R.slice($);return{checkpoint:W,projectedEntries:S(R,E),removedTurns:H.filter(J).length,snapshotMessageIds:H.flatMap((k)=>k.type==="part_created"&&k.data.partType==="tool_call"?[k.data.partId]:[])}}import*as f from"node:fs";import{createReadStream as M_}from"node:fs";import*as V from"node:fs/promises";import*as O from"node:path";import{createInterface as Q_}from"node:readline";var m=65536;function x(_){let E=_.data;if(E===null||typeof E!=="object"||Array.isArray(E))throw Error("Session event data must be a JSON object");return JSON.stringify(_)}function V_(_,E,R){let W=_.trim();if(!W)return;try{return JSON.parse(W)}catch($){throw Error(`Invalid session JSONL in ${R} at line ${E}`,{cause:$})}}function z(_,E="session transcript"){let R=_.split(`
|
|
2
2
|
`),W=!_.endsWith(`
|
|
3
3
|
`),$=[];for(let[H,k]of R.entries())try{let M=V_(k,H+1,E);if(M){if(typeof M.seq!=="number")M.seq=$.length+1;$.push(M)}}catch(M){if(W&&H===R.length-1)break;throw M}return $}class Y{static appendQueues=new Map;filePath;constructor(_){this.filePath=_}static maxSeq(_){let E=0;for(let R of _)if(typeof R.seq==="number"&&R.seq>E)E=R.seq;return E}static stampSeqFrom(_,E){let R=E;return _.map((W)=>{if(typeof W.seq==="number"){if(W.seq>R)R=W.seq;return W}return R+=1,{...W,seq:R}})}static stampSeq(_,E){return Y.stampSeqFrom(_,Y.maxSeq(E))}async append(_){try{let[E]=await this.appendEntries([_]);return E}catch(E){throw console.error(`[JSONLStore] 追加写入失败: ${this.filePath}`,E),E}}async appendBatch(_){try{return await this.appendEntries(_)}catch(E){throw console.error(`[JSONLStore] 批量追加写入失败: ${this.filePath}`,E),E}}async appendEntries(_){if(_.length===0)return[];return this.enqueue(async()=>{await V.mkdir(O.dirname(this.filePath),{recursive:!0,mode:493});let E=await V.open(this.filePath,"a+",384);try{let R=await this.repairIncompleteTail(E),W=await this.readTailSeq(E),$=Y.stampSeqFrom(_,W),H=`${$.map(x).join(`
|
|
4
4
|
`)}
|
|
@@ -113,4 +113,4 @@ CREATE VIRTUAL TABLE IF NOT EXISTS parts_fts USING fts5(
|
|
|
113
113
|
ORDER BY timestamp DESC LIMIT ?`:`SELECT session_id, role, timestamp, text FROM parts_fts
|
|
114
114
|
WHERE parts_fts MATCH ?
|
|
115
115
|
ORDER BY timestamp DESC LIMIT ?`,M=_.prepare(k);return R?M.all(H,R,W):M.all(H,W)}
|
|
116
|
-
export{w as
|
|
116
|
+
export{w as sc,q_ as tc,y_ as uc,z as vc,Y as wc,y as xc,$_ as yc,z_ as zc,k_ as Ac,f_ as Bc,r as Cc,K_ as Dc,U_ as Ec,B_ as Fc,A_ as Gc,n_ as Hc,i_ as Ic,d_ as Jc};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{H as
|
|
1
|
+
import{lf as F}from"./chunk-vx8a7e1j.js";import{Jf as D,Kf as E}from"./chunk-8gv6hsrf.js";import G from"node:path";function A(b){if(Array.isArray(b))return b.map((q)=>A(q));if(b!==null&&typeof b==="object"&&Object.getPrototypeOf(b)===Object.prototype)return Object.fromEntries(Object.entries(b).map(([q,w])=>[q,A(w)]));return b}function H(b){return A(b)}function I(b,q){let w=new D(q?.credentials??E().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=G.resolve(b),x=F.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...H(q),...J,...K},B=I(z);return x.validateConfig(z,B),{projectRoot:w,config:z,catalog:B}}function T(b){let q=H(b.config);return{projectRoot:G.resolve(b.projectRoot),config:q,catalog:I(q,b.catalog)}}
|
|
2
|
+
export{H as Jd,Q as Kd,T as Ld};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{spawn as I}from"node:child_process";var X=500;function x(j){return new Promise((q)=>setTimeout(q,j))}function Z(j){return j&&typeof j==="object"&&"code"in j?String(j.code):void 0}function L(j){return j()||j()}function G(j,q=process.platform,y=process.kill.bind(process)){if(q==="win32"||!Number.isInteger(j)||j<=1||j===process.pid)return!1;try{return y(-j,0),!0}catch(z){let B=Z(z);if(B==="ESRCH")return!1;if(B==="EPERM")return!0;throw z}}function N(j,q){return new Promise((y)=>{let z=["/PID",String(j),"/T"];if(q)z.push("/F");let B=I("taskkill",z,{stdio:"ignore",windowsHide:!0}),K=!1,J=(H)=>{if(K)return;K=!0,y(H)};B.once("error",()=>J(!1)),B.once("close",(H)=>J(H===0))})}async function F(j,q={}){if(!Number.isInteger(j)||j<=1||j===process.pid)return{success:!1,alreadyExited:!1,forced:!1};let y=q.platform??process.platform,z=q.gracePeriodMs??X,B=q.killProcess??process.kill.bind(process),K=q.taskkill??N,J=q.wait??x,H=q.validatePidOwnership??(()=>!0);if(!L(H))return{success:!1,alreadyExited:!1,forced:!1};if(y==="win32"){let V=await K(j,!1);if(await J(z),!H())return{success:V,alreadyExited:!1,forced:!1};let Y=await K(j,!0);return{success:V||Y,alreadyExited:!V&&!Y,forced:Y}}let Q=(V,Y)=>{try{return B(V,Y)}catch(D){return Z(D)==="ESRCH"}},W=Q(-j,"SIGTERM")||Q(j,"SIGTERM");if(await J(z),!H())return{success:W,alreadyExited:!1,forced:!1};let $=Q(-j,"SIGKILL")||Q(j,"SIGKILL");return{success:W||$,alreadyExited:!1,forced:$}}async function R(j,q={}){if(!Number.isInteger(j)||j<=1||j===process.pid)return{success:!1,alreadyExited:!1,forced:!1};if((q.platform??process.platform)==="win32")return{success:!1,alreadyExited:!1,forced:!1};let z=q.gracePeriodMs??X,B=q.killProcess??process.kill.bind(process),K=q.wait??x,J=q.validatePidOwnership??(()=>!0);if(!J())return{success:!1,alreadyExited:!1,forced:!1};let H=($)=>{try{return B(-j,$),"sent"}catch(V){return Z(V)==="ESRCH"?"missing":"failed"}},Q=H("SIGTERM");if(Q==="missing")return{success:!0,alreadyExited:!0,forced:!1};if(Q==="failed")return{success:!1,alreadyExited:!1,forced:!1};if(await K(z),!J())return{success:!1,alreadyExited:!1,forced:!1};let W=H("SIGKILL");return{success:W!=="failed",alreadyExited:W==="missing",forced:W==="sent"}}class b{child;state="owned";terminationPromise;terminationResult;platform;gracePeriodMs;killProcess;taskkill;wait;constructor(j,q={}){this.child=j;if(this.platform=q.platform??process.platform,this.gracePeriodMs=q.gracePeriodMs??X,this.killProcess=q.killProcess??process.kill.bind(process),this.taskkill=q.taskkill??N,this.wait=q.wait??x,q.releaseOnExit!==!1){let y=()=>{if(this.state==="owned")this.state="released"};j.once("close",y),j.once("error",y)}}release(){if(this.state==="owned")this.state="released"}terminate(){if(this.terminationPromise)return this.terminationPromise;if(this.terminationResult)return Promise.resolve(this.terminationResult);if(this.state==="released")return this.terminationResult={success:!0,alreadyExited:!0,forced:!1},Promise.resolve(this.terminationResult);return this.state="terminating",this.terminationPromise=this.terminateOwnedTree().then((j)=>{return this.state="released",this.terminationResult=j,j}),this.terminationPromise}async terminateOwnedTree(){let j=this.child.pid;if(!j)return{success:!1,alreadyExited:!0,forced:!1};if(this.platform==="win32"){let z=await this.taskkill(j,!1);await this.wait(this.gracePeriodMs);let B=await this.taskkill(j,!0);if(!z&&!B)return{success:this.signalDirectChild("SIGKILL"),alreadyExited:!1,forced:!0};return{success:!0,alreadyExited:!1,forced:!0}}let q=this.signalPosixTree(j,"SIGTERM");await this.wait(this.gracePeriodMs);let y=this.signalPosixTree(j,"SIGKILL");return{success:q||y,alreadyExited:!1,forced:y}}signalPosixTree(j,q){if(j<=1||j===process.pid)return this.signalDirectChild(q);try{return this.killProcess(-j,q)}catch(y){if(Z(y)==="ESRCH")return!0;return this.signalDirectChild(q)}}signalDirectChild(j){try{return this.child.kill(j)}catch(q){return Z(q)==="ESRCH"}}}function v(j,q,y={},z={}){let B=I(j,q,{...y,detached:process.platform==="win32"?y.detached:!0,windowsHide:y.windowsHide??!0});return{child:B,processTree:new b(B,z)}}
|
|
2
|
-
export{G as
|
|
2
|
+
export{G as ve,F as we,R as xe,v as ye};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Dd as a}from"./chunk-4qtb8yf6.js";import"./chunk-ekv4hpy8.js";import"./chunk-8gv6hsrf.js";import"./chunk-5m5nxkfs.js";import"./chunk-heydawsf.js";import"./chunk-37se34rx.js";export{a as createChatServiceAsync};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{of as En,pf as j,qf as T}from"./chunk-4qyhtrhx.js";import{uf as On,vf as Zn}from"./chunk-s6rdv601.js";import{Af as L}from"./chunk-1ggxyyar.js";import{Ef as $n}from"./chunk-ekv4hpy8.js";import{Hf as rt,Kf as p}from"./chunk-8gv6hsrf.js";import{Sf as sn,Tf as wn}from"./chunk-7e7zgzag.js";import{Xf as $}from"./chunk-2d35rmyg.js";import{fg as Sn}from"./chunk-heydawsf.js";var et=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function St(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function B(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:"&&St(M.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return M}var U=async(n,t)=>{B(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 y(n){let t=n.oauth;if(!t)return;let M=t;for(let S of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(M[S]!==void 0)throw Error(`MCP OAuth "${S}" 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(B(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((S)=>S.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 e=t.scopes?.map((S)=>S.trim());if(e){if(e.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(e.some((S)=>!S||S.length>128||!et.test(S)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(e).size!==e.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:_}:{},...e?.length?{scopes:e}:{},...r!==void 0?{callbackPort:r}:{}}}import{randomUUID as l}from"node:crypto";import xt from"node:http";import{auth as Tn}from"@modelcontextprotocol/sdk/client/auth.js";import $t from"open";import{createHash as Et,randomUUID as mt}from"node:crypto";import{constants as D,promises as P}from"node:fs";import W from"node:path";import{Mutex as At}from"async-mutex";import Tt from"write-file-atomic";var mn=1,bt=1048576,ct=5000,ot=50,st=/^[a-f0-9]{64}$/,wt=T.Object({client_id:T.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),Lt=T.Object({access_token:T.String({minLength:1,maxLength:65536}),token_type:T.String({minLength:1,maxLength:64}),expires_in:T.Optional(T.Number({minimum:0})),refresh_token:T.Optional(T.String({minLength:1,maxLength:65536})),scope:T.Optional(T.String({maxLength:16384})),id_token:T.Optional(T.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),ft=T.Unsafe({type:"object",properties:{authorizationServerUrl:T.String({format:"uri"}),resourceMetadataUrl:T.Optional(T.String({format:"uri"})),resourceMetadata:T.Optional(T.Unknown()),authorizationServerMetadata:T.Optional(T.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),An=T.Object({serverUrl:T.String({format:"uri"}),clientId:T.Optional(T.String({minLength:1,maxLength:4096})),clientInformation:T.Optional(wt),tokens:T.Optional(Lt),tokenExpiresAt:T.Optional(T.Number({minimum:0})),discoveryState:T.Optional(ft),updatedAt:T.String({format:"date-time"})},{additionalProperties:!1}),rn=T.Object({version:T.Literal(mn),credentials:T.Record(T.String(),An)},{additionalProperties:!1});function q(n,t){return n instanceof Error&&"code"in n&&n.code===t}function Pt(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return q(t,"EPERM")}}function k(n){return structuredClone(n)}function en(n){if(Object.keys(n.credentials).some((t)=>!st.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function G(n){let t=new URL(n);return t.hash="",t.toString()}function F(n,t,M=[]){return Et("sha256").update(JSON.stringify({serverUrl:G(n),clientId:t?.trim()||null,scopes:[...M].sort()})).digest("hex")}class I{static mutexes=new Map;stateRoot;tokenFilePath;mutex;constructor(n=Sn()){this.stateRoot=W.join(n,"mcp"),this.tokenFilePath=W.join(this.stateRoot,"oauth-credentials.json");let t=I.mutexes.get(this.tokenFilePath);if(!t)t=new At,I.mutexes.set(this.tokenFilePath,t);this.mutex=t}async getCredential(n){return this.mutex.runExclusive(async()=>{let M=(await this.readStore()).credentials[n];return M?k(M):null})}async updateCredential(n,t){return this.runMutation(async(M)=>{let u=M.credentials[n],_=await t(u?k(u):null);if(_)M.credentials[n]=j(An,_);else delete M.credentials[n];return _?k(M.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return this.mutex.runExclusive(async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return this.mutex.runExclusive(async()=>{let t=await this.acquireStoreLock();try{let M=await this.readStore(),u=await n(M);return await this.writeStore(M),u}finally{await t()}})}async ensureStateRoot(){await P.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await P.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 P.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>bt)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await P.readFile(this.tokenFilePath,"utf8")),M=En(rn,t);if(!M.success)throw Error("MCP OAuth credential store has an invalid schema");return en(M.data),M.data}catch(n){if(q(n,"ENOENT"))return{version:mn,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=j(rn,n);en(t),await Tt(this.tokenFilePath,`${JSON.stringify(t,null,2)}
|
|
2
2
|
`,{mode:384,encoding:"utf8"}),await P.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let n=W.join(this.stateRoot,".oauth-credentials.lock"),t=mt(),M=Date.now()+ct;while(Date.now()<M)try{let u=await P.open(n,D.O_CREAT|D.O_EXCL|D.O_WRONLY,384);return await u.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:t,createdAt:new Date().toISOString()})}
|
|
3
3
|
`,"utf8"),await u.close(),async()=>{try{if(JSON.parse(await P.readFile(n,"utf8")).token===t)await P.unlink(n)}catch(_){if(!q(_,"ENOENT"))throw _}}}catch(u){if(!q(u,"EEXIST"))throw u;await this.removeDeadLock(n),await new Promise((_)=>setTimeout(_,ot))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(n){let t=await P.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 P.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(!Pt(M.pid))await P.unlink(n)}}var bn="127.0.0.1",cn=7777,on="/oauth/callback",dt=300000;class v 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 Ln extends Error{constructor(n){super(`MCP OAuth credentials are unavailable in this runtime for server "${n}"`);this.name="McpOAuthUnavailableError"}}function Xt(n){let t=n?"Authentication complete":"Authentication failed";return`<!doctype html>
|
|
4
4
|
<html lang="en">
|
|
@@ -41,4 +41,4 @@ ${M.map((u)=>` - ${u}`).join(`
|
|
|
41
41
|
]
|
|
42
42
|
}
|
|
43
43
|
`)}}function Uu(n,t={}){let M={...n};if(t.debug!==void 0)M.debug=t.debug===""?!0:t.debug;if(t.model){if(!n.models.some((_)=>_.id===t.model))throw Error(`模型配置未找到: ${t.model}`);M.currentModelId=t.model}if(t.yolo===!0)M.permissionMode="yolo";else if(t.permissionMode!==void 0)M.permissionMode=t.permissionMode;if(t.maxTurns!==void 0)M.maxTurns=t.maxTurns;if(t.maxConcurrentTasks!==void 0)M.maxConcurrentTasks=t.maxConcurrentTasks;if(t.maxQueuedTasks!==void 0)M.maxQueuedTasks=t.maxQueuedTasks;return M.systemPrompt=t.systemPrompt,M.appendSystemPrompt=t.appendSystemPrompt,M.model=t.model,M.resumeSessionId=t.sessionId,M.forkSession=t.forkSession,M.allowedTools=t.allowedTools,M.disallowedTools=t.disallowedTools,M.mcpConfigPaths=t.mcpConfig,M.strictMcpConfig=t.strictMcpConfig,M.addDirs=t.addDir,M.outputFormat=t.outputFormat,M.inputFormat=t.inputFormat,M.print=t.print,M.includePartialMessages=t.includePartialMessages,M.replayUserMessages=t.replayUserMessages,M.agentsConfig=t.agents,M.settingSources=t.settingSources,M}
|
|
44
|
-
export{U as
|
|
44
|
+
export{U as ze,y as Ae,I as Be,v as Ce,Ln as De,N as Ee,Nn as Fe,qM as Ge,V as He,VM as Ie,OM as Je,ZM as Ke,Bn as Le,Ut as Me,JM as Ne,qt as Oe,QM as Pe,Jn as Qe,DM as Re,WM as Se,jM as Te,FM as Ue,lM as Ve,pn as We,vM as Xe,nu as Ye,tu as Ze,Mu as _e,BM as $e,b as af,d as bf,gt as cf,i as df,Q as ef,ln as ff,vn as gf,nt as hf,tt as if,Mt as jf,ut as kf,R as lf,Uu as mf};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{clampThinkingLevel as t,getSupportedThinkingLevels as i}from"@earendil-works/pi-ai";var f=["auto","off","minimal","low","medium","high","xhigh","max"];function s(e){return typeof e==="string"&&f.includes(e)}function g(e,o){let n=i(e);if(o!=="auto"&&!n.includes(o))throw Error(`Reasoning effort ${o} is not supported by ${e.name}`);return{selection:o,effective:o==="auto"?t(e,"high"):o,supported:n}}
|
|
2
|
-
export{s as
|
|
2
|
+
export{s as Hd,g as Id};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Mc as a,Nc as b,Oc as c}from"./chunk-1444wfhr.js";import"./chunk-48tz6s0s.js";import"./chunk-mbrgz77y.js";import"./chunk-v508x7cg.js";import"./chunk-6kc12pma.js";import"./chunk-0rwz7tm0.js";import"./chunk-vx8a7e1j.js";import"./chunk-gdp6fg4e.js";import"./chunk-4qyhtrhx.js";import"./chunk-s6rdv601.js";import"./chunk-1ggxyyar.js";import"./chunk-ekv4hpy8.js";import"./chunk-8gv6hsrf.js";import"./chunk-5m5nxkfs.js";import"./chunk-7e7zgzag.js";import"./chunk-2d35rmyg.js";import"./chunk-d4327k1v.js";import"./chunk-heydawsf.js";import"./chunk-37se34rx.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Ac as x$,
|
|
1
|
+
import{Ac as _$,Bc as x$,Dc as g0,Gc as J$,Hc as Uf,sc as u,tc as Hf,uc as C$,vc as Yf,wc as I,xc as N$,yc as Wf,zc as G$}from"./chunk-rezjy4mp.js";import{Hd as V0}from"./chunk-vz0zsct0.js";import{me as Z0}from"./chunk-9pww3s5m.js";import{ye as i$}from"./chunk-s3zfyy7r.js";import{uf as Qf,vf as Xf}from"./chunk-s6rdv601.js";import{Af as A$}from"./chunk-1ggxyyar.js";import{Ef as U0}from"./chunk-ekv4hpy8.js";import{Lf as x0,Of as J0}from"./chunk-5m5nxkfs.js";import{Sf as p}from"./chunk-7e7zgzag.js";import{$f as Kf,Zf as Ff,_f as q0,ag as A,bg as m,dg as G0,eg as c,fg as C0}from"./chunk-heydawsf.js";import{readdir as L$,readFile as a,rm as $0,stat as E0}from"node:fs/promises";import*as V from"node:path";import{nanoid as j}from"nanoid";import{createHash as yf,randomUUID as Sf}from"node:crypto";import*as v from"node:fs/promises";import*as H0 from"node:path";import{execFileSync as Mf}from"node:child_process";import{createHash as gf}from"node:crypto";import{readFileSync as Ef}from"node:fs";var bf=/^[a-f0-9]{64}$/;function Y$($){if(!$||typeof $!=="object")return!1;let f=$;return(f.platform==="linux"||f.platform==="darwin"||f.platform==="win32")&&typeof f.fingerprint==="string"&&bf.test(f.fingerprint)}var W$={readFile:($)=>Ef($,"utf8"),execFile:($,f)=>Mf($,f,{encoding:"utf8",timeout:$==="powershell.exe"?3000:2000,windowsHide:!0})},wf=($)=>{try{return process.kill($,0),!0}catch(f){return f instanceof Error&&"code"in f&&f.code==="EPERM"}};function u0($,f){return{platform:$,fingerprint:gf("sha256").update(`${$}\x00${f}`).digest("hex")}}function kf($,f){let T=f.readFile(`/proc/${$}/stat`).trim(),q=T.lastIndexOf(")");if(q<0)throw Error("Invalid /proc process stat");let L=T.slice(q+2).split(/\s+/)[19];if(!L||!/^\d+$/.test(L))throw Error("Missing process start ticks");return L}function Q0($,f=process.platform,T=W$){if(!Number.isInteger($)||$<=1)return;try{if(f==="linux")return u0(f,kf($,T));if(f==="darwin"){let q=T.execFile("ps",["-o","lstart=","-p",String($)]).trim();return q?u0(f,q):void 0}if(f==="win32"){let q=`(Get-CimInstance Win32_Process -Filter "ProcessId = ${$}").CreationDate.ToUniversalTime().ToString('O')`,B=T.execFile("powershell.exe",["-NoProfile","-NonInteractive","-Command",q]).trim();return B?u0(f,B):void 0}}catch{return}return}function U$($,f){return Q0($,f.platform)?.fingerprint===f.fingerprint}function o1($,f,T=W$,q=wf){if(!Number.isInteger($)||$<=1)return!1;let B=Q0($,f.platform,T);if(B)return B.fingerprint===f.fingerprint;return!q($)}var z$=1;function jf($,f){let T=yf("sha256").update(f).digest("hex");return H0.join(q0($),".locks",`${T}.lock`)}function X0($,f){return $ instanceof Error&&"code"in $&&$.code===f}async function P0($){try{let f=JSON.parse(await v.readFile($,"utf8"));if(f.version!==z$||typeof f.sessionId!=="string"||typeof f.ownerId!=="string"||!Number.isInteger(f.pid)||(f.pid??0)<=0||f.processIdentity!==void 0&&!Y$(f.processIdentity)||typeof f.acquiredAt!=="string")return;return f}catch{return}}async function D$($){let f=await P0($);if(f)return f;return await new Promise((T)=>setTimeout(T,10)),P0($)}function mf($){try{return process.kill($,0),!0}catch(f){return X0(f,"EPERM")}}async function R$($,f){let T;try{return T=await v.open($,"wx",384),await T.writeFile(`${JSON.stringify(f)}
|
|
2
2
|
`,"utf8"),!0}catch(q){if(X0(q,"EEXIST"))return!1;if(T)await v.unlink($).catch(()=>{return});throw q}finally{await T?.close().catch(()=>{return})}}class h extends Error{code="BLADE_SESSION_IN_USE";constructor($){super($?`Session is already active in another Blade process (PID ${$}). Stop that process or choose a different session.`:"Session is already active in another Blade process. Stop that process or choose a different session.");this.name="SessionInUseError"}}class n{filePath;record;released=!1;constructor($,f){this.filePath=$;this.record=f}static async acquire($,f=A$()){let T=jf(f,$),q={version:z$,sessionId:$,ownerId:Sf(),pid:process.pid,processIdentity:Q0(process.pid),acquiredAt:new Date().toISOString()};if(await v.mkdir(H0.dirname(T),{recursive:!0,mode:448}),await R$(T,q))return new n(T,q);let B=await D$(T);if(B&&mf(B.pid)&&(!B.processIdentity||U$(B.pid,B.processIdentity)))throw new h(B.pid);if(await v.unlink(T).catch((L)=>{if(!X0(L,"ENOENT"))throw L}),await R$(T,q))return new n(T,q);throw new h((await D$(T))?.pid)}async release(){if(this.released)return;if(this.released=!0,(await P0(this.filePath))?.ownerId!==this.record.ownerId)return;await v.unlink(this.filePath).catch((f)=>{if(!X0(f,"ENOENT"))throw f})}}var TT=1;function h0($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function If($){if(!h0($)||typeof $.type!=="string")return!1;if($.type==="text")return typeof $.text==="string";return $.type==="image_url"&&h0($.image_url)&&typeof $.image_url.url==="string"}function vf($){if(!h0($))return!1;if(!["system","user","assistant","tool"].includes(String($.role)))return!1;return typeof $.content==="string"||Array.isArray($.content)&&$.content.every(If)}function M$($){if(!Array.isArray($)||$.length===0||$.length>4096)return;let f=JSON.stringify($);if(Buffer.byteLength(f)>16777216)return;let T=JSON.parse(f);if(!Array.isArray(T)||!T.every(vf))return;return T}function qT($){let f=M$($);if(!f)throw Error("Compaction replacement context is invalid or exceeds limits");return f}function g$($){return M$($)}function uf($,f){for(let T of $){if(T.type!=="part_created"||T.data.partType!=="tool_result")continue;let q=T.data.payload;if(!q||typeof q!=="object"||Array.isArray(q))continue;let B=q;if(B.toolCallId===f||T.data.partId===f||T.data.messageId===f)return B}return}function E$($){let f=u($),T=new Map;for(let q of f){if(q.type==="interaction_requested"){T.set(q.data.requestId,{request:q.data,hasToolResult:!1,hasRecoveryToolResult:!1});continue}if(q.type==="interaction_responded"){let B=T.get(q.data.requestId);if(B)B.response=q.data;continue}if(q.type==="interaction_recovered"){let B=T.get(q.data.requestId);if(B)B.recovery=q.data}}for(let q of T.values()){let B=uf(f,q.request.toolCallId);q.hasToolResult=B!==void 0;let L=B?.metadata&&typeof B.metadata==="object"?B.metadata:void 0;q.hasRecoveryToolResult=L?.interactionRecovery===!0&&L.requestId===q.request.requestId}return[...T.values()]}function b$($){return E$($).reverse().find((f)=>!f.response&&!f.recovery)}function OT($){let f=new Map;for(let T of E$($))f.set(T.request.toolCallId,T);return[...f.values()].filter((T)=>T.response&&!T.recovery&&(!T.hasToolResult||T.hasRecoveryToolResult))}function w$($){if(!$)return;return{type:$.request.interactionType,requestId:$.request.requestId}}function Y0($){let f=new Map,T=[];for(let q of $){if(q.type==="review_started"){if(!f.has(q.data.reviewId))T.push(q.data.reviewId),f.set(q.data.reviewId,{start:q.data});continue}if(q.type!=="review_completed")continue;let B=f.get(q.data.reviewId);if(B&&B.completion===void 0)B.completion=q.data}return T.map((q)=>f.get(q)).filter((q)=>q!==void 0)}function NT($){return Y0($).reverse().find((f)=>f.completion===void 0)}function n0($){switch($){case"completed":return"completed";case"stale":return"stale: the review target changed while the reviewer was running";case"aborted":return"aborted";case"interrupted":return"interrupted by process restart";case"failed":return"failed"}}function k$($,f){let T=["## Code Review","",`Target: ${$.target.label}`,`Status: ${n0(f.status)}`,"",f.overallExplanation||"No overall explanation was provided."];if(f.findings.length===0)T.push("","No actionable findings.");else{T.push("","### Findings");for(let[q,B]of f.findings.entries()){let L=B.codeLocation.lineStart===B.codeLocation.lineEnd?`${B.codeLocation.lineStart}`:`${B.codeLocation.lineStart}-${B.codeLocation.lineEnd}`;T.push("",`${q+1}. ${B.title}`,` ${B.codeLocation.path}:L${L} · confidence ${B.confidenceScore.toFixed(2)}`,` ${B.body}`)}}if(f.error)T.push("",`Error: ${f.error}`);return T.join(`
|
|
3
3
|
`)}function y$($,f){return{reviewId:$.reviewId,phase:"completed",status:f.status,target:{kind:$.target.kind,label:$.target.label,...$.target.baseSha?{reference:$.target.baseSha}:{},...$.target.commitSha?{reference:$.target.commitSha}:{}},overallExplanation:f.overallExplanation,findings:f.findings.map((T)=>({title:T.title,body:T.body,priority:T.priority,confidenceScore:T.confidenceScore,codeLocation:{...T.codeLocation}})),...f.error?{error:f.error}:{}}}var l0={authentication:{message:"Provider authentication failed. Check model credentials.",retryable:!1},permission:{message:"Provider rejected this request. Check account and model permissions.",retryable:!1},rate_limit:{message:"Provider rate limit or quota exceeded.",retryable:!0},timeout:{message:"Provider request timed out.",retryable:!0},network:{message:"Provider connection failed.",retryable:!0},model_unavailable:{message:"The selected model is unavailable.",retryable:!0},context_limit:{message:"The request exceeded the model context limit.",retryable:!1},unsupported_input:{message:"The selected model does not support this input.",retryable:!1},runtime:{message:"Agent execution failed.",retryable:!0}};function Pf($){try{if($ instanceof Error)return $.message;if($!==null&&typeof $==="object"&&"message"in $&&typeof $.message==="string")return $.message;return String($)}catch{return"Unknown error"}}function hf($){let f=$.toLowerCase();if(/\b(401|unauthorized|authentication|invalid (?:api[ _-]?)?key|api[ _-]?key|credential)\b/.test(f))return"authentication";if(/\b(403|forbidden|permission denied|not permitted)\b/.test(f))return"permission";if(/\b(429|rate limit|too many requests|quota)\b/.test(f))return"rate_limit";if(/\b(timeout|timed out|deadline exceeded|etimedout)\b/.test(f))return"timeout";if(/\b(econnreset|econnrefused|enotfound|network|socket|connection)\b/.test(f))return"network";if(/\b(model not found|model unavailable|unsupported model|no such model)\b/.test(f))return"model_unavailable";if(/\b(context (?:length|window)|maximum context|too many tokens|token limit)\b/.test(f))return"context_limit";if(/\b(image|vision|multimodal|unsupported input|does not support)\b/.test(f))return"unsupported_input";return"runtime"}function nf($){return{code:$,...l0[$]}}function c0($){return nf(hf(Pf($)))}function p0($){if(!$||typeof $!=="object")return!1;let f=$;if(typeof f.code!=="string"||!(f.code in l0))return!1;let T=l0[f.code];return f.message===T.message&&f.retryable===T.retryable}import{promises as L0,realpathSync as cf}from"node:fs";import W0 from"node:path";import*as r from"fs/promises";import*as H from"path";var S$=[".git",".claude","node_modules",".env",".env.local",".env.production",".env.development",".env.test"];class d extends Error{code;constructor($,f){super($);this.code=f;this.name="PathSecurityError"}}class i0{static normalize($,f){let T=H.isAbsolute($)?$:H.resolve(f,$),q=H.normalize(T),B=H.normalize(f);if(!this.isWithinWorkspace(q,B))throw new d(`Path outside workspace: ${$} (resolved to ${q}, workspace: ${B})`,"PATH_OUTSIDE_WORKSPACE");return q}static checkRestricted($){let f=$.split(H.sep);for(let T of S$)if(f.includes(T))throw new d(`Access denied: "${T}" is a protected directory`,"RESTRICTED_PATH")}static checkTraversal($){if($.includes(".."))throw new d(`Path traversal not allowed: ${$}`,"PATH_TRAVERSAL")}static async validatePath($,f){this.checkTraversal($);let T=this.normalize($,f);this.checkRestricted(T);try{await r.access(T)}catch(q){throw new d(`Path not found: ${$}`,"PATH_NOT_FOUND")}return T}static async resolveSymlink($,f){try{let T=await r.realpath($),q=await r.realpath(f);if(!this.isWithinWorkspace(T,q))throw new d(`Symlink points outside workspace: ${$} -> ${T}`,"SYMLINK_OUTSIDE_WORKSPACE");return T}catch(T){if(T instanceof d)throw T;return $}}static getRelativePath($,f){return H.relative(f,$)}static isWithinWorkspace($,f){let T=H.resolve($),q=H.resolve(f),B=H.relative(q,T);return B===""||B!==".."&&!B.startsWith(`..${H.sep}`)&&!H.isAbsolute(B)}static async isWithinWorkspaceResolved($,f){let T=H.resolve(f),q=H.isAbsolute($)?H.resolve($):H.resolve(T,$);if(!this.isWithinWorkspace(q,T))return!1;let B;try{B=await r.realpath(T)}catch{return!1}let L=q;while(!0){try{let C=await r.realpath(L);return this.isWithinWorkspace(C,B)}catch(C){let _=C.code;if(_!=="ENOENT"&&_!=="ENOTDIR")return!1}let O=H.dirname(L);if(O===L)return!1;L=O}}static isRestricted($){let f=$.split(H.sep);return S$.some((T)=>f.includes(T))}}var B0=U0("Tool");class l{static instance=null;accessedFiles=new Map;pathAliases=new Map;constructor(){}static getInstance(){if(!l.instance)l.instance=new l;return l.instance}async recordFileRead($,f){try{let T=await L0.stat($),q={filePath:W0.resolve($),accessTime:Date.now(),mtime:T.mtimeMs,sessionId:f,lastOperation:"read"};this.setRecord(q),await this.recordAliases($,q.filePath),B0.debug(`记录文件读取: ${$}`)}catch(T){B0.warn(`记录文件读取失败: ${$}`,T)}}async recordFileEdit($,f,T="edit"){try{let q=await L0.stat($),B={filePath:W0.resolve($),accessTime:Date.now(),mtime:q.mtimeMs,sessionId:f,lastOperation:T};this.setRecord(B),await this.recordAliases($,B.filePath),B0.debug(`记录文件${T==="edit"?"编辑":"写入"}: ${$}`)}catch(q){B0.warn(`记录文件${T==="edit"?"编辑":"写入"}失败: ${$}`,q)}}hasFileBeenRead($,f){let T=this.accessedFiles.get(this.resolveTrackedPath($));if(!T)return!1;return f?T.has(f):T.size>0}async checkFileModification($,f){let T=this.getFileRecord($,f);if(!T)return{modified:!1,message:"文件未被跟踪"};try{let q=await L0.stat($);if(Math.abs(q.mtimeMs-T.mtime)>1)return{modified:!0,message:`文件在访问后被修改(访问时间: ${new Date(T.accessTime).toISOString()}, 当前修改时间: ${q.mtime.toISOString()})`};return{modified:!1}}catch(q){let B=q;if(B.code==="ENOENT")return{modified:!0,message:"文件已被删除"};return{modified:!1,message:`无法检查文件状态: ${B.message}`}}}async checkExternalModification($,f){let T=this.getFileRecord($,f);if(!T)return{isExternal:!1,message:"文件未被跟踪"};try{let q=await L0.stat($);if(q.mtimeMs-T.mtime>2000)return{isExternal:!0,message:`文件在 ${new Date(T.accessTime).toISOString()} (${T.lastOperation}) 之后被外部程序修改(当前修改时间: ${q.mtime.toISOString()})`};return{isExternal:!1}}catch(q){let B=q;if(B.code==="ENOENT")return{isExternal:!0,message:"文件已被删除"};return B0.warn(`检查文件外部修改失败: ${$}`,q),{isExternal:!1,message:`无法检查文件状态: ${B.message}`}}}getFileRecord($,f){let T=this.accessedFiles.get(this.resolveTrackedPath($));if(!T)return;if(f)return T.get(f);return[...T.values()].sort((q,B)=>B.accessTime-q.accessTime)[0]}getTrackedRecords(){return[...this.accessedFiles.values()].flatMap(($)=>[...$.values()])}clearFileRecord($,f){let T=this.resolveTrackedPath($);if(!f){this.accessedFiles.delete(T),this.removeAliases(T);return}let q=this.accessedFiles.get(T);if(q?.delete(f),q?.size===0)this.accessedFiles.delete(T),this.removeAliases(T)}clearAll(){this.accessedFiles.clear(),this.pathAliases.clear()}clearSession($,f){for(let[T,q]of this.accessedFiles.entries()){if(f&&!i0.isWithinWorkspace(T,f))continue;if(q.delete($),q.size===0)this.accessedFiles.delete(T),this.removeAliases(T)}}getTrackedFiles(){return Array.from(this.accessedFiles.keys())}getTrackedFileCount(){return this.accessedFiles.size}static resetInstance(){l.instance=null}setRecord($){let f=this.accessedFiles.get($.filePath);if(!f)f=new Map,this.accessedFiles.set($.filePath,f);f.set($.sessionId,$)}async recordAliases($,f){this.pathAliases.set(W0.resolve($),f);let T=await L0.realpath($).catch(()=>{return});if(T)this.pathAliases.set(T,f)}resolveTrackedPath($){let f=W0.resolve($);if(this.accessedFiles.has(f))return f;let T=this.pathAliases.get(f);if(T)return T;try{let q=cf.native(f);return this.pathAliases.get(q)??q}catch{return f}}removeAliases($){for(let[f,T]of this.pathAliases)if(T===$)this.pathAliases.delete(f)}}import*as O0 from"node:crypto";import{promises as F}from"node:fs";import*as Q from"node:path";import d0 from"write-file-atomic";var j$="missing";class D0{sessionId;workspaceRoot;enableCheckpoints;maxSnapshots;snapshotDir;manifestPath;trackedFileBackups=new Map;snapshots=[];constructor($){if(A($.sessionId),this.sessionId=$.sessionId,$.workspaceRoot&&!Q.isAbsolute($.workspaceRoot))throw Error("Snapshot workspace root must be absolute");this.workspaceRoot=$.workspaceRoot?Q.resolve($.workspaceRoot):void 0,this.enableCheckpoints=$.enableCheckpoints??!0,this.maxSnapshots=$.maxSnapshots??10;let f=C0();this.snapshotDir=Q.join(f,"file-history",this.sessionId),this.manifestPath=Q.join(this.snapshotDir,"manifest.json")}async initialize(){if(!this.enableCheckpoints)return;if(this.workspaceRoot)await this.selectWorkspaceSnapshotDir();await F.mkdir(this.snapshotDir,{recursive:!0,mode:493}),await this.loadManifest()}async selectWorkspaceSnapshotDir(){let $=C0(),f=await F.realpath(this.workspaceRoot).catch(()=>this.workspaceRoot),T=O0.createHash("sha256").update(f).digest("hex").slice(0,24),q=Q.join($,"file-history",this.sessionId),B=Q.join($,"file-history","workspaces",T,this.sessionId),L=Q.join(B,"manifest.json");try{await F.access(L)}catch{await this.migrateLegacySnapshotDir(q,B,f)}this.snapshotDir=B,this.manifestPath=L}async migrateLegacySnapshotDir($,f,T){let q;try{q=JSON.parse(await F.readFile(Q.join($,"manifest.json"),"utf8"))}catch{return}if(q.schemaVersion!==1||!Array.isArray(q.snapshots)||!q.snapshots.every((B)=>this.isWithinWorkspace(B.filePath,T)))return;await F.mkdir(Q.dirname(f),{recursive:!0,mode:493});try{await F.rename($,f)}catch(B){let L=B.code;if(L!=="ENOENT"&&L!=="EEXIST"&&L!=="ENOTEMPTY")throw B}}isWithinWorkspace($,f){if(!Q.isAbsolute($))return!1;let T=Q.relative(f,Q.resolve($));return T===""||T!==".."&&!T.startsWith(`..${Q.sep}`)&&!Q.isAbsolute(T)}async createSnapshot($,f){if(!this.enableCheckpoints)return{backupFileName:"",version:0,backupTime:new Date};let T=await this.resolveFileIdentity($),q=!0;try{await F.access(T)}catch{q=!1}let B=this.trackedFileBackups.get(T),L=B?B.version+1:1,O=this.generateFileHash(T,L),C=this.getSnapshotPath(O,L),_=new Date;if(q){let G=await F.readFile(T);await F.writeFile(C,G)}let N={backupFileName:O,version:L,backupTime:_};return this.trackedFileBackups.set(T,N),this.snapshots.push({messageId:f,backupFileName:O,timestamp:_,filePath:T,version:L,existedBefore:q}),await this.cleanupOldSnapshots(T),await this.persistManifest(),N}async recordPostEditState($,f){if(!this.enableCheckpoints||!f.backupFileName)return;let T=await this.resolveFileIdentity($),q=this.snapshots.find((B)=>B.filePath===T&&B.backupFileName===f.backupFileName&&B.version===f.version);if(!q)throw Error(`未找到待完成的快照: ${T}`);q.postEditHash=await this.hashFile(T),await this.persistManifest()}async discardSnapshot($,f){if(!this.enableCheckpoints||!f.backupFileName)return;let T=await this.resolveFileIdentity($),q=this.snapshots.find((B)=>B.filePath===T&&B.backupFileName===f.backupFileName&&B.version===f.version);if(!q)return;this.removeSnapshot(q),await F.rm(this.getSnapshotPath(q.backupFileName,q.version),{force:!0}),await this.persistManifest()}async rewindLatest($){let f=await this.resolveFileIdentity($),T=this.snapshots.slice().reverse().find((L)=>L.filePath===f&&L.postEditHash!==void 0);if(!T?.postEditHash)throw Error(`未找到可回退快照: ${f}`);if(await this.hashFile(f)!==T.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${f}`);let B=this.getSnapshotPath(T.backupFileName,T.version);if(T.existedBefore){let L=await F.readFile(B);await F.mkdir(Q.dirname(f),{recursive:!0}),await F.writeFile(f,L)}else await F.rm(f,{force:!0});return this.removeSnapshot(T),await F.rm(B,{force:!0}),await this.persistManifest(),T}async restoreSnapshot($,f){let T=await this.resolveFileIdentity($),q=this.snapshots.slice().reverse().find((L)=>L.messageId===f&&L.filePath===T);if(!q)throw Error(`未找到快照: messageId=${f}, filePath=${T}`);let B=this.getSnapshotPath(q.backupFileName,q.version);if(q.existedBefore){let L=await F.readFile(B);await F.mkdir(Q.dirname(T),{recursive:!0}),await F.writeFile(T,L)}else await F.rm(T,{force:!0})}async listSnapshots($){let f=await this.resolveFileIdentity($);return this.snapshots.filter((T)=>T.filePath===f)}async listAllSnapshots(){return this.snapshots.filter(($)=>$.postEditHash!==void 0)}async previewRewind($){let f=this.buildRewindPlan($);return{files:f.map((T)=>T.filePath),snapshotCount:f.reduce((T,q)=>T+q.selected.length,0)}}async rewindSnapshots($){let f=this.buildRewindPlan($);if(f.length===0)return{files:[],snapshotCount:0};let T=new Map;for(let B of f){let L,O=!0;try{L=await F.readFile(B.filePath)}catch(_){if(_.code!=="ENOENT")throw _;O=!1}if((L?O0.createHash("sha256").update(L).digest("hex"):j$)!==B.latest.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${B.filePath}`);if(T.set(B.filePath,{existed:O,content:L}),B.target.existedBefore)await F.access(this.getSnapshotPath(B.target.backupFileName,B.target.version))}let q=[...this.snapshots];try{for(let L of f)if(L.target.existedBefore){let O=await F.readFile(this.getSnapshotPath(L.target.backupFileName,L.target.version));await F.mkdir(Q.dirname(L.filePath),{recursive:!0}),await d0(L.filePath,O)}else await F.rm(L.filePath,{force:!0});let B=new Set(f.flatMap((L)=>L.selected));this.snapshots=this.snapshots.filter((L)=>!B.has(L)),this.rebuildTrackedFileBackups(),await this.persistManifest(),await Promise.all([...B].map((L)=>F.rm(this.getSnapshotPath(L.backupFileName,L.version),{force:!0}).catch(()=>{return})))}catch(B){this.snapshots=q,this.rebuildTrackedFileBackups();let L=[];for(let[O,C]of T)try{if(C.existed&&C.content)await d0(O,C.content);else await F.rm(O,{force:!0})}catch(_){L.push(_)}if(L.length>0)throw AggregateError([B,...L],"快照回退失败且无法完整恢复回退前状态");throw B}return{files:f.map((B)=>B.filePath),snapshotCount:f.reduce((B,L)=>B+L.selected.length,0)}}async commitSnapshots($){let f=this.buildRewindPlan($),T=new Set(f.flatMap((B)=>B.selected));if(T.size===0)return{files:[],snapshotCount:0};let q=[...this.snapshots];this.snapshots=this.snapshots.filter((B)=>!T.has(B)),this.rebuildTrackedFileBackups();try{await this.persistManifest()}catch(B){throw this.snapshots=q,this.rebuildTrackedFileBackups(),B}return await Promise.all([...T].map((B)=>F.rm(this.getSnapshotPath(B.backupFileName,B.version),{force:!0}).catch(()=>{return}))),{files:f.map((B)=>B.filePath),snapshotCount:T.size}}buildRewindPlan($){let f=new Set($),T=this.snapshots.filter((L)=>L.postEditHash!==void 0),q=T.filter((L)=>f.has(L.messageId));return[...new Set(q.map((L)=>L.filePath))].sort().map((L)=>{let O=T.filter((G)=>G.filePath===L),C=O.filter((G)=>f.has(G.messageId)),_=O.indexOf(C[0]),N=O.slice(_);if(N.length!==C.length||N.some((G)=>!f.has(G.messageId)))throw Error(`请求的快照不是文件历史的连续后缀: ${L}`);return{filePath:L,selected:C,target:C[0],latest:C.at(-1)}})}async loadManifest(){try{let $=await F.readFile(this.manifestPath,"utf-8"),f=JSON.parse($);if(f.schemaVersion!==1||!Array.isArray(f.snapshots))throw Error("Unsupported snapshot manifest");this.snapshots=await Promise.all(f.snapshots.map(async(T)=>({...T,filePath:await this.resolveFileIdentity(T.filePath),timestamp:new Date(T.timestamp)}))),this.rebuildTrackedFileBackups()}catch($){if($.code!=="ENOENT")throw $;this.snapshots=[],this.trackedFileBackups.clear()}}async persistManifest(){if(this.snapshots.length===0){await F.rm(this.manifestPath,{force:!0});return}let $={schemaVersion:1,snapshots:this.snapshots.map((f)=>({...f,timestamp:f.timestamp.toISOString()}))};await d0(this.manifestPath,JSON.stringify($,null,2),{encoding:"utf-8",mode:384})}async cleanupOldSnapshots($){let T=this.snapshots.filter((q)=>q.filePath===$).slice(0,-this.maxSnapshots);for(let q of T)await F.rm(this.getSnapshotPath(q.backupFileName,q.version),{force:!0}),this.removeSnapshot(q)}async cleanup($=0){let f=this.snapshots.slice().sort((q,B)=>B.timestamp.getTime()-q.timestamp.getTime()),T=new Set(f.slice(0,$));for(let q of this.snapshots)if(!T.has(q))await F.rm(this.getSnapshotPath(q.backupFileName,q.version),{force:!0});this.snapshots=f.slice(0,$).reverse(),this.rebuildTrackedFileBackups(),await this.persistManifest()}getSnapshotPath($,f){return Q.join(this.snapshotDir,`${$}@v${f}`)}async resolveFileIdentity($){let f=Q.resolve($),T=[],q=f;while(!0){try{let L=await F.realpath(q);return Q.join(L,...T.reverse())}catch(L){let O=L.code;if(O!=="ENOENT"&&O!=="ENOTDIR")throw L}let B=Q.dirname(q);if(B===q)return f;T.push(Q.basename(q)),q=B}}async hashFile($){try{let f=await F.readFile($);return O0.createHash("sha256").update(f).digest("hex")}catch(f){if(f.code==="ENOENT")return j$;throw f}}removeSnapshot($){let f=this.snapshots.indexOf($);if(f>=0)this.snapshots.splice(f,1);this.rebuildTrackedFileBackups()}rebuildTrackedFileBackups(){this.trackedFileBackups.clear();for(let $ of this.snapshots){let f=this.trackedFileBackups.get($.filePath);if(!f||f.version<$.version)this.trackedFileBackups.set($.filePath,{backupFileName:$.backupFileName,version:$.version,backupTime:$.timestamp})}}generateFileHash($,f){let T=O0.createHash("md5");return T.update(`${$}:${f}`),T.digest("hex").substring(0,16)}getSnapshotDir(){return this.snapshotDir}getSessionId(){return this.sessionId}getTrackedFileCount(){return this.trackedFileBackups.size}getSnapshotCount(){return this.snapshots.length}}var DT=1200,RT=2000,AT=2000,zT=2000;function I$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function pf($){if(typeof $==="string"&&$.length>0)return $;if(I$($)&&typeof $.message==="string")return $.message;return}function df($,f){if($===null||$===void 0)return f??"";if(typeof $==="string")return $;if(typeof $==="object")return $;return String($)}function v$($){let f=$.error!==null&&$.error!==void 0,T=f?pf($.error)??"Tool execution failed":void 0,q=I$($.metadata)?$.metadata:void 0;return{success:!f,llmContent:df($.output,T),...T?{error:{type:"execution_error",message:T}}:{},...q?{metadata:q}:{}}}function o0($,f){if($.length<=f)return $;let T=Math.max(0,f);if(T>0&&T<$.length&&/[\uD800-\uDBFF]/.test($.charAt(T-1)))T-=1;return $.slice(0,T)}function m$($,f){if($.length<=f)return $;let T=Math.max(0,$.length-f);if(T<$.length&&/[\uDC00-\uDFFF]/.test($.charAt(T)))T+=1;return $.slice(T)}function r0($,f){if($.length<=f)return $;if(f<=0)return"";let T=`
|
|
4
4
|
... (display clipped) ...
|
|
@@ -108,4 +108,4 @@ ${[...s,...e].join(`
|
|
|
108
108
|
s.project_sort_key ASC,
|
|
109
109
|
s.session_sort_key ASC
|
|
110
110
|
LIMIT ?`).all(...B,$.limit+1),O=await Promise.all(L.map(async(_)=>{let N=JSON.parse(_.metadata_json);if(_.archive_root_id&&_.effective_archived_at)return this.reconcileInterruptedTask({...N,archivedAt:_.effective_archived_at,archivedBySessionId:_.archive_root_id});let{archivedAt:G,archivedBySessionId:x,...J}=N;return this.reconcileInterruptedTask(J)})),C=x$(O,$);return{sessions:C.sessions.map((_)=>this.toPublicMetadata(_)),nextCursor:C.nextCursor}}catch{return null}}static async listSessions($={}){let f=G$($),T=await this.scanStoredSessions(f.cwd??void 0,f.includeSubagents,0,f.archived),q=new Set;return T.sort(_$).flatMap((B)=>{let L=`${B.projectPath}\x00${B.sessionId}`;if(q.has(L))return[];return q.add(L),[this.toPublicMetadata(B)]})}static async collectStaleEmptySessions($={}){let f=$.now??Date.now(),T=$.olderThanMs??z1;if(!Number.isFinite(T)||T<0)throw Error("Stale empty session age must be a non-negative number");let q=$.projectPath?[{storagePath:q0(this.resolveCatalogWorkspace($.projectPath)),projectPath:this.resolveCatalogWorkspace($.projectPath)}]:await this.listAllProjectStorageDirectories(),B=0;for(let L of q){let O;try{O=await L$(L.storagePath)}catch(C){if(C.code==="ENOENT")continue;throw C}for(let C of O){if(!C.endsWith(".jsonl"))continue;let _=C.slice(0,-6);if(!Kf(_))continue;let N=V.join(L.storagePath,C);try{let x=await E0(N);if(f-x.mtimeMs<T)continue;if(await Promise.all([E0(V.join(L.storagePath,`${_}.inbox.json`)).then(()=>!0).catch(()=>!1),E0(G0(L.projectPath,_)).then(()=>!0).catch(()=>!1)]).then((Z)=>Z.some(Boolean)))continue}catch(x){if(x.code==="ENOENT")continue;throw x}let G;try{G=await n.acquire(_,L.projectPath)}catch(x){if(x instanceof h)continue;throw x}try{if(!await new I(N).deleteValidated((J)=>J.length===1&&J[0]?.type==="session_created"&&J[0].data.relationType!=="subagent"))continue;B++,await $0(V.join(L.storagePath,`${_}.inbox.json`),{force:!0}),await $0(G0(L.projectPath,_),{force:!0}),await this.removeFromProjection(_,L.projectPath)}catch(x){N0.warn(`[SessionService] Skipping stale empty session cleanup: ${_}`,x)}finally{await G.release()}}}return B}static async findSessionMetadata($,f){if(A($),f!==void 0){if(!V.isAbsolute(f))throw Error("Session catalog cwd must be absolute");let q=V.resolve(f),B=this.getSessionFilePath(q,$);try{let L=await this.readStoredSessionMetadata(B,$,q);if(L.projectPath!==q)return;if(!L.parentId||L.archivedAt)return this.toPublicMetadata(O$([L],null)[0]??L);let O=await this.scanStoredSessions(q,!0,0,null);return this.toPublicMetadata(O.find((C)=>C.sessionId===$)??L)}catch(L){if(L.code==="ENOENT")return;throw L}}let T=(await this.scanStoredSessions(void 0,!0,0,null)).filter((q)=>q.sessionId===$);if(T.length===0)return;if(T.length>1)throw Error(`Ambiguous session ID: ${$}`);return this.toPublicMetadata(T[0])}static async loadSession($,f){try{if(f){if(!V.isAbsolute(f))throw Error("Session catalog cwd must be absolute");let q=V.resolve(f),B=this.getSessionFilePath(q,$);try{return await this.loadSessionFromFile(B,$,q)}catch(L){if(L.code==="ENOENT")throw Error(`未找到会话: ${$}`);throw L}}let T=(await this.scanStoredSessions(void 0,!0,0,null)).find((q)=>q.sessionId===$);if(!T)throw Error(`未找到会话: ${$}`);return await this.loadSessionFromFile(T.filePath,$)}catch(T){throw N0.error(`[SessionService] 加载会话失败 (${$}):`,T),T}}static async loadSessionModelContext($,f){try{if(f){if(!V.isAbsolute(f))throw Error("Session catalog cwd must be absolute");let q=V.resolve(f),B=this.getSessionFilePath(q,$);try{return await this.loadSessionModelContextFromFile(B,$,q)}catch(L){if(L.code==="ENOENT")throw Error(`未找到会话: ${$}`);throw L}}let T=(await this.scanStoredSessions(void 0,!0,0,null)).find((q)=>q.sessionId===$);if(!T)throw Error(`未找到会话: ${$}`);return await this.loadSessionModelContextFromFile(T.filePath,$)}catch(T){throw N0.error(`[SessionService] 加载模型上下文失败 (${$}):`,T),T}}static async exportSessionMarkdown($,f,T={}){A($);let q=this.resolveCatalogWorkspace(f),B=m(q,$),L;try{L=await this.readStableSessionSnapshot(B,$)}catch(_){throw this.sanitizeStoredSessionError(_,$)}let O=this.projectMetadataFromEntries(L,$,q,B);if(O.projectPath!==q)throw Error(`Session export workspace mismatch: ${$}`);let C=O.archivedAt;if(!C&&O.parentId)C=(await this.findArchivedAncestor(O.parentId,q))?.archivedAt;return a$(L,{...O,archivedAt:C},T)}static async listRewindCheckpoints($,f){A($);let T=this.resolveCatalogWorkspace(f),q=m(T,$),B=await this.readStableSessionSnapshot(q,$);this.validateSessionWorkspace(B,$,T);let L=new D0({sessionId:$,workspaceRoot:T});await L.initialize();let O=Hf(B),C=[];for(let _ of O){let N=C$(B,_.messageId),G=await L.previewRewind(N.snapshotMessageIds);C.push({..._,fileCount:G.files.length})}return C}static async rewindSession($,f,T){A($);let q=this.resolveCatalogWorkspace(f);await this.assertSessionWritable($,q);let B=m(q,$),L=new I(B),O;try{await L.appendValidatedAsync(async(C)=>{this.validateSessionWorkspace(C,$,q);let _=C$(C,T.targetMessageId),N=new D0({sessionId:$,workspaceRoot:q});await N.initialize();let G=await N.previewRewind(_.snapshotMessageIds),x=T.mode==="conversation"?await N.commitSnapshots(_.snapshotMessageIds):await N.rewindSnapshots(_.snapshotMessageIds),J=new Date().toISOString(),Z={id:j(),sessionId:$,timestamp:J,type:"session_rewound",cwd:q,gitBranch:c(q),version:p(),data:{rewindId:j(),targetMessageId:T.targetMessageId,mode:T.mode,restoredFiles:T.mode==="conversation"?[]:x.files,createdAt:J}},E=u([...C,Z]);return O={checkpoint:{..._.checkpoint,fileCount:G.files.length},mode:T.mode,removedTurns:_.removedTurns,restoredFiles:Z.data.restoredFiles,messages:this.convertJSONLToMessages(E)},Z})}catch(C){throw this.sanitizeStoredSessionError(C,$)}if(!O)throw Error(`Session rewind did not produce a result: ${$}`);for(let C of O.restoredFiles)l.getInstance().clearFileRecord(C);return O}static async forkSession($,f){A($);let T=f.newSessionId??`fork-${Date.now()}-${j(8)}`;A(T);let q=this.resolveForkWorkspace(f.sourceProjectPath),B=this.resolveForkWorkspace(f.targetProjectPath);if(q!==B)throw Error("Session forks must stay in the source workspace");let L=m(q,$),O=await this.readStableSessionSnapshot(L,$),C=this.getSessionCreatedEntry(O,$);if(C.data.sessionId!==$)throw Error("Fork source session_created.data.sessionId must match the requested session ID");if(!V.isAbsolute(C.cwd)||V.resolve(C.cwd)!==q)throw Error("Fork source session_created.cwd must resolve to the requested source workspace");let _=this.projectMetadataFromEntries(O,$,q,L);if(_.archivedAt)throw new f0($,$);if(_.parentId){let Y=await this.findArchivedAncestor(_.parentId,q);if(Y)throw new f0($,Y.sessionId)}let N=u(O),G=new Date().toISOString(),x=C.data.rootId||$,J=c(B),Z=p(),{status:E,taskStatus:M,taskStatusReason:b,taskFailure:W,taskStartedAt:s,taskCompletedAt:e,taskOwnerPid:y,taskPromptSummary:S,taskDispatch:R,taskModelId:D,taskRetriedFrom:z,taskDelivery:K,taskIsolation:g,taskSourceProjectPath:w0,taskWorktree:F$,taskDiffStat:K$,taskQueuePosition:Q$,taskQueueDepth:X$,taskConcurrencyLimit:H$,pendingInteraction:k0,...y0}=C.data,S0={id:j(),sessionId:T,timestamp:G,type:"session_created",cwd:B,gitBranch:J,version:Z,data:{...y0,sessionId:T,rootId:x,parentId:$,relationType:"fork",taskStatus:"completed",taskCompletedAt:G,taskIsolation:"local",taskSourceProjectPath:B,createdAt:G,updatedAt:G}},j0=N.filter((Y)=>Y.type!=="session_created"&&Y.type!=="inbox_acknowledged"&&Y.type!=="interaction_requested"&&Y.type!=="interaction_responded"&&Y.type!=="interaction_recovered"&&Y.type!=="review_started"&&Y.type!=="review_completed").map((Y)=>{let i={...Y,id:j(),sessionId:T,cwd:B,gitBranch:J,version:Z};if(Y.type==="session_updated"){let{status:K0,taskStatus:U,taskStatusReason:v0,taskFailure:E1,taskStartedAt:b1,taskCompletedAt:w1,taskOwnerPid:k1,taskPromptSummary:y1,taskDispatch:S1,taskModelId:j1,taskRetriedFrom:m1,taskDelivery:I1,taskIsolation:v1,taskSourceProjectPath:u1,taskWorktree:P1,taskDiffStat:h1,taskQueuePosition:n1,taskQueueDepth:l1,taskConcurrencyLimit:c1,pendingInteraction:p1,...zf}=Y.data;return{...i,type:"session_updated",data:{...zf,sessionId:T,rootId:x,parentId:$,relationType:"fork"}}}if(Y.type==="message_created"){let{inboxMessageId:K0,...U}=Y.data;return{...i,type:"message_created",data:U}}return i}),m0={id:j(),sessionId:T,timestamp:G,type:"session_updated",cwd:B,gitBranch:J,version:Z,data:{sessionId:T,rootId:x,parentId:$,relationType:"fork",taskStatus:"completed",taskStatusReason:null,taskFailure:null,taskStartedAt:null,taskCompletedAt:G,taskOwnerPid:null,taskIsolation:"local",taskSourceProjectPath:B,taskWorktree:null,taskDiffStat:null,taskDelivery:null,taskQueuePosition:null,taskQueueDepth:null,taskConcurrencyLimit:null,updatedAt:G}},T0=[S0,...j0,m0],F0=m(B,T);try{await new I(F0).createExclusive(T0)}catch(Y){if(Y.code==="EEXIST")throw Error(`Fork session already exists: ${T}`,{cause:Y});throw Y}let I0=this.projectMetadataFromEntries(T0,T,B,F0);return{sessionId:T,parentSessionId:$,projectPath:B,messages:this.convertJSONLToMessages(T0),metadata:this.toPublicMetadata(I0)}}static async deleteSession($,f){if(A($),f){if(!V.isAbsolute(f))throw Error("Session catalog cwd must be absolute");let q=V.resolve(f),B=this.getSessionFilePath(q,$),L=new I(B),O;try{O=await L.deleteValidated((C)=>{return this.projectMetadataFromEntries(C,$,q,B).projectPath===q})}catch(C){if(!this.isCorruptSessionJSONLError(C))throw C;O=await L.delete()}if(!O)return 0;return await $0(V.join(V.dirname(B),`${$}.inbox.json`),{force:!0}),await $0(G0(q,$),{force:!0}),await this.removeFromProjection($,q),1}let T=(await this.scanStoredSessions(void 0,!0)).filter((q)=>q.sessionId===$);if(T.length===0)return 0;return await Promise.all(T.map(async(q)=>{await new I(q.filePath).delete(),await $0(V.join(V.dirname(q.filePath),`${q.sessionId}.inbox.json`),{force:!0}),await $0(G0(q.projectPath,q.sessionId),{force:!0}),await this.removeFromProjection(q.sessionId,q.projectPath)})),T.length}static async removeFromProjection($,f){try{let T=await g0();if(T)Uf(T,$,f)}catch{}}static validateTaskMetadataUpdate($,f){if($.taskPromptSummary!==void 0&&$.taskPromptSummary!==null&&(!$.taskPromptSummary.trim()||$.taskPromptSummary.length>1000))throw Error("Session task prompt summary must contain 1-1000 characters");if($.taskFailure!==void 0&&$.taskFailure!==null&&!p0($.taskFailure))throw Error("Invalid session task failure");if($.taskDispatch!==void 0&&$.taskDispatch!==null&&!Jf($.taskDispatch))throw Error("Invalid durable task dispatch");if($.taskModelId!==void 0&&$.taskModelId!==null&&(!$.taskModelId.trim()||$.taskModelId.length>500))throw Error("Invalid session task model ID");if($.selectedModelId!==void 0&&$.selectedModelId!==null&&(!$.selectedModelId.trim()||$.selectedModelId.length>500))throw Error("Invalid selected session model ID");if($.permissionMode!==void 0&&$.permissionMode!==null&&!b0($.permissionMode))throw Error("Invalid session permission mode");if($.reasoningEffort!==void 0&&$.reasoningEffort!==null&&!V0($.reasoningEffort))throw Error("Invalid session reasoning effort");if($.serviceTier!==void 0&&$.serviceTier!==null&&!J0($.serviceTier))throw Error("Invalid session service tier");if($.responseVerbosity!==void 0&&$.responseVerbosity!==null&&!x0($.responseVerbosity))throw Error("Invalid session response verbosity");if($.communicationStyle!==void 0&&$.communicationStyle!==null&&!Z0($.communicationStyle))throw Error("Invalid session communication style");if($.communicationStyleDigest!==void 0&&$.communicationStyleDigest!==null&&!/^[a-f0-9]{64}$/.test($.communicationStyleDigest))throw Error("Invalid session communication style digest");if($.projectInstructionsDigest!==void 0&&$.projectInstructionsDigest!==null&&!/^[a-f0-9]{64}$/.test($.projectInstructionsDigest))throw Error("Invalid session project instructions digest");if($.taskRetriedFrom!==void 0&&$.taskRetriedFrom!==null&&!Vf($.taskRetriedFrom))throw Error("Invalid session task retry source");if($.taskDelivery!==void 0&&$.taskDelivery!==null&&!_f($.taskDelivery))throw Error("Invalid session task delivery");if($.taskIsolation!==void 0&&$.taskIsolation!==null&&!V$.has($.taskIsolation))throw Error(`Invalid session task isolation: ${String($.taskIsolation)}`);if($.taskSourceProjectPath!==void 0&&$.taskSourceProjectPath!==null&&!V.isAbsolute($.taskSourceProjectPath))throw Error("Session task source project path must be absolute");if($.taskWorktree!==void 0&&$.taskWorktree!==null){let T=Gf($.taskWorktree);if(!T||T.sessionId!==f||![T.repositoryRoot,T.originalWorkspaceRoot,T.worktreeRoot,T.workspaceRoot].every((q)=>V.isAbsolute(q)))throw Error("Invalid session task worktree metadata")}if($.taskDiffStat!==void 0&&$.taskDiffStat!==null&&!xf($.taskDiffStat))throw Error("Invalid session task diff stat");if($.taskQueuePosition!==void 0&&$.taskQueuePosition!==null&&(!Number.isInteger($.taskQueuePosition)||$.taskQueuePosition<1))throw Error("Invalid session task queue position");if($.taskQueueDepth!==void 0&&$.taskQueueDepth!==null&&(!Number.isInteger($.taskQueueDepth)||$.taskQueueDepth<0))throw Error("Invalid session task queue depth");if($.taskConcurrencyLimit!==void 0&&$.taskConcurrencyLimit!==null&&(!Number.isInteger($.taskConcurrencyLimit)||$.taskConcurrencyLimit<1))throw Error("Invalid session task concurrency limit");if(typeof $.taskQueuePosition==="number"&&typeof $.taskQueueDepth==="number"&&$.taskQueuePosition>$.taskQueueDepth)throw Error("Session task queue position exceeds queue depth")}static async createSessionMetadata($,f,T={}){A($),X.validateTaskMetadataUpdate(T,$);let q=X.resolveCatalogWorkspace(f);if(T.taskWorktree&&V.resolve(T.taskWorktree.workspaceRoot)!==q)throw Error("Session task worktree must match the catalog workspace");let B=new Date().toISOString(),L={id:j(),sessionId:$,timestamp:B,type:"session_created",cwd:q,gitBranch:c(q),version:p(),data:{sessionId:$,rootId:$,...T.title!==void 0?{title:T.title}:{},taskStatus:T.taskStatus??"queued",...T.taskPromptSummary!==void 0?{taskPromptSummary:T.taskPromptSummary}:{},...T.taskDispatch!==void 0?{taskDispatch:T.taskDispatch}:{},...T.taskModelId!==void 0?{taskModelId:T.taskModelId}:{},...T.taskRetriedFrom!==void 0?{taskRetriedFrom:T.taskRetriedFrom}:{},...T.taskIsolation!==void 0?{taskIsolation:T.taskIsolation}:{},...T.taskSourceProjectPath!==void 0?{taskSourceProjectPath:T.taskSourceProjectPath}:{},...T.taskWorktree!==void 0?{taskWorktree:T.taskWorktree}:{},...T.selectedModelId!==void 0?{selectedModelId:T.selectedModelId}:{},...T.permissionMode!==void 0?{permissionMode:T.permissionMode}:{},...T.reasoningEffort!==void 0?{reasoningEffort:T.reasoningEffort}:{},...T.serviceTier!==void 0?{serviceTier:T.serviceTier}:{},...T.responseVerbosity!==void 0?{responseVerbosity:T.responseVerbosity}:{},...T.communicationStyle!==void 0?{communicationStyle:T.communicationStyle}:{},...T.communicationStyleDigest!==void 0?{communicationStyleDigest:T.communicationStyleDigest}:{},...T.projectInstructionsDigest!==void 0?{projectInstructionsDigest:T.projectInstructionsDigest}:{},createdAt:B,updatedAt:B}},O=X.getSessionFilePath(q,$);return await new I(O).createExclusive([L]),X.toPublicMetadata(X.projectMetadataFromEntries([L],$,q,O))}static async assertSessionWritable($,f){let T=await this.findSessionMetadata($,f);if(!T)throw Error(`Session not found: ${$}`);if(T.archivedAt)throw new f0($,T.archivedBySessionId??$);return T}static async findArchivedAncestor($,f){let T=new Set,q=$;while(q){if(T.has(q))throw Error("Session lineage contains a cycle");T.add(q),A(q);let B=m(f,q),L;try{L=await a(B,"utf8")}catch(C){if(C.code==="ENOENT")return;throw C}let O=this.projectMetadataFromEntries(this.parseStoredSession(L,q),q,f,B);if(O.projectPath!==f)throw Error("Session lineage escapes the requested workspace");if(O.archivedAt)return{sessionId:O.sessionId,archivedAt:O.archivedAt};q=O.parentId}return}static async listSessionArchiveMembers($,f){A($);let T=this.resolveCatalogWorkspace(f),q=await this.scanStoredSessions(T,!0,0,null);if(!q.some((O)=>O.sessionId===$))throw Error(`Session not found: ${$}`);let B=new Set([$]),L=!0;while(L){L=!1;for(let O of q)if(O.parentId&&B.has(O.parentId)&&!B.has(O.sessionId))B.add(O.sessionId),L=!0}return q.filter((O)=>B.has(O.sessionId)).sort((O,C)=>O.sessionId.localeCompare(C.sessionId)).map((O)=>this.toPublicMetadata(O))}static async archiveSession($,f){A($);let T=this.resolveCatalogWorkspace(f),q=await this.findSessionMetadata($,T);if(!q)throw Error(`Session not found: ${$}`);if(q.archivedAt)return q;let B=await this.listSessionArchiveMembers($,T),L=B.find((C)=>C.taskStatus==="queued"||C.taskStatus==="running");if(L)throw new P(`Stop session ${L.sessionId} before archiving this session tree`);let O=[];try{for(let G of B)O.push(await n.acquire(G.sessionId,T));let C=m(T,$),_=new I(C),N=[];return await _.appendValidated((G)=>{let x=this.projectMetadataFromEntries(G,$,T,C);if(x.archivedAt)throw new P(`Session archive state changed concurrently: ${$}`);if(x.taskStatus==="queued"||x.taskStatus==="running")throw new P(`Stop session ${$} before archiving it`);let J=new Date().toISOString(),Z={id:j(),sessionId:$,timestamp:J,type:"session_updated",cwd:T,gitBranch:c(T),version:p(),data:{sessionId:$,archivedAt:J,updatedAt:J}};return N=[...G,Z],Z}),this.toPublicMetadata({...this.projectMetadataFromEntries(N,$,T,C),archivedBySessionId:$})}catch(C){if(C instanceof P)throw C;if(C instanceof h)throw new P(C.message);throw this.sanitizeStoredSessionError(C,$)}finally{for(let C of O.reverse())await C.release()}}static async unarchiveSession($,f){A($);let T=this.resolveCatalogWorkspace(f),q=await this.findSessionMetadata($,T);if(!q)throw Error(`Session not found: ${$}`);if(!q.archivedAt)return q;if(q.archivedBySessionId&&q.archivedBySessionId!==$)throw new P(`Unarchive ancestor ${q.archivedBySessionId} to restore session ${$}`);let B;try{B=await n.acquire($,T);let L=m(T,$),O=new I(L),C=[];return await O.appendValidated((_)=>{if(!this.projectMetadataFromEntries(_,$,T,L).archivedAt)throw new P(`Session archive state changed concurrently: ${$}`);let G=new Date().toISOString(),x={id:j(),sessionId:$,timestamp:G,type:"session_updated",cwd:T,gitBranch:c(T),version:p(),data:{sessionId:$,archivedAt:null,updatedAt:G}};return C=[..._,x],x}),this.toPublicMetadata(this.projectMetadataFromEntries(C,$,T,L))}catch(L){if(L instanceof P)throw L;if(L instanceof h)throw new P(L.message);throw this.sanitizeStoredSessionError(L,$)}finally{await B?.release()}}static async updateSessionMetadata($,f,T){if(A($),X.validateTaskMetadataUpdate(T,$),T.taskStatus!==void 0&&!Cf.has(T.taskStatus))throw Error(`Invalid session task status: ${String(T.taskStatus)}`);if(T.taskOwnerPid!==void 0&&T.taskOwnerPid!==null&&(!Number.isInteger(T.taskOwnerPid)||T.taskOwnerPid<=0))throw Error("Session task owner PID must be a positive integer");let q=X.resolveCatalogWorkspace(f);if(T.taskWorktree&&V.resolve(T.taskWorktree.workspaceRoot)!==q)throw Error("Session task worktree must match the catalog workspace");let B=X.getSessionFilePath(q,$),L=new I(B),O=[];try{await L.appendValidatedAsync(async(C)=>{let _=X.getSessionCreatedEntry(C,$);if(_.data.sessionId!==$)throw Error(`Session metadata creation record sessionId mismatch: ${$}`);if(!V.isAbsolute(_.cwd)||V.resolve(_.cwd)!==q)throw Error(`Session metadata creation record cwd mismatch: ${$}`);let N=X.projectMetadataFromEntries(C,$,q,B);if(N.archivedAt)throw new f0($,$);if(N.parentId){let J=await X.findArchivedAncestor(N.parentId,q);if(J)throw new f0($,J.sessionId)}let G=new Date().toISOString(),x={id:j(),sessionId:$,timestamp:G,type:"session_updated",cwd:q,gitBranch:c(q),version:p(),data:{sessionId:$,...T.title!==void 0?{title:T.title}:{},...T.taskStatus!==void 0?{taskStatus:T.taskStatus}:{},...T.taskStatusReason!==void 0?{taskStatusReason:T.taskStatusReason}:{},...T.taskFailure!==void 0?{taskFailure:T.taskFailure}:{},...T.taskStartedAt!==void 0?{taskStartedAt:T.taskStartedAt}:{},...T.taskCompletedAt!==void 0?{taskCompletedAt:T.taskCompletedAt}:{},...T.taskOwnerPid!==void 0?{taskOwnerPid:T.taskOwnerPid}:{},...T.taskPromptSummary!==void 0?{taskPromptSummary:T.taskPromptSummary}:{},...T.taskDispatch!==void 0?{taskDispatch:T.taskDispatch}:{},...T.taskModelId!==void 0?{taskModelId:T.taskModelId}:{},...T.taskRetriedFrom!==void 0?{taskRetriedFrom:T.taskRetriedFrom}:{},...T.taskDelivery!==void 0?{taskDelivery:T.taskDelivery}:{},...T.taskIsolation!==void 0?{taskIsolation:T.taskIsolation}:{},...T.taskSourceProjectPath!==void 0?{taskSourceProjectPath:T.taskSourceProjectPath}:{},...T.taskWorktree!==void 0?{taskWorktree:T.taskWorktree}:{},...T.taskDiffStat!==void 0?{taskDiffStat:T.taskDiffStat}:{},...T.taskQueuePosition!==void 0?{taskQueuePosition:T.taskQueuePosition}:{},...T.taskQueueDepth!==void 0?{taskQueueDepth:T.taskQueueDepth}:{},...T.taskConcurrencyLimit!==void 0?{taskConcurrencyLimit:T.taskConcurrencyLimit}:{},...T.selectedModelId!==void 0?{selectedModelId:T.selectedModelId}:{},...T.permissionMode!==void 0?{permissionMode:T.permissionMode}:{},...T.reasoningEffort!==void 0?{reasoningEffort:T.reasoningEffort}:{},...T.serviceTier!==void 0?{serviceTier:T.serviceTier}:{},...T.responseVerbosity!==void 0?{responseVerbosity:T.responseVerbosity}:{},...T.communicationStyle!==void 0?{communicationStyle:T.communicationStyle}:{},...T.communicationStyleDigest!==void 0?{communicationStyleDigest:T.communicationStyleDigest}:{},...T.projectInstructionsDigest!==void 0?{projectInstructionsDigest:T.projectInstructionsDigest}:{},updatedAt:G}};return O=[...C,x],x})}catch(C){throw X.sanitizeStoredSessionError(C,$)}return X.toPublicMetadata(X.projectMetadataFromEntries(O,$,q,B))}static async setSessionPermissionMode($,f,T){if(A($),!b0(T))throw Error("Invalid session permission mode");let q=X.resolveCatalogWorkspace(f),B=await X.findSessionMetadata($,q);if(B?.permissionMode===T)return B;if(B)return X.updateSessionMetadata($,q,{permissionMode:T});try{return await X.createSessionMetadata($,q,{taskStatus:"completed",permissionMode:T})}catch(L){if(L.code!=="EEXIST")throw L;return X.updateSessionMetadata($,q,{permissionMode:T})}}static async findSessionTaskWorktree($,f){A($);let T=X.resolveCatalogWorkspace(f),q=X.getSessionFilePath(T,$);try{return(await X.readStoredSessionMetadata(q,$,T)).taskWorktree}catch(B){if(B.code==="ENOENT")return;throw X.sanitizeStoredSessionError(B,$)}}static async findSessionTaskDispatch($,f){A($);let T=X.resolveCatalogWorkspace(f),q=X.getSessionFilePath(T,$);try{return(await X.readStoredSessionMetadata(q,$,T)).taskDispatch}catch(B){if(B.code==="ENOENT")return;throw X.sanitizeStoredSessionError(B,$)}}static async loadSessionFromFile($,f,T){let q=await a($,"utf-8"),B=this.parseStoredSession(q,f);if(T!==void 0){if(this.projectMetadataFromEntries(B,f,T,$).projectPath!==T)throw Error(`未找到会话: ${f}`)}return this.convertJSONLToMessages(B)}static async loadSessionModelContextFromFile($,f,T){let q=await a($,"utf-8"),B=this.parseStoredSession(q,f);if(T!==void 0){if(this.projectMetadataFromEntries(B,f,T,$).projectPath!==T)throw Error(`未找到会话: ${f}`)}return this.convertJSONLToModelContext(B)}static convertJSONLToModelContext($){let f=u($),T=-1,q;for(let L=0;L<f.length;L++){let O=f[L];if(O?.type!=="part_created"||O.data.partType!=="summary")continue;let C=O.data.payload;if(T=L,q=g$(C.replacementMessages),!q)q=[{role:"user",content:C.text??"",metadata:O.data.payload}]}if(T<0||!q)return this.convertJSONLToMessages(f);let B=this.convertJSONLToMessages(f.slice(T+1));return[...q,...B]}static convertJSONLToMessages($){let f=[],T=new Map,q=new Map,B=new Map,L=new Map,O=new Map,C=u($),_=new Set;for(let N of C){if(N.type==="message_created"){let G=N.data.metadata&&typeof N.data.metadata==="object"&&!Array.isArray(N.data.metadata)?N.data.metadata:void 0,x=G?.codeReview&&typeof G.codeReview==="object"&&!Array.isArray(G.codeReview)?G.codeReview:void 0;if(x?.phase==="completed"&&typeof x.reviewId==="string")_.add(x.reviewId);let J=N.data.role==="assistant"&&N.data.parentMessageId?B.get(N.data.parentMessageId):void 0,Z=J??{role:N.data.role,content:"",...N.data.metadata||N.data.inboxMessageId?{metadata:{...N.data.metadata&&typeof N.data.metadata==="object"&&!Array.isArray(N.data.metadata)?N.data.metadata:{},...N.data.inboxMessageId?{inboxMessageId:N.data.inboxMessageId}:{}}}:{}};if(T.set(N.data.messageId,Z),q.set(N.data.messageId,[]),!J)f.push(Z)}if(N.type==="part_created"){if(N.data.partType==="reasoning"){let G=T.get(N.data.messageId);if(G){let x=N.data.payload;G.reasoningContent=(G.reasoningContent??"")+(x.text??"")}}if(N.data.partType==="text"){let G=T.get(N.data.messageId);if(G){let x=N.data.payload,J=q.get(N.data.messageId);if(J)J.push({type:"text",text:x.text??""}),G.content=Zf(J);else G.content=x.text??""}}if(N.data.partType==="image"){let G=T.get(N.data.messageId);if(G){let x=N.data.payload,J=q.get(N.data.messageId);if(J&&x.dataUrl)J.push({type:"image_url",image_url:{url:x.dataUrl}}),G.content=Zf(J)}}if(N.data.partType==="tool_call"){let G=T.get(N.data.messageId);if(G?.role!=="assistant"){if(G=B.get(N.data.messageId),!G)G={role:"assistant",content:"",tool_calls:[]},B.set(N.data.messageId,G),f.push(G)}if(G.role==="assistant"){let x=N.data.payload,J=x.toolCallId??N.data.partId;L.set(N.data.partId,J),O.set(J,G),G.tool_calls??=[],G.tool_calls.push({id:J,type:"function",function:{name:x.toolName??"unknown",arguments:JSON.stringify(x.input??{})}})}}if(N.data.partType==="tool_result"){let G=N.data.payload,x=v$(G),J=x.error?`Error: ${x.error.message}`:typeof x.llmContent==="string"?x.llmContent:JSON.stringify(x.llmContent),Z=G;f.push({role:"tool",content:J,tool_call_id:L.get(N.data.messageId)??G.toolCallId,name:G.toolName,metadata:Z})}if(N.data.partType==="summary"){let G=N.data.payload,x=N.data.payload;f.push({role:"system",content:G.text??"",metadata:x})}if(N.data.partType==="subtask_ref"){let G=T.get(N.data.messageId)??O.get(N.data.messageId);if(G){let x=N.data.payload,J=G.metadata??{};G.metadata={...J,subtaskRef:x}}}}}for(let N of Y0(C)){if(N.completion===void 0||_.has(N.start.reviewId))continue;f.push({role:"assistant",content:k$(N.start,N.completion),metadata:{codeReview:{...y$(N.start,N.completion),synthetic:!0}}})}return f}static projectionDeriver(){return($,f,T)=>{try{let q=m(T,f);return this.projectMetadataFromEntries($,f,T,q)}catch{return null}}}static projectionDeriverForSearch(){return this.projectionDeriver()}static async scanStoredSessionsFromProjection($,f,T=0,q=!1){try{let B=await g0();if(!B)return null;await J$(B,this.projectionDeriver(),T);let L=$?B.prepare("SELECT metadata_json, is_subagent FROM sessions WHERE project_path=?").all($):B.prepare("SELECT metadata_json, is_subagent FROM sessions").all(),O=[];for(let C of L){if(!f&&C.is_subagent===1)continue;try{let _=JSON.parse(C.metadata_json);if($!==void 0&&_.projectPath!==$)continue;O.push(_)}catch{}}return O$(await Promise.all(O.map((C)=>this.reconcileInterruptedTask(C))),q)}catch{return null}}static async scanStoredSessions($,f=!1,T=0,q=!1){let B=$?V.resolve($):void 0,L=await this.scanStoredSessionsFromProjection(B,f,T,q);if(L)return L;let O=B?[{storagePath:q0(B),projectPath:B}]:await this.listAllProjectStorageDirectories(),C=[];for(let _ of O){let N;try{N=await L$(_.storagePath)}catch(G){if(G.code==="ENOENT")continue;throw G}for(let G of N){if(!G.endsWith(".jsonl"))continue;let x=G.slice(0,-6),J=V.join(_.storagePath,G);try{let Z=await this.readStoredSessionMetadata(J,x,_.projectPath);if(B!==void 0&&Z.projectPath!==B){N0.warn(`[SessionService] Skipping out-of-scope session transcript: ${x}`);continue}if(!f&&Z.relationType==="subagent")continue;C.push(Z)}catch(Z){let E=Z.code;if(E==="ENOENT")continue;if(E)throw Z;N0.warn(`[SessionService] Skipping invalid session transcript: ${x}`)}}}return O$(C,q)}static async listAllProjectStorageDirectories(){let $=V.join(C0(),"projects"),f;try{f=await L$($,{withFileTypes:!0,encoding:"utf8"})}catch(T){if(T.code==="ENOENT")return[];throw T}return f.filter((T)=>T.isDirectory()).map((T)=>({storagePath:V.join($,T.name),projectPath:Ff(T.name)}))}static async readStoredSessionMetadata($,f,T){let q=await a($,"utf-8"),B=this.parseStoredSession(q,f);return this.reconcileInterruptedTask(this.projectMetadataFromEntries(B,f,T,$))}static async reconcileInterruptedTask($){let f=$.taskOwnerPid;if($.taskStatus!=="running"||f===void 0||Nf(f))return $;let T;try{T=await n.acquire($.sessionId,$.projectPath)}catch(L){if(!(L instanceof h))throw L;let O=await a($.filePath,"utf-8");return this.projectMetadataFromEntries(this.parseStoredSession(O,$.sessionId),$.sessionId,$.projectPath,$.filePath)}let q=new I($.filePath),B;try{try{await q.appendValidated((L)=>{let O=this.projectMetadataFromEntries(L,$.sessionId,$.projectPath,$.filePath);if(O.taskStatus!=="running"||O.taskOwnerPid!==f||Nf(f))throw new Z$;let C=new Date().toISOString(),_={id:j(),sessionId:$.sessionId,timestamp:C,type:"session_updated",cwd:$.projectPath,gitBranch:c($.projectPath),version:p(),data:{sessionId:$.sessionId,taskStatus:"interrupted",taskStatusReason:"Task owner process exited before completion",taskCompletedAt:C,taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null,updatedAt:C}};return B=[...L,_],_})}catch(L){if(!(L instanceof Z$))throw L}if(!B){let L=await a($.filePath,"utf-8");B=this.parseStoredSession(L,$.sessionId)}return this.projectMetadataFromEntries(B,$.sessionId,$.projectPath,$.filePath)}finally{await T.release()}}static projectMetadataFromEntries($,f,T,q){if($.length===0)throw Error(`Empty session transcript: ${f}`);let B=this.getSessionCreatedEntry($,f),L=$.reduce((U,v0)=>v0.type==="session_updated"?{...U,...v0.data}:U,{...B.data}),O=u($),C=w$(b$(O)),N=Y0(O).at(-1),G=O.findLastIndex((U)=>U.type==="review_started"&&U.data.reviewId===N?.start.reviewId||U.type==="review_completed"&&U.data.reviewId===N?.start.reviewId),x=O.findLastIndex((U)=>(U.type==="session_created"||U.type==="session_updated")&&Object.hasOwn(U.data,"taskStatus")),J=N!==void 0&&G>x,Z=J?N.completion===void 0?"running":N.completion.status==="completed"||N.completion.status==="stale"?"completed":N.completion.status==="aborted"?"cancelled":N.completion.status==="interrupted"?"interrupted":"failed":void 0,E=O.filter((U)=>U.type==="message_created"&&["user","assistant"].includes(U.data.role)).length,M=O.some((U)=>U.type==="part_created"&&U.data.partType==="tool_result"&&typeof U.data.payload.error==="string"),b=Cf.has(L.taskStatus)?L.taskStatus:void 0,W=Z??b??(M?"failed":"completed"),s=typeof L.taskOwnerPid==="number"&&Number.isInteger(L.taskOwnerPid)&&L.taskOwnerPid>0?L.taskOwnerPid:void 0,e=V$.has(L.taskIsolation)?L.taskIsolation:void 0,y=typeof L.taskSourceProjectPath==="string"&&V.isAbsolute(L.taskSourceProjectPath)?V.resolve(L.taskSourceProjectPath):void 0,S=B.cwd;if(S!==void 0&&!V.isAbsolute(S))throw Error(`Session catalog cwd must be absolute: ${f}`);let R=S===void 0?T:V.resolve(S),D=Gf(L.taskWorktree),z=D?.sessionId===f&&V.resolve(D.workspaceRoot)===R?D:void 0,K=xf(L.taskDiffStat),g=Jf(L.taskDispatch),w0=typeof L.taskModelId==="string"&&L.taskModelId.trim()?L.taskModelId:g?.modelId,F$=typeof L.selectedModelId==="string"&&L.selectedModelId.trim()?L.selectedModelId:w0,K$=b0(L.permissionMode)?L.permissionMode:g?.permissionMode,Q$=V0(L.reasoningEffort)?L.reasoningEffort:g?.reasoningEffort,X$=J0(L.serviceTier)?L.serviceTier:g?.serviceTier,H$=x0(L.responseVerbosity)?L.responseVerbosity:g?.responseVerbosity,k0=Z0(L.communicationStyle)?L.communicationStyle:g?.communicationStyle,y0=Object.hasOwn(L,"communicationStyleDigest")?typeof L.communicationStyleDigest==="string"&&/^[a-f0-9]{64}$/.test(L.communicationStyleDigest)?L.communicationStyleDigest:void 0:k0===g?.communicationStyle?g?.communicationStyleDigest:void 0,S0=Object.hasOwn(L,"projectInstructionsDigest")?typeof L.projectInstructionsDigest==="string"&&/^[a-f0-9]{64}$/.test(L.projectInstructionsDigest)?L.projectInstructionsDigest:void 0:g?.projectInstructionsDigest,j0=Af(L.archivedAt)?L.archivedAt:void 0,m0=Vf(L.taskRetriedFrom),T0=_f(L.taskDelivery),F0=typeof L.taskQueuePosition==="number"&&Number.isInteger(L.taskQueuePosition)&&L.taskQueuePosition>0?L.taskQueuePosition:void 0,I0=typeof L.taskQueueDepth==="number"&&Number.isInteger(L.taskQueueDepth)&&L.taskQueueDepth>=0?L.taskQueueDepth:void 0,Y=typeof L.taskConcurrencyLimit==="number"&&Number.isInteger(L.taskConcurrencyLimit)&&L.taskConcurrencyLimit>0?L.taskConcurrencyLimit:void 0,i=J?N?.completion?N.completion.status==="completed"?void 0:`Code review ${n0(N.completion.status)}`:`Reviewing ${N?.start.target.label??"changes"}`:void 0,K0=J?W==="failed"&&i?c0(i):void 0:p0(L.taskFailure)?L.taskFailure:W==="failed"&&typeof L.taskStatusReason==="string"?c0(L.taskStatusReason):void 0;return{sessionId:f,projectPath:R,gitBranch:B.gitBranch,rootId:L.rootId||f,parentId:L.parentId,relationType:L.relationType,resumedFrom:L.resumedFrom,rootAgentId:L.rootAgentId,resumeDepth:L.resumeDepth,title:L.title,agentType:L.agentType,model:L.model,selectedModelId:F$,permissionMode:K$,reasoningEffort:Q$,serviceTier:X$,responseVerbosity:H$,communicationStyle:k0,communicationStyleDigest:y0,projectInstructionsDigest:S0,pendingInteraction:C,taskStatus:W,taskStatusReason:K0?.message??i??(typeof L.taskStatusReason==="string"?L.taskStatusReason:void 0),taskFailure:K0,taskStartedAt:J?N?.start.startedAt:typeof L.taskStartedAt==="string"?L.taskStartedAt:void 0,taskCompletedAt:J?N?.completion?.completedAt:typeof L.taskCompletedAt==="string"?L.taskCompletedAt:void 0,taskPromptSummary:J?N?M1(N.start.target):"/review uncommitted":typeof L.taskPromptSummary==="string"?L.taskPromptSummary:void 0,taskModelId:w0,taskRetryAvailable:g!==void 0,taskRetriedFrom:m0,taskDelivery:T0,taskIsolation:e,taskSourceProjectPath:y,taskWorktreePath:z?.worktreeRoot,taskWorktreeBranch:z?.branch,taskBaseCommit:z?.baseCommit,taskDiffStat:K,taskQueuePosition:F0,taskQueueDepth:I0,taskConcurrencyLimit:Y,archivedAt:j0,taskOwnerPid:J?void 0:s,taskWorktree:z,taskDispatch:g,messageCount:E,firstMessageTime:$[0].timestamp,lastMessageTime:$.at(-1).timestamp,hasErrors:M||W==="failed",filePath:q}}static toPublicMetadata($){let{filePath:f,taskOwnerPid:T,taskWorktree:q,taskDispatch:B,...L}=$;return L}static getSessionFilePath($,f){return m($,f)}static getSessionCreatedEntry($,f){let T=$.find((q)=>q.type==="session_created");if(!T)throw new Rf(f);return T}static resolveCatalogWorkspace($){if(!V.isAbsolute($))throw Error("Session catalog cwd must be absolute");return V.resolve($)}static validateSessionWorkspace($,f,T){let q=this.getSessionCreatedEntry($,f);if(q.data.sessionId!==f)throw Error(`Session creation record sessionId mismatch: ${f}`);if(!V.isAbsolute(q.cwd)||V.resolve(q.cwd)!==T)throw Error(`Session creation record cwd mismatch: ${f}`)}static resolveForkWorkspace($){if(!V.isAbsolute($))throw Error("Fork workspace paths must be absolute");return V.resolve($)}static parseStoredSession($,f){return Yf($,`session ${f}`)}static isCorruptSessionJSONLError($){return $ instanceof Error&&$.message.startsWith("Invalid session JSONL ")}static sanitizeStoredSessionError($,f){if(!this.isCorruptSessionJSONLError($)||!($ instanceof Error))return $;let T=$.message.match(/ at line (\d+)$/)?.[1];return Error(`Invalid session JSONL in session ${f}${T?` at line ${T}`:""}`,{cause:$.cause})}static async readStableSessionSnapshot($,f,T=3){for(let q=0;q<T;q+=1){let B=await _0.stat($),L=await _0.readFile($),O=this.parseStoredSession(L,f),C=await _0.stat($);if(B.size===C.size&&B.mtimeNs===C.mtimeNs&&B.dev===C.dev&&B.ino===C.ino)return O}throw Error("Session changed while creating fork; retry the operation")}}function Zf($){if($.length===1&&$[0]?.type==="text")return $[0].text;return[...$]}
|
|
111
|
-
export{i0 as
|
|
111
|
+
export{i0 as wb,Y$ as xb,Q0 as yb,U$ as zb,o1 as Ab,h as Bb,n as Cb,TT as Db,qT as Eb,b$ as Fb,OT as Gb,Y0 as Hb,NT as Ib,n0 as Jb,k$ as Kb,y$ as Lb,c0 as Mb,l as Nb,D0 as Ob,DT as Pb,RT as Qb,AT as Rb,zT as Sb,v$ as Tb,MT as Ub,ET as Vb,u$ as Wb,wT as Xb,a0 as Yb,s0 as Zb,vT as _b,uT as $b,d$ as ac,A0 as bc,pT as cc,Bf as dc,s$ as ec,oT as fc,Of as gc,tT as hc,z1 as ic,Rq as jc,Aq as kc,Rf as lc,f0 as mc,P as nc,X as oc};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{$a as e,Ta as a,Ua as b,Wa as c,_a as d,ab as f,bb as g,cb as h,db as i,eb as j,fb as k,kb as l,lb as m,mb as n,nb as o,ob as p,pb as q,qb as r}from"./chunk-q9ghq6jw.js";import"./chunk-ej1z75jf.js";import"./chunk-x9940mcy.js";import"./chunk-4djps7bz.js";import"./chunk-rezjy4mp.js";import"./chunk-6kc12pma.js";import"./chunk-4qtb8yf6.js";import"./chunk-vz0zsct0.js";import"./chunk-0prp87ys.js";import"./chunk-9pww3s5m.js";import"./chunk-m8jen593.js";import"./chunk-s3zfyy7r.js";import"./chunk-gdp6fg4e.js";import"./chunk-4qyhtrhx.js";import"./chunk-s6rdv601.js";import"./chunk-1ggxyyar.js";import"./chunk-ekv4hpy8.js";import"./chunk-8gv6hsrf.js";import"./chunk-5m5nxkfs.js";import"./chunk-7e7zgzag.js";import"./chunk-d4327k1v.js";import"./chunk-heydawsf.js";import"./chunk-37se34rx.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{eg as $,fg as F}from"./chunk-heydawsf.js";import{promises as J}from"node:fs";import Q from"node:path";import{Mutex as U}from"async-mutex";import w from"write-file-atomic";var X=1;function D(k){if(!k||typeof k!=="object"||Array.isArray(k))return!1;let q=k;return typeof q.path==="string"&&Q.isAbsolute(q.path)&&typeof q.boundAt==="string"}async function Z(k){if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k);if(!(await J.stat(q)).isDirectory())throw Error("Project path must be a directory");return q}class K{filePath;mutex=new U;constructor(k=Q.join(F(),"bound-projects.json")){this.filePath=k}async list(k){let q=await this.read(),z=await Z(k),H=new Map;for(let C of q.projects)H.set(C.path,C);if(!H.has(z))H.set(z,{path:z,boundAt:new Date(0).toISOString()});return(await Promise.all([...H.values()].map(async(C)=>{let L=!1;try{L=(await J.stat(C.path)).isDirectory()}catch{}return{path:C.path,name:Q.basename(C.path)||C.path,...L?{gitBranch:$(C.path)}:{},available:L,isCurrent:C.path===z,boundAt:C.boundAt}}))).sort((C,L)=>{if(C.isCurrent!==L.isCurrent)return C.isCurrent?-1:1;return C.name.localeCompare(L.name)})}async bind(k,q){return this.mutex.runExclusive(async()=>{let z=await Z(k),H=await this.read(),W=H.projects.find((M)=>M.path===z),C=W??{path:z,boundAt:new Date().toISOString()};if(!W)H.projects.push(C),await this.write(H);let L=await Z(q),A=$(z);return{path:z,name:Q.basename(z)||z,...A?{gitBranch:A}:{},available:!0,isCurrent:z===L,boundAt:C.boundAt}})}async unbind(k){return this.mutex.runExclusive(async()=>{if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k).catch(()=>Q.resolve(k)),z=await this.read(),H=z.projects.filter((W)=>W.path!==q);if(H.length===z.projects.length)return!1;return z.projects=H,await this.write(z),!0})}async read(){try{let k=await J.readFile(this.filePath,"utf8"),q=JSON.parse(k);if(q.version!==X||!Array.isArray(q.projects))return{version:X,projects:[]};return{version:X,projects:q.projects.filter(D)}}catch(k){if(k.code==="ENOENT"||k instanceof SyntaxError)return{version:X,projects:[]};throw k}}async write(k){let q=Q.dirname(this.filePath);await J.mkdir(q,{recursive:!0,mode:448}),await J.chmod(q,448),await w(this.filePath,`${JSON.stringify(k,null,2)}
|
|
2
2
|
`,{mode:384}),await J.chmod(this.filePath,384)}}var _=new K;
|
|
3
3
|
export{_ as l};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{l as i}from"./chunk-
|
|
1
|
+
import{l as i}from"./chunk-xr033fd3.js";import{Af as s}from"./chunk-1ggxyyar.js";import"./chunk-heydawsf.js";import"./chunk-37se34rx.js";import m from"node:path";var r={registry:i,currentWorkspace:s,inputCwd:()=>process.cwd(),write:console.log};function c(t,e){return m.resolve(e.inputCwd(),t)}function p(t){return t.map((e)=>{let o=e.isCurrent?"*":" ",n=e.gitBranch?` · ${e.gitBranch}`:"",d=e.available?"":" · unavailable";return`${o} ${e.name}${n}${d}
|
|
2
2
|
${e.path}`}).join(`
|
|
3
3
|
`)}async function l(t,e=r){let o=await e.registry.list(e.currentWorkspace());return e.write(t.json?JSON.stringify(o,null,2):p(o)),o}async function u(t,e=r){let o=await e.registry.bind(c(t.path,e),e.currentWorkspace());return e.write(t.json?JSON.stringify(o,null,2):`Bound project: ${o.path}`),o}async function j(t,e=r){let o=c(t.path,e),n=await e.registry.unbind(o);return e.write(t.json?JSON.stringify({path:o,removed:n},null,2):n?`Unbound project: ${o}`:`Project was not bound: ${o}`),n}var a={type:"boolean",default:!1,describe:"Print machine-readable JSON"},P={command:"list",aliases:["ls"],describe:"List bound projects",builder:(t)=>t.option("json",a),handler:async(t)=>{await l(t)}},b={command:"add <path>",aliases:["bind"],describe:"Bind a project folder",builder:(t)=>t.positional("path",{type:"string",demandOption:!0,describe:"Absolute or relative project folder"}).option("json",a),handler:async(t)=>{await u(t)}},h={command:"remove <path>",aliases:["rm","unbind"],describe:"Unbind a project folder",builder:(t)=>t.positional("path",{type:"string",demandOption:!0,describe:"Absolute or relative project folder"}).option("json",a),handler:async(t)=>{await j(t)}},y={command:"projects",aliases:["project"],describe:"Manage project bindings shared with Blade Web",builder:(t)=>t.command(P).command(b).command(h).demandCommand(1,"Choose list, add, or remove"),handler:()=>{return}};export{j as runProjectsRemove,l as runProjectsList,u as runProjectsAdd,y as projectsCommands,p as formatProjectList};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Jd as a,Kd as b,Ld as c}from"./chunk-rh5g6em4.js";import"./chunk-vx8a7e1j.js";import"./chunk-gdp6fg4e.js";import"./chunk-4qyhtrhx.js";import"./chunk-s6rdv601.js";import"./chunk-1ggxyyar.js";import"./chunk-ekv4hpy8.js";import"./chunk-8gv6hsrf.js";import"./chunk-5m5nxkfs.js";import"./chunk-7e7zgzag.js";import"./chunk-2d35rmyg.js";import"./chunk-d4327k1v.js";import"./chunk-heydawsf.js";import"./chunk-37se34rx.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,a as cloneWorkspaceModelConfig};
|