blade-code 0.10.64 → 0.10.66
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-wy4pn9sk.js → chunk-0j22w4wh.js} +1 -1
- package/dist/chunk-0qtrv97b.js +2 -0
- package/dist/chunk-0scxrkcf.js +1 -0
- package/dist/{chunk-2z3xe3rw.js → chunk-0wxkymqv.js} +1 -1
- package/dist/{chunk-egb457mv.js → chunk-1c69c4rd.js} +1 -1
- package/dist/{chunk-b19f55s7.js → chunk-1z9wct9w.js} +1 -1
- package/dist/chunk-2eq5dyga.js +1 -0
- package/dist/{chunk-0jxh2zq5.js → chunk-2kkpn41a.js} +2 -2
- package/dist/{chunk-pxy15vf3.js → chunk-2xk6m4fc.js} +12 -3
- package/dist/{chunk-81pdgcq7.js → chunk-30kmydfj.js} +2 -2
- package/dist/{chunk-z8heg5qv.js → chunk-4sztphe9.js} +1 -1
- package/dist/{chunk-6rg6mngq.js → chunk-50jthhfq.js} +1 -1
- package/dist/chunk-5147jh26.js +2 -0
- package/dist/{chunk-cm9mph7j.js → chunk-5d2cdvdy.js} +1 -1
- package/dist/chunk-69j98a7j.js +166 -0
- package/dist/{chunk-8ekk8pa7.js → chunk-6pyktfa4.js} +1 -1
- package/dist/chunk-89090tyx.js +1 -0
- package/dist/chunk-8c677xtx.js +1 -0
- package/dist/chunk-8nmwft1y.js +112 -0
- package/dist/{chunk-y8r2knxm.js → chunk-98n2rxmq.js} +2 -2
- package/dist/{chunk-pdys123h.js → chunk-a2594p5r.js} +1 -1
- package/dist/{chunk-2m7at619.js → chunk-a3xnd8cg.js} +2 -2
- package/dist/{chunk-7p0bzza4.js → chunk-abef6dq1.js} +2 -2
- package/dist/chunk-ax9ftraa.js +1 -0
- package/dist/{chunk-d9z0rbz1.js → chunk-b66veqye.js} +2 -2
- package/dist/{chunk-6g3qzz9h.js → chunk-bbcb9jzb.js} +1 -1
- package/dist/{chunk-3tednchw.js → chunk-bjqjdw34.js} +2 -2
- package/dist/chunk-c8zcyvss.js +1 -0
- package/dist/{chunk-detkh4dd.js → chunk-cdy9efgm.js} +1 -1
- package/dist/chunk-dc64v4sa.js +1 -0
- package/dist/{chunk-83wm4akj.js → chunk-dktrankr.js} +1 -1
- package/dist/chunk-e7pssnr9.js +1 -0
- package/dist/chunk-eq99gcj8.js +1 -0
- package/dist/{chunk-j9snkjpe.js → chunk-f99n8812.js} +2 -2
- package/dist/{chunk-gdrqxnzh.js → chunk-gezg1mpa.js} +1 -1
- package/dist/{chunk-khkhsaan.js → chunk-h0ft81a3.js} +1 -1
- package/dist/{chunk-rcv4q8hm.js → chunk-ha50z8dp.js} +1 -1
- package/dist/{chunk-d1t91jgz.js → chunk-hat9v5c5.js} +1 -1
- package/dist/{chunk-av10vmxk.js → chunk-hcv17986.js} +1 -1
- package/dist/{chunk-5g2p1fwn.js → chunk-j38jh128.js} +2 -2
- package/dist/chunk-jmjn6zcc.js +1 -0
- package/dist/{chunk-kjvntyr5.js → chunk-k0pa8874.js} +1 -1
- package/dist/{chunk-6fwh0m6d.js → chunk-k99r5c4v.js} +3 -3
- package/dist/chunk-kmarzy98.js +1 -0
- package/dist/chunk-kv0bkxhd.js +8 -0
- package/dist/{chunk-87jz5600.js → chunk-m57w4p91.js} +1 -1
- package/dist/{chunk-9zdx6jsh.js → chunk-nt55nz8d.js} +40 -40
- package/dist/chunk-p0b4mv7e.js +10 -0
- package/dist/{chunk-cz68x56m.js → chunk-ppsvzgs5.js} +2 -2
- package/dist/{chunk-3m640njb.js → chunk-pzb5sqwd.js} +1 -1
- package/dist/{chunk-wrw5hegj.js → chunk-q3mfescm.js} +2 -2
- package/dist/{chunk-wqewxnez.js → chunk-qdah5kkc.js} +246 -246
- package/dist/{chunk-as5z4m2d.js → chunk-rf01e14b.js} +1 -1
- package/dist/chunk-rhs1dv6w.js +1 -0
- package/dist/{chunk-jk8bqc5b.js → chunk-s7jsadnc.js} +2 -2
- package/dist/{chunk-ej6h16ae.js → chunk-t2gq918a.js} +2 -2
- package/dist/chunk-t89q7d03.js +22 -0
- package/dist/{chunk-fp1h8wdh.js → chunk-t8xmh4w2.js} +1 -1
- package/dist/{chunk-z2hmx0jz.js → chunk-te21eb71.js} +1 -1
- package/dist/{chunk-9r0yebs1.js → chunk-th4jjfgm.js} +1 -1
- package/dist/{chunk-7b467h8k.js → chunk-v0rsz1rt.js} +1 -1
- package/dist/{chunk-wt4wv5rb.js → chunk-w6p2hcfw.js} +1 -1
- package/dist/{chunk-rctbavme.js → chunk-xny9q252.js} +2 -2
- package/dist/chunk-xz6y0w4n.js +2 -0
- package/dist/{chunk-tcga95a4.js → chunk-ybv6stfh.js} +2 -2
- package/dist/{chunk-69rc9hw6.js → chunk-yn51162x.js} +1 -1
- package/dist/{chunk-1jc7d3nt.js → chunk-ypqp368c.js} +2 -2
- package/dist/{chunk-eeac8teg.js → chunk-yvg961q3.js} +1 -1
- package/dist/chunk-yy6h97k0.js +1 -0
- package/dist/chunk-zdxxqchm.js +140 -0
- package/dist/chunk-zk42hrdh.js +1 -0
- package/dist/{chunk-2xbmkyb2.js → chunk-zvz2cnt4.js} +1 -1
- package/dist/web/assets/{ChatView-B6IO9U-D.js → ChatView-BVrhnE2j.js} +6 -6
- package/dist/web/assets/{CodeBlockHighlighter-DVGtFQgX.js → CodeBlockHighlighter-Dy7QpAmC.js} +1 -1
- package/dist/web/assets/{FilePreview-C-8_o7yw.js → FilePreview-BI3nkxz1.js} +2 -2
- package/dist/web/assets/KanbanBoard-D5dYOyPH.js +1 -0
- package/dist/web/assets/{MarkdownRenderer-D04IKQhF.js → MarkdownRenderer-Da1vB81L.js} +12 -12
- package/dist/web/assets/{SettingsModal-BMoZLVEe.js → SettingsModal-jcCFqLqS.js} +2 -2
- package/dist/web/assets/TaskSwitcher-CQ--jOLB.js +1 -0
- package/dist/web/assets/{TerminalPanel-fTk9D5hU.js → TerminalPanel-CWzjEXOb.js} +1 -1
- package/dist/web/assets/index-BOgOL4hG.js +11 -0
- package/dist/web/assets/index-DbWgTuT3.css +1 -0
- package/dist/web/assets/{vendor-icons-ICv1v-tf.js → vendor-icons-B63aW_OM.js} +82 -62
- package/dist/web/index.html +3 -3
- package/package.json +2 -2
- package/dist/chunk-0d1197b9.js +0 -1
- package/dist/chunk-1vw79f30.js +0 -1
- package/dist/chunk-1wr6hrwt.js +0 -1
- package/dist/chunk-7781czcd.js +0 -1
- package/dist/chunk-86gc2mqb.js +0 -1
- package/dist/chunk-9c31jemm.js +0 -1
- package/dist/chunk-9kmtcgm6.js +0 -2
- package/dist/chunk-acfka6w7.js +0 -1
- package/dist/chunk-addsr9hg.js +0 -22
- package/dist/chunk-avhwgbg0.js +0 -1
- package/dist/chunk-bcp7nwwy.js +0 -10
- package/dist/chunk-bjz7t9fe.js +0 -8
- package/dist/chunk-dbs94h44.js +0 -1
- package/dist/chunk-g0n88mhg.js +0 -1
- package/dist/chunk-jy1e6ve5.js +0 -111
- package/dist/chunk-q8zp4je9.js +0 -1
- package/dist/chunk-qs4erqd0.js +0 -2
- package/dist/chunk-vjyysxhx.js +0 -1
- package/dist/chunk-wwsg165p.js +0 -116
- package/dist/chunk-wy2b5hsh.js +0 -2
- package/dist/chunk-xm44tqjb.js +0 -1
- package/dist/chunk-y78m734s.js +0 -204
- package/dist/chunk-y83x0w26.js +0 -1
- package/dist/web/assets/TaskSwitcher-CIuCEbvU.js +0 -1
- package/dist/web/assets/index-CO5sUiJn.js +0 -11
- package/dist/web/assets/index-Dxdnbd79.css +0 -1
package/dist/chunk-addsr9hg.js
DELETED
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
import{s as Oz,t as Rz}from"./chunk-pdys123h.js";import{u as T}from"./chunk-egb457mv.js";import{A as Qz,v as Kz,w as e,x as zz,y as Hz,z as Jz}from"./chunk-wy2b5hsh.js";import{E as P,N as o,Q as n,R as t,V as s,ja as Zz,ka as $z,la as Wz,ma as Yz}from"./chunk-wqewxnez.js";import{wa as Az}from"./chunk-3m640njb.js";import"./chunk-qs4erqd0.js";import{_a as i,nb as r,wb as a}from"./chunk-y78m734s.js";import{Fb as M}from"./chunk-9r0yebs1.js";import{Cc as G,Yb as p,dc as m,gc as d,oc as k,pc as v,rc as E,uc as l,zc as R}from"./chunk-jy1e6ve5.js";import"./chunk-2z3xe3rw.js";import"./chunk-wwsg165p.js";import{ed as Nz}from"./chunk-rctbavme.js";import"./chunk-3tednchw.js";import{Ad as Vz,zd as Uz}from"./chunk-2m7at619.js";import"./chunk-v508x7cg.js";import{Ld as I}from"./chunk-wy4pn9sk.js";import"./chunk-0jxh2zq5.js";import"./chunk-j9snkjpe.js";import{Yd as wz}from"./chunk-69rc9hw6.js";import"./chunk-d9z0rbz1.js";import"./chunk-pxy15vf3.js";import"./chunk-d1t91jgz.js";import{He as _z}from"./chunk-detkh4dd.js";import"./chunk-2xbmkyb2.js";import"./chunk-6fwh0m6d.js";import"./chunk-87jz5600.js";import{Cf as Gz,zf as Lz}from"./chunk-7p0bzza4.js";import"./chunk-khkhsaan.js";import"./chunk-7b467h8k.js";import{eg as y,fg as c,gg as h}from"./chunk-9kmtcgm6.js";import{kg as Bz}from"./chunk-kjvntyr5.js";import"./chunk-8ekk8pa7.js";import{Lg as x}from"./chunk-y8r2knxm.js";import"./chunk-1jc7d3nt.js";import{Sg as Dz,Vg as Fz}from"./chunk-fp1h8wdh.js";import"./chunk-5g2p1fwn.js";import"./chunk-ej6h16ae.js";import"./chunk-cm9mph7j.js";import"./chunk-cz68x56m.js";import"./chunk-av10vmxk.js";import{Readable as Mz,Writable as kz}from"node:stream";import*as S from"@agentclientprotocol/sdk";import jz from"node:path";import{PROTOCOL_VERSION as yz,RequestError as hz}from"@agentclientprotocol/sdk";import{RequestError as Ez}from"@agentclientprotocol/sdk";import{nanoid as b}from"nanoid";var F=x("Agent");function g(z){if(!z)return{};return Object.fromEntries(z.map((J)=>[J.name,J.value]))}function Tz(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:g(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:g("headers"in z?z.headers:void 0)};return null}function xz(z){let J={};for(let H of z){let W=Tz(H);if(W)J[H.name]=W}return J}function Xz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((J)=>{if(J.type==="text")return J.text?[{type:"text",text:J.text}]:[];let H=J.image_url.url,W=/^data:([^;,]+);base64,(.+)$/s.exec(H);if(!W)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:W[1]??"image/png",data:W[2]??""}]})}function Sz(z){let J=v(z.metadata);return J?[{type:"text",text:k(J)}]:Xz(z.content)}function bz(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
|
|
2
|
-
`)}class q{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingPromptCompletion=null;pendingUserShell=null;pendingUserShellCompletion=null;pendingResumeRequested=!1;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;destroyFinished=!1;destroyPromise;messages;contextMessages;mode;updateEgress;constructor(z,J,H,W,Y={}){this.id=z;this.cwd=J;this.connection=H;this.clientCapabilities=W;this.options=Y;this.messages=[...Y.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(Y.permissionMode),this.updateEgress=new Qz({maxPendingItems:e,maxPendingBytes:zz,writeTimeoutMs:Hz,signal:H.signal,sizeOf:($)=>Buffer.byteLength(JSON.stringify($)),write:async($)=>{await H.sessionUpdate($)},onFailure:($)=>this.handleUpdateEgressFailure($)})}async refreshPersistedMessages(){let[z,J]=await Promise.all([G.loadSession(this.id,this.cwd),G.loadSessionModelContext(this.id,this.cwd)]);if(z.length>0)this.messages=z;if(J.length>0)this.contextMessages=J}async loadModelContextOr(z){let J=await G.loadSessionModelContext(this.id,this.cwd);return J.length>0?J:[...z]}mapPermissionModeToMode(z){switch(z){case"yolo":return"yolo";case"autoEdit":return"auto-edit";case"plan":return"plan";case"default":default:return"default"}}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return s.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(F.debug(`[AcpSession ${this.id}] Initializing...`),await G.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),P.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd,async($)=>{await this.sendUpdateAndWait($)}),F.debug(`[AcpSession ${this.id}] ACP service context initialized`),await a.resolvePendingWithHandler(this.cwd,this.id,{requestConfirmation:($)=>this.requestPermission($)}))await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let J=this.options.mcpServers?xz(this.options.mcpServers):void 0,H=P.getInstance().getTerminalService(this.id);if(this.runtime=await o.create({sessionId:this.id,workspaceRoot:this.cwd,permissionMode:this.mapModeToPermissionMode(),...J?{mcpServers:J}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async($,Z)=>{let X=await H.execute($,{cwd:Z.cwd,env:Z.env,timeout:Z.timeoutMs,signal:Z.signal,allowLocalFallback:!1,onOutput:(j)=>Z.onOutput?.("stdout",j)});return{exitCode:X.exitCode,stdout:X.stdout,stderr:X.stderr,...X.error?{error:X.error}:{},timedOut:X.failureKind==="timeout",aborted:X.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),await T.recoverInterrupted(this.cwd,this.id,this.runtime))await this.refreshPersistedMessages();this.agent=await this.createAgent(),await $z(this.cwd),F.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=i.subscribe(($)=>{if($.sessionId!==this.id||$.projectPath!==this.cwd)return;if($.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":$.properties}}),this.schedulePendingResume();return}if($.type==="task.delivery"){if(!$.properties.taskDelivery||typeof $.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof $.properties.updatedAt==="string"?$.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":$.properties.taskDelivery,...$.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if($.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof $.properties.updatedAt==="string"?$.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":$.properties.taskStatus,...typeof $.properties.taskStatusReason==="string"?{"blade/taskStatusReason":$.properties.taskStatusReason}:{},...$.properties.taskFailure&&typeof $.properties.taskFailure==="object"?{"blade/taskFailure":$.properties.taskFailure}:{},...typeof $.properties.taskStartedAt==="string"?{"blade/taskStartedAt":$.properties.taskStartedAt}:{},...typeof $.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":$.properties.taskCompletedAt}:{},...$.properties.taskDiffStat&&typeof $.properties.taskDiffStat==="object"?{"blade/taskDiffStat":$.properties.taskDiffStat}:{},...typeof $.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":$.properties.taskQueuePosition}:{},...typeof $.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":$.properties.taskQueueDepth}:{},...typeof $.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":$.properties.taskConcurrencyLimit}:{},...typeof $.properties.taskInFlight==="number"?{"blade/taskInFlight":$.properties.taskInFlight}:{}}})});let Y=await this.runtime.getGoal();if(this.runtime.getPendingSteeringCount()>0||Y?.status==="active"||Y?.status==="verifying")if(this.options.initialMessages===void 0)this.schedulePendingResume();else this.pendingResumeRequested=!0}async replayHistory(){for(let J of this.messages){if(!this.canSendUpdates())return;let H=J.role==="user"?"user_message_chunk":J.role==="assistant"?"agent_message_chunk":void 0;if(!H)continue;for(let W of Sz(J)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:H,content:W}))return}}let z=await this.runtime?.getGoal();if(z&&!await this.sendUpdateAndWait(this.goalSessionUpdate(z)))return;if(this.pendingResumeRequested)this.schedulePendingResume()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);F.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendAvailableCommands()},500)}async handleSlashCommand(z,J){try{F.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let H={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(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let X=await this.runtime.rewindSession(Z);return this.messages=[...X.messages],this.contextMessages=await this.loadModelContextOr(X.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),X}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async(Z)=>{if(await this.setReasoningEffort(Z),!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(Z)=>{if(await this.setServiceTier(Z),!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(Z)=>{if(await this.setResponseVerbosity(Z),!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(Z)=>{if(await this.setCommunicationStyle(Z),!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(Z,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let j=!1,B,L=(U)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:U.id,status:U.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:U.result?.message||U.result?.error||`Subagent ${U.status}`}}]})},D=this.runtime.resumeSubagent({agentId:Z,prompt:X,onCompleted:(U)=>{if(j)L(U);else B=U}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:D.session.id,status:"in_progress",title:`Resuming ${D.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${D.source.id} at depth ${D.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),j=!0,B)L(B);return D}},mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs(Z)},getPrompt:async(Z,X,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Z,X,j)},complete:async(Z,X,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Z,X,j)},listTasks:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks(Z)},getTask:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask(Z)},cancelTask:async(Z,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Z,X)},getLogs:async(Z,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Z,X)},setLoggingLevel:async(Z,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Z,X)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},codeReview:{run:async(Z,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let j=await T.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:Z,signal:X,onEvent:(D)=>{if(D.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:D.toolCall.id,status:"in_progress",title:`Review: ${D.toolCall.function.name}`,content:[],kind:this.mapToolKind(D.toolKind)});else if(D.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:D.toolCall.id,status:D.result.success?"completed":"failed",content:[]})}}),B=await j.completion,L=(await T.list(this.cwd,this.id)).find((D)=>D.start.reviewId===j.reviewId);if(!L)throw Error(`Review not found: ${j.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:j.reviewId,status:B.status,findings:B.findings.length,content:p(L.start,B)}}},signal:J,acp:{sendMessage:(Z)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Z}})},sendToolStart:(Z,X,j)=>{let B=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,L=this.mapToolKind(j);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:B,status:"in_progress",title:`${Z}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(X,null,2)}}],kind:L})},sendToolResult:(Z,X)=>{if(X.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:X.summary}})}}},W=await Wz(z,H),Y=W.data?.action;if(Y==="start_goal"||Y==="resume_goal")this.schedulePendingResume();if(Y==="rewind_session"&&Array.isArray(W.data?.messages))this.messages=[...W.data.messages],this.contextMessages=await this.loadModelContextOr(W.data.messages);if((W.message==="compact_completed"||W.message==="compact_fallback")&&W.data?.compactedMessages){this.contextMessages=[...W.data.compactedMessages];let Z=await G.loadSession(this.id,this.cwd);if(Z.length>0)this.messages=Z}let $=W.content||W.message;if($)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$}});if(W.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${W.error}`}});return await this.flushUpdates(),{stopReason:W.success?"end_turn":"cancelled"}}catch(H){return F.error(`[AcpSession ${this.id}] Slash command error:`,H),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${H instanceof Error?H.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async sendAvailableCommands(){try{let z=Yz(this.cwd,this.runtime?.getAgentResources()),J=["model","permissions","theme","config","exit","ide"],W=z.filter((Y)=>!J.includes(Y.name)).map((Y)=>{let $;if(Y.usage){let Z=Y.usage.replace(/^\/\w+\s*/,"").trim();if(Z)$=Z}if(Y.aliases?.length){let Z=`Aliases: ${Y.aliases.join(", ")}`;$=$?`${$} | ${Z}`:Z}return{name:Y.name,description:Y.description,input:$?{hint:$}:void 0}});F.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(W.map((Y)=>Y.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:W}),F.info(`[AcpSession ${this.id}] Sent ${W.length} available commands`)}catch(z){F.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,J={}){if(P.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let H=this.resolvePrompt(z.prompt),W=H.content,Y=H.displayText,$=z._meta?.outputSchema??(J.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((D)=>D.outputSchema)?.outputSchema:void 0),Z;if($!==void 0)Z=l($).schema;if(Y.trimStart().startsWith("!")){if(Z)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(Y)}if(this.pendingPrompt){if(Z)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test(Y.trim()))return this.handleSlashCommand(Y,this.pendingPrompt.signal);let D=await this.runtime.enqueueSteering(W,{allowBeforeTurn:!0});if(!D.accepted)throw Error(D.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(F.debug(`[AcpSession ${this.id}] Queued steering for active turn (${D.queued})`),D.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let X=new AbortController,j=!1,B,L=new Promise((D)=>{B=D});this.pendingPrompt=X,this.pendingPromptCompletion=L;try{if(F.debug(`[AcpSession ${this.id}] Received prompt: ${Y.slice(0,100)}...`),Zz(Y)){if(Z)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(Y,X.signal)}let D={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.contextMessages],signal:X.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async(Q)=>{this.mode=this.mapPermissionModeToMode(Q),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async(Q)=>{return this.requestPermission(Q)}}},U=await r(this.agent.chatStream(W,D,{pendingInputOnly:J.pendingInputOnly,goalContinuationOnly:J.goalContinuationOnly,outputSchema:Z}),async(Q)=>{switch(Q.kind){case"content_delta":if(Z)break;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:Q.delta}});break;case"tool_start":{let w=Q.toolCall,K=w.function.name;if(K===E)break;let O=this.mapToolKind(Q.toolKind),V=`Executing ${K}`;if(K==="Task"&&"function"in w)try{let N=JSON.parse(w.function.arguments),_=N.resume_from??N.resume;if(typeof _==="string")V=`Resuming ${String(N.subagent_type||"subagent")} from ${_}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:w.id,status:"in_progress",title:V,content:[],kind:O});break}case"tool_progress":{let w=Q.toolCall;if(w.function.name===E)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:w.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:Q.update.message}}]});break}case"tool_result":{let w=Q.toolCall;if(w.function.name===E)break;let K=Q.result,O=[],V=K.metadata;if(V?.kind==="patch"&&Array.isArray(V.changes))for(let _ of V.changes){if(!_||typeof _!=="object"||!("path"in _)||typeof _.path!=="string")continue;O.push({type:"diff",path:_.path,oldText:"oldContent"in _&&typeof _.oldContent==="string"?_.oldContent:null,newText:"newContent"in _&&typeof _.newContent==="string"?_.newContent:null})}else if(V?.kind==="edit"&&typeof V.file_path==="string"&&typeof V.oldContent==="string"&&(typeof V.newContent==="string"||V.newContent===void 0))O.push({type:"diff",path:V.file_path,oldText:V.oldContent,newText:V.newContent??null});else{let _=w.function.name,Pz=t(d(n(_,K),m));O.push({type:"content",content:{type:"text",text:Pz}})}if(w.function.name==="Task"&&(V?.verificationVerdict==="pass"||V?.verificationVerdict==="fail"||V?.verificationVerdict==="partial"))O.unshift({type:"content",content:{type:"text",text:`Verification result: ${V.verificationVerdict.toUpperCase()}`}});let N=K.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:w.id,status:N,content:O});break}case"structured_output":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify(Q.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${Q.revision} (${Q.serverName}): +${Q.added.length} -${Q.removed.length} ~${Q.updated.length}
|
|
3
|
-
`}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${Q.contentKind} r${Q.revision} (${Q.serverName}): +${Q.added.length} -${Q.removed.length} ~${Q.updated.length}
|
|
4
|
-
`}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${Q.revision} (${Q.serverName}): ${Q.uri}
|
|
5
|
-
`}});break;case"mcp_connection_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP connection r${Q.revision} (${Q.serverName}): ${Q.phase} ${Q.attempt}/${Q.maxAttempts}
|
|
6
|
-
`}});break;case"mcp_log":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP log r${Q.revision} (${Q.serverName}) ${Q.level}${Q.logger?` logger=${Q.logger}`:""}: ${Q.message}
|
|
7
|
-
`}});break;case"mcp_instructions_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP instructions r${Q.revision} (${Q.serverName}): ${Q.action}${Q.detailsOmitted?" details-omitted":""}
|
|
8
|
-
`}});break;case"mcp_task_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP task r${Q.revision} ${Q.taskId} (${Q.serverName}/${Q.toolName}): ${Q.status}${Q.hasResult?" result-available":""}
|
|
9
|
-
`}});break;case"project_rules_loaded":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Project rules loaded: ${Q.files.length}${Q.blockedWrite?" (write retry required)":""}
|
|
10
|
-
`}});break;case"provider_admission":j=Q.phase!=="admitted",this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":Q.phase!=="admitted"?{phase:Q.phase,requestClass:Q.requestClass,resource:Q.resource,scope:Q.scope,...Q.reason!==void 0?{reason:Q.reason}:{},queuePosition:Q.queuePosition,queueDepth:Q.queueDepth,inFlight:Q.inFlight,limit:Q.limit,waitMs:Q.waitMs,maxWaitMs:Q.maxWaitMs,...Q.recoveryRemainingMs!==void 0?{recoveryRemainingMs:Q.recoveryRemainingMs}:{}}:null}});break;case"provider_circuit":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerCircuit":{phase:Q.phase,reason:Q.reason,...Q.statusCode!==void 0?{statusCode:Q.statusCode}:{},...Q.retryAfterMs!==void 0?{retryAfterMs:Q.retryAfterMs}:{},...Q.nextProbeAt!==void 0?{nextProbeAt:Q.nextProbeAt}:{},openDurationMs:Q.openDurationMs,...Q.sampleCount!==void 0?{sampleCount:Q.sampleCount}:{},...Q.failureCount!==void 0?{failureCount:Q.failureCount}:{},...Q.recoveryRemainingMs!==void 0?{recoveryRemainingMs:Q.recoveryRemainingMs}:{}}}});break;case"provider_retry":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerRetry":{phase:Q.phase,attempt:Q.attempt,maxRetries:Q.maxRetries,reason:Q.reason,...Q.statusCode!==void 0?{statusCode:Q.statusCode}:{},...Q.delayMs!==void 0?{delayMs:Q.delayMs}:{},...Q.nextRetryAt!==void 0?{nextRetryAt:Q.nextRetryAt}:{},...Q.mode!==void 0?{mode:Q.mode}:{},...Q.recoveryBudgetMs!==void 0?{recoveryBudgetMs:Q.recoveryBudgetMs}:{},...Q.recoveryElapsedMs!==void 0?{recoveryElapsedMs:Q.recoveryElapsedMs}:{},...Q.recoveryRemainingMs!==void 0?{recoveryRemainingMs:Q.recoveryRemainingMs}:{},...Q.exhaustedBy!==void 0?{exhaustedBy:Q.exhaustedBy}:{}}}});break;case"provider_stall":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerStall":{phase:Q.phase,stallCount:Q.stallCount,durationMs:Q.durationMs,warningAfterMs:Q.warningAfterMs,timeoutMs:Q.timeoutMs,outputStarted:Q.outputStarted}}});break;case"action_stationarity":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/actionStationarity":{phase:Q.phase,toolName:Q.toolName,runLength:Q.runLength,nudgeThreshold:Q.nudgeThreshold,haltThreshold:Q.haltThreshold,progressAware:Q.progressAware}}});break;case"task_update":this.sendPlanUpdate(Q.tasks);break;case"steering_applied":break;case"follow_up_started":for(let w of Q.messages){if(!w.recovered||w.persisted)continue;for(let K of Xz(w.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:K})}if(Q.recovered>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${Q.recovered} queued instruction${Q.recovered===1?"":"s"} recovered after restart]
|
|
11
|
-
`}});break;case"goal_updated":if(Q.goal)this.sendUpdate(this.goalSessionUpdate(Q.goal));if(Q.goal&&Q.goal.status!=="active")this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Goal ${Q.goal.status}: ${Q.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:Q.phase,...Q.reason?{reason:Q.reason}:{},...Q.strategy?{strategy:Q.strategy}:{},...Q.outcome?{outcome:Q.outcome}:{},...Q.preTokens!==void 0?{preTokens:Q.preTokens}:{},...Q.postTokens!==void 0?{postTokens:Q.postTokens}:{}}}});break;default:break}if(!await this.flushUpdates())X.abort("acp-egress-failed")});if(!await this.flushUpdates())X.abort("acp-egress-failed");this.contextMessages=[...D.messages];let f=await G.loadSession(this.id,this.cwd);if(this.messages=f.length>0?f:[...D.messages],!U.success){let Q=U.error?.type??"unknown";throw Ez.internalError({failureType:Q},`Agent turn failed (${Q})`)}if(X.signal.aborted)return{stopReason:"cancelled"};let u={...U.metadata?.structuredOutput?{structuredOutput:U.metadata.structuredOutput,outputSchemaDigest:U.metadata.structuredOutputSchemaDigest}:{},...U.metadata?.goalCompletionVerified?{goalCompletion:{verified:!0,verdict:U.metadata.goalVerificationVerdict,...U.metadata.goalVerifierSessionId?{verifierSessionId:U.metadata.goalVerifierSessionId}:{},...U.metadata.goalVerificationEvidenceSha256?{evidenceSha256:U.metadata.goalVerificationEvidenceSha256}:{}}}:{}};return{stopReason:"end_turn",...Object.keys(u).length>0?{_meta:u}:{}}}catch(D){if(X.signal.aborted||D instanceof Error&&D.name==="AbortError")return{stopReason:"cancelled"};throw F.error(`[AcpSession ${this.id}] Prompt error:`,D),D}finally{if(j&&!this.destroyed)this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":null}}),await this.flushUpdates();if(B(),this.pendingPromptCompletion===L)this.pendingPromptCompletion=null;if(this.pendingPrompt===X){if(this.pendingPrompt=null,!this.destroyed&&this.pendingResumeRequested)this.schedulePendingResume()}}}async handleUserShellCommand(z){if(!this.runtime)throw Error("Session runtime is unavailable");if(this.pendingUserShell)throw Error("A user shell command is already running");let J=z.trimStart().slice(1).trim();if(!J)throw Error("User shell command cannot be empty");let H=new AbortController,W,Y=new Promise((X)=>{W=X});this.pendingUserShell=H,this.pendingUserShellCompletion=Y;let $,Z="";try{let X=await this.runtime.executeUserShellCommand(J,{signal:H.signal,onEvent:async(B)=>{if($=B.executionId,B.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:B.executionId,status:"in_progress",title:`! ${B.command}`,content:[],kind:"execute"});return}if(B.type==="output"){Z+=B.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:B.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:B.chunk}}]});return}let L=k(B.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:B.executionId,status:B.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:Z?bz(B.record):L}}]})}}),j={role:"user",content:X.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify(X.record))}};if(this.messages.push(j),this.contextMessages.push(j),X.delivery==="next_turn")this.schedulePendingResume();if(!await this.flushUpdates())return H.abort("acp-egress-failed"),{stopReason:"cancelled"};return{stopReason:X.record.status==="aborted"?"cancelled":"end_turn"}}catch(X){if($)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:$,status:"failed",content:[{type:"content",content:{type:"text",text:X instanceof Error?X.message:String(X)}}]});if(H.signal.aborted)return{stopReason:"cancelled"};throw X}finally{if(W(),this.pendingUserShellCompletion===Y)this.pendingUserShellCompletion=null;if(this.pendingUserShell===H)this.pendingUserShell=null}}schedulePendingResume(){if(this.destroyed||this.connection.signal.aborted)return;this.pendingResumeRequested=!0,queueMicrotask(()=>{this.resumePendingIfIdle()})}async resumePendingIfIdle(){if(this.destroyed||this.connection.signal.aborted)return;if(this.pendingPrompt||this.pendingUserShell||!this.runtime||!this.agent)return;let z=this.runtime.getPendingSteeringCount()>0,J=z?null:await this.runtime.getGoal(),H=J?.status==="active"||J?.status==="verifying";if(!z&&!H){this.pendingResumeRequested=!1;return}this.pendingResumeRequested=!1,await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:z,goalContinuationOnly:H}).catch((W)=>{F.error(`[AcpSession ${this.id}] Failed to resume pending input:`,W)})}cancel(){F.info(`[AcpSession ${this.id}] Cancel requested`),this.pendingResumeRequested=!1;let z=!1;if(this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,z=!0;if(this.pendingUserShell)this.pendingUserShell.abort(),this.pendingUserShell=null,z=!0;if(!z)F.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(z){let H=["default","auto-edit","yolo","plan"].includes(z)?z:"default",W=this.mapModeIdToPermissionMode(H);await G.setSessionPermissionMode(this.id,this.cwd,W),this.mode=H,F.info(`[AcpSession ${this.id}] Mode set to: ${this.mode}`),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})}mapModeToPermissionMode(){return this.mapModeIdToPermissionMode(this.mode)}mapModeIdToPermissionMode(z){switch(z){case"yolo":return"yolo";case"auto-edit":return"autoEdit";case"plan":return"plan";case"default":default:return"default"}}shouldAutoApprove(z){switch(this.mode){case"yolo":return!0;case"auto-edit":return z==="readonly"||z==="write";case"plan":return z==="readonly";case"default":default:return!1}}async setModel(z){if(F.info(`[AcpSession ${this.id}] Model set to: ${z}`),this.pendingPrompt)throw Error("Cannot switch models while a prompt is active");if(!this.agent)throw Error("Session not initialized");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getCurrentModelId();await this.agent.switchModel(z);try{try{await G.updateSessionMetadata(this.id,this.cwd,{selectedModelId:z})}catch(H){if(!(H instanceof R)&&H.code!=="ENOENT")throw H;await G.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:z})}}catch(H){if(J&&J!==z)await this.agent.switchModel(J).catch((W)=>{F.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,W)});throw H}}getCurrentModelId(){return this.runtime?.getCurrentModelId()}async setReasoningEffort(z){if(this.pendingPrompt)throw Error("Cannot switch reasoning effort while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getReasoningConfiguration();try{this.runtime.resolveReasoningConfiguration(z)}catch(H){throw Error(H instanceof Error?H.message:"Invalid reasoning effort")}if(J.selection===z)return;await this.runtime.refresh({reasoningEffort:z});try{try{await G.updateSessionMetadata(this.id,this.cwd,{reasoningEffort:z})}catch(H){if(!(H instanceof R)&&H.code!=="ENOENT")throw H;await G.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),reasoningEffort:z})}}catch(H){throw await this.runtime.refresh({reasoningEffort:J.selection}),H}}async setServiceTier(z){if(this.pendingPrompt)throw Error("Cannot switch service tier while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getServiceTierConfiguration();try{this.runtime.resolveServiceTierConfiguration(z)}catch(H){throw Error(H instanceof Error?H.message:"Invalid service tier")}if(J.selection===z)return;await this.runtime.refresh({serviceTier:z});try{try{await G.updateSessionMetadata(this.id,this.cwd,{serviceTier:z})}catch(H){if(!(H instanceof R)&&H.code!=="ENOENT")throw H;await G.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),serviceTier:z})}}catch(H){throw await this.runtime.refresh({serviceTier:J.selection}),H}}async setResponseVerbosity(z){if(this.pendingPrompt)throw Error("Cannot switch response verbosity while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getResponseVerbosityConfiguration();try{this.runtime.resolveResponseVerbosityConfiguration(z)}catch(H){throw Error(H instanceof Error?H.message:"Invalid response verbosity")}if(J.selection===z)return;await this.runtime.refresh({responseVerbosity:z});try{try{await G.updateSessionMetadata(this.id,this.cwd,{responseVerbosity:z})}catch(H){if(!(H instanceof R)&&H.code!=="ENOENT")throw H;await G.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),responseVerbosity:z})}}catch(H){throw await this.runtime.refresh({responseVerbosity:J.selection}),H}}async setCommunicationStyle(z){if(this.pendingPrompt)throw Error("Cannot switch communication style while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getCommunicationStyleConfiguration(),H=this.runtime.resolveCommunicationStyleConfiguration(z);if(H.source!=="built-in"&&!H.contentSha256)throw Error("Custom communication style has no provenance");if(J.selection===z)return;await this.runtime.refresh({communicationStyle:z});try{try{await G.updateSessionMetadata(this.id,this.cwd,{communicationStyle:z,communicationStyleDigest:H.source==="built-in"?null:H.contentSha256})}catch(W){if(!(W instanceof R)&&W.code!=="ENOENT")throw W;await G.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:z,...H.source!=="built-in"&&H.contentSha256?{communicationStyleDigest:H.contentSha256}:{}})}}catch(W){throw await this.runtime.refresh({communicationStyle:J.selection}),W}}getModelConfiguration(){if(!this.runtime)return;let z=this.runtime.getConfig();return{currentModelId:this.runtime.getCurrentModelId()??z.currentModelId,models:z.models.map((J)=>structuredClone(J)),modelProviders:structuredClone(z.modelProviders),reasoning:this.runtime.getReasoningConfiguration(),serviceTier:this.runtime.getServiceTierConfiguration(),responseVerbosity:this.runtime.getResponseVerbosityConfiguration(),communicationStyle:this.runtime.getCommunicationStyleConfiguration()}}getMode(){return this.mode}isIdleForResidency(){return!this.destroyed&&this.pendingPrompt===null&&this.pendingUserShell===null&&(this.runtime?.isIdleForResidency()??!1)}destroy(z={}){if(this.destroyPromise)return this.destroyFinished?Promise.resolve():this.destroyPromise;return this.destroyPromise=this.destroyOwnedResources(z.discardPendingInput===!0).finally(()=>{this.destroyFinished=!0}),this.destroyPromise}async destroyOwnedResources(z){if(this.destroyed=!0,this.updateEgress.close(new Jz("closed","ACP Session was destroyed")),this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let J=this.agent,H=this.runtime,W=this.pendingPromptCompletion,Y=this.pendingUserShellCompletion;this.agent=null,this.runtime=null;let $,Z=async(X)=>{try{await X()}catch(j){$??=j}};if(await Z(()=>this.cancel()),W)await Z(()=>W);if(Y)await Z(()=>Y);if(z&&W&&H)await Z(()=>H.discardPendingInput());if(J)await Z(()=>J.destroy());if(H)await Z(()=>H.dispose());if(await Z(()=>P.destroySession(this.id)),F.debug(`[AcpSession ${this.id}] Destroyed`),$!==void 0)throw $}resolvePrompt(z){let J=[],H=[],W=0,Y=0,$=0,Z=(j)=>{if(H.length>0)H.push({type:"text",text:`
|
|
13
|
-
`}),$+=1;if(H.push(j),j.type==="text")$+=j.text.length};for(let j of z)if(j.type==="text")J.push(j.text),Z({type:"text",text:j.text});else if(j.type==="image"){let B=`data:${j.mimeType};base64,${j.data}`;W+=1,Y+=B.length,J.push(`[Image: ${j.mimeType}]`),Z({type:"image_url",image_url:{url:B}})}else if(j.type==="resource"){let B=j.resource;if("text"in B){let L=`<file path="${B.uri}">
|
|
14
|
-
${B.text}
|
|
15
|
-
</file>`;J.push(L),Z({type:"text",text:L})}}else if(j.type==="resource_link"){let B=`[Resource: ${j.uri}]`;J.push(B),Z({type:"text",text:B})}if(W>y)throw Error(`ACP prompt contains more than ${y} images`);if(Y>c)throw Error("ACP prompt images exceed the 5 MiB limit");if($>h)throw Error(`ACP prompt text exceeds ${h} characters`);let X=J.join(`
|
|
16
|
-
`);return{content:W>0?H:X,displayText:X}}canSendUpdates(){return!this.destroyed&&!this.connection.signal.aborted&&!this.updateEgress.stats().closed}async sendUpdateAndWait(z){if(!this.canSendUpdates())return!1;let J=this.updateEgress.offer({sessionId:this.id,update:z});if(!J.accepted)return!1;try{return await J.completion,this.canSendUpdates()}catch{return!1}}goalSessionUpdate(z){return{sessionUpdate:"session_info_update",updatedAt:z.updatedAt,_meta:{"blade/goal":{goalId:z.goalId,status:z.status,verificationAttempt:z.completionVerification?.attempt,verificationStatus:z.completionVerification?.status,verifierSessionId:z.completionVerification?.verifierSessionId,verificationEvidenceSha256:z.completionVerification?.evidenceSha256}}}}sendUpdate(z){if(!this.canSendUpdates())return;this.updateEgress.offer({sessionId:this.id,update:z})}async flushUpdates(){if(!this.canSendUpdates())return!1;try{return await this.updateEgress.flush(),this.canSendUpdates()}catch{return!1}}handleUpdateEgressFailure(z){if(this.destroyed)return;F.warn(`[AcpSession ${this.id}] Update egress closed: kind=${z.kind}`),this.pendingPrompt?.abort("acp-egress-failed"),this.pendingUserShell?.abort("acp-egress-failed")}sendPlanUpdate(z){let J=z.map((H)=>({content:H.subject,priority:H.priority,status:H.status}));F.debug(`[AcpSession ${this.id}] Sending plan update with ${J.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:J})}async requestPermission(z){let J=this.pendingPrompt?.signal;if(z.type==="askUserQuestion")return this.requestUserQuestions(z,J);if(z.type==="mcpElicitation")return this.requestMcpElicitation(z,J);let H=z.kind?.toLowerCase()||"execute";if(z.type!=="mcpSampling"&&this.shouldAutoApprove(H))return F.debug(`[AcpSession ${this.id}] Auto-approving ${H} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(H==="write"||H==="execute"))return F.debug(`[AcpSession ${this.id}] Rejecting ${H} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};try{let W=b(),Y=[];if(z.message)Y.push({type:"content",content:{type:"text",text:z.message}});if(z.details)Y.push({type:"content",content:{type:"text",text:z.details}});if(z.risks&&z.risks.length>0)Y.push({type:"content",content:{type:"text",text:`Risks:
|
|
17
|
-
- ${z.risks.join(`
|
|
18
|
-
- `)}`}});let $=this.mapToolKind(H),Z={sessionId:this.id,options:z.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:W,status:"pending",title:z.title||"Permission Required",content:Y,kind:$}},X=await this.waitForClientInteraction(this.connection.requestPermission(Z),J);if(!X)return{approved:!1,reason:M};let j=X.outcome;if(j.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let B=j.optionId;if(B==="allow_always")return{approved:!0,scope:"project"};if(B==="reject_always")return{approved:!1,scope:"project",reason:"User permanently denied the permission request"};let L=B==="allow_once";return{approved:L,scope:"once",reason:L?void 0:"User denied the operation"}}catch(W){return F.warn(`[AcpSession ${this.id}] Permission request failed:`,W),{approved:!1,reason:"Permission request failed"}}}async requestUserQuestions(z,J){let H=z.questions??[];if(H.length===0)return{approved:!1,reason:"No structured questions were provided"};if(H.some((Y)=>Y.multiSelect))return{approved:!1,reason:"ACP does not support multi-select question responses"};let W={};try{for(let[Y,$]of H.entries()){let Z=$.options.map((L,D)=>`answer:${Y}:${D}`),X=`answer:${Y}:cancel`,j=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...$.options.map((L,D)=>({optionId:Z[D],name:L.label,kind:"allow_once"})),{optionId:X,name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:b(),status:"pending",title:$.header,kind:"think",content:[{type:"content",content:{type:"text",text:[$.question,...$.options.map((L)=>`${L.label}: ${L.description}`)].join(`
|
|
19
|
-
`)}}]}}),J);if(!j)return{approved:!1,reason:M};if(j.outcome.outcome!=="selected")return{approved:!1,reason:"User cancelled the question prompt"};let B=Z.indexOf(j.outcome.optionId);if(B<0)return{approved:!1,reason:"User cancelled the question prompt"};W[$.header]=$.options[B].label}return{approved:!0,answers:W}}catch(Y){return F.warn(`[AcpSession ${this.id}] Question request failed:`,Y),{approved:!1,reason:"Question request failed"}}}async requestMcpElicitation(z,J){let H=z.mcpElicitation;if(!H)return{approved:!1,reason:"MCP elicitation details are missing",elicitation:{action:"cancel"}};try{if(H.mode==="url"){let Y=await this.requestElicitationChoice("MCP external authorization",[H.message,`Server: ${H.serverName}`,`Domain: ${H.domain??"unknown"}`,`URL: ${H.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"}],J);if(Y==="accept")return{approved:!0,elicitation:{action:"accept"}};return{approved:!1,reason:Y==="decline"?"User declined URL":"User cancelled",elicitation:{action:Y==="decline"?"decline":"cancel"}}}let W=Object.create(null);for(let Y of H.fields??[]){let $=await this.collectAcpElicitationField(Y,J);if($.cancelled)return{approved:!1,reason:$.reason,elicitation:{action:"cancel"}};if($.value!==void 0)W[Y.name]=$.value}return{approved:!0,elicitation:{action:"accept",content:W}}}catch(W){return F.warn(`[AcpSession ${this.id}] MCP elicitation failed:`,W),{approved:!1,reason:"MCP elicitation failed",elicitation:{action:"cancel"}}}}async collectAcpElicitationField(z,J){if(z.type==="select"||z.type==="boolean"){let H=z.type==="boolean"?[{id:"true",label:"Yes",value:!0},{id:"false",label:"No",value:!1}]:(z.options??[]).map(($,Z)=>({id:`option:${Z}`,label:$.label,value:$.value})),W=await this.requestElicitationChoice(z.title,[z.description,z.required?"Required":"Optional"].filter(Boolean).join(`
|
|
21
|
-
`),[...H.map(($)=>({id:$.id,label:$.label})),...!z.required?[{id:"skip",label:"Skip"}]:[]],J);if(W==="skip")return{cancelled:!1};let Y=H.find(($)=>$.id===W);if(!Y)return{cancelled:!0,reason:"User cancelled MCP elicitation"};return{cancelled:!1,value:Y.value}}if(z.defaultValue!==void 0){let H=await this.requestElicitationChoice(z.title,[z.description,`ACP cannot collect ${z.type} input. Use the server default: ${String(z.defaultValue)}?`].filter(Boolean).join(`
|
|
22
|
-
`),[{id:"default",label:"Use default"},...!z.required?[{id:"skip",label:"Skip"}]:[]],J);if(H==="default")return{cancelled:!1,value:z.defaultValue};if(H==="skip")return{cancelled:!1};return{cancelled:!0,reason:"User cancelled MCP elicitation"}}if(!z.required)return{cancelled:!1};return{cancelled:!0,reason:`ACP cannot collect required ${z.type} field "${z.name}"`}}async requestElicitationChoice(z,J,H,W){let Y=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...H.map(($)=>({optionId:$.id,name:$.label,kind:"allow_once"})),{optionId:"cancel",name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:b(),status:"pending",title:z,kind:"think",content:[{type:"content",content:{type:"text",text:J}}]}}),W);return Y?.outcome.outcome==="selected"?Y.outcome.optionId:void 0}async waitForClientInteraction(z,J){if(!J)return z;if(J.aborted)return;return new Promise((H,W)=>{let Y=!1,$=(X)=>{if(Y)return;Y=!0,J.removeEventListener("abort",Z),X()},Z=()=>$(()=>H(void 0));if(J.addEventListener("abort",Z,{once:!0}),J.aborted)Z();z.then((X)=>$(()=>H(X)),(X)=>$(()=>W(X)))})}mapToolKind(z){return{readonly:"read",write:"edit",execute:"execute",read:"read",edit:"edit",delete:"delete",move:"move",search:"search",think:"think",fetch:"fetch"}[z||""]||"other"}}var A=x("Agent");class C{connection;sessions=new Map;sessionLoadQueues=new Map;runtimeResidencyValue;clientCapabilities;destroyed=!1;destroyPromise;constructor(z){this.connection=z}get runtimeResidency(){if(!this.runtimeResidencyValue){let z=Uz();this.runtimeResidencyValue=new Rz({maxResident:z?.maxResidentSessionRuntimes??Lz,idleMs:z?.sessionRuntimeIdleMs??Gz})}return this.runtimeResidencyValue}async reserveSessionRuntime(z){try{return await this.runtimeResidency.reserve(z,{surface:"acp",allowEviction:!1})}catch(J){if(J instanceof Oz)throw hz.internalError({resource:J.resource,limit:J.limit,retryable:J.retryable},J.message);throw J}}async initialize(z){return A.info("[BladeAgent] Initializing ACP connection"),A.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(z.clientCapabilities)}`),this.clientCapabilities=z.clientCapabilities,await Vz(),{protocolVersion:yz,agentCapabilities:{loadSession:!0,sessionCapabilities:{list:{},fork:{},close:{}},promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0}}}}async authenticate(z){return}async newSession(z){this.assertNotDestroyed();let J=I("acp"),H=await this.reserveSessionRuntime(J),W=z.cwd||Bz(),Y=z._meta?.["blade/taskIsolation"],$=Y==="local"||Y==="worktree"?Y:void 0,Z=z._meta?.["blade/taskPrompt"],X;try{let j=$?await Kz.createSessionTask({sessionId:J,prompt:typeof Z==="string"&&Z.trim()?Z:"ACP task session",sourceProjectPath:W,isolation:$}):void 0,B=j?.metadata.projectPath??W;return A.info(`[BladeAgent] Creating new session: ${J}`),A.debug(`[BladeAgent] Session cwd: ${B}`),X=new q(J,B,this.connection,this.clientCapabilities,{mcpServers:z.mcpServers,...j?.taskWorktree?{taskWorktree:j.taskWorktree}:{},...j?.metadata.taskIsolation?{taskIsolation:j.metadata.taskIsolation}:{}}),await X.initialize(),this.assertNotDestroyed(),this.commitSession(J,X,H),A.info(`[BladeAgent] Session ${J} created, scheduling available commands update`),X.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(J,j?.metadata,X.getModelConfiguration())}catch(j){throw H.cancel(),await X?.destroy().catch(()=>{return}),j}}async listSessions(z){if(z.cwd!=null&&!jz.isAbsolute(z.cwd))throw Error("ACP session list cwd must be absolute");let J=await G.listSessionPage({cwd:z.cwd??void 0,cursor:z.cursor??void 0,limit:50,includeSubagents:!1});return{sessions:J.sessions.map((H)=>({sessionId:H.sessionId,cwd:H.projectPath,title:H.title??null,updatedAt:H.lastMessageTime,_meta:{"blade/taskStatus":H.taskStatus,...H.taskStatusReason?{"blade/taskStatusReason":H.taskStatusReason}:{},...H.taskFailure?{"blade/taskFailure":H.taskFailure}:{},...H.taskStartedAt?{"blade/taskStartedAt":H.taskStartedAt}:{},...H.taskCompletedAt?{"blade/taskCompletedAt":H.taskCompletedAt}:{},...H.taskModelId?{"blade/taskModelId":H.taskModelId}:{},...H.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...H.taskRetriedFrom?{"blade/taskRetriedFrom":H.taskRetriedFrom}:{},...H.taskDelivery?{"blade/taskDelivery":H.taskDelivery}:{},...H.taskIsolation?{"blade/taskIsolation":H.taskIsolation}:{},...H.taskSourceProjectPath?{"blade/taskSourceProjectPath":H.taskSourceProjectPath}:{},...H.taskWorktreeBranch?{"blade/taskWorktreeBranch":H.taskWorktreeBranch}:{},...H.taskBaseCommit?{"blade/taskBaseCommit":H.taskBaseCommit}:{},...H.taskDiffStat?{"blade/taskDiffStat":H.taskDiffStat}:{},...H.taskQueuePosition?{"blade/taskQueuePosition":H.taskQueuePosition}:{},...H.taskQueueDepth!==void 0?{"blade/taskQueueDepth":H.taskQueueDepth}:{},...H.taskConcurrencyLimit!==void 0?{"blade/taskConcurrencyLimit":H.taskConcurrencyLimit}:{}}})),nextCursor:J.nextCursor}}async unstable_forkSession(z){if(this.assertNotDestroyed(),!jz.isAbsolute(z.cwd))throw Error("ACP session fork cwd must be absolute");let J=I("fork"),H=await this.reserveSessionRuntime(J),W;try{let Y=await G.forkSession(z.sessionId,{sourceProjectPath:z.cwd,targetProjectPath:z.cwd,newSessionId:J});return this.assertNotDestroyed(),W=new q(Y.sessionId,z.cwd,this.connection,this.clientCapabilities,{initialMessages:Y.messages,permissionMode:Y.metadata.permissionMode,mcpServers:z.mcpServers}),await W.initialize(),this.assertNotDestroyed(),this.commitSession(Y.sessionId,W,H),W.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Y.sessionId,Y.metadata,W.getModelConfiguration())}catch(Y){throw H.cancel(),await W?.destroy().catch(()=>{return}),Y}}async loadSession(z){this.assertNotDestroyed(),A.info(`[BladeAgent] Loading session: ${z.sessionId}`);let H=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.replaceSession(z)),W=H.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,W);try{return await H}finally{if(this.sessionLoadQueues.get(z.sessionId)===W)this.sessionLoadQueues.delete(z.sessionId)}}async replaceSession(z){this.assertNotDestroyed(),await G.assertSessionWritable(z.sessionId,z.cwd),await this.closeResidentSession(z.sessionId);let J=await this.reserveSessionRuntime(z.sessionId),H;try{let[W,Y]=await Promise.all([G.loadSession(z.sessionId,z.cwd),G.findSessionMetadata(z.sessionId,z.cwd)]);if(!Y)throw Error(`Session not found: ${z.sessionId}`);return H=new q(z.sessionId,z.cwd,this.connection,this.clientCapabilities,{initialMessages:W,permissionMode:Y.permissionMode,mcpServers:z.mcpServers}),await H.initialize(),await H.replayHistory(),this.assertNotDestroyed(),this.commitSession(z.sessionId,H,J),H.sendAvailableCommandsDelayed(),this.buildSessionSetup(H.getModelConfiguration(),H.getMode())}catch(W){throw J.cancel(),await H?.destroy().catch(()=>{return}),W}}commitSession(z,J,H){let W=H.commit({key:z,surface:"acp",value:J,canEvict:()=>J.isIdleForResidency(),dispose:async()=>{if(this.sessions.get(z)===J)this.sessions.delete(z);await J.destroy()}});this.sessions.set(z,J),W.release()}async closeResidentSession(z,J={}){let H=this.sessions.get(z);if(!H)return;let W=this.runtimeResidency.owns(z,H),Y;try{await H.destroy(J)}catch(Z){Y=Z}let $=await this.runtimeResidency.forget(z,H);if(this.sessions.get(z)===H)this.sessions.delete(z);if(W&&!$&&Y===void 0)throw Error(`ACP Session is still active: ${z}`);if(Y!==void 0)throw Y}buildChildSessionResponse(z,J,H){return{sessionId:z,...this.buildSessionSetup(H,J?.permissionMode==="autoEdit"?"auto-edit":J?.permissionMode),...J?{_meta:{"blade/taskIsolation":J.taskIsolation,"blade/taskSourceProjectPath":J.taskSourceProjectPath,"blade/taskProjectPath":J.projectPath,...J.taskModelId?{"blade/taskModelId":J.taskModelId}:{},...J.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...J.taskRetriedFrom?{"blade/taskRetriedFrom":J.taskRetriedFrom}:{},...J.taskDelivery?{"blade/taskDelivery":J.taskDelivery}:{},...J.taskWorktreeBranch?{"blade/taskWorktreeBranch":J.taskWorktreeBranch}:{},...J.taskBaseCommit?{"blade/taskBaseCommit":J.taskBaseCommit}:{}}}:{}}}assertNotDestroyed(){if(this.destroyed)throw Error("BladeAgent is destroyed")}getRuntimeResidencyStats(){return this.runtimeResidency.getStats()}buildSessionSetup(z,J="default"){let H=z?.models??[],W=(z?.currentModelId&&H.some((Z)=>Z.id===z.currentModelId)?z.currentModelId:void 0)??H[0]?.id,Y=[{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"}],$=[];if(H.length>0)$.push({type:"select",id:"model",name:"Model",description:"Active language model",category:"model",currentValue:W,options:H.map((Z)=>({value:Z.id,name:Z.displayName??Z.model,description:`${z?.modelProviders[Z.provider]?.name??Z.provider} · ${Z.model}`}))});if(z?.reasoning)$.push({type:"select",id:"reasoning_effort",name:"Reasoning effort",description:"Session-owned model reasoning intensity",category:"model",currentValue:z.reasoning.selection,options:[{value:"auto",name:"Auto",description:`Resolve near high for this model (currently ${z.reasoning.effective})`},...z.reasoning.supported.map((Z)=>({value:Z,name:Z[0].toUpperCase()+Z.slice(1),description:Z==="off"?"Disable model reasoning":`Use ${Z} reasoning effort`}))]});if(z?.serviceTier)$.push({type:"select",id:"service_tier",name:"Service tier",description:"Session-owned provider latency and pricing tier",category:"model",currentValue:z.serviceTier.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default tier"},...z.serviceTier.supported.map((Z)=>({value:Z,name:Z[0].toUpperCase()+Z.slice(1),description:Z==="fast"?"Use the provider priority tier":Z==="flex"?"Use the lower-cost flexible tier":"Use the standard provider tier"}))]});if(z?.responseVerbosity)$.push({type:"select",id:"response_verbosity",name:"Response verbosity",description:"Session-owned model response detail",category:"model",currentValue:z.responseVerbosity.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default verbosity"},...z.responseVerbosity.supported.map((Z)=>({value:Z,name:Z[0].toUpperCase()+Z.slice(1),description:`Use ${Z} response verbosity`}))]});if(z?.communicationStyle)$.push({type:"select",id:"communication_style",name:"Communication style",description:"Session-owned tone and explanatory framing",category:"model",currentValue:z.communicationStyle.selection,options:z.communicationStyle.supported.map((Z)=>({value:Z.id,name:Z.name,description:`${Z.description} · ${Z.source}`}))});return{modes:{availableModes:Y,currentModeId:J},configOptions:$.length>0?$:void 0}}async closeSession(z){this.assertNotDestroyed();let H=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.closeResidentSession(z.sessionId,{discardPendingInput:!0})),W=H.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,W);try{await H}finally{if(this.sessionLoadQueues.get(z.sessionId)===W)this.sessionLoadQueues.delete(z.sessionId)}}async prompt(z){let J=this.runtimeResidency.acquire(z.sessionId);if(!J)throw Error(`Session not found: ${z.sessionId}`);try{return await J.value.prompt(z)}finally{J.release()}}async cancel(z){A.info(`[BladeAgent] Cancel notification received for session: ${z.sessionId}`);let J=this.runtimeResidency.acquire(z.sessionId);if(J){A.info("[BladeAgent] Found session, calling session.cancel()");try{J.value.cancel()}finally{J.release()}}else A.warn(`[BladeAgent] Session not found for cancel: ${z.sessionId}`)}async setSessionMode(z){A.info(`[BladeAgent] Setting session mode: ${z.modeId}`);let J=this.runtimeResidency.acquire(z.sessionId);if(J)try{await J.value.setMode(z.modeId)}finally{J.release()}return{}}async setSessionConfigOption(z){let J=this.runtimeResidency.acquire(z.sessionId);if(!J)throw Error(`Session not found: ${z.sessionId}`);try{let H=J.value;if(z.configId==="model"&&"value"in z&&typeof z.value==="string")A.info(`[BladeAgent] Setting session model: ${z.value}`),await H.setModel(z.value);else if(z.configId==="reasoning_effort"&&"value"in z&&wz(z.value))A.info(`[BladeAgent] Setting reasoning effort: ${z.value}`),await H.setReasoningEffort(z.value);else if(z.configId==="service_tier"&&"value"in z&&Fz(z.value))A.info(`[BladeAgent] Setting service tier: ${z.value}`),await H.setServiceTier(z.value);else if(z.configId==="response_verbosity"&&"value"in z&&Dz(z.value))A.info(`[BladeAgent] Setting response verbosity: ${z.value}`),await H.setResponseVerbosity(z.value);else if(z.configId==="communication_style"&&"value"in z&&_z(z.value))A.info(`[BladeAgent] Setting communication style: ${z.value}`),await H.setCommunicationStyle(z.value);else throw Error(`Invalid session config option: ${z.configId}`);return{configOptions:this.buildSessionSetup(H.getModelConfiguration(),H.getMode()).configOptions??[]}}finally{J.release()}}destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=this.destroyOwnedResources(),this.destroyPromise}async destroyOwnedResources(){this.destroyed=!0,await Promise.all([...this.sessionLoadQueues.values()]),this.sessionLoadQueues.clear();let z;for(let J of[...this.sessions.keys()])try{await this.closeResidentSession(J)}catch(H){z??=H}try{await this.runtimeResidency.disposeAll()}catch(J){z??=J}this.sessions.clear();try{await Az.getInstance().disconnectAll()}catch(J){z??=J}if(z!==void 0)throw z}}async function NH(){let z=kz.toWeb(process.stdout),J=Mz.toWeb(process.stdin),H=S.ndJsonStream(z,J),W,Y=new S.AgentSideConnection((Z)=>{return W=new C(Z),W},H),$=Nz(async()=>{await W?.destroy()});try{await Y.closed}finally{$(),await W?.destroy()}}export{NH as runAcpIntegration};
|
package/dist/chunk-avhwgbg0.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Zc as a,_c as b}from"./chunk-81pdgcq7.js";import"./chunk-5g2p1fwn.js";import"./chunk-av10vmxk.js";export{a as globalOptions,b as cliConfig};
|
package/dist/chunk-bcp7nwwy.js
DELETED
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import{f as T,g as W,h as X,i as Y}from"./chunk-bjz7t9fe.js";import"./chunk-83wm4akj.js";import"./chunk-eeac8teg.js";import"./chunk-pdys123h.js";import"./chunk-egb457mv.js";import"./chunk-wy2b5hsh.js";import"./chunk-wqewxnez.js";import"./chunk-3m640njb.js";import"./chunk-qs4erqd0.js";import"./chunk-y78m734s.js";import"./chunk-9r0yebs1.js";import"./chunk-jy1e6ve5.js";import"./chunk-2z3xe3rw.js";import"./chunk-wwsg165p.js";import{ed as R}from"./chunk-rctbavme.js";import"./chunk-3tednchw.js";import{Ad as Q}from"./chunk-2m7at619.js";import"./chunk-v508x7cg.js";import"./chunk-wy4pn9sk.js";import"./chunk-0jxh2zq5.js";import"./chunk-j9snkjpe.js";import"./chunk-69rc9hw6.js";import"./chunk-d9z0rbz1.js";import"./chunk-pxy15vf3.js";import"./chunk-d1t91jgz.js";import"./chunk-detkh4dd.js";import"./chunk-2xbmkyb2.js";import"./chunk-6fwh0m6d.js";import"./chunk-87jz5600.js";import"./chunk-7p0bzza4.js";import"./chunk-khkhsaan.js";import"./chunk-7b467h8k.js";import"./chunk-9kmtcgm6.js";import"./chunk-kjvntyr5.js";import"./chunk-8ekk8pa7.js";import"./chunk-y8r2knxm.js";import"./chunk-1jc7d3nt.js";import"./chunk-fp1h8wdh.js";import{Zg as M}from"./chunk-5g2p1fwn.js";import"./chunk-ej6h16ae.js";import"./chunk-cm9mph7j.js";import"./chunk-cz68x56m.js";import"./chunk-av10vmxk.js";import m from"chalk";import K from"open";var A=`
|
|
2
|
-
____ _ _
|
|
3
|
-
| __ )| | __ _ __| | ___
|
|
4
|
-
| _ \\| |/ _\` |/ _\` |/ _ \\
|
|
5
|
-
| |_) | | (_| | (_| | __/
|
|
6
|
-
|____/|_|\\__,_|\\__,_|\\___|
|
|
7
|
-
`,C={command:"web",describe:"Start Blade server and open web interface",builder:T,handler:async(Z)=>{let H=W(Z);if(await Q(),!process.env.BLADE_SERVER_PASSWORD)console.log(m.yellow("[WARN] BLADE_SERVER_PASSWORD is not set; server is unsecured.")),console.log(m.gray(` Set this environment variable to enable Basic Auth.
|
|
8
|
-
`));let F=await Y.listenAsync(H);if(console.log(m.cyan(A)),console.log(m.gray(` v${M()}
|
|
9
|
-
`)),H.hostname==="0.0.0.0"){let q=`http://localhost:${F.port}`;console.log(m.blue.bold(" Local access: "),m.white(q));let x=X();for(let z of x)console.log(m.blue.bold(" Network access: "),m.white(`http://${z}:${F.port}`));K(q).catch(()=>{})}else{let q=F.url.toString();console.log(m.blue.bold(" Web interface: "),m.white(q)),K(q).catch(()=>{})}console.log(""),console.log(m.gray(` Press Ctrl+C to stop the server.
|
|
10
|
-
`));let J,$=new Promise((q)=>{J=q}),b=R(async()=>{await F.stop(),J()});try{await $}finally{b(),await F.stop()}}};export{C as webCommand};
|
package/dist/chunk-bjz7t9fe.js
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import{j as z4,k as X4}from"./chunk-83wm4akj.js";import{l as tO}from"./chunk-eeac8teg.js";import{s as xO,t as m1}from"./chunk-pdys123h.js";import{u as p0}from"./chunk-egb457mv.js";import{A as c$,v as k1,w as d$,x as p$,y as l$,z as s0}from"./chunk-wy2b5hsh.js";import{$ as s1,C as B4,F as j1,G as zO,H as A$,I as iO,J as V$,K as C0,L as W$,M as e0,N as AO,Q as qO,R as kO,T as C1,U as b1,V as q1,W as i1,X as a1,Y as o1,Z as n1,_ as t1,aa as r1,ba as e1,ca as O4,fa as Y4,ia as P4,na as L4}from"./chunk-wqewxnez.js";import{qa as x1,wa as F0}from"./chunk-3m640njb.js";import{Ba as A4,Ca as M4,Da as S1,Ea as I1,Fa as E4,Ga as M$,Ha as T4,Ia as i0,Ja as K4,Ka as N4,La as V4,Ma as P1,Na as f1,Oa as y1,Pa as g$,Qa as C$,ya as $$}from"./chunk-qs4erqd0.js";import{$a as R1,Xa as f0,Ya as v,_a as C,nb as N$,wb as l0}from"./chunk-y78m734s.js";import{Fb as L1}from"./chunk-9r0yebs1.js";import{Ac as G$,Bc as K$,Cc as q,Yb as w1,_b as aO,ec as CO,fc as D$,gc as bO,ic as A1,oc as M1,pc as E1,rc as QO,uc as X$,zc as T1}from"./chunk-jy1e6ve5.js";import{Dd as Y1,Kd as L0,zd as x0}from"./chunk-2m7at619.js";import{Ld as z$}from"./chunk-wy4pn9sk.js";import{Zd as H1}from"./chunk-69rc9hw6.js";import{$d as cO}from"./chunk-d9z0rbz1.js";import{Be as d4,ie as U4,le as c1,pe as BO,qe as LO,ue as u4,xe as E0,ye as wO}from"./chunk-pxy15vf3.js";import{Je as z1,Ke as B1}from"./chunk-detkh4dd.js";import{Oe as r$,Pe as OO}from"./chunk-6fwh0m6d.js";import{Cf as D1,Ef as _1,Rf as e$,Wf as HO,ff as $1,zf as U1}from"./chunk-7p0bzza4.js";import{Zf as Y$}from"./chunk-khkhsaan.js";import{_f as g,ag as U,dg as W0}from"./chunk-7b467h8k.js";import{fg as oO}from"./chunk-9kmtcgm6.js";import{kg as i}from"./chunk-kjvntyr5.js";import{Lg as a}from"./chunk-y8r2knxm.js";import{Rg as d0}from"./chunk-1jc7d3nt.js";import{Tg as Q1,Ug as W1,Wg as Z1,Xg as F1}from"./chunk-fp1h8wdh.js";import{Zg as r0}from"./chunk-5g2p1fwn.js";import{dh as R$}from"./chunk-ej6h16ae.js";import{ih as dO,mh as a$}from"./chunk-cz68x56m.js";import{ph as E$}from"./chunk-av10vmxk.js";var d5={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function p5(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{existsSync as b$,readFileSync as fO}from"node:fs";import{createServer as B5}from"node:http";import{networkInterfaces as L5}from"node:os";import{dirname as w5,extname as A5,join as g0}from"node:path";import{fileURLToPath as M5}from"node:url";import{brotliCompressSync as E5,gzipSync as T5,constants as j5}from"node:zlib";import{Hono as R5}from"hono";import{cors as C5}from"hono/cors";import{WebSocketServer as b5}from"ws";var t0=a("Service"),c4=30000,i4=new Set(["completed","failed","cancelled","interrupted"]);class x${dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor(O){this.dispatch=O.dispatch,this.store=O.store??g$.getInstance(),this.tickMs=O.tickMs??c4}start(){if(this.timer)return;t0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=C.subscribe((O)=>{if(O.type!=="task.status")return;let $=O.properties.taskStatus;if(typeof $!=="string"||!i4.has($))return;this.recordTerminalStatus(O.sessionId,$,typeof O.properties.taskStatusReason==="string"?O.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,t0.info("[TaskScheduler] Stopped scheduler tick loop")}async tick(O=new Date){if(this.ticking)return;this.ticking=!0;try{let $=await this.store.list();for(let x of $)await this.evaluate(x,O)}catch($){t0.warn("[TaskScheduler] Tick failed:",$)}finally{this.ticking=!1}}async evaluate(O,$){if(!O.enabled)return;if(this.inFlight.has(O.id))return;if(O.expiresAt&&new Date(O.expiresAt).getTime()<=$.getTime()){await this.store.update(O.id,{enabled:!1,nextRunAt:null}),t0.info(`[TaskScheduler] Schedule ${O.id} expired; disabled`);return}if(!O.nextRunAt)return;if(!(new Date(O.nextRunAt).getTime()<=$.getTime()))return;await this.fire(O,$)}async fire(O,$=new Date,x={}){if(this.inFlight.has(O.id))throw Error(`Schedule ${O.id} is already dispatching`);this.inFlight.add(O.id);let J=$.toISOString();try{let Q=await this.dispatch({prompt:O.prompt,title:O.title??a4(O),sourceProjectPath:O.projectPath,isolation:O.dispatch.isolation??"worktree",permissionMode:O.dispatch.permissionMode??"default",modelId:O.dispatch.modelId,reasoningEffort:O.dispatch.reasoningEffort,serviceTier:O.dispatch.serviceTier,responseVerbosity:O.dispatch.responseVerbosity,communicationStyle:O.dispatch.communicationStyle}),X=O.trigger.kind==="once"?null:x.manual?O.nextRunAt?new Date(O.nextRunAt):null:$$(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:J,lastRunSessionId:Q.session.sessionId,lastStatus:Q.status,lastError:void 0,runCount:O.runCount+1,nextRunAt:X?X.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled}),C.publish({sessionId:Q.session.sessionId,projectPath:O.projectPath},"schedule.fired",{scheduleId:O.id,firedAt:J,sessionId:Q.session.sessionId,runId:Q.runId,status:Q.status}),t0.info(`[TaskScheduler] Fired schedule ${O.id} -> session ${Q.session.sessionId} (${Q.status})`)}catch(Q){let X=Q instanceof Error?Q.message:String(Q);t0.warn(`[TaskScheduler] Schedule ${O.id} dispatch failed:`,Q);let Y=O.trigger.kind==="once"?null:x.manual?O.nextRunAt?new Date(O.nextRunAt):null:$$(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:J,lastStatus:"error",lastError:X,nextRunAt:Y?Y.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled})}finally{this.inFlight.delete(O.id)}}async recordTerminalStatus(O,$,x){let Q=(await this.store.list()).find((X)=>X.lastRunSessionId===O);if(!Q)return;await this.store.update(Q.id,{lastStatus:$,...x?{lastError:x}:{lastError:void 0}})}}function a4(O){return`Scheduled: ${O.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class Q0 extends Error{code;statusCode;details;constructor(O,$,x=500,J){super($);this.code=O;this.statusCode=x;this.details=J;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class m extends Q0{constructor(O,$){super("NOT_FOUND",$?`${O} not found: ${$}`:`${O} not found`,404)}}class L extends Q0{constructor(O){super("BAD_REQUEST",O,400)}}class b extends Q0{constructor(O){super("CONFLICT",O,409)}}class k0 extends Q0{constructor(O,$){super("TOO_MANY_REQUESTS",O,429,$)}}class u0 extends Q0{constructor(O="Server is shutting down"){super("SERVICE_UNAVAILABLE",O,503)}}class B0 extends Q0{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class e extends Q0{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var s5=U.Object({error:U.Object({code:U.String(),message:U.String(),details:U.Optional(U.Record(U.String(),U.Unknown()))})});import{Hono as o4}from"hono";var J$=a("Service"),n4=U.Object({updates:U.Record(U.String(),U.Any()),options:U.Optional(U.Object({scope:U.Optional(W0(["local","project","global"])),immediate:U.Optional(U.Boolean())}))});function t4(O){return{currentModelId:O.currentModelId,permissionMode:O.permissionMode,language:O.language,codeTheme:O.codeTheme,uiTheme:O.uiTheme,autoSaveSessions:O.autoSaveSessions,notifyBuild:O.notifyBuild,notifyErrors:O.notifyErrors,notifySounds:O.notifySounds,privacyTelemetry:O.privacyTelemetry,privacyCrash:O.privacyCrash,communicationStyle:O.communicationStyle,maxConcurrentTasks:O.maxConcurrentTasks,maxQueuedTasks:O.maxQueuedTasks,maxQueuedTaskBytes:O.maxQueuedTaskBytes,maxResidentSessionRuntimes:O.maxResidentSessionRuntimes,sessionRuntimeIdleMs:O.sessionRuntimeIdleMs}}var v$=()=>{let O=new o4;return O.get("/",async($)=>{try{let x=x0();return $.json(x?t4(x):{})}catch(x){return J$.error("[ConfigRoutes] Failed to get config:",x),$.json({})}}),O.put("/",async($)=>{try{let x=await $.req.json(),J=g(n4,x);if(!J.success)throw new L("Invalid config update format");let{updates:Q,options:X}=J.data;return await L0().updateConfig(Q,X),$.json({success:!0,updates:Q})}catch(x){throw J$.error("[ConfigRoutes] Failed to update config:",x),x}}),O.get("/permissions",async($)=>{try{let x=x0();return $.json(x?.permissions||{})}catch(x){return J$.error("[ConfigRoutes] Failed to get permissions:",x),$.json({})}}),O};import{Hono as s4}from"hono";import{streamSSE as r4}from"hono/streaming";function u$(O){let $="";if(O.id!==void 0)$+=`id: ${O.id}
|
|
2
|
-
`;if(O.event!==void 0)$+=`event: ${O.event}
|
|
3
|
-
`;for(let x of O.data.split(/\r\n|\r|\n/))$+=`data: ${x}
|
|
4
|
-
`;if(O.retry!==void 0)$+=`retry: ${O.retry}
|
|
5
|
-
`;return $+=`
|
|
6
|
-
`,Buffer.byteLength($)}class DO{serial;buffered=[];bufferedBytes=0;nextOrder=0;phase="buffering";highestDeliveredSequence=0;highestReplaySequence=0;failure;maxPendingItems;maxPendingBytes;constructor(O){this.maxPendingItems=O.maxPendingItems??d$,this.maxPendingBytes=O.maxPendingBytes??p$,this.serial=new c$({maxPendingItems:this.maxPendingItems,maxPendingBytes:this.maxPendingBytes,writeTimeoutMs:O.writeTimeoutMs??l$,sizeOf:u$,write:O.write,onFailure:($)=>{this.failure=$,this.phase="closed",this.buffered.length=0,this.bufferedBytes=0,O.onFailure?.($)}})}async writeInitial(O){await this.offerDirect(O)}observe(O,$){if(this.phase==="closed")return;if(this.phase==="buffering"){this.buffer(O,$);return}this.offerLive(O,$)}async writeReplay(O,$){if(!Number.isSafeInteger($)||$<=0)throw this.fail(new s0("invalid_size","SSE committed sequence must be a positive safe integer")),this.currentFailure();if($<=this.highestReplaySequence)return;await this.offerDirect(O),this.highestReplaySequence=$,this.highestDeliveredSequence=$}finishInitialization(O){if(this.phase!=="buffering")return;let $=this.buffered.splice(0);this.bufferedBytes=0,this.phase="live";let x=O.replayed?$.filter((Q)=>Q.sequence!==void 0&&Q.sequence>this.highestReplaySequence).sort((Q,X)=>Q.sequence-X.sequence||Q.order-X.order):$.sort((Q,X)=>Q.order-X.order),J;for(let Q of x){if(O.replayed&&Q.sequence!==void 0&&Q.sequence===J)continue;if(this.offerLive(Q.message,Q.sequence),this.serial.stats().closed)return;J=Q.sequence}}offerHeartbeat(O){if(this.phase!=="live"||this.buffered.length>0||this.serial.stats().pendingItems>0)return!1;return this.offerLive(O),!this.serial.stats().closed}async flush(){await this.serial.flush()}close(O){if(this.phase==="closed")return;this.phase="closed",this.buffered.length=0,this.bufferedBytes=0,this.serial.close(O)}stats(){let O=this.serial.stats();return{closed:this.phase==="closed",pendingItems:O.pendingItems+this.buffered.length,pendingBytes:O.pendingBytes+this.bufferedBytes,bufferedItems:this.buffered.length,bufferedBytes:this.bufferedBytes}}buffer(O,$){let x=u$(O),J=this.serial.stats();if(x>this.maxPendingBytes){this.fail(new s0("oversized",`SSE frame requires ${x} bytes; limit is ${this.maxPendingBytes}`,{pendingItems:J.pendingItems+this.buffered.length,pendingBytes:J.pendingBytes+this.bufferedBytes}));return}if(J.pendingItems+this.buffered.length>=this.maxPendingItems||J.pendingBytes+this.bufferedBytes+x>this.maxPendingBytes){this.fail(new s0("overflow","SSE initialization buffer limit exceeded",{pendingItems:J.pendingItems+this.buffered.length,pendingBytes:J.pendingBytes+this.bufferedBytes}));return}this.nextOrder+=1,this.buffered.push({message:O,bytes:x,sequence:$,order:this.nextOrder}),this.bufferedBytes+=x}offerLive(O,$){if($!==void 0){if($<=this.highestReplaySequence)return;if($<=this.highestDeliveredSequence){this.fail(new s0("write_failed","SSE committed sequence regressed"));return}this.highestDeliveredSequence=$}if(!this.serial.offer(O).accepted)this.phase="closed"}async offerDirect(O){if(this.phase==="closed")throw this.currentFailure();let $=this.serial.offer(O);if(!$.accepted)throw this.phase="closed",$.error;await $.completion}fail(O){this.serial.close(O)}currentFailure(){return this.failure??new s0("closed","SSE egress is closed")}}var e4=15000,O2=a("Service"),$2=new Set(["task.status","task.delivery","session.created","session.updated","session.deleted","schedule.fired","permission.asked","question.required","elicitation.required","interaction.resolved"]),x2=new Set(["queued","running","completed","failed","cancelled","interrupted"]);function J2(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O,x=["changedFiles","additions","deletions","commits"];if(x.some((J)=>typeof $[J]!=="number"||!Number.isInteger($[J])||$[J]<0))return;return Object.fromEntries(x.map((J)=>[J,$[J]]))}function _O(O,$){return typeof O==="number"&&Number.isInteger(O)&&O>=$?O:void 0}function Q2(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O;if(!["applied","discarded","conflicted"].includes(String($.status))||typeof $.updatedAt!=="string")return;return{status:$.status,updatedAt:$.updatedAt,...typeof $.sourceCommit==="string"?{sourceCommit:$.sourceCommit}:{},..._O($.changedFiles,0)!==void 0?{changedFiles:$.changedFiles}:{},...typeof $.message==="string"?{message:$.message}:{}}}var i$=()=>{let O=new s4;return O.get("/",($)=>r4($,async(x)=>{let J,Q,X=!1,Y,W,T=new Promise((F)=>{W=F}),_=()=>{if(Q!==void 0)clearInterval(Q),Q=void 0;J?.(),J=void 0},j=(F)=>{if(X)return;X=!0,_(),Y?.close(F),W()};x.onAbort(j),Y=new DO({write:async(F)=>{await x.writeSSE(F)},onFailure:(F)=>{O2.warn(`[EventRoutes] SSE egress closed: kind=${F.kind} pendingItems=${F.pendingItems??0} pendingBytes=${F.pendingBytes??0}`),j(F)}});let w=(F,S)=>{Y?.observe({data:JSON.stringify({type:F,properties:S})})};J=C.subscribe((F)=>{if(!$2.has(F.type))return;if(F.type==="permission.asked"||F.type==="question.required"||F.type==="elicitation.required"){let d=F.properties.requestId;if(typeof d!=="string"||!d)return;w("interaction.pending",{sessionId:F.sessionId,projectPath:F.projectPath,interactionType:F.type==="question.required"?"question":F.type==="elicitation.required"?"elicitation":"permission",requestId:d});return}if(F.type==="interaction.resolved"){let d=F.properties.requestId;if(typeof d!=="string"||!d)return;w(F.type,{sessionId:F.sessionId,projectPath:F.projectPath,requestId:d});return}if(F.type==="session.created"||F.type==="session.deleted"){w(F.type,{sessionId:F.sessionId,projectPath:F.projectPath});return}if(F.type==="session.updated"){let d=F.properties.title;if(typeof d!=="string"||!d.trim())return;w(F.type,{sessionId:F.sessionId,projectPath:F.projectPath,title:d});return}if(F.type==="task.delivery"){let d=Q2(F.properties.taskDelivery);if(!d)return;w(F.type,{sessionId:F.sessionId,projectPath:F.projectPath,taskDelivery:d,...F.properties.taskWorktreeRemoved===!0?{taskWorktreeRemoved:!0}:{},...typeof F.properties.updatedAt==="string"?{updatedAt:F.properties.updatedAt}:{}});return}if(F.type==="schedule.fired"){let d=F.properties.scheduleId,_0=F.properties.firedAt;if(typeof d!=="string"||typeof _0!=="string")return;w(F.type,{scheduleId:d,firedAt:_0,sessionId:F.sessionId,projectPath:F.projectPath,...typeof F.properties.runId==="string"?{runId:F.properties.runId}:{},...typeof F.properties.status==="string"?{status:F.properties.status}:{}});return}let S=F.properties.taskStatus;if(typeof S!=="string"||!x2.has(S))return;let J0=J2(F.properties.taskDiffStat),p=_O(F.properties.taskQueuePosition,1),R=_O(F.properties.taskQueueDepth,0),s=_O(F.properties.taskConcurrencyLimit,1),u=_O(F.properties.taskInFlight,0);w(F.type,{sessionId:F.sessionId,projectPath:F.projectPath,taskStatus:S,...typeof F.properties.taskStatusReason==="string"?{taskStatusReason:F.properties.taskStatusReason}:{},...F.properties.taskFailure&&typeof F.properties.taskFailure==="object"?{taskFailure:F.properties.taskFailure}:{},...typeof F.properties.taskStartedAt==="string"?{taskStartedAt:F.properties.taskStartedAt}:{},...typeof F.properties.taskCompletedAt==="string"?{taskCompletedAt:F.properties.taskCompletedAt}:{},...typeof F.properties.updatedAt==="string"?{updatedAt:F.properties.updatedAt}:{},...J0?{taskDiffStat:J0}:{},...p!==void 0?{taskQueuePosition:p}:{},...R!==void 0?{taskQueueDepth:R}:{},...s!==void 0?{taskConcurrencyLimit:s}:{},...u!==void 0?{taskInFlight:u}:{}})});try{if(x.aborted||X)return;if(await Y.writeInitial({data:JSON.stringify({type:"connected",properties:{timestamp:Date.now()}})}),x.aborted||X)return;if(Y.finishInitialization({replayed:!1}),x.aborted||X)return;Q=setInterval(()=>{if(x.aborted||X)return;Y?.offerHeartbeat({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})})},e4),await T}finally{j()}})),O};import{Hono as Z2}from"hono";var o$=()=>{let O=new Z2;return O.get("/health",($)=>{return $.json({healthy:!0,version:r0()})}),O.get("/info",($)=>{let x=i(),J=x0();if(J)e0.configure(J.maxConcurrentTasks,J.maxQueuedTasks,J.maxQueuedTaskBytes);let Q=e0.getStats();return $.json({version:r0(),platform:process.platform,arch:process.arch,nodeVersion:process.version,cwd:x,gitBranch:a$(x),taskAdmission:{inFlight:Q.inFlight,queued:Q.queued,maxConcurrent:Q.maxConcurrent,maxQueued:Q.maxQueued}})}),O};import n$ from"node:path";import{Hono as Y2}from"hono";var z2=U.Object({projectPath:U.String({minLength:1}),action:W0(["trust","revoke"]),expectedDigest:U.Optional(U.String())}),X2=U.Object({projectPath:U.String({minLength:1}),sessionId:U.String({minLength:1}),enabled:U.Boolean()});function Q$(O){if(!O||!n$.isAbsolute(O))throw new L("projectPath must be absolute");return n$.resolve(O)}function t$(O){if(!O)throw new L("sessionId is required");try{dO(O)}catch($){throw new L($ instanceof Error?$.message:"sessionId is invalid")}return O}async function uO(O){let $=Q$(O),x=x0()?.hooks??e$.hooks,J=await HO.getInstance().loadWorkspaceHooks($,x,{includeBaseForCurrentWorkspace:!1});return wO($,async()=>{LO($);let Q=OO.getInstance();return Q.loadConfig(J,$),await BO($),Q.getConfig($)})}function s$(O,$){let x=OO.getInstance(),J=x.getConfig($).enabled,Q=x.isSessionPaused(O,$);return{sessionId:O,projectPath:$,enabled:x.isSessionEnabled(O,$),paused:Q,configEnabled:J}}var O1=()=>{let O=new Y2;return O.get("/trust",async($)=>{let x=$.req.query("projectPath");if(!x)throw new L("projectPath query parameter is required");return await uO(x),$.json(await OO.getInstance().getTrustStatus(x))}),O.post("/trust",async($)=>{let x=g(z2,await $.req.json());if(!x.success)throw new L("Invalid hook trust request");let{projectPath:J,action:Q,expectedDigest:X}=x.data;await uO(J);let Y=OO.getInstance(),W;try{W=Q==="trust"?await Y.trustProject(J,X):await Y.revokeProjectTrust(J)}catch(T){if(T instanceof r$)throw new b(T.message);throw T}return $.json(W)}),O.get("/session",async($)=>{let x=Q$($.req.query("projectPath")),J=t$($.req.query("sessionId"));return await uO(x),$.json(s$(J,x))}),O.post("/session",async($)=>{let x=g(X2,await $.req.json());if(!x.success)throw new L("Invalid hook session request");let J=Q$(x.data.projectPath),Q=t$(x.data.sessionId);await uO(J);let X=OO.getInstance();if(x.data.enabled)X.enableSession(Q,J);else X.disableSession(Q,J);return $.json(s$(Q,J))}),O};import{Hono as G2}from"hono";var R0=a("Service");function K2(O){try{return x1(O)}catch{return[]}}function N2(O){if(!pO(O)||!pO(O.reference)||!pO(O.argument))throw Error("Invalid MCP completion request");let $=O.reference.type,x=$==="prompt"&&typeof O.reference.name==="string"?{type:"prompt",name:O.reference.name}:$==="resource"&&typeof O.reference.uri==="string"?{type:"resource",uri:O.reference.uri}:void 0;if(!x||typeof O.argument.name!=="string"||typeof O.argument.value!=="string")throw Error("Invalid MCP completion request");let J;if(O.context!==void 0){if(!pO(O.context))throw Error("Invalid MCP completion context");J=Object.create(null);for(let[Q,X]of Object.entries(O.context)){if(typeof X!=="string")throw Error("Invalid MCP completion context");J[Q]=X}}return{reference:x,argument:{name:O.argument.name,value:O.argument.value},...J?{context:J}:{}}}function pO(O){return O!==null&&typeof O==="object"&&!Array.isArray(O)}async function P0(O,$){let x=x0()?.mcpServers??{};for(let[J,Q]of Object.entries(x)){if($&&J!==$)continue;if(!O.getServerStatus(J))await O.registerServer(J,Q,{connect:!1})}}var J1=()=>{let O=new G2;return O.get("/",async($)=>{try{let x=F0.getInstance();await P0(x);let J=x.getAllServers(),Q=await Promise.all(Array.from(J.entries()).map(async([X,Y])=>({id:X,name:X,status:Y.status==="connected"?"connected":Y.status==="reconnecting"?"reconnecting":Y.status==="connecting"?"connecting":Y.lastError?"error":"offline",endpoint:Y.config.command?`${Y.config.command} ${(Y.config.args||[]).join(" ")}`.trim():Y.config.url||"Unknown",description:`MCP server: ${X}`,tools:Y.tools.map((W)=>W.name),completionSupported:Y.client.completionSupported,tasks:Y.client.tasks,resources:Y.contentCatalog.resources,resourceTemplates:Y.contentCatalog.resourceTemplates.map((W)=>({...W,variables:K2(W.uriTemplate)})),prompts:Y.contentCatalog.prompts,connectedAt:Y.connectedAt?.toISOString(),error:Y.lastError?.message,recovery:Y.recovery,logging:Y.logging,instructions:Y.instructions,oauthEnabled:Y.client.oauthEnabled,oauthStatus:await Y.client.getOAuthStatus()})));return $.json(Q)}catch(x){return R0.error("[McpRoutes] Failed to get MCP servers:",x),$.json({error:x instanceof Error?x.message:"Failed to get MCP servers"},500)}}),O.post("/:name/connect",async($)=>{try{let x=$.req.param("name"),J=F0.getInstance();return await P0(J,x),await J.connectServer(x),$.json({success:!0})}catch(x){return R0.error("[McpRoutes] Failed to connect MCP server:",x),$.json({success:!1,error:x.message},500)}}),O.post("/:name/disconnect",async($)=>{try{let x=$.req.param("name"),J=F0.getInstance();return await P0(J,x),await J.disconnectServer(x),$.json({success:!0})}catch(x){return R0.error("[McpRoutes] Failed to disconnect MCP server:",x),$.json({success:!1,error:x.message},500)}}),O.get("/:name/logs",async($)=>{try{let x=$.req.param("name"),J=Number($.req.query("limit")??20),Q=Number($.req.query("afterRevision")??0);if(!Number.isSafeInteger(J)||J<1||J>100||!Number.isSafeInteger(Q)||Q<0)return $.json({error:"Invalid MCP log pagination"},400);let X=F0.getInstance();return await P0(X,x),$.json(X.getLogSnapshot(x,{limit:J,afterRevision:Q}))}catch(x){return R0.error("[McpRoutes] Failed to get MCP logs:",x),$.json({error:x.message},500)}}),O.post("/:name/logging-level",async($)=>{try{let x=$.req.param("name"),J=await $.req.json();if(!$1(J.level))return $.json({success:!1,error:"Invalid MCP logging level"},400);let Q=F0.getInstance();return await P0(Q,x),await Q.setServerLoggingLevel(x,J.level),$.json({success:!0,level:J.level})}catch(x){return R0.error("[McpRoutes] Failed to set MCP logging level:",x),$.json({success:!1,error:x.message},400)}}),O.post("/:name/complete",async($)=>{try{let x=$.req.param("name"),J=N2(await $.req.json()),Q=F0.getInstance();await P0(Q,x);let X=await Q.complete(x,J);return $.json(X)}catch(x){return R0.error("[McpRoutes] Failed to complete MCP argument:",x),$.json({error:x.message},400)}}),O.post("/:name/oauth/login",async($)=>{try{let x=$.req.param("name"),J=F0.getInstance();await P0(J,x);let Q=await J.beginOAuthLogin(x);return $.json({success:!0,flowId:Q.flowId,authorizationUrl:Q.authorizationUrl},202)}catch(x){return R0.error("[McpRoutes] Failed to start MCP OAuth login:",x),$.json({success:!1,error:x.message},400)}}),O.post("/:name/oauth/logout",async($)=>{try{let x=$.req.param("name"),J=F0.getInstance();return await P0(J,x),await J.logoutOAuth(x),$.json({success:!0})}catch(x){return R0.error("[McpRoutes] Failed to log out MCP OAuth:",x),$.json({success:!1,error:x.message},400)}}),O.delete("/:name",async($)=>{try{let x=$.req.param("name");await F0.getInstance().unregisterServer(x);let Q=x0();if(Q?.mcpServers){let{[x]:X,...Y}=Q.mcpServers;await L0().updateConfig({mcpServers:Y})}return $.json({success:!0})}catch(x){return R0.error("[McpRoutes] Failed to delete MCP server:",x),$.json({success:!1,error:x.message},500)}}),O.post("/",async($)=>{try{let x=await $.req.json(),{name:J,config:Q}=x;if(!J||!Q)return $.json({success:!1,error:"Missing name or config"},400);await F0.getInstance().registerServer(J,Q);let Y=x0();return await L0().updateConfig({mcpServers:{...Y?.mcpServers,[J]:Q}}),$.json({success:!0})}catch(x){return R0.error("[McpRoutes] Failed to add MCP server:",x),$.json({success:!1,error:x.message},500)}}),O};import{getSupportedThinkingLevels as V2}from"@earendil-works/pi-ai";import{Hono as W2}from"hono";var lO=a("Service");function F2(O,$,x=z1.list()){return{id:O.id,displayName:O.displayName,provider:O.provider,model:O.model,overrides:O.overrides,fallbackModels:O.fallbackModels,contextWindow:$.contextWindow,maxTokens:$.maxTokens,reasoning:$.reasoning,supportedReasoningEfforts:V2($),supportedServiceTiers:Z1($),supportedResponseVerbosities:Q1($),communicationStyles:x,input:$.input}}function U2(O){X1(O.overrides);let $={displayName:O.displayName||void 0,overrides:O.overrides||void 0};if(O.model)$.model=O.model;return $}function X1(O){let $=O?.streamIdleTimeout;if($!==void 0&&(!Number.isFinite($)||$<1000))throw new L("streamIdleTimeout must be at least 1000ms")}var G1=()=>{let O=new W2;return O.get("/",async($)=>{try{let x=x0();if(!x)throw Error("Config not initialized");let J=$.get("directory")||i(),[Q,X]=await Promise.all([cO(J,x),E0(J)]),Y=Q.config.models,W=Y.find((w)=>w.id===Q.config.currentModelId)??Y[0],T=Q.catalog,_=X.communicationStyles.list(),j=(w)=>F2(w,T.resolveConfig(w),_);return $.json({configured:Y.map(j),current:W?j(W):null})}catch(x){lO.error("[ModelsRoutes] Failed to get models:",x);let J=new e("Failed to get models");return $.json(J.toObject(),500)}}),O.post("/",async($)=>{let x=d0(),J,Q;try{let X=await $.req.json(),{provider:Y,displayName:W,model:T,overrides:_,apiKey:j,modelProvider:w}=X;if(!Y||!T)throw new L("provider and model are required");X1(_);let F;if(w){if(w.id!==Y)throw new L("modelProvider.id must match the model provider");if(x0()?.modelProviders[Y])throw new L(`model provider already exists: ${Y}`);F={name:w.name,baseUrl:w.baseUrl,wireApi:w.wireApi,...w.apiKeyEnv?{apiKeyEnv:w.apiKeyEnv}:{}};try{x.registerModelProvider(Y,F,[T]),Q=Y}catch(p){throw new L(p instanceof Error?p.message:"Invalid model provider")}}else x.getModel(Y,T);if(j?.trim()){if(await x.setApiKey(Y,j.trim()),F)J=Y}let S={provider:Y,displayName:W||void 0,model:T,overrides:_||void 0},J0=F?await L0().addModelWithProvider(S,F):await L0().addModel(S);return $.json({success:!0,model:J0})}catch(X){if(J)await x.credentials.delete(J);if(Q){let Y=x0();x.configureModelProviders(Y?.modelProviders??{},Y?.models??[])}throw lO.error("[ModelsRoutes] Failed to add model:",X),X}}),O.put("/:modelId",async($)=>{try{let x=$.req.param("modelId"),J=await $.req.json(),{displayName:Q,overrides:X,model:Y}=J,W=Y1(x);if(!W)throw new L("model config not found");if(Y)d0().getModel(W.provider,Y);return await L0().updateModel(x,U2({displayName:Q,overrides:X,model:Y})),$.json({success:!0})}catch(x){throw lO.error("[ModelsRoutes] Failed to update model:",x),x}}),O.delete("/:modelId",async($)=>{try{let x=$.req.param("modelId");return await L0().removeModel(x),$.json({success:!0})}catch(x){throw lO.error("[ModelsRoutes] Failed to delete model:",x),x}}),O};import{Hono as I2}from"hono";import K1 from"node:path";import{Hono as D2}from"hono";import{streamSSE as _2}from"hono/streaming";import{LRUCache as H2}from"lru-cache";import{nanoid as JO}from"nanoid";var P=a("Service"),B2=U.Object({title:U.Optional(U.String()),projectPath:U.Optional(U.String())}),L2=P1,w2=U.Object({title:U.Optional(U.String()),projectPath:U.Optional(U.String())}),A2=U.Object({projectPath:U.String()}),M2=U.Object({objective:U.String({minLength:1}),tokenBudget:U.Optional(U.Integer({minimum:1})),permissionMode:U.Optional(W0(["default","autoEdit","plan","yolo"]))}),E2=U.Union([U.Object({action:U.Literal("pause")}),U.Object({action:U.Literal("resume")}),U.Object({action:U.Literal("edit"),objective:U.String({minLength:1})})]),t=new Map,ZO,j0=new Map,S0=new Map,T0=new Map,nO=new H2({max:100,ttl:1800000});function N1(O){return{sessionId:O.sessionId,projectPath:O.projectPath}}function D0(O){if(!O)return;return j0.get(O)??nO.get(O)}function T2(O){if(j0.get(O.id)!==O)return;j0.delete(O.id),nO.set(O.id,O)}function j2(O){j0.delete(O),nO.delete(O)}function U0(O){return O?.status==="queued"||O?.status==="running"||O?.status==="waiting_permission"}function TO(O,$="user-cancel"){if(O.status==="cancelled"||O.status==="completed"||O.status==="failed")return!1;let x=O.pendingPermission;if(O.pendingPermission=void 0,x?.resolve({approved:!1,reason:L1}),x)C.publish(N1(O),"interaction.resolved",{requestId:x.permissionId});return O.abortController.abort($),O.status="cancelled",C.publish(N1(O),"run.cancelled",{runId:O.id}),!0}function h1(O,$=!1){let{permissionId:x,details:J}=O;if(J.type==="askUserQuestion"&&J.questions)return{type:"question.required",properties:{requestId:x,toolCallId:J.toolCallId??x,questions:J.questions,details:J,...$?{replayed:!0}:{}}};if(J.type==="mcpElicitation"&&J.mcpElicitation)return{type:"elicitation.required",properties:{requestId:x,toolCallId:J.toolCallId??x,elicitation:J.mcpElicitation,...$?{replayed:!0}:{}}};return{type:"permission.asked",properties:{requestId:x,toolName:J.toolName,description:J.message,args:J.args,details:J,...$?{replayed:!0}:{}}}}function R2(O){return{...typeof O.seq==="number"?{id:String(O.seq)}:{},data:JSON.stringify({type:O.type,...typeof O.seq==="number"?{seq:O.seq}:{},properties:{...O.properties,sessionId:O.sessionId,projectPath:O.projectPath}})}}function C2(){for(let O of j0.values())TO(O,"route-reset");j0.clear();for(let O of S0.values())O.controller.abort("route-reset");S0.clear(),nO.clear(),ZO=void 0,t.clear()}function b2(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O,x=$.code,J=$.reason,Q=$.scope,X=$.kind,Y=$.limit;if(x!=="tool_busy"&&x!=="tool_batch_full"||J!=="queue_full"&&J!=="wait_timeout"&&J!=="turn_limit"||Q!=="global"&&Q!=="session"||typeof $.retryable!=="boolean"||!Number.isSafeInteger(Y)||Y<=0||X!==void 0&&X!=="readonly"&&X!=="write"&&X!=="execute")return;return{code:x,reason:J,scope:Q,retryable:$.retryable,...X===void 0?{}:{kind:X},limit:Y}}var jO=(O,$)=>{if(!$||typeof $!=="object")return $;let x={...$},J=b2(x.tool_admission);if(J)x.tool_admission=J;else delete x.tool_admission;if(O==="Bash"){let Y={},W=["message","signal","status","summary"],T=["aborted","acp_mode","admission_failed","auto_backgrounded","background","capture_truncated","finalization_failed","has_stderr","output_accounting_complete","output_truncated","projection_truncated","sandbox_required","sandboxed","stderr_projection_truncated","stdout_projection_truncated","terminal_output_merged","timeout"],_=["execution_time","foreground_budget_ms","pid","raw_output_bytes","stderr_length","stderr_omitted_bytes","stderr_retained_bytes","stderr_total_bytes","stdout_length","stdout_omitted_bytes","stdout_retained_bytes","stdout_total_bytes"];for(let w of W){let F=x[w];if(typeof F==="string")Y[w]=F.slice(0,8192)}for(let w of T){let F=x[w];if(typeof F==="boolean")Y[w]=F}for(let w of _){let F=x[w];if(typeof F==="number"&&Number.isSafeInteger(F)&&F>=0)Y[w]=F}if(x.exit_code===null||typeof x.exit_code==="number"&&Number.isSafeInteger(x.exit_code))Y.exit_code=x.exit_code;if(x.terminal_transport==="local"||x.terminal_transport==="acp"||x.terminal_transport==="local_fallback")Y.terminal_transport=x.terminal_transport;if(x.background_reason==="explicit"||x.background_reason==="foreground_budget")Y.background_reason=x.background_reason;for(let w of["bash_id","shell_id"]){let F=x[w];if(typeof F==="string"&&F.length<=128&&/^bash_[A-Za-z0-9-]+$/.test(F))Y[w]=F}if(J)Y.tool_admission=J;let j=x.background_shell_admission;if(j&&typeof j==="object"&&!Array.isArray(j)){let w=j;if(w.code==="background_shell_busy"&&(w.scope==="session"||w.scope==="global")&&w.retryable===!0&&Number.isSafeInteger(w.limit)&&w.limit>0)Y.background_shell_admission={code:w.code,scope:w.scope,retryable:w.retryable,limit:w.limit}}return Y}let Q=200000,X=(Y,W)=>typeof Y==="number"&&Number.isSafeInteger(Y)&&Y>=0&&Y<=W?Y:0;if(typeof x.oldContent==="string"&&x.oldContent.length>Q)delete x.oldContent;if(typeof x.newContent==="string"&&x.newContent.length>Q)delete x.newContent;if(x.mcpResult&&typeof x.mcpResult==="object"&&!Array.isArray(x.mcpResult)){let Y=x.mcpResult,W=Array.isArray(Y.artifacts)?Y.artifacts.slice(0,64).flatMap((T)=>{if(!T||typeof T!=="object"||Array.isArray(T))return[];let _=T,j=new Set(["text","image","audio","resource"]);if(typeof _.id!=="string"||!/^[a-f0-9]{64}$/.test(_.id)||typeof _.sha256!=="string"||_.sha256!==_.id||typeof _.kind!=="string"||!j.has(_.kind)||X(_.size,67108864)!==_.size||typeof _.persisted!=="boolean")return[];return[{id:_.id.slice(0,128),sha256:_.sha256.slice(0,128),kind:_.kind,size:_.size,persisted:_.persisted,...typeof _.mimeType==="string"?{mimeType:_.mimeType.slice(0,256)}:{},...typeof _.sourceUri==="string"?{sourceUri:_.sourceUri.slice(0,8192)}:{},...typeof _.path==="string"?{path:_.path.slice(0,8192)}:{}}]}):[];x.mcpResult={isError:Y.isError===!0,contentCount:X(Y.contentCount,64),textBytes:X(Y.textBytes,4194304),structuredBytes:X(Y.structuredBytes,4194304),artifactCount:X(Y.artifactCount,64),truncated:Y.truncated===!0,binaryOmitted:Y.binaryOmitted===!0,artifacts:W}}else delete x.mcpResult;return x};function q2(O){let $=typeof O.seq==="number"?{seq:O.seq}:{};if(O.type==="part_created"&&O.data.partType==="tool_call"){let x=O.data.payload;return{type:"tool.start",...$,properties:{messageId:O.data.messageId,toolCallId:x.toolCallId??O.data.partId,toolName:x.toolName??"unknown",arguments:JSON.stringify(x.input??{})}}}if(O.type==="part_created"&&O.data.partType==="tool_result"){let x=O.data.payload,J=x.toolName??"unknown",Q=D$(x),X=bO(qO(J,Q),CO);return{type:"tool.result",...$,properties:{messageId:O.data.messageId,toolCallId:x.toolCallId??O.data.partId,toolName:J,success:Q.success,status:Q.success?"completed":"failed",summary:Q.metadata?.summary,output:kO(X),metadata:jO(J,Q.metadata)}}}return{type:`committed.${O.type}`,...$,properties:{event:O}}}function k2(O,$,x){switch(x.kind){case"tool_start":if("function"in x.toolCall)C.publish(O,"subagent.update",{subagentSessionId:$,toolName:x.toolCall.function.name}),C.publish(O,"subagent.tool.start",{subagentSessionId:$,toolCallId:x.toolCall.id,toolName:x.toolCall.function.name,arguments:x.toolCall.function.arguments,toolKind:x.toolKind});break;case"tool_result":if("function"in x.toolCall)C.publish(O,"subagent.tool.result",{subagentSessionId:$,toolCallId:x.toolCall.id,toolName:x.toolCall.function.name,success:x.result.success,summary:x.result.metadata?.summary,output:kO(bO(qO(x.toolCall.function.name,x.result),CO)),metadata:jO(x.toolCall.function.name,x.result.metadata)});break;case"tool_progress":if("function"in x.toolCall)C.publish(O,"subagent.tool.progress",{subagentSessionId:$,toolCallId:x.toolCall.id,toolName:x.toolCall.function.name,...x.update});break;case"content_delta":C.publish(O,"subagent.delta",{subagentSessionId:$,delta:x.delta});break;case"thinking_delta":C.publish(O,"subagent.thinking.delta",{subagentSessionId:$,delta:x.delta});break;case"stream_end":C.publish(O,"subagent.stream.end",{subagentSessionId:$});break;case"provider_admission":C.publish(O,"subagent.provider.admission",{subagentSessionId:$,phase:x.phase,requestClass:x.requestClass,resource:x.resource,scope:x.scope,reason:x.reason,queuePosition:x.queuePosition,queueDepth:x.queueDepth,inFlight:x.inFlight,limit:x.limit,waitMs:x.waitMs,maxWaitMs:x.maxWaitMs,recoveryRemainingMs:x.recoveryRemainingMs});break;case"provider_circuit":C.publish(O,"subagent.provider.circuit",{subagentSessionId:$,phase:x.phase,reason:x.reason,statusCode:x.statusCode,retryAfterMs:x.retryAfterMs,nextProbeAt:x.nextProbeAt,openDurationMs:x.openDurationMs,sampleCount:x.sampleCount,failureCount:x.failureCount,recoveryRemainingMs:x.recoveryRemainingMs});break;case"provider_retry":C.publish(O,"subagent.provider.retry",{subagentSessionId:$,phase:x.phase,attempt:x.attempt,maxRetries:x.maxRetries,reason:x.reason,statusCode:x.statusCode,delayMs:x.delayMs,nextRetryAt:x.nextRetryAt,mode:x.mode,recoveryBudgetMs:x.recoveryBudgetMs,recoveryElapsedMs:x.recoveryElapsedMs,recoveryRemainingMs:x.recoveryRemainingMs,exhaustedBy:x.exhaustedBy});break;case"provider_stall":C.publish(O,"subagent.provider.stall",{subagentSessionId:$,phase:x.phase,stallCount:x.stallCount,durationMs:x.durationMs,warningAfterMs:x.warningAfterMs,timeoutMs:x.timeoutMs,outputStarted:x.outputStarted});break;case"action_stationarity":C.publish(O,"subagent.action.stationarity",{subagentSessionId:$,phase:x.phase,toolName:x.toolName,runLength:x.runLength,nudgeThreshold:x.nudgeThreshold,haltThreshold:x.haltThreshold,progressAware:x.progressAware});break;case"mcp_catalog_changed":C.publish(O,"subagent.mcp.catalog.changed",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,added:x.added,removed:x.removed,updated:x.updated});break;case"mcp_content_changed":C.publish(O,"subagent.mcp.content.changed",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,contentKind:x.contentKind,added:x.added,removed:x.removed,updated:x.updated});break;case"mcp_resource_updated":C.publish(O,"subagent.mcp.resource.updated",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,uri:x.uri});break;case"mcp_connection_changed":C.publish(O,"subagent.mcp.connection.changed",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,phase:x.phase,reason:x.reason,attempt:x.attempt,maxAttempts:x.maxAttempts,nextRetryAt:x.nextRetryAt,error:x.error});break;case"mcp_log":C.publish(O,"subagent.mcp.log",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,level:x.level,logger:x.logger,message:x.message,projectedBytes:x.projectedBytes,dataSha256:x.dataSha256,truncated:x.truncated,detailsOmitted:x.detailsOmitted,timestamp:x.timestamp,synthetic:x.synthetic});break;case"mcp_instructions_changed":C.publish(O,"subagent.mcp.instructions.changed",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,action:x.action,reason:x.reason,text:x.text,sourceBytes:x.sourceBytes,projectedBytes:x.projectedBytes,sha256:x.sha256,truncated:x.truncated,detailsOmitted:x.detailsOmitted});break;case"mcp_task_changed":C.publish(O,"subagent.mcp.task.changed",{subagentSessionId:$,revision:x.revision,taskId:x.taskId,serverName:x.serverName,toolName:x.toolName,status:x.status,statusMessage:x.statusMessage,createdAt:x.createdAt,updatedAt:x.updatedAt,completedAt:x.completedAt,hasResult:x.hasResult,error:x.error});break;case"project_rules_loaded":C.publish(O,"subagent.project.rules.loaded",{subagentSessionId:$,files:x.files,triggerPaths:x.triggerPaths,blockedWrite:x.blockedWrite});break;default:break}}function MO(O,$="projectPath"){if(!K1.isAbsolute(O))throw new L(`${$} must be absolute`);return K1.resolve(O)}function F$(O){try{dO(O)}catch($){throw new L($ instanceof Error?$.message:`Invalid session ID: ${O}`)}}function Z0(O){return{sessionId:O.id,projectPath:O.projectPath}}function EO(O,$,x){return{id:O.sessionId,projectPath:O.projectPath,title:O.title??`Session ${O.sessionId.slice(0,6)}`,createdAt:new Date(O.firstMessageTime),updatedAt:new Date(O.lastMessageTime),rootId:O.rootId,parentId:O.parentId,relationType:O.relationType,taskStatus:O.taskStatus,taskStatusReason:O.taskStatusReason,taskFailure:O.taskFailure,taskStartedAt:O.taskStartedAt,taskCompletedAt:O.taskCompletedAt,taskPromptSummary:O.taskPromptSummary,taskModelId:O.taskModelId,selectedModelId:O.selectedModelId,permissionMode:O.permissionMode,reasoningEffort:O.reasoningEffort,serviceTier:O.serviceTier,responseVerbosity:O.responseVerbosity,communicationStyle:O.communicationStyle,communicationStyleDigest:O.communicationStyleDigest,projectInstructionsDigest:O.projectInstructionsDigest,pendingInteraction:O.pendingInteraction,taskRetryAvailable:O.taskRetryAvailable,taskRetriedFrom:O.taskRetriedFrom,taskDelivery:O.taskDelivery,taskIsolation:O.taskIsolation,taskSourceProjectPath:O.taskSourceProjectPath,taskWorktreePath:O.taskWorktreePath,taskWorktreeBranch:O.taskWorktreeBranch,taskBaseCommit:O.taskBaseCommit,taskDiffStat:O.taskDiffStat,taskQueuePosition:O.taskQueuePosition,taskQueueDepth:O.taskQueueDepth,taskConcurrencyLimit:O.taskConcurrencyLimit,archivedAt:O.archivedAt,archivedBySessionId:O.archivedBySessionId,taskWorktree:x,messages:$}}function Z$(O){return O.flatMap(($)=>{if(!A1($)||$.role==="system"||$.role==="tool"&&$.name===QO)return[];let x=$.tool_calls?.filter((Y)=>!("function"in Y)||Y.function.name!==QO),J=typeof $.content==="string"?$.content.trim():"";if($.role==="assistant"&&$.tool_calls?.length&&!x?.length&&!J&&!$.reasoningContent&&!$.metadata)return[];let Q={...$,...$.tool_calls?{tool_calls:x&&x.length>0?x:void 0}:{}};if($.role==="tool"){let Y=$.metadata&&typeof $.metadata==="object"&&!Array.isArray($.metadata)?$.metadata:void 0,W=$.name??(typeof Y?.toolName==="string"?Y.toolName:"unknown");if(Y!==void 0&&(Object.hasOwn(Y,"output")||Object.hasOwn(Y,"error"))){let _=D$(Y),j=bO(qO(W,_),CO);return[{...Q,name:W,content:kO(j),metadata:jO(W,{..._.metadata,status:_.success?"completed":"failed"})}]}return[{...Q,name:W,metadata:jO(W,Y)}]}let X=E1($.metadata);return[X?{...Q,content:M1(X)}:Q]})}function RO(O,$){O.taskStatus=$.taskStatus,O.taskStatusReason=$.taskStatusReason,O.taskFailure=$.taskFailure,O.taskStartedAt=$.taskStartedAt,O.taskCompletedAt=$.taskCompletedAt,O.taskPromptSummary=$.taskPromptSummary,O.taskModelId=$.taskModelId,O.selectedModelId=$.selectedModelId,O.permissionMode=$.permissionMode,O.reasoningEffort=$.reasoningEffort,O.serviceTier=$.serviceTier,O.responseVerbosity=$.responseVerbosity,O.communicationStyle=$.communicationStyle,O.communicationStyleDigest=$.communicationStyleDigest,O.projectInstructionsDigest=$.projectInstructionsDigest,O.pendingInteraction=$.pendingInteraction,O.taskRetryAvailable=$.taskRetryAvailable,O.taskRetriedFrom=$.taskRetriedFrom,O.taskDelivery=$.taskDelivery,O.taskIsolation=$.taskIsolation,O.taskSourceProjectPath=$.taskSourceProjectPath,O.taskWorktreePath=$.taskWorktreePath,O.taskWorktreeBranch=$.taskWorktreeBranch,O.taskBaseCommit=$.taskBaseCommit,O.taskDiffStat=$.taskDiffStat,O.taskQueuePosition=$.taskQueuePosition,O.taskQueueDepth=$.taskQueueDepth,O.taskConcurrencyLimit=$.taskConcurrencyLimit,O.archivedAt=$.archivedAt,O.archivedBySessionId=$.archivedBySessionId,O.updatedAt=new Date($.lastMessageTime)}async function c0(O){let $=await q.findSessionMetadata(O.id,O.projectPath);if($)RO(O,$)}function $O(O){let $=D0(O.currentRunId),x=$?.status==="waiting_permission"?"running":$?.status??O.taskStatus;return{sessionId:O.id,projectPath:O.projectPath,title:O.title,rootId:O.rootId,parentId:O.parentId,relationType:O.relationType,status:void 0,taskStatus:x,taskStatusReason:O.taskStatusReason,taskFailure:O.taskFailure,taskStartedAt:O.taskStartedAt,taskCompletedAt:O.taskCompletedAt,taskPromptSummary:O.taskPromptSummary,taskModelId:O.taskModelId,selectedModelId:O.selectedModelId,permissionMode:O.permissionMode,reasoningEffort:O.reasoningEffort,serviceTier:O.serviceTier,responseVerbosity:O.responseVerbosity,communicationStyle:O.communicationStyle,communicationStyleDigest:O.communicationStyleDigest,projectInstructionsDigest:O.projectInstructionsDigest,taskRetryAvailable:O.taskRetryAvailable,taskRetriedFrom:O.taskRetriedFrom,taskDelivery:O.taskDelivery,taskIsolation:O.taskIsolation,taskSourceProjectPath:O.taskSourceProjectPath,taskWorktreePath:O.taskWorktreePath,taskWorktreeBranch:O.taskWorktreeBranch,taskBaseCommit:O.taskBaseCommit,taskDiffStat:O.taskDiffStat,taskQueuePosition:$?.status==="queued"?$.taskQueuePosition:x==="queued"?O.taskQueuePosition:void 0,taskQueueDepth:$?.status==="queued"?$.taskQueueDepth:x==="queued"?O.taskQueueDepth:void 0,taskConcurrencyLimit:$?.taskConcurrencyLimit??O.taskConcurrencyLimit,archivedAt:O.archivedAt,archivedBySessionId:O.archivedBySessionId,pendingInteraction:$?.pendingPermission?{type:$.pendingPermission.details.type==="askUserQuestion"?"question":$.pendingPermission.details.type==="mcpElicitation"?"elicitation":"permission",requestId:$.pendingPermission.permissionId}:O.pendingInteraction,agentType:void 0,model:void 0,messageCount:O.messages.length,firstMessageTime:O.createdAt.toISOString(),lastMessageTime:O.updatedAt.toISOString(),hasErrors:!1,isActive:!0}}async function K0(O,$){if(F$(O),$!==void 0){let J=f0({sessionId:O,projectPath:MO($)});if(t.has(v(J)))return J;let Q=await q.findSessionMetadata(J.sessionId,J.projectPath);if(!Q)throw new m("Session",O);return f0({sessionId:Q.sessionId,projectPath:Q.projectPath})}let x=new Map;for(let J of t.values()){if(J.id!==O)continue;let Q=Z0(J);x.set(v(Q),Q)}for(let J of await q.listSessions()){if(J.sessionId!==O)continue;let Q=f0({sessionId:J.sessionId,projectPath:J.projectPath});x.set(v(Q),Q)}if(x.size===0)try{let J=await q.findSessionMetadata(O);if(!J)throw new m("Session",O);return f0({sessionId:J.sessionId,projectPath:J.projectPath})}catch(J){if(J instanceof m)throw J;if(J instanceof Error&&J.message.startsWith("Ambiguous session ID:"))throw new B0;throw J}if(x.size>1)throw new B0;return x.values().next().value}function U$(O){if(typeof O==="string")return O;return O.filter(($)=>$.type==="text").map(($)=>$.text).join(`
|
|
7
|
-
`)}function V1(O,$){let x=($??[]).filter((Q)=>Q.type==="image"&&typeof Q.content==="string").map((Q)=>({type:"image_url",image_url:{url:Q.content}}));if(x.length===0)return O;let J=[];if(O.trim())J.push({type:"text",text:O});return J.push(...x),J}var g1=()=>{C2();let O=new D2;O.onError((Z,K)=>{if(Z instanceof xO){let z=new k0("Session runtime capacity is full",{resource:Z.resource,limit:Z.limit});return K.json(z.toObject(),429)}if(Z instanceof Q0)return K.json(Z.toObject(),Z.statusCode);return P.error("[SessionRoutes] Unhandled route error:",Z),K.json({error:{code:"INTERNAL_ERROR",message:"Internal server error"}},500)});let $=new Map,x=new Map,J=new Map,Q=new Map,X=new Y$,Y=new Y$,W=x0(),T=new m1({maxResident:W?.maxResidentSessionRuntimes??U1,idleMs:W?.sessionRuntimeIdleMs??D1}),_=new C1,j=setInterval(()=>{T.sweepIdle().catch((Z)=>{P.warn("[SessionRoutes] Session Runtime idle sweep failed:",Z)})},_1);j.unref?.();let w,F=async(Z)=>{let K;try{K=_.enter()}catch{throw new u0}try{return await Z()}finally{K.release()}};O.use("*",async(Z,K)=>{if(Z.req.method==="GET"||Z.req.method==="HEAD")return K();return F(K)});let S=(Z,K)=>X.runExclusive(v(Z),K),J0=(Z,K)=>Y.runExclusive(v(Z),K),p=(Z)=>[...j0.values()].some((K)=>K.sessionId===Z.sessionId&&K.projectPath===Z.projectPath&&U0(K)),R=async(Z,K,z)=>{let G=J.get(K);if(!G)G=(async()=>{if($.get(K)===z)$.delete(K);for(let[H,D]of $)if(D===z)$.delete(H);let V=Z0(Z);if(t.get(K)===Z&&!p(V)&&!S0.has(K)&&!T0.has(K))t.delete(K);if(await z.dispose(),$.size===0)await F0.getInstance().disconnectAll()})().finally(()=>{if(J.get(K)===G)J.delete(K)}),J.set(K,G);await G},s=async(Z,K={})=>{let z=Z0(Z),G=v(z);await J.get(G);let V=T.acquire(G);if(V){if($.get(G)!==V.value)throw V.release(),Error("Session Runtime residency identity is inconsistent");return V}if(T.owns(G))throw new xO(T.getStats().maxResident);let H=x.get(G);if(!H){let D=K.communicationStyle??Z.communicationStyle;H=(async()=>{let B=await T.reserve(G,{surface:"web",allowEviction:!0});try{let M=await AO.create({sessionId:Z.id,workspaceRoot:Z.projectPath,...Z.selectedModelId??Z.taskModelId?{modelId:Z.selectedModelId??Z.taskModelId}:{},permissionMode:K.permissionMode??Z.permissionMode??"default",...Z.reasoningEffort?{reasoningEffort:Z.reasoningEffort}:{},...Z.serviceTier?{serviceTier:Z.serviceTier}:{},...Z.responseVerbosity?{responseVerbosity:Z.responseVerbosity}:{},...D?{communicationStyle:D}:{},...D===Z.communicationStyle&&Z.communicationStyleDigest?{communicationStyleDigest:Z.communicationStyleDigest}:{},...Z.projectInstructionsDigest?{projectInstructionsDigest:Z.projectInstructionsDigest}:{},...Z.taskWorktree?{taskWorktree:Z.taskWorktree}:{},...Z.taskIsolation?{taskIsolation:Z.taskIsolation}:{},...Z.messages.length>0?{sessionStart:{isResume:!0,resumeSessionId:Z.id}}:{}}),A=B.commit({key:G,surface:"web",value:M,canEvict:()=>!p(z)&&!S0.has(G)&&!T0.has(G)&&!x.has(G)&&!J.has(G)&&M.isIdleForResidency(),dispose:()=>R(Z,G,M)});return $.set(G,M),{runtime:M,claimLease:()=>{if(A){let k=A;return A=void 0,k}let E=T.acquire(G);if(!E||E.value!==M)throw Error("Initialized Session Runtime lost residency");return E}}}catch(M){throw B.cancel(),M}})(),x.set(G,H)}try{return(await H).claimLease()}finally{if(x.get(G)===H)x.delete(G)}},u=async(Z,K,z={})=>{let G=await s(Z,z);try{return await K(G.value)}finally{G.release()}},d=async(Z,K)=>{let z=v(Z0(Z)),G=x.get(z);if(G)await G.catch(()=>{return});x.delete(z);let V=K??$.get(z);if(!V)return;if(!await T.remove(z,V))throw Error(`Session Runtime is pinned and cannot be disposed: ${z}`)},_0=async(Z)=>{let K=v(Z),z=t.get(K);if(z)return z;let G=Q.get(K);if(!G)G=(async()=>{let V=await q.findSessionMetadata(Z.sessionId,Z.projectPath);if(!V)throw new m("Session",Z.sessionId);let[H,D]=await Promise.all([q.loadSession(Z.sessionId,Z.projectPath),q.findSessionTaskWorktree(Z.sessionId,Z.projectPath)]),B=EO(V,H,D);return t.set(K,B),B})(),Q.set(K,G);try{return await G}finally{if(Q.get(K)===G)Q.delete(K)}},X0=async(Z,K)=>{let z=await K0(Z,K);try{await q.assertSessionWritable(z.sessionId,z.projectPath)}catch(G){if(G instanceof G$)throw new b(G.message);throw G}return _0(z)},NO=async(Z,K)=>{if(Z.permissionMode===K)return;let z=await q.setSessionPermissionMode(Z.id,Z.projectPath,K);Z.permissionMode=z.permissionMode,Z.updatedAt=new Date(z.lastMessageTime),C.publish(Z0(Z),"session.updated",{permissionMode:K})},$0=(Z,K,z,G={})=>{if(!_.stats().accepting)throw new u0;let V=JO(12),H={id:V,sessionId:Z.id,projectPath:Z.projectPath,status:"running",abortController:new AbortController,disposeRuntimeOnSettle:Z.taskIsolation!==void 0&&G.runtimeLease!==void 0,createdAt:new Date};if(Z.taskIsolation&&G.runtimeLease){let D=G.runtimeLease.value,B=e0.admit({key:`${Z.projectPath}\x00${Z.id}`,...D.getTaskAdmissionLimits(),pendingBytes:b1({content:K,outputSchema:G.outputSchema,pendingMessages:D.getPendingSteeringMessages()}),signal:H.abortController.signal,onUpdate:(A)=>{H.status=A.state,H.taskQueuePosition=A.queuePosition,H.taskQueueDepth=A.queueDepth,H.taskConcurrencyLimit=A.maxConcurrent,Z.taskStatus=A.state,Z.taskQueuePosition=A.queuePosition,Z.taskQueueDepth=A.queueDepth,Z.taskConcurrencyLimit=A.maxConcurrent,H.taskAdmissionUpdate=(H.taskAdmissionUpdate??Promise.resolve()).then(async()=>{await D.setTaskAdmission(A)}).catch((E)=>{P.warn(`[SessionRoutes] Failed to persist admission for ${Z.id}:`,E)})}});H.taskAdmission=B;let M=B.getSnapshot();H.status=M.state,H.taskQueuePosition=M.queuePosition,H.taskQueueDepth=M.queueDepth,H.taskConcurrencyLimit=M.maxConcurrent}return j0.set(V,H),Z.currentRunId=V,H.completion=S2(H,Z,K,z,s,{pendingInputOnly:G.pendingInputOnly,preparedInputTurn:G.preparedInputTurn,goalContinuationOnly:G.goalContinuationOnly,outputSchema:G.outputSchema,taskAdmission:H.taskAdmission,runtimeLease:G.runtimeLease,disposeRuntime:d}).catch((D)=>{P.error(`[SessionRoutes] Run ${V} failed:`,D)}),H},yO=async(Z)=>{let K;if(Z.outputSchema)try{K=X$(Z.outputSchema).schema}catch(h){throw new L(h instanceof Error?h.message:"Invalid output schema")}let z=z$("task",12),G=MO(Z.sourceProjectPath),V=Z.modelId?.trim(),H=x0();if(!H)throw new L("Config not initialized");let[D,B]=await Promise.all([cO(G,H),E0(G)]);if(V&&!D.config.models.some((h)=>h.id===V))throw new L(`Task model not found: ${V}`);let M=V||D.config.models.find((h)=>h.id===D.config.currentModelId)?.id||D.config.models[0]?.id;if(!M)throw new L("No model is configured. Add or select a model before dispatching a task.");let A=D.config.models.find((h)=>h.id===M);if(!A)throw new L(`Task model not found: ${M}`);let E=Z.reasoningEffort??"off",k=Z.serviceTier??"auto",G0=Z.responseVerbosity??"auto",I0=Z.communicationStyle??"auto",M0,Y0=B.projectRules?.staticRules(G),r=Y0&&Y0.files.length>0?Y0.provenanceSha256:void 0;try{let h=D.catalog.resolveConfig(A);H1(h,E),F1(h,k),W1(h,G0);let c=B1(I0,B.communicationStyles);M0=c.source==="built-in"?void 0:c.contentSha256}catch(h){throw new L(h instanceof Error?h.message:"Invalid reasoning effort")}let o0={version:1,prompt:Z.prompt,...Z.title?{title:Z.title}:{},sourceProjectPath:G,isolation:Z.isolation,permissionMode:Z.permissionMode,modelId:M,reasoningEffort:E,serviceTier:k,responseVerbosity:G0,communicationStyle:I0,...M0?{communicationStyleDigest:M0}:{},...r?{projectInstructionsDigest:r}:{},...Z.attachments?{attachments:Z.attachments.map((h)=>({...h}))}:{},...K?{outputSchema:K}:{}},f,y,I;try{let h=await k1.createSessionTask({sessionId:z,prompt:Z.prompt,title:Z.title,sourceProjectPath:G,isolation:Z.isolation,dispatch:o0,retriedFrom:Z.retriedFrom}),{metadata:c}=h;f=h.taskWorktree,y=EO(c,[],f);let l=Z0(y);t.set(v(l),y),C.publish(l,"task.status",{taskStatus:c.taskStatus,updatedAt:c.lastMessageTime});let n=V1(Z.prompt,Z.attachments);I=await s(y);let WO=I.value,o=K?await WO.prepareInputTurn(n,{outputSchema:K}):await WO.prepareInputTurn(n);if(!o.accepted)throw new b(`Task prompt was not accepted: ${o.reason}`);let O0=$0(y,n,Z.permissionMode,{preparedInputTurn:o,runtimeLease:I,outputSchema:K});return I=void 0,await O0.taskAdmissionUpdate,{session:$O(y),runId:O0.id,messageId:o.messageId,status:O0.status==="queued"?"queued":"running",queuePosition:O0.taskQueuePosition,queueDepth:O0.taskQueueDepth,maxConcurrentTasks:O0.taskConcurrencyLimit}}catch(h){if(I?.release(),I=void 0,(h instanceof W$||h instanceof xO)&&y){let c=Z0(y),l=v(c);if(f)await C0.exit({sessionId:y.id,action:"remove",discardChanges:!0}).catch(()=>{return});throw await d(y).catch(()=>{return}),await q.deleteSession(y.id,y.projectPath).catch(()=>{return}),t.delete(l),new k0(h instanceof xO?"Session runtime capacity is full":"Task admission capacity is full",{resource:h.resource,limit:h.limit})}if(y){let c=await q.findSessionMetadata(y.id,y.projectPath).catch(()=>{return});if(!c||c.taskStatus==="queued"){let l=aO(h),n=await q.updateSessionMetadata(y.id,y.projectPath,{taskStatus:"failed",taskStatusReason:l.message,taskFailure:l,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null}).catch(()=>{return});y.taskStatus=n?.taskStatus??"failed",y.taskStatusReason=n?.taskStatusReason??l.message,y.taskFailure=n?.taskFailure??l,y.taskCompletedAt=n?.taskCompletedAt}else y.taskStatus=c.taskStatus,y.taskStatusReason=c.taskStatusReason,y.taskFailure=c.taskFailure,y.taskCompletedAt=c.taskCompletedAt}throw h}},b0=(Z)=>F(()=>yO(Z)),N=async(Z,K)=>{let z=await K0(Z,K),G=await q.findSessionMetadata(z.sessionId,z.projectPath);if(!G)throw new m("Session",z.sessionId);if(!["failed","interrupted","cancelled"].includes(G.taskStatus))throw new b(`Task cannot be retried while status is ${G.taskStatus}`);let V=await q.findSessionTaskDispatch(z.sessionId,z.projectPath);if(!V)throw new b("Task retry payload is unavailable");return b0({prompt:V.prompt,title:V.title,sourceProjectPath:V.sourceProjectPath,isolation:V.isolation,permissionMode:V.permissionMode,modelId:V.modelId,reasoningEffort:V.reasoningEffort,serviceTier:V.serviceTier,responseVerbosity:V.responseVerbosity,communicationStyle:V.communicationStyle,attachments:V.attachments,outputSchema:V.outputSchema,retriedFrom:z})},V0=(Z,K)=>F(()=>N(Z,K)),k$=async(Z,K)=>{let z=await X0(Z,K);if(!z.taskWorktree)throw new L("Session does not have a task worktree");try{await C0.restoreSession(z.taskWorktree);let G=await C0.getDiffArtifact(z.id);if(!G)throw new b("Task diff artifact is unavailable");return{sessionId:z.id,projectPath:z.projectPath,...G}}catch(G){if(G instanceof b)throw G;throw P.error("[SessionRoutes] Failed to load task diff artifact:",G),new b("Task diff artifact is unavailable")}},eO=async(Z,K,z)=>{let G=await K0(Z,z);return J0(G,async()=>{let V=await X0(G.sessionId,G.projectPath);if(["queued","running"].includes(V.taskStatus))throw new b(`Task artifacts cannot be delivered while status is ${V.taskStatus}`);if(V.taskDelivery?.status==="applied")throw new b("Task changes have already been applied");if(V.taskDelivery?.status==="discarded")throw new b("Task changes have already been discarded");if(!V.taskWorktree)throw new b("Task worktree is unavailable");let H=async(D,B=!1)=>{let M=await q.updateSessionMetadata(V.id,V.projectPath,{taskDelivery:D,...B?{taskWorktree:null}:{}});if(RO(V,M),B)V.taskWorktree=void 0;return C.publish(G,"task.delivery",{taskDelivery:D,...B?{taskWorktreeRemoved:!0}:{},updatedAt:M.lastMessageTime}),$O(V)};try{if(K==="discard"){try{await C0.restoreSession(V.taskWorktree)}catch(M){return P.warn(`[SessionRoutes] Abandoning unavailable task worktree for ${V.id}:`,M),H({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:V.taskDiffStat?.changedFiles??0,message:"Task artifact discarded; worktree was unavailable"},!0)}let B=await C0.exit({sessionId:V.id,action:"remove",discardChanges:!0});return H({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:B.discardedFiles??0,message:"Task worktree removed"},!0)}try{await C0.restoreSession(V.taskWorktree)}catch(B){throw P.warn(`[SessionRoutes] Task worktree is unavailable for ${V.id}:`,B),new V$("artifact_unavailable","Task worktree is unavailable")}let D=await C0.apply(V.id);return H({status:"applied",updatedAt:new Date().toISOString(),sourceCommit:D.sourceCommit,changedFiles:D.changedFiles,message:"Task changes applied to the source workspace"})}catch(D){if(D instanceof V$)throw await H({status:"conflicted",updatedAt:new Date().toISOString(),message:D.message}),new b(D.message);throw D}})},VO=(Z,K,z)=>F(()=>eO(Z,K,z)),mO=async(Z)=>{let K=D0(Z.currentRunId);if(U0(K))return;if(Z.taskIsolation&&Z.taskStatus!=="queued"&&Z.taskStatus!=="running")return;let z=await AO.hasPendingInbox(Z.projectPath,Z.id),G=!z&&await AO.hasActiveGoal(Z.projectPath,Z.id);if(!z&&!G)return;let V=await s(Z),H=!1;try{let D=V.value,B=D0(Z.currentRunId);if(U0(B))return;if(z&&D.getPendingSteeringCount()===0)await D.reloadPendingInbox();let M=D.getPendingSteeringCount()>0,A=M?null:await D.getGoal(),E=A?.status==="active"||A?.status==="verifying";if(!M&&!E||D.hasTurnOwner())return;$0(Z,"",Z.permissionMode??"default",{pendingInputOnly:M,goalContinuationOnly:E,runtimeLease:V}),H=!0}finally{if(!H)V.release()}},q0=async(Z)=>{let K;try{K=_.enter()}catch{return}try{await mO(Z)}finally{K.release()}};ZO=q0;let hO=async()=>{let Z={scheduled:0,failed:0,deferred:0};if(!_.stats().accepting)return Z;let K=(await q.listSessions()).filter((z)=>z.taskStatus==="queued"&&z.taskIsolation!==void 0).sort((z,G)=>z.firstMessageTime.localeCompare(G.firstMessageTime)||z.projectPath.localeCompare(G.projectPath)||z.sessionId.localeCompare(G.sessionId));for(let[z,G]of K.entries()){let V={sessionId:G.sessionId,projectPath:G.projectPath};try{if(!await AO.hasPendingInbox(G.projectPath,G.sessionId)){let D=aO("Queued task input is missing");await q.updateSessionMetadata(G.sessionId,G.projectPath,{taskStatus:"failed",taskStatusReason:D.message,taskFailure:D,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null}),Z.failed++;continue}let H=await _0(V);if(await q0(H),H.currentRunId)Z.scheduled++}catch(H){if(H instanceof W$||H instanceof xO){Z.deferred+=K.length-z;break}P.warn(`[SessionRoutes] Failed to recover queued task ${G.sessionId}:`,H),Z.deferred++}}return Z};return O.get("/",async(Z)=>{try{let K=await q.listSessions(),z=new Set(K.filter((A)=>A.relationType==="subagent").map((A)=>v({sessionId:A.sessionId,projectPath:A.projectPath}))),G=Array.from(t.values()).filter((A)=>!z.has(v(Z0(A)))&&A.relationType!=="subagent").map((A)=>$O(A)),V=new Set(G.map((A)=>v({sessionId:A.sessionId,projectPath:A.projectPath}))),H=K.filter((A)=>{if(A.relationType==="subagent")return!1;return!V.has(v({sessionId:A.sessionId,projectPath:A.projectPath}))}),D=new Set(V),B=H.filter((A)=>{let E=v({sessionId:A.sessionId,projectPath:A.projectPath});if(D.has(E))return!1;return D.add(E),!0}),M=[...G,...B];return Z.json(M)}catch(K){throw P.error("[SessionRoutes] Failed to list sessions:",K),new e("Failed to list sessions")}}),O.get("/catalog",async(Z)=>{try{let K=Z.req.query("limit"),z=K===void 0?void 0:Number(K),G=Z.req.query("cursor"),V=Z.req.query("projectPath"),H=Z.req.query("archived");if(H!==void 0&&H!=="true"&&H!=="false")throw new L("archived must be true or false");let D=H==="true",B=await q.listSessionPage({...V?{cwd:MO(V)}:{},...G?{cursor:G}:{},...z===void 0?{}:{limit:z},includeSubagents:!1,archived:D}),M=new Map((D?[]:Array.from(t.values())).filter((A)=>A.relationType!=="subagent").map((A)=>[v(Z0(A)),$O(A)]));return Z.json({sessions:B.sessions.map((A)=>M.get(v({sessionId:A.sessionId,projectPath:A.projectPath}))??A),...B.nextCursor?{nextCursor:B.nextCursor}:{}})}catch(K){if(K instanceof L)throw K;if(K instanceof Error&&(K.message.startsWith("Invalid session cursor")||K.message.startsWith("Session cursor scope")||K.message.startsWith("Session catalog")))throw new L(K.message);throw P.error("[SessionRoutes] Failed to list session catalog:",K),new e("Failed to list session catalog")}}),O.post("/",async(Z)=>{try{let K=await Z.req.json(),z=g(B2,K);if(!z.success)throw new L("Invalid request body");let{title:G,projectPath:V}=z.data,H=z$("web",12),D=MO(V||Z.get("directory")||i(),V?"projectPath":"directory"),B=await q.createSessionMetadata(H,D,{title:G,taskStatus:"completed"}),M=EO(B,[]),A=Z0(M);return t.set(v(A),M),C.publish(A,"session.created",{}),Z.json({...$O(M),status:void 0,agentType:void 0,model:void 0})}catch(K){if(P.error("[SessionRoutes] Failed to create session:",K),K instanceof L)throw K;throw new e("Failed to create session")}}),O.get("/:sessionId/export",async(Z)=>{let K=Z.req.param("sessionId");try{let z=Z.req.query("includeReasoning");if(z!==void 0&&z!=="true"&&z!=="false")throw new L("includeReasoning must be true or false");let G=await K0(K,Z.req.query("projectPath")),V=await q.exportSessionMarkdown(G.sessionId,G.projectPath,{includeReasoning:z==="true"});return Z.body(V.markdown,200,{"Cache-Control":"no-store","Content-Disposition":`attachment; filename="${V.filename}"`,"Content-Length":String(Buffer.byteLength(V.markdown,"utf8")),"Content-Type":"text/markdown; charset=utf-8","X-Blade-Content-Sha256":V.contentSha256,"X-Blade-Export-Activities":String(V.activityCount),"X-Blade-Export-Messages":String(V.messageCount),"X-Blade-Export-Redactions":String(V.redactionCount)})}catch(z){if(z instanceof L||z instanceof m||z instanceof B0)throw z;if(z instanceof Error&&z.message==="No conversation content to export")throw new b(z.message);throw P.error("[SessionRoutes] Failed to export session:",z),new e("Failed to export session")}}),O.post("/:sessionId/fork",async(Z)=>{let K=Z.req.param("sessionId");try{F$(K);let z=await Z.req.json(),G=g(A2,z);if(!G.success)throw new L("Invalid request body");let V=MO(G.data.projectPath),H=await q.findSessionMetadata(K,V);if(!H)throw new m("Session",K);let D=await q.forkSession(K,{sourceProjectPath:H.projectPath,targetProjectPath:H.projectPath}),B=EO(D.metadata,D.messages),M=Z0(B);return t.set(v(M),B),C.publish(M,"task.status",{taskStatus:D.metadata.taskStatus,...D.metadata.taskCompletedAt?{taskCompletedAt:D.metadata.taskCompletedAt}:{},updatedAt:D.metadata.lastMessageTime}),Z.json({session:D.metadata,messages:Z$(D.messages)},201)}catch(z){if(z instanceof L||z instanceof m||z instanceof b)throw z;if(z instanceof T1)throw new b("Session has no durable creation record");throw P.error("[SessionRoutes] Failed to fork session:",z),new e("Failed to fork session")}}),O.get("/:sessionId",async(Z)=>{let K=Z.req.param("sessionId");try{let z=await K0(K,Z.req.query("projectPath")),G=t.get(v(z));if(G)return Z.json($O(G));let V=await q.findSessionMetadata(z.sessionId,z.projectPath);if(!V)throw new m("Session",K);return Z.json(V)}catch(z){if(z instanceof L||z instanceof m||z instanceof B0)throw z;throw P.error("[SessionRoutes] Failed to get session:",z),new e("Failed to get session")}}),O.patch("/:sessionId",async(Z)=>{let K=Z.req.param("sessionId");try{let z=await Z.req.json(),G=g(w2,z);if(!G.success)throw new L("Invalid request body");if(G.data.title===void 0)throw new L("title is required");let V=await K0(K,G.data.projectPath),H=await q.updateSessionMetadata(V.sessionId,V.projectPath,{title:G.data.title}),D=t.get(v(V));if(D)D.title=H.title??D.title,D.updatedAt=new Date(H.lastMessageTime);if(H.title)C.publish(V,"session.updated",{title:H.title});return Z.json({success:!0,title:H.title})}catch(z){if(P.error("[SessionRoutes] Failed to update session:",z),z instanceof L||z instanceof m||z instanceof B0)throw z;throw new e("Failed to update session")}}),O.get("/:sessionId/rewind",async(Z)=>{let K=await X0(Z.req.param("sessionId"),Z.req.query("projectPath"));return u(K,async(z)=>Z.json({checkpoints:await z.listRewindCheckpoints()}))}),O.post("/:sessionId/rewind",async(Z)=>{let K=g(S1,await Z.req.json());if(!K.success)throw new L("Invalid rewind request");let z=await X0(Z.req.param("sessionId"),Z.req.query("projectPath")),G=Z0(z);return S(G,async()=>{let V=D0(z.currentRunId);if(U0(V))throw new b("Cannot rewind while a run is active");return u(z,async(H)=>{let D;try{D=await H.rewindSession(K.data)}catch(M){if(M instanceof Error&&M.message.startsWith("Cannot rewind while"))throw new b(M.message);throw M}z.messages=[...D.messages],z.updatedAt=new Date;let B=Z$(D.messages);return C.publish(G,"session.rewound",{targetMessageId:D.checkpoint.messageId,mode:D.mode,removedTurns:D.removedTurns,restoredFiles:D.restoredFiles,messages:B}),Z.json({...D,messages:B})})})}),O.get("/:sessionId/review",async(Z)=>{let K=Z.req.param("sessionId"),z=await K0(K,Z.req.query("projectPath")),G=await p0.list(z.projectPath,z.sessionId);return Z.json({reviews:G.map((V)=>({...V,content:V.completion?w1(V.start,V.completion):void 0}))})}),O.post("/:sessionId/review",async(Z)=>{let K=Z.req.param("sessionId"),z=g(y1,await Z.req.json());if(!z.success)throw new L("Invalid code review request");let G=await X0(K,z.data.projectPath),V=Z0(G),H=v(V);return S(V,async()=>{if(U0(D0(G.currentRunId)))throw new b("Cannot start a review during an active turn");if(T0.has(H))throw new b("Session already has an active review");return u(G,async(D)=>{if(await p0.recoverInterrupted(V.projectPath,V.sessionId,D),z.data.modelId&&!D.getModelById(z.data.modelId))throw new L(`Model not found: ${z.data.modelId}`);if(z.data.modelId&&D.getCurrentModelId()!==z.data.modelId)await D.refresh({modelId:z.data.modelId});if(z.data.modelId&&G.selectedModelId!==z.data.modelId){let E=await q.updateSessionMetadata(G.id,G.projectPath,{selectedModelId:z.data.modelId});RO(G,E)}let B=new AbortController,M;try{M=await p0.start({sessionId:V.sessionId,projectPath:V.projectPath,runtime:D,request:{kind:z.data.kind,...z.data.ref?{ref:z.data.ref}:{},...z.data.instructions?{instructions:z.data.instructions}:{}},signal:B.signal,onEvent:(E)=>{if(E.kind==="tool_start")C.publish(V,"review.tool.started",{reviewId:M?.reviewId,toolCallId:E.toolCall.id,toolName:E.toolCall.function.name});else if(E.kind==="tool_progress")C.publish(V,"review.tool.progress",{reviewId:M?.reviewId,toolCallId:E.toolCall.id,message:E.update.message.slice(0,1000)});else if(E.kind==="tool_result")C.publish(V,"review.tool.completed",{reviewId:M?.reviewId,toolCallId:E.toolCall.id,success:E.result.success})}})}catch(E){if(E instanceof Error&&(E.message.includes("active review")||E.message.includes("interrupted review")||E.message.includes("active turn")))throw new b(E.message);if(E instanceof Error&&(E.message.includes("review")||E.message.includes("Git")||E.message.includes("changes")||E.message.includes("ref")))throw new L(E.message);throw E}if(!M)throw new e("Code review failed to start");await c0(G),C.publish(V,"review.started",{reviewId:M.reviewId,kind:z.data.kind}),C.publish(V,"task.status",{taskStatus:G.taskStatus,...G.taskStatusReason?{taskStatusReason:G.taskStatusReason}:{},...G.taskStartedAt?{taskStartedAt:G.taskStartedAt}:{},...G.taskPromptSummary?{taskPromptSummary:G.taskPromptSummary}:{},updatedAt:new Date().toISOString()});let A=M.completion.then(async(E)=>{G.messages=await q.loadSession(V.sessionId,V.projectPath),await c0(G),C.publish(V,"task.status",{taskStatus:G.taskStatus,...G.taskStatusReason?{taskStatusReason:G.taskStatusReason}:{},...G.taskFailure?{taskFailure:G.taskFailure}:{},...G.taskStartedAt?{taskStartedAt:G.taskStartedAt}:{},...G.taskCompletedAt?{taskCompletedAt:G.taskCompletedAt}:{},...G.taskPromptSummary?{taskPromptSummary:G.taskPromptSummary}:{},updatedAt:new Date().toISOString()}),C.publish(V,"review.completed",{reviewId:M.reviewId,status:E.status,findings:E.findings.length})}).catch((E)=>{P.error(`[SessionRoutes] Code review ${M.reviewId} failed:`,E)}).finally(()=>{if(T0.get(H)?.reviewId===M.reviewId)T0.delete(H)});return T0.set(H,{reviewId:M.reviewId,controller:B,completion:A}),Z.json({reviewId:M.reviewId,status:"running"},202)})})}),O.get("/:sessionId/subagents",async(Z)=>{let K=await X0(Z.req.param("sessionId"),Z.req.query("projectPath"));return u(K,(z)=>Z.json({subagents:z.listSubagents().map(iO)}))}),O.post("/:sessionId/subagents/:agentId/resume",async(Z)=>{F$(Z.req.param("agentId"));let K=I1.safeParse(await Z.req.json());if(!K.success)throw new L("Invalid subagent resume request");let z=await X0(Z.req.param("sessionId"),Z.req.query("projectPath")),G=Z0(z);return S(G,async()=>{let V=D0(z.currentRunId);if(U0(V))throw new b("Cannot resume a subagent while a parent run is active");return u(z,async(H)=>{let D=!1,B,M=(E)=>{C.publish(G,"subagent.complete",{subagentSessionId:E.id,success:E.status==="completed",status:E.status,summary:E.result?.message?.slice(0,500),type:E.subagentType,verificationVerdict:E.result?.verificationVerdict,resumedFrom:E.resumedFrom,rootAgentId:E.rootAgentId,resumeDepth:E.resumeDepth})},A;try{A=H.resumeSubagent({agentId:Z.req.param("agentId"),prompt:K.data.prompt,onEvent:(E,k)=>{k2(G,k,E)},onCompleted:(E)=>{if(D)M(E);else B=E}})}catch(E){if(E instanceof Error&&(E.message.startsWith("Cannot resume")||E.message.startsWith("Subagent cannot")))throw new b(E.message);if(E instanceof Error&&E.message.startsWith("Subagent not found"))throw new m(E.message);throw E}if(C.publish(G,"subagent.start",{subagentSessionId:A.session.id,type:A.session.subagentType,description:A.session.description,resumedFrom:A.source.id,rootAgentId:A.session.rootAgentId,resumeDepth:A.session.resumeDepth}),D=!0,B)M(B);return Z.json({source:iO(A.source),session:iO(A.session)})})})}),O.get("/:sessionId/goal",async(Z)=>{let K=await X0(Z.req.param("sessionId"),Z.req.query("projectPath"));return Z.json({goal:await new j1(K.projectPath,K.id).get()})}),O.put("/:sessionId/goal",async(Z)=>{let K=g(M2,await Z.req.json());if(!K.success)throw new L("Invalid goal request");let z=await X0(Z.req.param("sessionId"),Z.req.query("projectPath")),G=Z0(z);return S(G,async()=>{let V=D0(z.currentRunId);if(U0(V))return Z.json({status:"rejected",reason:"run_active"},409);let D=K.data.permissionMode??z.permissionMode??"default";if(z.permissionMode!==D)await NO(z,D);let B=await s(z),M=!1;try{let A=await B.value.createGoal(K.data);C.publish(G,"goal.updated",{goal:A});let E=$0(z,"",D,{goalContinuationOnly:!0,runtimeLease:B});return M=!0,await E.taskAdmissionUpdate,Z.json({status:E.status==="queued"?"queued":"running",runId:E.id,goal:A,queuePosition:E.taskQueuePosition,queueDepth:E.taskQueueDepth,maxConcurrentTasks:E.taskConcurrencyLimit},202)}finally{if(!M)B.release()}})}),O.patch("/:sessionId/goal",async(Z)=>{let K=g(E2,await Z.req.json());if(!K.success)throw new L("Invalid goal update");let z=await X0(Z.req.param("sessionId"),Z.req.query("projectPath")),G=Z0(z);return S(G,async()=>{let V=await s(z),H=!1;try{let D=V.value,B;if(K.data.action==="pause")B=await D.pauseGoal();else if(K.data.action==="edit")B=await D.editGoal(K.data.objective);else B=await D.resumeGoal();if(C.publish(G,"goal.updated",{goal:B}),B.status==="active"&&!U0(D0(z.currentRunId))){let M=$0(z,"","default",{goalContinuationOnly:!0,runtimeLease:V});return H=!0,await M.taskAdmissionUpdate,Z.json({status:M.status==="queued"?"queued":"running",runId:M.id,goal:B,queuePosition:M.taskQueuePosition,queueDepth:M.taskQueueDepth,maxConcurrentTasks:M.taskConcurrencyLimit},202)}return Z.json({status:B.status,goal:B})}finally{if(!H)V.release()}})}),O.delete("/:sessionId/goal",async(Z)=>{let K=await X0(Z.req.param("sessionId"),Z.req.query("projectPath")),z=Z0(K);return u(K,async(G)=>{let V=await G.clearGoal();if(V)C.publish(z,"goal.cleared",{});return Z.json({cleared:V})})}),O.post("/:sessionId/archive",async(Z)=>{let K=Z.req.param("sessionId");try{let z=await K0(K,Z.req.query("projectPath")),G=await q.listSessionArchiveMembers(z.sessionId,z.projectPath);for(let H of G){let D=f0({sessionId:H.sessionId,projectPath:H.projectPath}),B=t.get(v(D));if(U0(D0(B?.currentRunId)))throw new b(`Stop session ${H.sessionId} before archiving this session tree`)}for(let H of G){let D=f0({sessionId:H.sessionId,projectPath:H.projectPath}),B=t.get(v(D));if(B)await d(B)}let V=await q.archiveSession(z.sessionId,z.projectPath);for(let H of G){let D=f0({sessionId:H.sessionId,projectPath:H.projectPath}),B=v(D);t.delete(B),Q.delete(B),x.delete(B),C.publish(D,"session.archived",{archiveRootId:z.sessionId,archivedAt:V.archivedAt})}if($.size===0)await F0.getInstance().disconnectAll();return Z.json({session:V,archivedSessionIds:G.map((H)=>H.sessionId)})}catch(z){if(z instanceof L||z instanceof m||z instanceof B0||z instanceof b)throw z;if(z instanceof K$)throw new b(z.message);throw P.error("[SessionRoutes] Failed to archive session:",z),new e("Failed to archive session")}}),O.post("/:sessionId/unarchive",async(Z)=>{let K=Z.req.param("sessionId");try{let z=await K0(K,Z.req.query("projectPath")),G=await q.listSessionArchiveMembers(z.sessionId,z.projectPath),V=await q.unarchiveSession(z.sessionId,z.projectPath),H=G.filter((D)=>D.sessionId===z.sessionId||D.archivedBySessionId===z.sessionId).map((D)=>D.sessionId);for(let D of H)C.publish({sessionId:D,projectPath:z.projectPath},"session.unarchived",{archiveRootId:z.sessionId});return Z.json({session:V,restoredSessionIds:H})}catch(z){if(z instanceof L||z instanceof m||z instanceof B0)throw z;if(z instanceof K$)throw new b(z.message);throw P.error("[SessionRoutes] Failed to unarchive session:",z),new e("Failed to unarchive session")}}),O.delete("/:sessionId",async(Z)=>{let K=Z.req.param("sessionId"),z=Z.req.query("projectPath");try{let G=await K0(K,z),V=v(G),H=t.get(V),D=$.get(V),B=H?.taskWorktree??await q.findSessionTaskWorktree(G.sessionId,G.projectPath),M;if(H?.currentRunId){let k=D0(H.currentRunId);if(k)TO(k),await k.completion,M=k.id}let A=T0.get(V);if(A)A.controller.abort("session-delete"),await A.completion;if(D)await D.clearGoal().catch((k)=>{P.warn("[SessionRoutes] Failed to clear session goal:",k)});if(await q.deleteSession(G.sessionId,G.projectPath),C.publish(G,"session.deleted",{}),M)j2(M);t.delete(V),Q.delete(V),x.delete(V);let E=$.get(V);if(E){if(!await T.remove(V,E))throw new b("Session Runtime is still active and cannot be deleted")}if(B)try{await C0.restoreSession(B),await C0.exit({sessionId:G.sessionId,action:"remove",discardChanges:!0})}catch(k){P.warn(`[SessionRoutes] Failed to remove deleted task worktree ${G.sessionId}:`,k)}return Z.json({success:!0})}catch(G){if(P.error("[SessionRoutes] Failed to delete session:",G),G instanceof L||G instanceof m||G instanceof B0)throw G;throw new e("Failed to delete session")}}),O.get("/:sessionId/message",async(Z)=>{let K=Z.req.param("sessionId");try{let z=await K0(K,Z.req.query("projectPath")),G=t.get(v(z)),V=G?.messages?G.messages:await q.loadSession(z.sessionId,z.projectPath);return Z.json(Z$(V))}catch(z){if(P.error("[SessionRoutes] Failed to get messages:",z),z instanceof L||z instanceof m||z instanceof B0)throw z;throw new e("Failed to get messages")}}),O.get("/:sessionId/events",async(Z)=>{let K=Z.req.param("sessionId"),z=await K0(K,Z.req.query("projectPath"));try{await q.assertSessionWritable(z.sessionId,z.projectPath)}catch(B){if(B instanceof G$)throw new b(B.message);throw B}let G=await _0(z),V=Z.req.header("Last-Event-ID")??Z.req.query("lastEventId"),H=V?Number.parseInt(V,10):Number.NaN,D=Number.isInteger(H)?H+1:void 0;return _2(Z,async(B)=>{let A,E,k=!1,G0,I0,M0=new Promise((f)=>{I0=f}),Y0=()=>{if(E!==void 0)clearInterval(E),E=void 0;A?.(),A=void 0},r=(f)=>{if(k)return;k=!0,Y0(),G0?.close(f),I0()},o0=new Set;B.onAbort(r),G0=new DO({write:async(f)=>{await B.writeSSE(f)},onFailure:(f)=>{P.warn(`[SessionRoutes] SSE egress closed for ${z.sessionId}: kind=${f.kind} pendingItems=${f.pendingItems??0} pendingBytes=${f.pendingBytes??0}`),r(f)}}),A=C.subscribe((f)=>{if(f.sessionId!==z.sessionId||f.projectPath!==z.projectPath)return;let y=f.properties.requestId;if((f.type==="permission.asked"||f.type==="question.required"||f.type==="elicitation.required")&&typeof y==="string"){if(o0.has(y))return;o0.add(y)}if(f.type==="subagent.completion.queued")S(z,()=>q0(G)).catch((I)=>{P.error(`[SessionRoutes] Failed to wake background completion for ${G.id}:`,I)});G0?.observe(R2(f),f.seq)});try{if(B.aborted||k)return;let f=D0(G.currentRunId),y=U0(f)?await s(G):void 0;try{let c=y?.value,l=c?.getPendingSteeringCount()??0;await G0.writeInitial({data:JSON.stringify({type:"connected",properties:{sessionId:z.sessionId,projectPath:z.projectPath,timestamp:Date.now(),status:U0(f)?f.status:"idle",runId:U0(f)?f.id:void 0,queued:l,pendingInputDelivery:l>0?c?.hasActiveTurn()?"current_turn":"next_turn":null,recovered:c?.getRecoveredSteeringCount()??0}})})}finally{y?.release()}if(B.aborted||k)return;if(D!==void 0){if(await R1.for(z.sessionId,z.projectPath).replay({onCommitted:async(l)=>{if(B.aborted||k)return;let n=q2(l);if(n.seq===void 0)return;await G0.writeReplay({...typeof l.seq==="number"?{id:String(l.seq)}:{},data:JSON.stringify({type:n.type,...n.seq!==void 0?{seq:n.seq}:{},properties:{...n.properties,sessionId:z.sessionId,projectPath:z.projectPath}})},n.seq)}},D),B.aborted||k)return}if(G0.finishInitialization({replayed:D!==void 0}),B.aborted||k)return;if(!f&&!T0.has(v(z))){let l=(await p0.list(z.projectPath,z.sessionId)).some((n)=>n.completion===void 0)?await u(G,(n)=>p0.recoverInterrupted(z.projectPath,z.sessionId,n)):void 0;if(l)G.messages=await q.loadSession(z.sessionId,z.projectPath),await c0(G),C.publish(z,"review.completed",{reviewId:l.reviewId,status:l.status,findings:0,recovered:!0})}if(B.aborted||k)return;if(!f)await l0.recoverResponded(z.projectPath,z.sessionId);if(B.aborted||k)return;let I=f?void 0:await l0.findPending(z.projectPath,z.sessionId),h=f?.pendingPermission??(I?{permissionId:I.request.requestId,details:l0.confirmationDetails(I),resolve:()=>{return}}:void 0);if(h){o0.add(h.permissionId);let c=h1(h,!0);G0.observe({data:JSON.stringify({type:c.type,properties:{...c.properties,sessionId:z.sessionId,projectPath:z.projectPath}})})}if(B.aborted||k)return;if(q0(G).catch((c)=>{P.error(`[SessionRoutes] Failed to resume pending input for ${K}:`,c)}),B.aborted||k)return;E=setInterval(()=>{if(B.aborted||k)return;G0?.offerHeartbeat({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})})},15000),await M0}finally{r()}})}),O.post("/:sessionId/message",async(Z)=>{let K=Z.req.param("sessionId"),z=await Z.req.json(),G=g(L2,z);if(!G.success)throw new L("Invalid message format");let{content:V,attachments:H,modelId:D,reasoningEffort:B,serviceTier:M,responseVerbosity:A,communicationStyle:E,permissionMode:k,projectPath:G0,outputSchema:I0}=G.data,M0;if(I0)try{M0=X$(I0).schema}catch(l){throw new L(l instanceof Error?l.message:"Invalid output schema")}let Y0=E,r=D?.trim();if((H??[]).reduce((l,n)=>l+(typeof n.content==="string"?Buffer.byteLength(n.content):0),0)>oO)throw new L("Message attachments exceed the 5 MiB limit");let f=k,y=V1(V,H),I=await X0(K,G0??Z.req.query("projectPath")),h=f??I.permissionMode??"default",c=Z0(I);return S(c,async()=>{let l=D0(I.currentRunId);if(U0(l)){if(M0)throw new b("Wait for the active turn to finish before setting an output schema");return u(I,async(o)=>{if(r&&!o.getModelById(r))throw new L(`Model not found: ${r}`);if(r&&o.getCurrentModelId()!==r)throw new b("Wait for the active turn to finish before switching models");if(B&&o.getReasoningConfiguration().selection!==B)throw new b("Wait for the active turn to finish before switching reasoning effort");if(M&&o.getServiceTierConfiguration().selection!==M)throw new b("Wait for the active turn to finish before switching service tier");if(A&&o.getResponseVerbosityConfiguration().selection!==A)throw new b("Wait for the active turn to finish before switching response verbosity");if(Y0&&o.getCommunicationStyleConfiguration().selection!==Y0)throw new b("Wait for the active turn to finish before switching communication style");if(f&&I.permissionMode!==f)throw new b("Wait for the active turn to finish before switching permission mode");let O0=await o.enqueueSteering(y,{allowBeforeTurn:!0});if(!O0.accepted)return Z.json({status:"rejected",reason:O0.reason??"turn_unavailable"},409);let v0=O0.messageId??JO(12),FO=O0.queued;C.publish(c,"message.created",{messageId:v0,role:"user",content:U$(y)});let gO=O0.delivery==="next_turn"?"follow_up.queued":"steering.queued";if(C.publish(c,gO,{runId:l.id,messageId:v0,queued:FO}),O0.delivery==="next_turn"&&l.status!=="running"&&l.status!=="waiting_permission")q0(I).catch((vO)=>{P.error(`[SessionRoutes] Failed to wake queued follow-up for ${K}:`,vO)});if(O0.delivery==="next_turn")l.pendingFollowUpRequested=!0;return Z.json({runId:l.id,messageId:v0,status:O0.delivery==="next_turn"?"follow_up_queued":"steering_queued",queued:FO},202)})}if(I.permissionMode!==h)await NO(I,h);let n=await s(I,{permissionMode:h,...Y0&&!Y0.includes(":")?{communicationStyle:Y0}:{}}),WO=!1;try{let o=n.value;if(r&&!o.getModelById(r))throw new L(`Model not found: ${r}`);if(B)try{o.resolveReasoningConfiguration(B,r)}catch(z0){throw new L(z0 instanceof Error?z0.message:"Invalid reasoning effort")}if(M)try{o.resolveServiceTierConfiguration(M,r)}catch(z0){throw new L(z0 instanceof Error?z0.message:"Invalid service tier")}if(A)try{o.resolveResponseVerbosityConfiguration(A,r)}catch(z0){throw new L(z0 instanceof Error?z0.message:"Invalid response verbosity")}let O0=Y0?o.resolveCommunicationStyleConfiguration(Y0):void 0;if(O0?.source!==void 0&&O0.source!=="built-in"&&!O0.contentSha256)throw new L("Custom communication style has no provenance");let v0=o.getCurrentModelId(),FO=o.getReasoningConfiguration(),gO=o.getServiceTierConfiguration(),vO=o.getResponseVerbosityConfiguration(),I$=o.getCommunicationStyleConfiguration(),P$=Boolean(r)&&v0!==r,f$=Boolean(B)&&FO.selection!==B,y$=Boolean(M)&&gO.selection!==M,m$=Boolean(A)&&vO.selection!==A,h$=Boolean(Y0)&&I$.selection!==Y0;if(P$||f$||y$||m$||h$)await o.refresh({...r?{modelId:r}:{},...B?{reasoningEffort:B}:{},...M?{serviceTier:M}:{},...A?{responseVerbosity:A}:{},...Y0?{communicationStyle:Y0}:{}});let O$={...r&&I.selectedModelId!==r?{selectedModelId:r}:{},...B&&I.reasoningEffort!==B?{reasoningEffort:B}:{},...M&&I.serviceTier!==M?{serviceTier:M}:{},...A&&I.responseVerbosity!==A?{responseVerbosity:A}:{},...O0&&(I.communicationStyle!==Y0||I.communicationStyleDigest!==O0.contentSha256)?{communicationStyle:Y0,communicationStyleDigest:O0.source==="built-in"?null:O0.contentSha256}:{}};if(Object.keys(O$).length>0)try{let z0=await q.updateSessionMetadata(I.id,I.projectPath,O$);I.permissionMode=z0.permissionMode,I.selectedModelId=z0.selectedModelId,I.reasoningEffort=z0.reasoningEffort,I.serviceTier=z0.serviceTier,I.responseVerbosity=z0.responseVerbosity,I.communicationStyle=z0.communicationStyle,I.communicationStyleDigest=z0.communicationStyleDigest,I.updatedAt=new Date(z0.lastMessageTime),C.publish(c,"session.updated",O$)}catch(z0){if(P$||f$||y$||m$||h$)await o.refresh({...v0?{modelId:v0}:{},reasoningEffort:FO.selection,serviceTier:gO.selection,responseVerbosity:vO.selection,communicationStyle:I$.selection}).catch((l4)=>P.error("[SessionRoutes] Failed to roll back non-durable model settings:",l4));throw z0}let UO=M0?await o.prepareInputTurn(y,{outputSchema:M0}):await o.prepareInputTurn(y);if(!UO.accepted)return Z.json({status:"rejected",reason:UO.reason},UO.reason==="queue_full"?429:409);let n0=$0(I,y,h,{preparedInputTurn:UO,outputSchema:M0,runtimeLease:n});return WO=!0,await n0.taskAdmissionUpdate,Z.json({runId:n0.id,messageId:UO.messageId,status:n0.status==="queued"?"queued":"running",queuePosition:n0.taskQueuePosition,queueDepth:n0.taskQueueDepth,maxConcurrentTasks:n0.taskConcurrencyLimit},202)}finally{if(!WO)n.release()}})}),O.post("/:sessionId/shell",async(Z)=>{let K=Z.req.param("sessionId"),z=g(f1,await Z.req.json());if(!z.success)throw new L("Invalid user shell command");let G=await X0(K,z.data.projectPath??Z.req.query("projectPath")),V=Z0(G),H=v(V);return S(V,async()=>{if(S0.has(H))throw new b("A user shell command is already running in this Session");let D=await s(G),B=D.value,M=new AbortController,A,E=new Promise((k)=>{A=k});S0.set(H,{controller:M,completion:E});try{let k=await B.executeUserShellCommand(z.data.command,{signal:M.signal});G.messages=await q.loadSession(G.id,G.projectPath),G.updatedAt=new Date;let G0=D0(G.currentRunId);if(k.delivery==="next_turn"&&U0(G0))G0.pendingFollowUpRequested=!0;return Z.json({executionId:k.executionId,messageId:k.messageId,record:k.record,auxiliary:k.auxiliary,...k.delivery?{delivery:k.delivery}:{},...k.queued!==void 0?{queued:k.queued}:{}})}finally{S0.delete(H),A(),D.release()}})}),O.post("/:sessionId/abort",async(Z)=>{let K=Z.req.param("sessionId"),z=await K0(K,Z.req.query("projectPath")),G=t.get(v(z));if(G?.currentRunId){let D=D0(G.currentRunId);if(D)TO(D),await D.completion}let V=S0.get(v(z));if(V)V.controller.abort("user-cancel"),await V.completion;let H=T0.get(v(z));if(H)H.controller.abort("user-cancel"),await H.completion;return Z.json({success:!0})}),O.get("/:sessionId/status",async(Z)=>{let K=Z.req.param("sessionId"),z=await K0(K,Z.req.query("projectPath")),G=t.get(v(z)),V=T0.get(v(z));if(V)return Z.json({sessionId:K,projectPath:z.projectPath,reviewId:V.reviewId,status:"reviewing"});if(!G?.currentRunId)return Z.json({sessionId:K,projectPath:z.projectPath,status:"idle"});let H=D0(G.currentRunId);return Z.json({sessionId:K,projectPath:z.projectPath,runId:G.currentRunId,status:H?.status||"idle"})}),{app:O,dispatchTask:b0,retryTask:V0,getTaskDiff:k$,deliverTask:VO,recoverQueuedTasks:hO,getRuntimeResidencyStats:()=>T.getStats(),getCoordinationStats:()=>({messageSubmissions:X.getStats(),taskDeliveries:Y.getStats()}),shutdown:(Z="server-shutdown")=>{if(w)return w;return _.close(Z),clearInterval(j),w=(async()=>{let K,z=async(B)=>{let M=await Promise.allSettled(B);for(let A of M)if(A.status==="rejected")K??=A.reason},G=new Set,V=()=>{for(let B of j0.values()){if(B.completion)G.add(B.completion);if(U0(B))TO(B,Z)}for(let B of S0.values())B.controller.abort(Z),G.add(B.completion);for(let B of T0.values())B.controller.abort(Z),G.add(B.completion)},H=_.waitForIdle(),D=!1;H.then(()=>{D=!0});while(!D)V(),await Promise.race([H,new Promise((B)=>setImmediate(B))]);if(await H,V(),await z([...G]),await z([...x.values()]),V(),await z([...G]),await z([T.disposeAll()]),$.clear(),await z([...J.values()]),await z([F0.getInstance().disconnectAll()]),x.clear(),J.clear(),Q.clear(),t.clear(),ZO===q0)ZO=void 0;if(K!==void 0)throw K})(),w}}};async function S2(O,$,x,J,Q,X={}){let{abortController:Y,sessionId:W,id:T}=O,_=X.preparedInputTurn?.messageId??JO(12),w=X.pendingInputOnly===!0||X.preparedInputTurn?.mode==="pending"||X.goalContinuationOnly===!0?void 0:JO(12),F=X.runtimeLease,S,J0,p=Z0($),R=(u,d)=>{C.publish(p,u,d)},s=async()=>{let u=String(Y.signal.reason||"Task run cancelled");if($.taskIsolation){if(!F)F=await Q($).catch(()=>{return});let d=S??F?.value;if(u==="user-cancel")await d?.discardPendingInput().catch((X0)=>{P.warn(`[SessionRoutes] Failed to discard cancelled input for ${$.id}:`,X0)});let _0=await d?.setTaskStatus("cancelled",u).catch(()=>{return});if(_0)RO($,_0);else await c0($).catch(()=>{return})}$.taskStatus="cancelled",$.taskStatusReason=u,$.taskCompletedAt??=new Date().toISOString()};try{if(X.taskAdmission){if(await X.taskAdmission.ready,await O.taskAdmissionUpdate,Y.signal.aborted)throw Error(String(Y.signal.reason||"Task run cancelled"))}if($.taskStatus="running",$.taskStatusReason=void 0,$.taskStartedAt=new Date().toISOString(),$.taskCompletedAt=void 0,!X.pendingInputOnly&&!X.goalContinuationOnly)R("message.created",{messageId:_,role:"user",content:U$(x)});if(R("session.status",{status:"running"}),w)R("message.created",{messageId:w,role:"assistant",content:""});F??=await Q($),S=F.value;let u=S,d=Boolean(X.outputSchema??u.getPendingSteeringMessages().find((N)=>N.outputSchema)?.outputSchema);J0=await q1.createWithRuntime(u,{sessionId:W,...$.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}});let _0=async(N)=>{let V0=N.interactionRequestId??JO(12),k$=300000;O.status="waiting_permission";let eO=new Promise((hO)=>{let S$=setTimeout(()=>{P.warn(`[SessionRoutes] Permission ${V0} timed out after 300000ms`),R("permission.timeout",{requestId:V0}),hO({approved:!1,reason:"timeout"})},300000);O.pendingPermission={permissionId:V0,resolve:(Z)=>{clearTimeout(S$),hO(Z)},details:N}}),VO=O.pendingPermission;if(!VO)throw Error("Permission request was not registered");let mO=h1(VO);R(mO.type,mO.properties),P.info(`[SessionRoutes] Permission request created: ${V0}, runId: ${T}`);let q0=await eO;if(P.info(`[SessionRoutes] Permission response received: ${V0}, approved: ${q0.approved}`),!Y.signal.aborted)O.status="running";if(O.pendingPermission===VO)O.pendingPermission=void 0;return R("interaction.resolved",{requestId:V0}),q0},NO={messages:await q.loadSessionModelContext($.id,$.projectPath),userId:"web-user",sessionId:W,workspaceRoot:$.projectPath,signal:Y.signal,permissionMode:J,onPermissionModeChange:async(N)=>{$.permissionMode=N,$.updatedAt=new Date,R("session.updated",{permissionMode:N})},...$.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:_0}},$0=()=>{if(!w)w=JO(12),R("message.created",{messageId:w,role:"assistant",content:""});return w},yO=async(N)=>{switch(N.kind){case"content_delta":if(d)break;R("message.delta",{messageId:$0(),delta:N.delta});break;case"structured_output":R("structured.output",{messageId:$0(),output:N.output,schemaDigest:N.schemaDigest});break;case"thinking_delta":R("thinking.delta",{messageId:$0(),delta:N.delta});break;case"tool_start":if("function"in N.toolCall){if(N.toolCall.function.name===QO)break;R("tool.start",{messageId:$0(),toolName:N.toolCall.function.name,toolCallId:N.toolCall.id,arguments:N.toolCall.function.arguments,toolKind:N.toolKind})}break;case"tool_result":if("function"in N.toolCall){if(N.toolCall.function.name===QO)break;R("tool.result",{messageId:$0(),toolName:N.toolCall.function.name,toolCallId:N.toolCall.id,success:N.result.success,summary:N.result.metadata?.summary,output:kO(bO(qO(N.toolCall.function.name,N.result),CO)),metadata:jO(N.toolCall.function.name,N.result.metadata)})}break;case"tool_progress":if("function"in N.toolCall){if(N.toolCall.function.name===QO)break;R("tool.progress",{messageId:$0(),toolName:N.toolCall.function.name,toolCallId:N.toolCall.id,...N.update})}break;case"token_usage":R("token.usage",{...N.usage});break;case"turn_start":R("turn.started",{turn:N.turn,maxTurns:N.maxTurns});break;case"provider_admission":R("provider.admission",{phase:N.phase,requestClass:N.requestClass,resource:N.resource,scope:N.scope,reason:N.reason,queuePosition:N.queuePosition,queueDepth:N.queueDepth,inFlight:N.inFlight,limit:N.limit,waitMs:N.waitMs,maxWaitMs:N.maxWaitMs,recoveryRemainingMs:N.recoveryRemainingMs});break;case"provider_circuit":R("provider.circuit",{phase:N.phase,reason:N.reason,statusCode:N.statusCode,retryAfterMs:N.retryAfterMs,nextProbeAt:N.nextProbeAt,openDurationMs:N.openDurationMs,sampleCount:N.sampleCount,failureCount:N.failureCount,recoveryRemainingMs:N.recoveryRemainingMs});break;case"provider_retry":R("provider.retry",{phase:N.phase,attempt:N.attempt,maxRetries:N.maxRetries,reason:N.reason,statusCode:N.statusCode,delayMs:N.delayMs,nextRetryAt:N.nextRetryAt,mode:N.mode,recoveryBudgetMs:N.recoveryBudgetMs,recoveryElapsedMs:N.recoveryElapsedMs,recoveryRemainingMs:N.recoveryRemainingMs,exhaustedBy:N.exhaustedBy});break;case"provider_stall":R("provider.stall",{phase:N.phase,stallCount:N.stallCount,durationMs:N.durationMs,warningAfterMs:N.warningAfterMs,timeoutMs:N.timeoutMs,outputStarted:N.outputStarted});break;case"action_stationarity":R("action.stationarity",{phase:N.phase,toolName:N.toolName,runLength:N.runLength,nudgeThreshold:N.nudgeThreshold,haltThreshold:N.haltThreshold,progressAware:N.progressAware});break;case"mcp_catalog_changed":R("mcp.catalog.changed",{messageId:$0(),revision:N.revision,serverName:N.serverName,added:N.added,removed:N.removed,updated:N.updated});break;case"mcp_content_changed":R("mcp.content.changed",{messageId:$0(),revision:N.revision,serverName:N.serverName,contentKind:N.contentKind,added:N.added,removed:N.removed,updated:N.updated});break;case"mcp_resource_updated":R("mcp.resource.updated",{messageId:$0(),revision:N.revision,serverName:N.serverName,uri:N.uri});break;case"mcp_connection_changed":R("mcp.connection.changed",{messageId:$0(),revision:N.revision,serverName:N.serverName,phase:N.phase,reason:N.reason,attempt:N.attempt,maxAttempts:N.maxAttempts,nextRetryAt:N.nextRetryAt,error:N.error});break;case"mcp_log":R("mcp.log",{messageId:$0(),revision:N.revision,serverName:N.serverName,level:N.level,logger:N.logger,message:N.message,projectedBytes:N.projectedBytes,dataSha256:N.dataSha256,truncated:N.truncated,detailsOmitted:N.detailsOmitted,timestamp:N.timestamp,synthetic:N.synthetic});break;case"mcp_instructions_changed":R("mcp.instructions.changed",{messageId:$0(),revision:N.revision,serverName:N.serverName,action:N.action,reason:N.reason,text:N.text,sourceBytes:N.sourceBytes,projectedBytes:N.projectedBytes,sha256:N.sha256,truncated:N.truncated,detailsOmitted:N.detailsOmitted});break;case"mcp_task_changed":R("mcp.task.changed",{messageId:$0(),revision:N.revision,taskId:N.taskId,serverName:N.serverName,toolName:N.toolName,status:N.status,statusMessage:N.statusMessage,createdAt:N.createdAt,updatedAt:N.updatedAt,completedAt:N.completedAt,hasResult:N.hasResult,error:N.error});break;case"project_rules_loaded":R("project.rules.loaded",{messageId:$0(),files:N.files,triggerPaths:N.triggerPaths,blockedWrite:N.blockedWrite});break;case"steering_applied":R("steering.applied",{runId:T,messageIds:N.messageIds,count:N.count,recovered:N.recovered,delivery:N.delivery,queued:u.getPendingSteeringCount()});break;case"follow_up_started":{if(w)R("message.complete",{messageId:w}),w=void 0;for(let V0 of N.messages){if(!V0.recovered||V0.persisted)continue;R("message.created",{messageId:V0.id,role:"user",content:U$(V0.content),recovered:!0})}R("follow_up.started",{runId:T,queued:N.queued,recovered:N.recovered}),$0();break}case"goal_updated":R("goal.updated",{goal:N.goal});break;case"goal_continuation_started":R("goal.continuation.started",{goal:N.goal,continuation:N.continuation}),$0();break;case"compaction":R(N.phase==="start"?"compaction.started":"compaction.completed",{...N.reason?{reason:N.reason}:{},...N.strategy?{strategy:N.strategy}:{},...N.outcome?{outcome:N.outcome}:{},...N.preTokens!==void 0?{preTokens:N.preTokens}:{},...N.postTokens!==void 0?{postTokens:N.postTokens}:{}});break;case"model_fallback":R("model.fallback",{});break;case"task_update":R("task.updated",{tasks:N.tasks});break;default:break}},b0=await N$(J0.chatStream(x,NO,{stream:!0,pendingInputOnly:X.pendingInputOnly,preparedInputTurn:X.preparedInputTurn,goalContinuationOnly:X.goalContinuationOnly,outputSchema:X.outputSchema,taskAdmission:X.taskAdmission}),yO);if(!b0.success)throw Error(b0.error?.message??"Agent run failed");for(let N=0;N<20;N++){let V0=O.pendingFollowUpRequested===!0;if(O.pendingFollowUpRequested=!1,u.getPendingSteeringCount()===0){if(!V0)break;continue}if(Y.signal.aborted)break;if(b0=await N$(J0.chatStream("",NO,{stream:!0,pendingInputOnly:!0,taskAdmission:X.taskAdmission}),yO),!b0.success)throw Error(b0.error?.message??"Agent follow-up failed")}if($.messages=await q.loadSession($.id,$.projectPath),$.updatedAt=new Date,await c0($),Y.signal.aborted||O.status==="cancelled"){await s(),R("session.status",{status:"idle"});return}if(w)R("message.complete",{messageId:w});R("thinking.completed",{}),O.status="completed",$.taskStatus="completed",$.taskCompletedAt??=new Date().toISOString(),R("session.completed",{runId:T,outputTruncated:b0.metadata?.outputTruncated??!1}),R("session.status",{status:"idle"})}catch(u){if(S&&X.preparedInputTurn)await S.finishTurn(X.preparedInputTurn.handle).catch(()=>{return});if(Y.signal.aborted||O.status==="cancelled"){TO(O,"runtime-abort"),await s(),R("session.status",{status:"idle"});return}await c0($).catch(()=>{return}),P.error("[SessionRoutes] Agent execution error:",u),O.status="failed",$.taskStatus="failed",$.taskCompletedAt??=new Date().toISOString();let d=aO(u);if(!$.taskFailure){let _0=S?await S.setTaskStatus("failed",u).catch(()=>{return}):await q.updateSessionMetadata($.id,$.projectPath,{taskStatus:"failed",taskStatusReason:d.message,taskFailure:d,taskCompletedAt:$.taskCompletedAt,taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null}).catch(()=>{return});if(_0)RO($,_0)}$.taskStatusReason??=d.message,$.taskFailure??=d,R("session.error",{error:$.taskFailure.message,taskFailure:$.taskFailure}),R("session.status",{status:"error"})}finally{if(X.taskAdmission?.release(),X.taskAdmission){let u=e0.getStats();R("task.status",{taskStatus:$.taskStatus,...$.taskStatusReason?{taskStatusReason:$.taskStatusReason}:{},...$.taskFailure?{taskFailure:$.taskFailure}:{},...$.taskStartedAt?{taskStartedAt:$.taskStartedAt}:{},...$.taskCompletedAt?{taskCompletedAt:$.taskCompletedAt}:{},...$.taskDiffStat?{taskDiffStat:$.taskDiffStat}:{},taskQueueDepth:u.queued,taskConcurrencyLimit:u.maxConcurrent,taskInFlight:u.inFlight,updatedAt:new Date().toISOString()})}if(await J0?.destroy().catch(()=>{return}),F?.release(),O.disposeRuntimeOnSettle&&X.disposeRuntime)await X.disposeRuntime($,S).catch((u)=>{P.warn(`[SessionRoutes] Failed to dispose terminal task runtime ${$.id}:`,u)});T2(O)}}async function v1(O,$,x){P.info(`[SessionRoutes] Looking for permission ${$} in session ${O.sessionId}`),P.info(`[SessionRoutes] Active runs: ${j0.size}`);for(let[X,Y]of j0.entries())if(P.info(`[SessionRoutes] Checking run ${X}: sessionId=${Y.sessionId}, projectPath=${Y.projectPath}, pendingPermission=${Y.pendingPermission?.permissionId}`),Y.sessionId===O.sessionId&&Y.projectPath===O.projectPath&&Y.pendingPermission?.permissionId===$){if(Y.pendingPermission.details.interactionRequestId)await l0.respond(O.projectPath,O.sessionId,$,x);return Y.pendingPermission.resolve(x),P.info(`[SessionRoutes] Permission ${$} responded, runId: ${Y.id}`),!0}let J=await l0.findPending(O.projectPath,O.sessionId);if(!J||J.request.requestId!==$)return P.error(`[SessionRoutes] Permission not found: ${$}`),!1;await l0.respondAndRecover(O.projectPath,O.sessionId,$,x);let Q=t.get(v(O));if(!Q){let X=await q.findSessionMetadata(O.sessionId,O.projectPath);if(!X)return!1;let[Y,W]=await Promise.all([q.loadSession(O.sessionId,O.projectPath),q.findSessionTaskWorktree(O.sessionId,O.projectPath)]);Q=EO(X,Y,W),t.set(v(O),Q)}else await c0(Q);if(C.publish(O,"interaction.resolved",{requestId:$}),ZO)ZO(Q).catch((X)=>{P.error(`[SessionRoutes] Failed to resume recovered interaction ${$}:`,X)});return!0}var _$=a("Service"),P2=U.Object({approved:U.Boolean(),remember:U.Optional(U.Boolean()),scope:U.Optional(W0(["once","session","project"])),targetMode:U.Optional(W0(["default","autoEdit","plan","yolo"])),feedback:U.Optional(U.String({maxLength:4000})),answers:U.Optional(U.Record(U.String({maxLength:80}),U.Union([U.String({maxLength:4000}),U.Array(U.String({maxLength:1000}),{maxItems:4})]),{maxProperties:4})),elicitation:U.Optional(U.Object({action:W0(["accept","decline","cancel"]),content:U.Optional(U.Record(U.String(),U.Union([U.String({maxLength:4000}),U.Number(),U.Boolean(),U.Array(U.String({maxLength:1000}),{maxItems:100})]),{maxProperties:32}))}))}),u1=()=>{let O=new I2;return O.post("/:permissionId",async($)=>{let x=$.req.param("permissionId"),J=$.req.query("sessionId"),Q=$.req.query("projectPath");_$.info(`[PermissionRoutes] Received permission response: permissionId=${x}, sessionId=${J}`);try{let X=await $.req.json(),Y=g(P2,X);if(!Y.success)throw new L("Invalid permission response format");let{approved:W,remember:T,scope:_,targetMode:j,feedback:w,answers:F,elicitation:S}=Y.data;if(!J)throw new L("sessionId query parameter is required");let J0=await K0(J,Q);if(!await v1(J0,x,{approved:W,reason:w,scope:_,targetMode:j,feedback:w,answers:F,elicitation:S}))throw new m("Permission request",x);return _$.info(`[PermissionRoutes] Permission ${x} ${W?"approved":"denied"}`),$.json({success:!0,approved:W,remember:T})}catch(X){if(_$.error("[PermissionRoutes] Failed to respond to permission:",X),X instanceof L||X instanceof B0||X instanceof m||X instanceof Q0)throw X;throw X}}),O};import d1 from"node:path";import{Hono as f2}from"hono";var y2=U.Object({projectPath:U.String({minLength:1}),enabled:U.Boolean(),scope:U.Optional(W0(["local","project","global"]))}),m2=U.Object({projectPath:U.String({minLength:1})}),h2=U.Object({projectPath:U.String({minLength:1}),source:U.String({minLength:1}),trust:U.Literal(!0),ref:U.Optional(U.String({minLength:1}))}),g2=U.Object({projectPath:U.String({minLength:1}),trust:U.Literal(!0)}),v2=U.Object({projectPath:U.String({minLength:1}),confirm:U.Literal(!0)}),u2=U.Object({projectPath:U.String({minLength:1}),source:U.String({minLength:1}),ref:U.Optional(U.String({minLength:1}))}),p1=U.Object({projectPath:U.String({minLength:1}),confirm:U.Optional(U.Literal(!0))}),d2=U.Object({projectPath:U.String({minLength:1}),scope:U.Optional(W0(["local","project","global"])),policy:U.Object({restrictToAllowedSources:U.Boolean(),requireGitCommitSha:U.Boolean(),allowedGitHosts:U.Array(U.String()),allowedMarketplaces:U.Array(U.String()),allowedLocalRoots:U.Array(U.String())})});function w0(O){if(!O||!d1.isAbsolute(O))throw new L("projectPath must be absolute");return d1.resolve(O)}async function l1(O){let[$,x]=await Promise.all([E0(O),HO.getInstance().loadWorkspacePluginSettingsResolution(O)]);return $.plugins.getAll().map((J)=>({name:J.manifest.name,description:J.manifest.description,version:J.manifest.version,source:J.source,enabled:J.status==="active",status:J.status,commands:J.commands.length,skills:J.skills.length,agents:J.agents.length,hooks:J.hooks?Object.values(J.hooks).reduce((Q,X)=>Q+(Array.isArray(X)?X.length:0),0):0,mcpServers:Object.keys(J.mcpServers??{}).length,configurable:J.source!=="cli",managed:J.installation!==void 0,marketplace:J.installation?.source.type==="marketplace"?J.installation.source.marketplace:void 0,revision:J.installation?.revision,installedAt:J.installation?.installedAt,updatedAt:J.installation?.updatedAt,compatibilityIssues:J.compatibilityIssues??[],effectiveScope:J.source==="cli"?"invocation":x.settings[J.manifest.name]?.effectiveScope??"default",settingLayers:J.source==="cli"?{invocation:!0}:x.settings[J.manifest.name]?.layers??{}}))}async function p2(){let O=c1(),[$,x]=await Promise.all([O.listCatalogs(),O.listInstallationRecords()]),J=new Map(x.map((Q)=>[Q.name,Q]));return $.map(({marketplace:Q,manifest:X})=>({name:Q.name,description:X.description??X.metadata?.description??"",sourceType:Q.source.type,revision:Q.revision,updatedAt:Q.updatedAt,plugins:X.plugins.map((Y)=>{let W=J.get(Y.name);return{name:Y.name,description:Y.description??"",version:Y.version,category:Y.category,tags:Y.tags??[],installed:W!==void 0,installedVersion:W?.version}})}))}function YO(O,$){if(!O.success)throw new L(O.error??$)}var $4=()=>{let O=new f2;return O.get("/",async($)=>{let x=w0($.req.query("projectPath"));return $.json(await l1(x))}),O.post("/refresh",async($)=>{let x=g(m2,await $.req.json());if(!x.success)throw new L("Invalid plugin refresh request");let J=w0(x.data.projectPath),Q=await a1(J);return $.json({plugins:await l1(J),errors:Q.discovery.errors.map((X)=>({code:X.code??"LOAD_ERROR",error:X.error}))})}),O.get("/catalog",async($)=>{return w0($.req.query("projectPath")),$.json(await p2())}),O.get("/policy",async($)=>{let x=w0($.req.query("projectPath")),J=await HO.getInstance().loadWorkspacePluginSourcePolicy(x);return $.json({policy:J,environmentRequiresSha:process.env.BLADE_PLUGIN_REQUIRE_SHA==="1"||process.env.BLADE_PLUGIN_REQUIRE_SHA==="true"})}),O.post("/policy",async($)=>{let x=g(d2,await $.req.json());if(!x.success)throw new L("Invalid plugin source policy request");let J=w0(x.data.projectPath),Q=await o1(J,x.data.policy,x.data.scope??"global");return $.json({policy:Q})}),O.post("/install",async($)=>{let x=g(h2,await $.req.json());if(!x.success)throw new L("Invalid plugin install request; explicit source trust is required");let J=w0(x.data.projectPath),{result:Q}=await n1(J,x.data.source,{trusted:x.data.trust,ref:x.data.ref});return YO(Q,"Plugin installation failed"),$.json({name:Q.pluginName,version:Q.manifest?.version,revision:Q.installation?.revision,changed:Q.changed,installedDependencies:Q.installedDependencies??[]})}),O.post("/marketplaces",async($)=>{let x=g(u2,await $.req.json());if(!x.success)throw new L("Invalid marketplace add request");let J=w0(x.data.projectPath),Q=await r1(J,x.data.source,x.data.ref);return YO(Q,"Marketplace installation failed"),$.json({name:Q.marketplace?.name,plugins:Q.manifest?.plugins.length??0,revision:Q.marketplace?.revision,changed:Q.changed})}),O.post("/marketplaces/:name/refresh",async($)=>{let x=g(p1,await $.req.json());if(!x.success)throw new L("Invalid marketplace refresh request");let J=await e1(w0(x.data.projectPath),$.req.param("name"));return YO(J,"Marketplace refresh failed"),$.json({name:J.marketplace?.name,plugins:J.manifest?.plugins.length??0,revision:J.marketplace?.revision,changed:J.changed})}),O.post("/marketplaces/:name/remove",async($)=>{let x=g(p1,await $.req.json());if(!x.success||x.data.confirm!==!0)throw new L("Invalid marketplace removal request; explicit confirmation is required");w0(x.data.projectPath);let J=await O4($.req.param("name"),!0);return YO(J,"Marketplace removal failed"),$.json({name:J.marketplace?.name,removed:!0})}),O.post("/:name/update",async($)=>{let x=g(g2,await $.req.json());if(!x.success)throw new L("Invalid plugin update request; explicit source trust is required");let J=w0(x.data.projectPath),{result:Q}=await t1(J,$.req.param("name"),{trusted:x.data.trust});return YO(Q,"Plugin update failed"),$.json({name:Q.pluginName,version:Q.manifest?.version,revision:Q.installation?.revision,changed:Q.changed,updatedDependencies:Q.updatedDependencies??[]})}),O.post("/:name/uninstall",async($)=>{let x=g(v2,await $.req.json());if(!x.success)throw new L("Invalid plugin uninstall request; explicit confirmation is required");let J=w0(x.data.projectPath),{result:Q}=await s1(J,$.req.param("name"),x.data.confirm);return YO(Q,"Plugin uninstall failed"),$.json({name:Q.pluginName,removed:!0})}),O.post("/:name/state",async($)=>{let x=g(y2,await $.req.json());if(!x.success)throw new L("Invalid plugin state request");let J=w0(x.data.projectPath),Q=$.req.param("name"),Y=(await E0(J)).plugins.get(Q);if(!Y)throw new m("Plugin",Q);if(Y.source==="cli")throw new L(`Plugin "${Q}" was loaded with --plugin-dir and is invocation-scoped`);let W=await i1(J,Q,x.data.enabled,x.data.scope??"local");return $.json(W)}),O};import{Hono as o2}from"hono";import{execFile as l2}from"node:child_process";import c2 from"node:path";var L$="__BLADE_DIRECTORY_PICKER_CANCELLED__",i2=900000;function a2(O,$){return new Promise((x)=>{l2(O,[...$],{timeout:i2,maxBuffer:65536,windowsHide:!0},(J,Q,X)=>{let Y=J?.code;x({stdout:Q,stderr:X,exitCode:typeof Y==="number"?Y:J?1:0,...typeof Y==="string"?{errorCode:Y}:{}})})})}function H$(O){let $=O.replace(/[\r\n]+$/,"");if(!$||$===L$)return{cancelled:!0};if(!c2.isAbsolute($))throw Error("The folder picker returned an invalid path");return{cancelled:!1,path:$}}function B$(O){return O.exitCode!==0||Boolean(O.errorCode)}class x4{platform;runCommand;activeSelection=null;constructor(O={}){this.platform=O.platform??process.platform,this.runCommand=O.runCommand??a2}pick(){if(this.activeSelection)return this.activeSelection;let O=this.pickForPlatform().finally(()=>{this.activeSelection=null});return this.activeSelection=O,O}async pickForPlatform(){switch(this.platform){case"darwin":return this.pickOnMac();case"win32":return this.pickOnWindows();case"linux":return this.pickOnLinux();default:throw Error("Native folder selection is unavailable on this system")}}async pickOnMac(){let O=["try",'set selectedFolder to choose folder with prompt "Choose a project folder"',"return POSIX path of selectedFolder","on error number -128",`return "${L$}"`,"end try"].join(`
|
|
8
|
-
`),$=await this.runCommand("osascript",["-e",O]);if(B$($))throw Error("Unable to open the macOS folder picker");return H$($.stdout)}async pickOnWindows(){let O=["Add-Type -AssemblyName System.Windows.Forms","$dialog = New-Object System.Windows.Forms.FolderBrowserDialog",'$dialog.Description = "Choose a project folder"',"$dialog.ShowNewFolderButton = $true","if ($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {"," [Console]::Out.Write($dialog.SelectedPath)","} else {",` [Console]::Out.Write("${L$}")`,"}"].join("; "),$=await this.runCommand("powershell.exe",["-NoProfile","-STA","-Command",O]);if(B$($))throw Error("Unable to open the Windows folder picker");return H$($.stdout)}async pickOnLinux(){let O=[{command:"zenity",args:["--file-selection","--directory","--title=Choose a project folder"]},{command:"kdialog",args:["--getexistingdirectory",".","--title","Choose a project folder"]}];for(let $ of O){let x=await this.runCommand($.command,$.args);if(x.errorCode==="ENOENT")continue;if(x.exitCode===1&&!x.stdout.trim()&&!x.stderr.trim())return{cancelled:!0};if(B$(x))throw Error("Unable to open the Linux folder picker");return H$(x.stdout)}throw Error("Install zenity or kdialog to use native folder selection")}}var J4=new x4;var n2=U.Object({path:U.String({minLength:1})});function t2(O){if(!O)return!1;if(O==="tauri://localhost"||O==="http://tauri.localhost")return!0;try{let $=new URL(O).hostname;return $==="localhost"||$==="127.0.0.1"||$==="::1"||$==="[::1]"}catch{return!1}}var Q4=(O={})=>{let $=new o2,x=O.pickDirectory??(()=>J4.pick()),J=O.allowDirectoryPickerRequest??t2;return $.get("/",async(Q)=>{return Q.json(await tO.list(i()))}),$.post("/",async(Q)=>{let X;try{X=await Q.req.json()}catch{throw new L("A valid JSON body is required")}let Y=g(n2,X);if(!Y.success)throw new L("A project path is required");try{let W=await tO.bind(Y.data.path,i());return Q.json(W,201)}catch(W){throw new L(W instanceof Error?W.message:"Failed to bind project")}}),$.post("/pick",async(Q)=>{if(!J(Q.req.header("Origin")))throw new Q0("LOCAL_ACCESS_REQUIRED","Folder selection is only available from this machine",403);try{return Q.json(await x())}catch(X){throw new L(X instanceof Error?X.message:"Failed to select a folder")}}),$.delete("/",async(Q)=>{let X=Q.req.query("path");if(!X)throw new L("A project path is required");try{let Y=await tO.unbind(X);return Q.json({success:!0,removed:Y})}catch(Y){throw new L(Y instanceof Error?Y.message:"Failed to unbind project")}}),$};import{Hono as s2}from"hono";var Z4=a("Service"),G4=()=>{let O=new s2;return O.get("/",async($)=>{try{let x=await z4();return $.json(x)}catch(x){return Z4.error("[ProviderRoutes] Failed to list providers:",x),$.json([])}}),O.get("/:provider/models",async($)=>{let x=$.req.param("provider");try{let J=await X4(x);return $.json(J)}catch(J){return Z4.error("[ProviderRoutes] Failed to list models:",J),$.json([])}}),O.put("/:provider/credential",async($)=>{let x=$.req.param("provider"),J=await $.req.json();if(!J.apiKey?.trim())throw new L("apiKey is required");return await d0().setApiKey(x,J.apiKey.trim()),$.json({success:!0})}),O.delete("/:provider/credential",async($)=>{return await d0().clearCredential($.req.param("provider")),$.json({success:!0})}),O.put("/:provider",async($)=>{let x=$.req.param("provider"),J=x0(),Q=J?.modelProviders[x];if(!J||!Q)throw new m("Model provider",x);let X=await $.req.json();if(!X.name||!X.baseUrl||!X.wireApi)throw new L("name, baseUrl and wireApi are required");let Y="apiKeyEnv"in X?X.apiKeyEnv?.trim():Q.apiKeyEnv,W={name:X.name,baseUrl:X.baseUrl,wireApi:X.wireApi,...Y?{apiKeyEnv:Y}:{}},T=d0(),_=X.apiKey?.trim()?await T.credentials.read(x):void 0;if(X.apiKey?.trim())await T.setApiKey(x,X.apiKey.trim());try{return await L0().updateModelProvider(x,W),$.json({success:!0})}catch(j){if(X.apiKey?.trim())if(_)await T.credentials.modify(x,async()=>_);else await T.credentials.delete(x);if(j instanceof Error&&(j.message.includes("modelProviders.")||j.message.includes("built-in provider")))throw new L(j.message);throw j}}),O.delete("/:provider",async($)=>{let x=$.req.param("provider");if(!x0()?.modelProviders[x])throw new m("Model provider",x);let Q=$.req.query("removeModels");if(Q!==void 0&&Q!=="true"&&Q!=="false")throw new L("removeModels must be true or false");try{let X=await L0().removeModelProvider(x,{removeModels:Q==="true"});return $.json({success:!0,...X})}catch(X){if(X instanceof Error&&(X.message.includes("still referenced")||X.message.includes("owns the only model")))throw new b(X.message);throw X}}),O.post("/:provider/probe",async($)=>{let x=$.req.param("provider"),J=x0();if(!J?.modelProviders[x])throw new m("Model provider",x);let Q=await $.req.json().catch(()=>({})),X=J.models.filter((W)=>W.provider===x),Y=Q.modelId?X.find((W)=>W.id===Q.modelId):X[0];if(!Y)throw new L(Q.modelId?"modelId does not reference this provider":"Model provider has no configured model to probe");return $.json(await Y4(Y,J))}),O};import{Hono as r2}from"hono";var e2=a("Service"),W4=(O,$)=>{let x=new r2;return x.onError((J,Q)=>{if(J instanceof Q0)return Q.json(J.toObject(),J.statusCode);return e2.error("[ScheduleRoutes] Unhandled route error:",J),Q.json(new e("Schedule request failed").toObject(),500)}),x.get("/",async(J)=>{let Q=await O.list();return J.json(V4.parse({schedules:Q}))}),x.post("/",async(J)=>{let Q;try{Q=await J.req.json()}catch{throw new L("Invalid request body")}let X=g(K4,Q);if(!X.success)throw new L("Invalid schedule request");let Y=X.data.projectPath||J.get("directory")||i();try{let W=await O.create({...X.data,projectPath:Y});return J.json(i0.parse(W),201)}catch(W){throw new L(W instanceof Error?W.message:"Failed to create schedule")}}),x.get("/:id",async(J)=>{let Q=await O.get(J.req.param("id"));if(!Q)throw new m("Schedule not found");return J.json(i0.parse(Q))}),x.patch("/:id",async(J)=>{let Q;try{Q=await J.req.json()}catch{throw new L("Invalid request body")}let X=g(N4,Q);if(!X.success)throw new L("Invalid schedule update");let{modelId:Y,reasoningEffort:W,serviceTier:T,responseVerbosity:_,communicationStyle:j,isolation:w,permissionMode:F,...S}=X.data,J0={...Y!==void 0?{modelId:Y}:{},...W!==void 0?{reasoningEffort:W}:{},...T!==void 0?{serviceTier:T}:{},..._!==void 0?{responseVerbosity:_}:{},...j!==void 0?{communicationStyle:j}:{},...w!==void 0?{isolation:w}:{},...F!==void 0?{permissionMode:F}:{}};try{let p=await O.update(J.req.param("id"),{...S,...Object.keys(J0).length>0?{dispatch:J0}:{}});if(!p)throw new m("Schedule not found");return J.json(i0.parse(p))}catch(p){if(p instanceof Q0)throw p;throw new L(p instanceof Error?p.message:"Failed to update schedule")}}),x.delete("/:id",async(J)=>{if(!await O.remove(J.req.param("id")))throw new m("Schedule not found");return J.json({ok:!0})}),x.post("/:id/enable",async(J)=>{let Q=await O.setEnabled(J.req.param("id"),!0);if(!Q)throw new m("Schedule not found");return J.json(i0.parse(Q))}),x.post("/:id/disable",async(J)=>{let Q=await O.setEnabled(J.req.param("id"),!1);if(!Q)throw new m("Schedule not found");return J.json(i0.parse(Q))}),x.post("/:id/run",async(J)=>{let Q=await O.get(J.req.param("id"));if(!Q)throw new m("Schedule not found");if(!$)throw new e("Scheduler is not running in this process");await $.fire(Q,new Date,{manual:!0});let X=await O.get(Q.id);return J.json(i0.parse(X??Q),202)}),x};import*as m0 from"node:fs/promises";import{homedir as D4}from"node:os";import*as A0 from"node:path";import{Hono as O5}from"hono";var a0=a("Service"),F4=A0.join(D4(),".blade","skills"),w$=A0.join(D4(),".blade","skills-config.json");async function _4(){try{let O=await m0.readFile(w$,"utf-8");return JSON.parse(O)}catch{return{disabled:[]}}}async function $5(O){await m0.mkdir(A0.dirname(w$),{recursive:!0}),await m0.writeFile(w$,JSON.stringify(O,null,2))}async function x5(O,$){let x=await _4();if($)x.disabled=x.disabled.filter((J)=>J!==O);else if(!x.disabled.includes(O))x.disabled.push(O);await $5(x)}var y0=null,J5=300000,Q5=6;async function Z5(){if(y0&&Date.now()-y0.timestamp<J5)return y0.data;try{let O=await fetch("https://api.github.com/repos/anthropics/skills/contents/skills",{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"Blade-Skills-Catalog"}});if(!O.ok){if(a0.warn(`GitHub API returned ${O.status}`),y0)return y0.data;throw Error(`GitHub skills catalog returned ${O.status}`)}let x=(await O.json()).filter((Y)=>Y.type==="dir"),J=Array(x.length),Q=0,X=Math.min(Q5,x.length);return await Promise.all(Array.from({length:X},async()=>{while(Q<x.length){let Y=Q++,W=x[Y];if(!W)continue;let T=`Official ${W.name} skill`;try{let _=await fetch(`https://raw.githubusercontent.com/anthropics/skills/main/skills/${W.name}/SKILL.md`,{headers:{"User-Agent":"Blade-Skills-Catalog"}});if(_.ok){let w=(await _.text()).match(/^#[^\n]*\n+([^\n#]+)/);if(w)T=w[1].trim().slice(0,100)}}catch{}J[Y]={name:W.name,description:T,tag:"Official",author:"Anthropic"}}})),y0={data:J,timestamp:Date.now()},J}catch(O){if(a0.warn("Failed to fetch skills catalog from GitHub:",O),y0)return y0.data;throw O}}var H4=()=>{let O=new O5;return O.get("/",async($)=>{try{let x=$.get("directory")||i(),Q=(await E0(x)).skills.getAll(),X=await _4(),Y=Q.map((W)=>({id:W.name,name:W.name,enabled:!X.disabled.includes(W.name),description:W.description||"",version:W.version||"1.0.0",provider:"Local",location:W.source==="builtin"?"Built-in":W.basePath,removable:W.source==="user"&&A0.dirname(A0.resolve(W.basePath))===A0.resolve(F4),capabilities:["prompts"],allowedTools:W.allowedTools||[]}));return $.json(Y)}catch(x){return a0.error("[SkillsRoutes] Failed to get skills:",x),$.json({error:x instanceof Error?x.message:"Failed to get skills"},500)}}),O.post("/:name/toggle",async($)=>{try{let x=$.req.param("name"),J=await $.req.json();return await x5(x,J.enabled),$.json({success:!0,enabled:J.enabled})}catch(x){return a0.error("[SkillsRoutes] Failed to toggle skill:",x),$.json({success:!1,error:x.message},500)}}),O.delete("/:name",async($)=>{try{let x=$.req.param("name"),J=$.get("directory")||i();return wO(J,async(Q)=>{let X=Q.skills,Y=X.get(x);if(!Y)return $.json({success:!1,error:"Skill not found"},404);let W=A0.resolve(Y.basePath),T=A0.resolve(F4);if(Y.source!=="user"||A0.dirname(W)!==T)return $.json({success:!1,error:"Only Blade user skills can be uninstalled"},400);return await m0.rm(W,{recursive:!0,force:!0}),await X.refresh(),LO(J),await BO(J),$.json({success:!0})})}catch(x){return a0.error("[SkillsRoutes] Failed to uninstall skill:",x),$.json({success:!1,error:x.message},500)}}),O.post("/install",async($)=>{try{let x=await $.req.json(),J=U4(),Q=$.get("directory")||i();return wO(Q,async(X)=>{let Y=X.skills,W=!1;if(x.source==="catalog"&&x.name){if(W=await J.installOfficialSkill(x.name),!W)return $.json({success:!1,error:"Failed to install skill from catalog"},500)}else if(x.source==="repo"&&x.url){if(W=await J.installFromRepo(x.url,x.name),!W)return $.json({success:!1,error:"Failed to install skill from repository. Make sure the repo contains a SKILL.md file."},500)}else if(x.source==="local"&&x.path){if(W=await J.installFromLocal(x.path,x.name),!W)return $.json({success:!1,error:"Failed to install skill from local path. Make sure the path exists and contains a SKILL.md file."},500)}else return $.json({success:!1,error:"Invalid install parameters. Required: source with corresponding url/path/name"},400);return await Y.refresh(),LO(Q),await BO(Q),$.json({success:!0})})}catch(x){return a0.error("[SkillsRoutes] Failed to install skill:",x),$.json({success:!1,error:x.message},500)}}),O.get("/catalog",async($)=>{try{let x=await Z5();return $.json(x)}catch(x){return a0.error("[SkillsRoutes] Failed to get catalog:",x),$.json({error:x instanceof Error?x.message:"Failed to get skills catalog"},502)}}),O};import{execSync as Y5}from"node:child_process";import{readdir as z5}from"node:fs/promises";import sO from"node:path";import X5 from"fast-glob";import{Hono as G5}from"hono";var SO=a("Service"),K5=(O)=>{try{return Y5("git rev-parse --abbrev-ref HEAD",{cwd:O,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}},N5=[...zO.map((O)=>`${O}/**`),...zO,...zO.map((O)=>`**/${O}/**`),...zO.map((O)=>`**/${O}`),...A$.map((O)=>`**/${O}`)],V5=new Set(["/theme","/model","/permissions","/mcp","/skills","/exit","/resume","/ide","/login","/logout"]),w4=()=>{let O=new G5;return O.get("/commands",async($)=>{try{let x=$.req.query("q")||"",J=$.get("directory")||i(),Q=await E0(J),X=L4(x,J,Q).filter((Y)=>!V5.has(Y.command));return $.json(X)}catch(x){return SO.error("[SuggestionsRoutes] Failed to get command suggestions:",x),$.json([])}}),O.get("/files",async($)=>{try{let x=$.req.query("q")||"",J=$.get("directory")||i(),Q=Math.min(Number($.req.query("limit"))||100,1000),X=$.req.query("type")==="file",W=(await X5("**/*",{cwd:J,dot:!1,followSymbolicLinks:!1,onlyFiles:X,markDirectories:!0,unique:!0,ignore:N5})).map((j)=>j.replace(/\\/g,"/"));if(!x)return $.json(W.slice(0,Q));let T=x.toLowerCase(),_=W.filter((j)=>j.toLowerCase().includes(T)).slice(0,Q);return $.json(_)}catch(x){return SO.error("[SuggestionsRoutes] Failed to get file suggestions:",x),$.json([])}}),O.get("/files/tree",async($)=>{try{let x=$.get("directory")||i(),J=$.req.query("path")||"",Q=J?sO.join(x,J):x,Y=(await z5(Q,{withFileTypes:!0})).map((_)=>({name:_.name,path:J?`${J}/${_.name}`:_.name,type:_.isDirectory()?"dir":"file"}));Y.sort((_,j)=>{if(_.type!==j.type)return _.type==="dir"?-1:1;return _.name.localeCompare(j.name)});let W=new Set(zO),T=Y.filter((_)=>{let j=_.name;if(j.startsWith("."))return!1;if(W.has(j))return!1;for(let w of A$)if(j.match(new RegExp(w.replace("*",".*"))))return!1;return!0});return $.json(T)}catch(x){return SO.error("[SuggestionsRoutes] Failed to get file tree:",x),$.json([])}}),O.get("/files/content",async($)=>{try{let x=$.req.query("path");if(!x)return $.json({error:"Missing file path"},400);let J=$.get("directory")||i(),Q=sO.resolve(J,x),X=sO.relative(J,Q);if(X.startsWith("..")||sO.isAbsolute(X))return $.json({error:"Invalid file path"},400);let Y=B4(),W=await Y.stat(Q);if(!W?.isFile)return $.json({error:"File not found"},404);let T=200000,_=await Y.readTextFile(Q),j=_.length>T;return $.json({path:x,content:j?_.slice(0,T):_,truncated:j,size:W.size})}catch(x){return SO.error("[SuggestionsRoutes] Failed to get file content:",x),$.json({error:"Failed to read file"},500)}}),O.get("/git-info",async($)=>{try{let x=$.get("directory")||i(),J=K5(x);return $.json({branch:J})}catch(x){return SO.error("[SuggestionsRoutes] Failed to get git info:",x),$.json({branch:null})}}),O};import{Hono as W5}from"hono";var IO=a("Service"),j4=(O)=>{let $=new W5;return $.onError((x,J)=>{if(x instanceof Q0)return J.json(x.toObject(),x.statusCode);return IO.error("[TaskRoutes] Unhandled route error:",x),J.json(new e("Failed to dispatch task").toObject(),500)}),$.post("/",async(x)=>{let J;try{J=await x.req.json()}catch{throw new L("Invalid request body")}let Q=g(E4,J);if(!Q.success)throw new L("Invalid task request");if((Q.data.attachments??[]).reduce((Y,W)=>Y+(typeof W.content==="string"?Buffer.byteLength(W.content):0),0)>oO)throw new L("Task attachments exceed the 5 MiB limit");try{let Y=await O.dispatchTask({prompt:Q.data.prompt,title:Q.data.title,sourceProjectPath:Q.data.projectPath||x.get("directory")||i(),isolation:Q.data.isolation,permissionMode:Q.data.permissionMode,modelId:Q.data.modelId,reasoningEffort:Q.data.reasoningEffort,serviceTier:Q.data.serviceTier,responseVerbosity:Q.data.responseVerbosity,communicationStyle:Q.data.communicationStyle,attachments:Q.data.attachments,outputSchema:Q.data.outputSchema});return x.json(M$.parse(Y),202)}catch(Y){if(Y instanceof L||Y instanceof b||Y instanceof u0||Y instanceof k0)throw Y;throw IO.error("[TaskRoutes] Failed to dispatch task:",Y),new e("Failed to dispatch task")}}),$.post("/:sessionId/retry",async(x)=>{try{let J=await O.retryTask(x.req.param("sessionId"),x.req.query("projectPath"));return x.json(M$.parse(J),202)}catch(J){if(J instanceof L||J instanceof m||J instanceof b||J instanceof u0||J instanceof k0)throw J;throw IO.error("[TaskRoutes] Failed to retry task:",J),new e("Failed to retry task")}}),$.get("/:sessionId/diff",async(x)=>{try{let J=await O.getTaskDiff(x.req.param("sessionId"),x.req.query("projectPath"));return x.json(A4.parse(J))}catch(J){if(J instanceof L||J instanceof m||J instanceof b)throw J;throw IO.error("[TaskRoutes] Failed to load task diff:",J),new e("Failed to load task diff")}}),$.post("/:sessionId/delivery",async(x)=>{let J;try{J=await x.req.json()}catch{throw new L("Invalid request body")}let Q=g(T4,J);if(!Q.success)throw new L("Invalid task delivery request");try{let X=await O.deliverTask(x.req.param("sessionId"),Q.data.action,x.req.query("projectPath"));return x.json(M4.parse(X))}catch(X){if(X instanceof L||X instanceof m||X instanceof b)throw X;throw IO.error("[TaskRoutes] Failed to deliver task:",X),new e("Failed to deliver task")}}),$};import{Hono as F5}from"hono";var h0=a("Service"),XO=new Map,R4=2097152,C4=65536;function b4(){return typeof globalThis.Bun<"u"}async function U5(O,$,x){if(b4()){let{spawn:X}=await import("bun-pty"),Y=X(O,$,{name:"xterm-256color",cwd:x.cwd,env:x.env});return{pid:Y.pid,write:(W)=>Y.write(W),resize:(W,T)=>Y.resize(W,T),kill:()=>Y.kill(),onData:(W)=>Y.onData(W),onExit:(W)=>Y.onExit(W)}}let Q=(await import("node-pty")).spawn(O,$,{name:"xterm-256color",cwd:x.cwd,env:x.env,cols:80,rows:24});return{pid:Q.pid,write:(X)=>Q.write(X),resize:(X,Y)=>Q.resize(X,Y),kill:()=>Q.kill(),onData:(X)=>{Q.onData(X)},onExit:(X)=>{Q.onExit(X)}}}var j$=void 0,T$;if(b4())try{let{createBunWebSocket:O}=await import("hono/bun"),$=O();T$=$.upgradeWebSocket,j$=$.websocket}catch(O){h0.warn("[Terminal] Failed to initialize Bun WebSocket support:",O)}async function q4(O,$){let x=`term-${Date.now()}`;h0.info(`[Terminal] New connection: ${x}, cwd: ${O}`);let J=process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/zsh",Q=J.endsWith("sh")?["-l"]:[],X=await U5(J,Q,{cwd:O,env:{...process.env,TERM:"xterm-256color",COLORTERM:"truecolor"}}),Y={id:x,process:X,cwd:O,buffer:"",subscribers:new Set};if(XO.set(x,Y),Y.subscribers.add($),X.onData((W)=>{let T=!1;for(let _ of Y.subscribers)try{_.send(W),T=!0}catch{Y.subscribers.delete(_)}if(T)return;if(Y.buffer+=W,Y.buffer.length>R4)Y.buffer=Y.buffer.slice(-R4)}),X.onExit(({exitCode:W})=>{h0.info(`[Terminal] Process exited: ${x}, code: ${W}`);for(let T of Y.subscribers)try{T.close()}catch{}XO.delete(x)}),Y.buffer){let W=Y.buffer;Y.buffer="";for(let T=0;T<W.length;T+=C4)$.send(W.slice(T,T+C4))}return{session:Y,cleanup:()=>{if(h0.info(`[Terminal] Connection closed: ${x}`),Y.subscribers.delete($),Y.subscribers.size===0){try{Y.process.kill()}catch{}XO.delete(x)}}}}function k4(O,$){O.on("connection",async(x,J)=>{let Q=new URL(J.url||"/",`http://${J.headers.host}`);if(!Q.pathname.endsWith("/terminal/ws")){x.close();return}let X=Q.searchParams.get("cwd")||$()||i();try{let{session:Y,cleanup:W}=await q4(X,{send:(T)=>x.send(T),close:()=>x.close()});x.on("message",(T)=>{try{Y.process.write(String(T))}catch(_){h0.error("[Terminal] Failed to write to PTY:",_)}}),x.on("close",W),x.on("error",W)}catch(Y){h0.error("[Terminal] Failed to spawn PTY:",Y),x.close()}})}var S4=()=>{let O=new F5;if(O.get("/status",($)=>{let x=Array.from(XO.values()).map((J)=>({id:J.id,cwd:J.cwd}));return $.json({active:x.length,terminals:x})}),O.post("/kill/:terminalId",($)=>{let x=$.req.param("terminalId"),J=XO.get(x);if(J){try{J.process.kill()}catch{}for(let Q of J.subscribers)Q.close();return XO.delete(x),$.json({success:!0})}return $.json({success:!1,error:"Terminal not found"},404)}),T$)O.get("/ws",T$(($)=>{let x=$.req.query("cwd")||$.get("directory")||i(),J;return{async onOpen(Q,X){try{J=await q4(x,{send:(Y)=>X.send(Y),close:()=>X.close()})}catch(Y){h0.error("[Terminal] Failed to spawn PTY:",Y),X.close()}},onMessage(Q){if(!J)return;try{J.session.process.write(String(Q.data))}catch(X){h0.error("[Terminal] Failed to write to PTY:",X)}},onClose(){J?.cleanup()}}}));else O.get("/ws",($)=>{return $.json({message:"WebSocket endpoint - connect via ws:// protocol",hint:"Use WebSocket client to connect to this endpoint"})});return O};import D5 from"node:path";import{Hono as _5}from"hono";var H5=U.Object({projectPath:U.String({minLength:1}),action:W0(["trust","revoke"])});function I4(O){if(!D5.isAbsolute(O))throw new L("projectPath must be absolute")}var f4=()=>{let O=new _5;return O.get("/",async($)=>{let x=$.req.query("projectPath");if(!x)throw new L("projectPath query parameter is required");return I4(x),$.json(await R$.getInstance().getStatus(x))}),O.post("/",async($)=>{let x=g(H5,await $.req.json());if(!x.success)throw new L("Invalid workspace trust request");let{projectPath:J,action:Q}=x.data;I4(J);let X=R$.getInstance(),Y=Q==="trust"?await X.trust(J):await X.revoke(J);return await P4(),$.json({...Y,reloadRequired:Y.sensitiveSources>0})}),O};var N0=a("Service"),q$=[],rO,GO,KO,PO,y4=new Map,m4=new Map,q5=new Set([".css",".html",".js",".json",".svg"]),k5=1024,S5=3600000;function I5(O,$){if(!O)return 0;let x=O.split(",").map((J)=>{let[Q,...X]=J.trim().toLowerCase().split(";"),Y=X.find((T)=>T.trim().startsWith("q=")),W=Y?Number(Y.trim().slice(2)):1;return{name:Q,quality:Number.isFinite(W)?Math.max(0,Math.min(1,W)):0}});return x.find((J)=>J.name===$)?.quality??x.find((J)=>J.name==="*")?.quality??0}function h4(){if(KO)return;let O=()=>{q.collectStaleEmptySessions().then(($)=>{if($>0)N0.info(`[SessionGC] removed ${$} stale empty session(s)`)}).catch(($)=>{N0.warn("[SessionGC] failed to collect stale empty sessions:",$)})};O(),KO=setInterval(O,S5),KO.unref?.()}function P5(){if(!KO)return;clearInterval(KO),KO=void 0}function f5(O){return["br","gzip"].map((x)=>({encoding:x,quality:I5(O,x)})).filter((x)=>x.quality>0).sort((x,J)=>J.quality-x.quality||(x.encoding==="br"?-1:1))[0]?.encoding}function y5(O){let $=y4.get(O);if($)return $;let x=fO(O);return y4.set(O,x),x}function m5(O,$,x){let J=`${x}:${O}`,Q=m4.get(J);if(Q)return Q;let X=x==="br"?E5($,{params:{[j5.BROTLI_PARAM_QUALITY]:5}}):T5($,{level:6});return m4.set(J,X),X}function h5(){let O=w5(M5(import.meta.url)),$=[g0(O,"web"),g0(i(),"dist/web"),g0(i(),"packages/cli/dist/web")];for(let x of $){let J=g0(x,"index.html");if(b$(J)){if(fO(J,"utf-8").includes("/assets/"))return N0.debug(`[Server] Found web dist at: ${x}`),x}}return null}function g5(){let O=new R5;O.onError((J,Q)=>{if(N0.error("[Server] Request error:",J),J instanceof u4){let Y=new k0(J.message,{resource:"workspace_agent_resources",limit:J.capacity});return Q.json(Y.toObject(),429)}if(J instanceof Q0)return Q.json(J.toObject(),J.statusCode);let X=J instanceof Error?J.message:String(J);return Q.json({error:{code:"INTERNAL_ERROR",message:X}},500)}),O.use(async(J,Q)=>{let X=process.env.BLADE_SERVER_PASSWORD;if(!X)return Q();let Y=J.req.path;if(Y==="/"||Y==="/favicon.svg"||Y.startsWith("/assets/")||Y.endsWith(".html")||Y.endsWith(".js")||Y.endsWith(".css"))return Q();let W=J.req.header("Authorization");if(!W?.startsWith("Basic "))return J.header("WWW-Authenticate",'Basic realm="Blade Server"'),J.json({error:{code:"UNAUTHORIZED",message:"Authentication required"}},401);let T=Buffer.from(W.slice(6),"base64").toString(),[_,j]=T.split(":"),w=process.env.BLADE_SERVER_USERNAME??"blade";if(_!==w||j!==X)return J.json({error:{code:"UNAUTHORIZED",message:"Invalid credentials"}},401);return Q()}),O.use(async(J,Q)=>{let X=J.req.path==="/health"||J.req.path==="/global/health"||J.req.path.startsWith("/assets/");if(!X)N0.debug(`[Server] ${J.req.method} ${J.req.path}`);let Y=Date.now();if(await Q(),!X){let W=Date.now()-Y;N0.debug(`[Server] ${J.req.method} ${J.req.path} - ${J.res.status} (${W}ms)`)}}),O.use(C5({origin(J){if(!J)return;if(J.startsWith("http://localhost:"))return J;if(J.startsWith("http://127.0.0.1:"))return J;if(J==="tauri://localhost"||J==="http://tauri.localhost")return J;if(q$.includes(J))return J;return}})),O.use(async(J,Q)=>{let X=J.req.query("directory")||J.req.header("x-blade-directory")||i();try{X=decodeURIComponent(X)}catch{}return J.set("directory",X),Q()});let $=g1();PO=$,rO=$.recoverQueuedTasks,GO=new x$({dispatch:(J)=>$.dispatchTask(J),store:C$}),O.route("/global",o$()),O.route("/events",i$()),O.route("/sessions",$.app),O.route("/tasks",j4($)),O.route("/schedules",W4(C$,GO)),O.route("/configs",v$()),O.route("/permissions",u1()),O.route("/plugins",$4()),O.route("/hooks",O1()),O.route("/workspace-trust",f4()),O.route("/providers",G4()),O.route("/models",G1()),O.route("/projects",Q4()),O.route("/suggestions",w4()),O.route("/terminal",S4()),O.route("/mcp",J1()),O.route("/skills",H4()),O.get("/health",(J)=>{return J.json({healthy:!0,version:r0()})});let x=h5();if(x)N0.info(`[Server] Serving static files from ${x}`),O.get("/favicon.svg",()=>{let J=g0(x,"favicon.svg");if(!b$(J))return new Response(null,{status:404});return new Response(fO(J),{headers:{"Content-Type":"image/svg+xml","Cache-Control":"public, max-age=86400"}})}),O.get("/assets/*",(J)=>{let Q=g0(x,J.req.path);if(!b$(Q))return J.json({error:{code:"NOT_FOUND",message:`File not found: ${J.req.path}`}},404);let X=y5(Q),Y=A5(Q).toLowerCase(),T={".js":"application/javascript",".css":"text/css",".html":"text/html",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".eot":"application/vnd.ms-fontobject"}[Y]||"application/octet-stream",_=q5.has(Y)&&X.byteLength>=k5?f5(J.req.header("Accept-Encoding")):void 0,j=_?m5(Q,X,_):X;return new Response(new Uint8Array(j),{headers:{"Content-Type":T,"Content-Length":String(j.byteLength),"Cache-Control":"public, max-age=31536000, immutable",Vary:"Accept-Encoding",..._?{"Content-Encoding":_}:{}}})}),O.get("/",(J)=>{let Q=g0(x,"index.html"),X=fO(Q,"utf-8");return J.html(X,200,{"Cache-Control":"no-cache"})}),O.get("*",(J)=>{let Q=J.req.path;if(Q.includes("."))return J.json({error:{code:"NOT_FOUND",message:`File not found: ${Q}`}},404);let X=g0(x,"index.html"),Y=fO(X,"utf-8");return J.html(Y,200,{"Cache-Control":"no-cache"})});else N0.warn('[Server] Web UI not found. Run "cd packages/cli/web && bun run build" to enable web interface.'),O.get("/",(J)=>{return J.json({message:"Blade API Server",version:r0(),webUI:!1,hint:'Web UI not built. Run "cd packages/cli/web && bun run build" to enable.',endpoints:{health:"/health",sessions:"/sessions",configs:"/configs",permissions:"/permissions",providers:"/providers"}})}),O.all("*",(J)=>{return J.json({error:{code:"NOT_FOUND",message:`Route not found: ${J.req.path}`}},404)});return O}function v5(){let O=L5(),$=[];for(let x of Object.keys(O)){let J=O[x];if(!J)continue;for(let Q of J){if(Q.internal||Q.family!=="IPv4")continue;if(Q.address.startsWith("172."))continue;$.push(Q.address)}}return $}function g4(){return typeof globalThis.Bun<"u"}function v4(O,$){let x=globalThis.Bun,J=(X)=>{try{return x.serve({hostname:$.hostname,port:X,fetch:O.fetch,idleTimeout:0,websocket:j$})}catch(Y){N0.error("Failed to start Bun server:",Y);return}},Q=$.port===0?J(4096)??J(0):J($.port);if(!Q)throw Error(`Failed to start Bun server on port ${$.port}`);return{url:Q.url,port:Q.port,hostname:Q.hostname,stop:async()=>{Q.stop(!0)}}}function u5(O,$){return new Promise((x,J)=>{let Q=B5(async(_,j)=>{let w=new URL(_.url||"/",`http://${_.headers.host}`),F=new Headers;for(let[p,R]of Object.entries(_.headers))if(R)if(Array.isArray(R))for(let s of R)F.append(p,s);else F.set(p,R);let S;if(_.method!=="GET"&&_.method!=="HEAD")S=(await new Promise((R)=>{let s=[];_.on("data",(u)=>s.push(u)),_.on("end",()=>R(Buffer.concat(s)))})).toString();let J0=new Request(w.toString(),{method:_.method,headers:F,body:S});try{let p=await O.fetch(J0);if(j.statusCode=p.status,p.headers.forEach((R,s)=>{j.setHeader(s,R)}),p.body){let R=p.body.getReader(),s=async()=>{let{done:u,value:d}=await R.read();if(u){j.end();return}return j.write(d),s()};await s()}else{let R=await p.text();j.end(R)}}catch(p){N0.error("[Server] Node request error:",p),j.statusCode=500,j.end(JSON.stringify({error:{code:"INTERNAL_ERROR",message:"Internal server error"}}))}}),X=new b5({noServer:!0}),Y=i();k4(X,()=>Y),Q.on("upgrade",(_,j,w)=>{if(new URL(_.url||"/",`http://${_.headers.host}`).pathname==="/terminal/ws")X.handleUpgrade(_,j,w,(S)=>{X.emit("connection",S,_)});else j.destroy()});let W=(_)=>{return new Promise((j,w)=>{Q.once("error",(F)=>{if(F.code==="EADDRINUSE")w(F);else w(F)}),Q.listen(_,$.hostname,()=>{let F=Q.address();if(F&&typeof F==="object")j(F.port);else j(_)})})};(async()=>{let _;if($.port===0)try{_=await W(4096)}catch{_=await W(0)}else _=await W($.port);let j=new URL(`http://${$.hostname==="0.0.0.0"?"localhost":$.hostname}:${_}`);x({url:j,port:_,hostname:$.hostname,stop:async()=>{return new Promise((w)=>{X.close(()=>{Q.close(()=>w())})})}})})().catch(J)})}var p4;((J6)=>{let O,$,x,J=(_,j)=>{if(O!==_)return Promise.resolve();if(x)return x;let w=j?.shutdown("server-shutdown");return GO?.stop(),P5(),x=(async()=>{let F,S=async(J0)=>{if(!J0)return;try{await J0()}catch(p){F??=p}};if(await S(()=>_.stop()),await S(w?()=>w:void 0),d4(),O===_)O=void 0,$=void 0,PO=void 0,rO=void 0,GO=void 0;if(N0.info("[Server] Blade server stopped"),F!==void 0)throw F})(),x};function Q(){if(!$)$=g5();return $}J6.getApp=Q;function X(_){q$=_.cors??[];let j=Q();if(g4())O=v4(j,_),x=void 0,N0.info(`[Server] Blade server listening on ${O.url} (Bun runtime)`);else throw Error("Blade web server requires Bun runtime. Please run with Bun: `bun run blade web` or install Bun from https://bun.sh");let w=O,F=PO;return rO?.().catch((S)=>{N0.warn("[Server] Failed to recover queued tasks:",S)}),GO?.start(),h4(),{url:w.url,port:w.port,hostname:w.hostname,stop:()=>J(w,F)}}J6.listen=X;async function Y(_){q$=_.cors??[];let j=Q();if(g4())O=v4(j,_),N0.info(`[Server] Blade server listening on ${O.url} (Bun runtime)`);else O=await u5(j,_),N0.info(`[Server] Blade server listening on ${O.url} (Node.js runtime)`);x=void 0;let w=O,F=PO;try{await rO?.()}catch(S){N0.warn("[Server] Failed to recover queued tasks:",S)}return GO?.start(),h4(),{url:w.url,port:w.port,hostname:w.hostname,stop:()=>J(w,F)}}J6.listenAsync=Y;function W(){return O!==void 0}J6.isRunning=W;function T(){return PO?.getCoordinationStats()}J6.getSessionCoordinationStatsForTests=T})(p4||={});export{d5 as f,p5 as g,v5 as h,p4 as i};
|
package/dist/chunk-dbs94h44.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{$c as a,ad as b,bd as c}from"./chunk-tcga95a4.js";import"./chunk-jk8bqc5b.js";import"./chunk-2m7at619.js";import"./chunk-v508x7cg.js";import"./chunk-wy4pn9sk.js";import"./chunk-2xbmkyb2.js";import"./chunk-7p0bzza4.js";import"./chunk-khkhsaan.js";import"./chunk-7b467h8k.js";import"./chunk-9kmtcgm6.js";import"./chunk-kjvntyr5.js";import"./chunk-8ekk8pa7.js";import"./chunk-y8r2knxm.js";import"./chunk-1jc7d3nt.js";import"./chunk-fp1h8wdh.js";import"./chunk-5g2p1fwn.js";import"./chunk-ej6h16ae.js";import"./chunk-cm9mph7j.js";import"./chunk-cz68x56m.js";import"./chunk-av10vmxk.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
|
package/dist/chunk-g0n88mhg.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Vd as a,Wd as b,Xd as c}from"./chunk-j9snkjpe.js";import"./chunk-69rc9hw6.js";import"./chunk-1jc7d3nt.js";import"./chunk-fp1h8wdh.js";import"./chunk-cz68x56m.js";import"./chunk-av10vmxk.js";export{b as resolveModelConfig,c as getModelDisplayName,a as getModelApiKeyEnvironmentVariable};
|