blade-code 0.10.5 → 0.10.7

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.
Files changed (108) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-z906d5tb.js → chunk-0n04bmta.js} +2 -2
  3. package/dist/{chunk-drrdzmaa.js → chunk-0xm8hn2h.js} +2 -2
  4. package/dist/chunk-0z7q89w7.js +2 -0
  5. package/dist/{chunk-gxmrakrk.js → chunk-1sw9z975.js} +1 -1
  6. package/dist/{chunk-948qe2pp.js → chunk-1v7hpr34.js} +1 -1
  7. package/dist/{chunk-fvhc1yj8.js → chunk-3fdyzgpv.js} +1 -1
  8. package/dist/{chunk-15d49qty.js → chunk-43j2f1b5.js} +1 -1
  9. package/dist/{chunk-njyvrtje.js → chunk-4hhkbyja.js} +2 -2
  10. package/dist/{chunk-6eragc74.js → chunk-4rhssb85.js} +2 -2
  11. package/dist/chunk-598egka3.js +22 -0
  12. package/dist/chunk-5ak9tw83.js +100 -0
  13. package/dist/chunk-738pkjf8.js +1 -0
  14. package/dist/{chunk-xv0maezy.js → chunk-7a200q5g.js} +2 -2
  15. package/dist/{chunk-5twefby5.js → chunk-7pkrwh10.js} +1 -1
  16. package/dist/chunk-7xfmzvxp.js +1 -0
  17. package/dist/{chunk-9ffr01c3.js → chunk-847e0sk9.js} +1 -1
  18. package/dist/chunk-867rz2ss.js +1 -0
  19. package/dist/chunk-a3e97syg.js +3 -0
  20. package/dist/{chunk-0n97186m.js → chunk-ahxc3n3g.js} +2 -2
  21. package/dist/{chunk-tq52pbde.js → chunk-akev4wsz.js} +1 -1
  22. package/dist/{chunk-epj56s0n.js → chunk-az4b6106.js} +1 -1
  23. package/dist/{chunk-63ysxybd.js → chunk-e9ckf8e7.js} +1 -1
  24. package/dist/chunk-f7854pbx.js +187 -0
  25. package/dist/chunk-fwt0kje3.js +1 -0
  26. package/dist/{chunk-1vx4sf1y.js → chunk-g1q27q6q.js} +2 -2
  27. package/dist/chunk-g3wgzyhx.js +160 -0
  28. package/dist/chunk-g4snq0dx.js +1 -0
  29. package/dist/chunk-ggm04adj.js +1 -0
  30. package/dist/chunk-hpytxsge.js +1 -0
  31. package/dist/chunk-htr91q9c.js +1 -0
  32. package/dist/chunk-hwcp940f.js +1 -0
  33. package/dist/chunk-j5ysjbyr.js +10 -0
  34. package/dist/{chunk-jza1rsan.js → chunk-jpy61wna.js} +1 -1
  35. package/dist/chunk-kqpwz9b7.js +8 -0
  36. package/dist/{chunk-gxzbv67r.js → chunk-m86ekqp0.js} +2 -2
  37. package/dist/{chunk-51wtvmzn.js → chunk-m8k1mv0j.js} +1 -1
  38. package/dist/{chunk-ydtcvxsm.js → chunk-mt4328yf.js} +1 -1
  39. package/dist/{chunk-35yktzm1.js → chunk-ne7zdjrh.js} +1 -1
  40. package/dist/{chunk-bexgcc2d.js → chunk-p0j8994h.js} +1 -1
  41. package/dist/{chunk-gb54hc78.js → chunk-p3ahf1fh.js} +1 -1
  42. package/dist/chunk-pt659n0v.js +1466 -0
  43. package/dist/chunk-q1gfeadm.js +1 -0
  44. package/dist/{chunk-vntzy7bc.js → chunk-qk2z6gag.js} +2 -2
  45. package/dist/{chunk-ea7wsges.js → chunk-qqwgb9ja.js} +2 -2
  46. package/dist/{chunk-am8dtvff.js → chunk-qycwavck.js} +72 -17
  47. package/dist/chunk-rk1w5pry.js +2 -0
  48. package/dist/{chunk-s645azsm.js → chunk-rn908m3v.js} +2 -2
  49. package/dist/{chunk-dqvcgwhe.js → chunk-rz2ftt6h.js} +2 -2
  50. package/dist/{chunk-19kg7yvw.js → chunk-rz9yh6e4.js} +2 -2
  51. package/dist/{chunk-qm11hjd3.js → chunk-tc83e1b0.js} +1 -1
  52. package/dist/{chunk-v93hcxe7.js → chunk-tcc3v4n2.js} +1 -1
  53. package/dist/{chunk-g6h6h8xr.js → chunk-tp9zk241.js} +1 -1
  54. package/dist/chunk-tzh4ahry.js +6 -0
  55. package/dist/chunk-v0rn831t.js +1 -0
  56. package/dist/{chunk-fz1vyc15.js → chunk-vafn0spm.js} +1 -1
  57. package/dist/{chunk-rh7v814a.js → chunk-vcq624qv.js} +2 -2
  58. package/dist/chunk-vynsgc2g.js +1 -0
  59. package/dist/{chunk-qda309d9.js → chunk-w01sec4f.js} +2 -2
  60. package/dist/chunk-w0ena7fe.js +9 -0
  61. package/dist/{chunk-6tx8k249.js → chunk-wmdgb5pz.js} +2 -2
  62. package/dist/{chunk-an96c54z.js → chunk-wrbm6rch.js} +8 -8
  63. package/dist/{chunk-sanhjqpd.js → chunk-x3780wpy.js} +2 -2
  64. package/dist/{chunk-yc53wz4r.js → chunk-y573s5r8.js} +2 -2
  65. package/dist/chunk-ydwjttdz.js +1 -0
  66. package/dist/{chunk-vpj0sv73.js → chunk-yyvx1avz.js} +3 -3
  67. package/dist/chunk-z9fsh3kn.js +1 -0
  68. package/dist/{chunk-ygx03mdh.js → chunk-zjf1z27e.js} +1 -1
  69. package/dist/web/assets/ChatView-BYfHmxKJ.js +7 -0
  70. package/dist/web/assets/{CodeBlockHighlighter-CFW6qjnA.js → CodeBlockHighlighter-CC4e9nFc.js} +1 -1
  71. package/dist/web/assets/{FilePreview-CR_XetY0.js → FilePreview-C3HEoLYS.js} +1 -1
  72. package/dist/web/assets/{MarkdownRenderer-CVrxJswQ.js → MarkdownRenderer-COycrGUX.js} +3 -3
  73. package/dist/web/assets/{McpModal-BO-85gll.js → McpModal-CDgr9kVq.js} +1 -1
  74. package/dist/web/assets/{SettingsModal-CW87OnxI.js → SettingsModal-CvdVIbeG.js} +1 -1
  75. package/dist/web/assets/{SkillsModal-Q8ZFPhys.js → SkillsModal-lSX1ZKTu.js} +1 -1
  76. package/dist/web/assets/{TaskSwitcher-BzH-0QXr.js → TaskSwitcher-peKi9KvN.js} +1 -1
  77. package/dist/web/assets/{TerminalPanel-DTqvx8yB.js → TerminalPanel-DqQ-7CTG.js} +1 -1
  78. package/dist/web/assets/index-BF5HEN_f.js +32 -0
  79. package/dist/web/assets/index-BrkTYxtS.css +1 -0
  80. package/dist/web/index.html +2 -2
  81. package/package.json +1 -1
  82. package/dist/chunk-069zpw09.js +0 -6
  83. package/dist/chunk-1m5r6mp2.js +0 -180
  84. package/dist/chunk-1q21sxhx.js +0 -1
  85. package/dist/chunk-1r6szcrj.js +0 -1
  86. package/dist/chunk-1x4fpe47.js +0 -1
  87. package/dist/chunk-2nkd1kjx.js +0 -1
  88. package/dist/chunk-417wefq7.js +0 -99
  89. package/dist/chunk-4ncbd4k0.js +0 -1
  90. package/dist/chunk-62881c2s.js +0 -1484
  91. package/dist/chunk-7443b95r.js +0 -1
  92. package/dist/chunk-79s052sw.js +0 -2
  93. package/dist/chunk-7jy60gnx.js +0 -1
  94. package/dist/chunk-c5tds5v0.js +0 -9
  95. package/dist/chunk-ccwskwb3.js +0 -1
  96. package/dist/chunk-f6mszdsd.js +0 -1
  97. package/dist/chunk-hh85pk77.js +0 -160
  98. package/dist/chunk-nz78b5c5.js +0 -10
  99. package/dist/chunk-r1764q6f.js +0 -1
  100. package/dist/chunk-r6mwyg3h.js +0 -3
  101. package/dist/chunk-rzzt21ef.js +0 -22
  102. package/dist/chunk-t8x2qpe2.js +0 -1
  103. package/dist/chunk-tjnfhm9v.js +0 -1
  104. package/dist/chunk-v0ygsjry.js +0 -1
  105. package/dist/chunk-zyz82mcd.js +0 -1
  106. package/dist/web/assets/ChatView-Y-6k-ayR.js +0 -7
  107. package/dist/web/assets/index-B7etZcne.css +0 -1
  108. package/dist/web/assets/index-ClOgGy-I.js +0 -32
@@ -1,10 +0,0 @@
1
- import{a as Q,b as R,c as T,d as W}from"./chunk-r6mwyg3h.js";import"./chunk-ygx03mdh.js";import"./chunk-15d49qty.js";import"./chunk-xv0maezy.js";import"./chunk-62881c2s.js";import"./chunk-s645azsm.js";import"./chunk-1m5r6mp2.js";import"./chunk-jza1rsan.js";import"./chunk-417wefq7.js";import"./chunk-an96c54z.js";import"./chunk-drrdzmaa.js";import{kc as M}from"./chunk-sanhjqpd.js";import"./chunk-g6h6h8xr.js";import"./chunk-fvhc1yj8.js";import"./chunk-dqvcgwhe.js";import"./chunk-ea7wsges.js";import"./chunk-gxmrakrk.js";import"./chunk-yc53wz4r.js";import"./chunk-am8dtvff.js";import"./chunk-35yktzm1.js";import"./chunk-63ysxybd.js";import"./chunk-vpj0sv73.js";import"./chunk-qm11hjd3.js";import"./chunk-qda309d9.js";import"./chunk-rh7v814a.js";import"./chunk-tq52pbde.js";import"./chunk-79s052sw.js";import"./chunk-epj56s0n.js";import"./chunk-gxzbv67r.js";import"./chunk-bexgcc2d.js";import{Ee as J}from"./chunk-1vx4sf1y.js";import"./chunk-z906d5tb.js";import"./chunk-948qe2pp.js";import"./chunk-0n97186m.js";import"./chunk-9ffr01c3.js";import b from"chalk";import H from"open";var $=`
2
- ____ _ _
3
- | __ )| | __ _ __| | ___
4
- | _ \\| |/ _\` |/ _\` |/ _ \\
5
- | |_) | | (_| | (_| | __/
6
- |____/|_|\\__,_|\\__,_|\\___|
7
- `,E={command:"web",describe:"Start Blade server and open web interface",builder:Q,handler:async(X)=>{let F=R(X);if(await M(),!process.env.BLADE_SERVER_PASSWORD)console.log(b.yellow("[WARN] BLADE_SERVER_PASSWORD is not set; server is unsecured.")),console.log(b.gray(` Set this environment variable to enable Basic Auth.
8
- `));let C=await W.listenAsync(F);if(console.log(b.cyan($)),console.log(b.gray(` v${J()}
9
- `)),F.hostname==="0.0.0.0"){let q=`http://localhost:${C.port}`;console.log(b.blue.bold(" Local access: "),b.white(q));let Y=T();for(let Z of Y)console.log(b.blue.bold(" Network access: "),b.white(`http://${Z}:${C.port}`));H(q).catch(()=>{})}else{let q=C.url.toString();console.log(b.blue.bold(" Web interface: "),b.white(q)),H(q).catch(()=>{})}console.log(""),console.log(b.gray(` Press Ctrl+C to stop the server.
10
- `)),await new Promise(()=>{}),await C.stop()}};export{E as webCommand};
@@ -1 +0,0 @@
1
- import{Jb as a,Kb as b}from"./chunk-6eragc74.js";import"./chunk-1vx4sf1y.js";import"./chunk-9ffr01c3.js";export{a as globalOptions,b as cliConfig};
@@ -1,3 +0,0 @@
1
- import{e as C1,f as I1}from"./chunk-ygx03mdh.js";import{g as BO}from"./chunk-15d49qty.js";import{q as Y1}from"./chunk-xv0maezy.js";import{$ as T1,A as A0,B as J1,C as vO,D as T0,E as dO,G as gO,H as yO,J as Z1,K as W1,L as U1,M as D1,N as _1,O as B1,P as H1,Q as w1,R as L1,S as A1,T as j1,W as n1,s as d1,u as $1,v as p0,w as oO,y as FO,z as mO}from"./chunk-62881c2s.js";import{ca as L$,ia as X0}from"./chunk-s645azsm.js";import{Aa as hO,Ba as R0,Ca as d,Da as k}from"./chunk-1m5r6mp2.js";import{Va as s$}from"./chunk-jza1rsan.js";import{bb as WO,ib as r$,jb as e$,nb as O1,ob as SO,pb as PO,qb as f}from"./chunk-417wefq7.js";import{jc as o,nc as M$,uc as F0}from"./chunk-sanhjqpd.js";import{wc as fO}from"./chunk-fvhc1yj8.js";import{Gc as n$}from"./chunk-gxmrakrk.js";import{Ic as GO}from"./chunk-yc53wz4r.js";import{Mc as S1,Nc as P1,Qc as F1,Uc as s0,Vc as r0,Zc as N0}from"./chunk-am8dtvff.js";import{cd as b$,dd as t$}from"./chunk-35yktzm1.js";import{hd as _$,id as u0}from"./chunk-vpj0sv73.js";import{nd as p}from"./chunk-qda309d9.js";import{$d as t0,Cd as w$,Rd as B$}from"./chunk-rh7v814a.js";import{ce as h,ee as $,fe as M,ge as e0,he as j}from"./chunk-tq52pbde.js";import{le as qO,me as g0,ne as I$}from"./chunk-79s052sw.js";import{re as T}from"./chunk-epj56s0n.js";import{we as f0}from"./chunk-gxzbv67r.js";import{Be as q$,Ce as o$,ye as E$,ze as a$}from"./chunk-bexgcc2d.js";import{Ee as d0}from"./chunk-1vx4sf1y.js";import{Je as rO}from"./chunk-z906d5tb.js";import{Oe as QO,Se as V$}from"./chunk-0n97186m.js";import{Ve as nO}from"./chunk-9ffr01c3.js";var Q5={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 N5(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{existsSync as eO,readFileSync as xO}from"node:fs";import{createServer as u2}from"node:http";import{networkInterfaces as g2}from"node:os";import{dirname as y2,extname as l2,join as k0}from"node:path";import{fileURLToPath as c2}from"node:url";import{brotliCompressSync as i2,gzipSync as p2,constants as a2}from"node:zlib";import{Hono as o2}from"hono";import{cors as n2}from"hono/cors";import{WebSocketServer as t2}from"ws";class Z0 extends Error{code;statusCode;constructor(O,J,Z=500){super(J);this.code=O;this.statusCode=Z;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message}}}}class v extends Z0{constructor(O,J){super("NOT_FOUND",J?`${O} not found: ${J}`:`${O} not found`,404)}}class _ extends Z0{constructor(O){super("BAD_REQUEST",O,400)}}class I extends Z0{constructor(O){super("CONFLICT",O,409)}}class v0 extends Z0{constructor(O){super("TOO_MANY_REQUESTS",O,429)}}class V0 extends Z0{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class a extends Z0{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var K5=$.Object({error:$.Object({code:$.String(),message:$.String()})});import{Hono as Y4}from"hono";var AO=p("Service"),x4=$.Object({updates:$.Record($.String(),$.Any()),options:$.Optional($.Object({scope:$.Optional(j(["local","project","global"])),immediate:$.Optional($.Boolean())}))});function z4(O){return{currentModelId:O.currentModelId,permissionMode:O.permissionMode,language:O.language,theme:O.theme,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}}var G$=()=>{let O=new Y4;return O.get("/",async(J)=>{try{let Z=o();return J.json(Z?z4(Z):{})}catch(Z){return AO.error("[ConfigRoutes] Failed to get config:",Z),J.json({})}}),O.put("/",async(J)=>{try{let Z=await J.req.json(),Y=h(x4,Z);if(!Y.success)throw new _("Invalid config update format");let{updates:z,options:N}=Y.data;return await F0().updateConfig(z,N),J.json({success:!0,updates:z})}catch(Z){throw AO.error("[ConfigRoutes] Failed to update config:",Z),Z}}),O.get("/permissions",async(J)=>{try{let Z=o();return J.json(Z?.permissions||{})}catch(Z){return AO.error("[ConfigRoutes] Failed to get permissions:",Z),J.json({})}}),O};import{Hono as Q4}from"hono";import{streamSSE as N4}from"hono/streaming";var X4=15000,G4=new Set(["task.status","task.delivery","session.created","session.updated","session.deleted","permission.asked","question.required","elicitation.required","interaction.resolved"]),K4=new Set(["queued","running","completed","failed","cancelled","interrupted"]);function V4(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let J=O,Z=["changedFiles","additions","deletions","commits"];if(Z.some((Y)=>typeof J[Y]!=="number"||!Number.isInteger(J[Y])||J[Y]<0))return;return Object.fromEntries(Z.map((Y)=>[Y,J[Y]]))}function n0(O,J){return typeof O==="number"&&Number.isInteger(O)&&O>=J?O:void 0}function F4(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let J=O;if(!["applied","discarded","conflicted"].includes(String(J.status))||typeof J.updatedAt!=="string")return;return{status:J.status,updatedAt:J.updatedAt,...typeof J.sourceCommit==="string"?{sourceCommit:J.sourceCommit}:{},...n0(J.changedFiles,0)!==void 0?{changedFiles:J.changedFiles}:{},...typeof J.message==="string"?{message:J.message}:{}}}var K$=()=>{let O=new Q4;return O.get("/",(J)=>N4(J,async(Z)=>{let Y,z,N=!1,X=()=>{if(z!==void 0)clearInterval(z),z=void 0;Y?.(),Y=void 0},K=()=>{if(N)return;N=!0,X()};Z.onAbort(K),Y=k.subscribe((W)=>{if(!G4.has(W.type))return;if(W.type==="permission.asked"||W.type==="question.required"||W.type==="elicitation.required"){let L=W.properties.requestId;if(typeof L!=="string"||!L)return;Z.writeSSE({data:JSON.stringify({type:"interaction.pending",properties:{sessionId:W.sessionId,projectPath:W.projectPath,interactionType:W.type==="question.required"?"question":W.type==="elicitation.required"?"elicitation":"permission",requestId:L}})}).catch(K);return}if(W.type==="interaction.resolved"){let L=W.properties.requestId;if(typeof L!=="string"||!L)return;Z.writeSSE({data:JSON.stringify({type:W.type,properties:{sessionId:W.sessionId,projectPath:W.projectPath,requestId:L}})}).catch(K);return}if(W.type==="session.created"||W.type==="session.deleted"){Z.writeSSE({data:JSON.stringify({type:W.type,properties:{sessionId:W.sessionId,projectPath:W.projectPath}})}).catch(K);return}if(W.type==="session.updated"){let L=W.properties.title;if(typeof L!=="string"||!L.trim())return;Z.writeSSE({data:JSON.stringify({type:W.type,properties:{sessionId:W.sessionId,projectPath:W.projectPath,title:L}})}).catch(K);return}if(W.type==="task.delivery"){let L=F4(W.properties.taskDelivery);if(!L)return;Z.writeSSE({data:JSON.stringify({type:W.type,properties:{sessionId:W.sessionId,projectPath:W.projectPath,taskDelivery:L,...W.properties.taskWorktreeRemoved===!0?{taskWorktreeRemoved:!0}:{},...typeof W.properties.updatedAt==="string"?{updatedAt:W.properties.updatedAt}:{}}})}).catch(K);return}let H=W.properties.taskStatus;if(typeof H!=="string"||!K4.has(H))return;let E=V4(W.properties.taskDiffStat),R=n0(W.properties.taskQueuePosition,1),C=n0(W.properties.taskQueueDepth,0),t=n0(W.properties.taskConcurrencyLimit,1),Y0=n0(W.properties.taskInFlight,0);Z.writeSSE({data:JSON.stringify({type:W.type,properties:{sessionId:W.sessionId,projectPath:W.projectPath,taskStatus:H,...typeof W.properties.taskStatusReason==="string"?{taskStatusReason:W.properties.taskStatusReason}:{},...W.properties.taskFailure&&typeof W.properties.taskFailure==="object"?{taskFailure:W.properties.taskFailure}:{},...typeof W.properties.taskStartedAt==="string"?{taskStartedAt:W.properties.taskStartedAt}:{},...typeof W.properties.taskCompletedAt==="string"?{taskCompletedAt:W.properties.taskCompletedAt}:{},...typeof W.properties.updatedAt==="string"?{updatedAt:W.properties.updatedAt}:{},...E?{taskDiffStat:E}:{},...R!==void 0?{taskQueuePosition:R}:{},...C!==void 0?{taskQueueDepth:C}:{},...t!==void 0?{taskConcurrencyLimit:t}:{},...Y0!==void 0?{taskInFlight:Y0}:{}}})}).catch(K)});try{if(Z.aborted||N)return;if(await Z.writeSSE({data:JSON.stringify({type:"connected",properties:{timestamp:Date.now()}})}),Z.aborted||N)return;z=setInterval(()=>{if(Z.aborted||N)return;Z.writeSSE({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})}).catch(K)},X4);while(!Z.aborted&&!N)await new Promise((W)=>setTimeout(W,1000))}finally{K()}})),O};import{Hono as W4}from"hono";var F$=()=>{let O=new W4;return O.get("/health",(J)=>{return J.json({healthy:!0,version:d0()})}),O.get("/info",(J)=>{let Z=T(),Y=o();if(Y)T0.configure(Y.maxConcurrentTasks,Y.maxQueuedTasks);return J.json({version:d0(),platform:process.platform,arch:process.arch,nodeVersion:process.version,cwd:Z,gitBranch:V$(Z),taskAdmission:T0.getStats()})}),O};import W$ from"node:path";import{Hono as U4}from"hono";var D4=$.Object({projectPath:$.String({minLength:1}),action:j(["trust","revoke"]),expectedDigest:$.Optional($.String())}),_4=$.Object({projectPath:$.String({minLength:1}),sessionId:$.String({minLength:1}),enabled:$.Boolean()});function EO(O){if(!O||!W$.isAbsolute(O))throw new _("projectPath must be absolute");return W$.resolve(O)}function U$(O){if(!O)throw new _("sessionId is required");try{QO(O)}catch(J){throw new _(J instanceof Error?J.message:"sessionId is invalid")}return O}async function zO(O){let J=EO(O),Z=o()?.hooks??B$.hooks,Y=await t0.getInstance().loadWorkspaceHooks(J,Z,{includeBaseForCurrentWorkspace:!1});await N0(J),r0(J);let z=u0.getInstance();return z.loadConfig(Y,J),await s0(J),z.getConfig(J)}function D$(O,J){let Z=u0.getInstance(),Y=Z.getConfig(J).enabled,z=Z.isSessionPaused(O,J);return{sessionId:O,projectPath:J,enabled:Z.isSessionEnabled(O,J),paused:z,configEnabled:Y}}var H$=()=>{let O=new U4;return O.get("/trust",async(J)=>{let Z=J.req.query("projectPath");if(!Z)throw new _("projectPath query parameter is required");return await zO(Z),J.json(await u0.getInstance().getTrustStatus(Z))}),O.post("/trust",async(J)=>{let Z=h(D4,await J.req.json());if(!Z.success)throw new _("Invalid hook trust request");let{projectPath:Y,action:z,expectedDigest:N}=Z.data;await zO(Y);let X=u0.getInstance(),K;try{K=z==="trust"?await X.trustProject(Y,N):await X.revokeProjectTrust(Y)}catch(W){if(W instanceof _$)throw new I(W.message);throw W}return J.json(K)}),O.get("/session",async(J)=>{let Z=EO(J.req.query("projectPath")),Y=U$(J.req.query("sessionId"));return await zO(Z),J.json(D$(Y,Z))}),O.post("/session",async(J)=>{let Z=h(_4,await J.req.json());if(!Z.success)throw new _("Invalid hook session request");let Y=EO(Z.data.projectPath),z=U$(Z.data.sessionId);await zO(Y);let N=u0.getInstance();if(Z.data.enabled)N.enableSession(z,Y);else N.disableSession(z,Y);return J.json(D$(z,Y))}),O};import{Hono as B4}from"hono";var L0=p("Service");function H4(O){try{return L$(O)}catch{return[]}}function w4(O){if(!NO(O)||!NO(O.reference)||!NO(O.argument))throw Error("Invalid MCP completion request");let J=O.reference.type,Z=J==="prompt"&&typeof O.reference.name==="string"?{type:"prompt",name:O.reference.name}:J==="resource"&&typeof O.reference.uri==="string"?{type:"resource",uri:O.reference.uri}:void 0;if(!Z||typeof O.argument.name!=="string"||typeof O.argument.value!=="string")throw Error("Invalid MCP completion request");let Y;if(O.context!==void 0){if(!NO(O.context))throw Error("Invalid MCP completion context");Y=Object.create(null);for(let[z,N]of Object.entries(O.context)){if(typeof N!=="string")throw Error("Invalid MCP completion context");Y[z]=N}}return{reference:Z,argument:{name:O.argument.name,value:O.argument.value},...Y?{context:Y}:{}}}function NO(O){return O!==null&&typeof O==="object"&&!Array.isArray(O)}async function b0(O,J){let Z=o()?.mcpServers??{};for(let[Y,z]of Object.entries(Z)){if(J&&Y!==J)continue;if(!O.getServerStatus(Y))await O.registerServer(Y,z,{connect:!1})}}var A$=()=>{let O=new B4;return O.get("/",async(J)=>{try{let Z=X0.getInstance();await b0(Z);let Y=Z.getAllServers(),z=await Promise.all(Array.from(Y.entries()).map(async([N,X])=>({id:N,name:N,status:X.status==="connected"?"connected":X.status==="reconnecting"?"reconnecting":X.status==="connecting"?"connecting":X.lastError?"error":"offline",endpoint:X.config.command?`${X.config.command} ${(X.config.args||[]).join(" ")}`.trim():X.config.url||"Unknown",description:`MCP server: ${N}`,tools:X.tools.map((K)=>K.name),completionSupported:X.client.completionSupported,tasks:X.client.tasks,resources:X.contentCatalog.resources,resourceTemplates:X.contentCatalog.resourceTemplates.map((K)=>({...K,variables:H4(K.uriTemplate)})),prompts:X.contentCatalog.prompts,connectedAt:X.connectedAt?.toISOString(),error:X.lastError?.message,recovery:X.recovery,logging:X.logging,instructions:X.instructions,oauthEnabled:X.client.oauthEnabled,oauthStatus:await X.client.getOAuthStatus()})));return J.json(z)}catch(Z){return L0.error("[McpRoutes] Failed to get MCP servers:",Z),J.json({error:Z instanceof Error?Z.message:"Failed to get MCP servers"},500)}}),O.post("/:name/connect",async(J)=>{try{let Z=J.req.param("name"),Y=X0.getInstance();return await b0(Y,Z),await Y.connectServer(Z),J.json({success:!0})}catch(Z){return L0.error("[McpRoutes] Failed to connect MCP server:",Z),J.json({success:!1,error:Z.message},500)}}),O.post("/:name/disconnect",async(J)=>{try{let Z=J.req.param("name"),Y=X0.getInstance();return await b0(Y,Z),await Y.disconnectServer(Z),J.json({success:!0})}catch(Z){return L0.error("[McpRoutes] Failed to disconnect MCP server:",Z),J.json({success:!1,error:Z.message},500)}}),O.get("/:name/logs",async(J)=>{try{let Z=J.req.param("name"),Y=Number(J.req.query("limit")??20),z=Number(J.req.query("afterRevision")??0);if(!Number.isSafeInteger(Y)||Y<1||Y>100||!Number.isSafeInteger(z)||z<0)return J.json({error:"Invalid MCP log pagination"},400);let N=X0.getInstance();return await b0(N,Z),J.json(N.getLogSnapshot(Z,{limit:Y,afterRevision:z}))}catch(Z){return L0.error("[McpRoutes] Failed to get MCP logs:",Z),J.json({error:Z.message},500)}}),O.post("/:name/logging-level",async(J)=>{try{let Z=J.req.param("name"),Y=await J.req.json();if(!w$(Y.level))return J.json({success:!1,error:"Invalid MCP logging level"},400);let z=X0.getInstance();return await b0(z,Z),await z.setServerLoggingLevel(Z,Y.level),J.json({success:!0,level:Y.level})}catch(Z){return L0.error("[McpRoutes] Failed to set MCP logging level:",Z),J.json({success:!1,error:Z.message},400)}}),O.post("/:name/complete",async(J)=>{try{let Z=J.req.param("name"),Y=w4(await J.req.json()),z=X0.getInstance();await b0(z,Z);let N=await z.complete(Z,Y);return J.json(N)}catch(Z){return L0.error("[McpRoutes] Failed to complete MCP argument:",Z),J.json({error:Z.message},400)}}),O.post("/:name/oauth/login",async(J)=>{try{let Z=J.req.param("name"),Y=X0.getInstance();await b0(Y,Z);let z=await Y.beginOAuthLogin(Z);return J.json({success:!0,flowId:z.flowId,authorizationUrl:z.authorizationUrl},202)}catch(Z){return L0.error("[McpRoutes] Failed to start MCP OAuth login:",Z),J.json({success:!1,error:Z.message},400)}}),O.post("/:name/oauth/logout",async(J)=>{try{let Z=J.req.param("name"),Y=X0.getInstance();return await b0(Y,Z),await Y.logoutOAuth(Z),J.json({success:!0})}catch(Z){return L0.error("[McpRoutes] Failed to log out MCP OAuth:",Z),J.json({success:!1,error:Z.message},400)}}),O.delete("/:name",async(J)=>{try{let Z=J.req.param("name");await X0.getInstance().unregisterServer(Z);let z=o();if(z?.mcpServers){let{[Z]:N,...X}=z.mcpServers;await F0().updateConfig({mcpServers:X})}return J.json({success:!0})}catch(Z){return L0.error("[McpRoutes] Failed to delete MCP server:",Z),J.json({success:!1,error:Z.message},500)}}),O.post("/",async(J)=>{try{let Z=await J.req.json(),{name:Y,config:z}=Z;if(!Y||!z)return J.json({success:!1,error:"Missing name or config"},400);await X0.getInstance().registerServer(Y,z);let X=o();return await F0().updateConfig({mcpServers:{...X?.mcpServers,[Y]:z}}),J.json({success:!0})}catch(Z){return L0.error("[McpRoutes] Failed to add MCP server:",Z),J.json({success:!1,error:Z.message},500)}}),O};import{getSupportedThinkingLevels as L4}from"@earendil-works/pi-ai";import{Hono as A4}from"hono";var XO=p("Service");function E4(O,J,Z=b$.list()){return{id:O.id,displayName:O.displayName,provider:O.provider,model:O.model,overrides:O.overrides,fallbackModels:O.fallbackModels,contextWindow:J.contextWindow,maxTokens:J.maxTokens,reasoning:J.reasoning,supportedReasoningEfforts:L4(J),supportedServiceTiers:q$(J),supportedResponseVerbosities:E$(J),communicationStyles:Z,input:J.input}}function q4(O){R$(O.overrides);let J={displayName:O.displayName||void 0,overrides:O.overrides||void 0};if(O.model)J.model=O.model;return J}function R$(O){let J=O?.streamIdleTimeout;if(J!==void 0&&(!Number.isFinite(J)||J<1000))throw new _("streamIdleTimeout must be at least 1000ms")}var j$=()=>{let O=new A4;return O.get("/",async(J)=>{try{let Z=o();if(!Z)throw Error("Config not initialized");let Y=J.get("directory")||T(),[z,N]=await Promise.all([GO(Y,Z),N0(Y)]),X=z.config.models,K=X.find((R)=>R.id===z.config.currentModelId)??X[0],W=z.catalog,H=N.communicationStyles.list(),E=(R)=>E4(R,W.resolveConfig(R),H);return J.json({configured:X.map(E),current:K?E(K):null})}catch(Z){XO.error("[ModelsRoutes] Failed to get models:",Z);let Y=new a("Failed to get models");return J.json(Y.toObject(),500)}}),O.post("/",async(J)=>{let Z=f0(),Y,z;try{let N=await J.req.json(),{provider:X,displayName:K,model:W,overrides:H,apiKey:E,modelProvider:R}=N;if(!X||!W)throw new _("provider and model are required");R$(H);let C;if(R){if(R.id!==X)throw new _("modelProvider.id must match the model provider");if(o()?.modelProviders[X])throw new _(`model provider already exists: ${X}`);C={name:R.name,baseUrl:R.baseUrl,wireApi:R.wireApi,...R.apiKeyEnv?{apiKeyEnv:R.apiKeyEnv}:{}};try{Z.registerModelProvider(X,C,[W]),z=X}catch(L){throw new _(L instanceof Error?L.message:"Invalid model provider")}}else Z.getModel(X,W);if(E?.trim()){if(await Z.setApiKey(X,E.trim()),C)Y=X}let t={provider:X,displayName:K||void 0,model:W,overrides:H||void 0},Y0=C?await F0().addModelWithProvider(t,C):await F0().addModel(t);return J.json({success:!0,model:Y0})}catch(N){if(Y)await Z.credentials.delete(Y);if(z){let X=o();Z.configureModelProviders(X?.modelProviders??{},X?.models??[])}throw XO.error("[ModelsRoutes] Failed to add model:",N),N}}),O.put("/:modelId",async(J)=>{try{let Z=J.req.param("modelId"),Y=await J.req.json(),{displayName:z,overrides:N,model:X}=Y,K=M$(Z);if(!K)throw new _("model config not found");if(X)f0().getModel(K.provider,X);return await F0().updateModel(Z,q4({displayName:z,overrides:N,model:X})),J.json({success:!0})}catch(Z){throw XO.error("[ModelsRoutes] Failed to update model:",Z),Z}}),O.delete("/:modelId",async(J)=>{try{let Z=J.req.param("modelId");return await F0().removeModel(Z),J.json({success:!0})}catch(Z){throw XO.error("[ModelsRoutes] Failed to delete model:",Z),Z}}),O};import{Hono as J2}from"hono";import{Mutex as l$}from"async-mutex";import{Hono as y4}from"hono";import{streamSSE as l4}from"hono/streaming";import{LRUCache as c4}from"lru-cache";import{nanoid as l0}from"nanoid";import c$ from"node:path";var KO=M(j(["default","autoEdit","yolo","plan"]));var MO=M(j(["user","assistant","system","tool"])),M4=M($.Union([$.Object({type:$.Literal("text"),text:$.String()}),$.Object({type:$.Literal("image_url"),image_url:$.Object({url:$.String()})})])),k$=$.Union([$.String(),$.Array(M4)]),W9=M($.Object({id:$.String(),role:MO,content:k$,timestamp:$.Number(),metadata:$.Optional($.Record($.String(),$.Unknown())),thinkingContent:$.Optional($.String()),tool_call_id:$.Optional($.String()),name:$.Optional($.String()),tool_calls:$.Optional($.Unknown())})),b4=M(j(["queued","running","completed","failed","cancelled","interrupted"])),f$=M(j(["local","worktree"])),R4=M(j(["applied","discarded","conflicted"])),j4=M($.Object({status:R4,updatedAt:$.String(),sourceCommit:$.Optional($.String()),changedFiles:$.Optional($.Integer({minimum:0})),message:$.Optional($.String())})),C4=M($.Object({changedFiles:$.Integer({minimum:0}),additions:$.Integer({minimum:0}),deletions:$.Integer({minimum:0}),commits:$.Integer({minimum:0})})),I4=M($.Object({path:$.String({minLength:1}),patch:$.String({maxLength:2097152}),additions:$.Integer({minimum:0}),deletions:$.Integer({minimum:0}),binary:$.Boolean(),truncated:$.Boolean()})),S$=M($.Object({sessionId:$.String(),projectPath:$.String(),baseCommit:$.String(),files:$.Array(I4,{maxItems:100}),truncated:$.Boolean()})),k4=$.Union([$.String(),$.Number(),$.Boolean(),$.Array($.String())]),f4=M($.Object({name:$.String(),type:j(["string","number","integer","boolean","select","multi-select"]),title:$.String(),description:$.Optional($.String()),required:$.Boolean(),defaultValue:$.Optional(k4),options:$.Optional($.Array($.Object({value:$.String(),label:$.String()}))),format:$.Optional(j(["date","uri","email","date-time"])),minimum:$.Optional($.Number()),maximum:$.Optional($.Number()),minLength:$.Optional($.Number()),maxLength:$.Optional($.Number()),minItems:$.Optional($.Number()),maxItems:$.Optional($.Number())})),U9=M($.Object({serverName:$.String(),mode:j(["form","url"]),message:$.String(),fields:$.Optional($.Array(f4)),requestedSchema:$.Optional($.Record($.String(),$.Unknown())),url:$.Optional($.String()),domain:$.Optional($.String()),elicitationId:$.Optional($.String())})),S4=M($.Object({type:j(["permission","question","elicitation"]),requestId:$.String()})),P4=M($.Object({code:j(["authentication","permission","rate_limit","timeout","network","model_unavailable","context_limit","unsupported_input","runtime"]),message:$.String({minLength:1,maxLength:500}),retryable:$.Boolean()})),bO=M(j(["auto","off","minimal","low","medium","high","xhigh","max"])),RO=M(j(["auto","standard","fast","flex"])),jO=M(j(["auto","low","medium","high"])),OO=M($.Union([j(["auto","pragmatic","friendly","explanatory"]),$.String({minLength:7,maxLength:300,pattern:"^(?:(?:user|project):[a-z0-9][a-z0-9._-]{0,63}(?::[a-z0-9][a-z0-9._-]{0,63}){0,3}|plugin:[a-z0-9][a-z0-9._-]{0,63}:[a-z0-9][a-z0-9._-]{0,63}(?::[a-z0-9][a-z0-9._-]{0,63}){0,3})$"})])),S0=M($.Object({sessionId:$.String(),projectPath:$.String(),title:$.Optional($.String()),gitBranch:$.Optional($.String()),rootId:$.String(),parentId:$.Optional($.String()),relationType:$.Optional(j(["subagent","fork"])),resumedFrom:$.Optional($.String()),rootAgentId:$.Optional($.String()),resumeDepth:$.Optional($.Integer({minimum:0})),taskStatus:e0(b4,"completed"),taskStatusReason:$.Optional($.String()),taskFailure:$.Optional(P4),taskStartedAt:$.Optional($.String()),taskCompletedAt:$.Optional($.String()),taskPromptSummary:$.Optional($.String()),taskModelId:$.Optional($.String()),selectedModelId:$.Optional($.String()),permissionMode:$.Optional(KO),reasoningEffort:$.Optional(bO),serviceTier:$.Optional(RO),responseVerbosity:$.Optional(jO),communicationStyle:$.Optional(OO),communicationStyleDigest:$.Optional($.String({pattern:"^[a-f0-9]{64}$"})),projectInstructionsDigest:$.Optional($.String({pattern:"^[a-f0-9]{64}$"})),taskRetryAvailable:$.Optional($.Boolean()),taskRetriedFrom:$.Optional($.Object({sessionId:$.String(),projectPath:$.String()})),taskDelivery:$.Optional(j4),taskIsolation:$.Optional(f$),taskSourceProjectPath:$.Optional($.String()),taskWorktreePath:$.Optional($.String()),taskWorktreeBranch:$.Optional($.String()),taskBaseCommit:$.Optional($.String()),taskDiffStat:$.Optional(C4),taskQueuePosition:$.Optional($.Integer({minimum:1})),taskQueueDepth:$.Optional($.Integer({minimum:0})),taskConcurrencyLimit:$.Optional($.Integer({minimum:1})),archivedAt:$.Optional($.String()),archivedBySessionId:$.Optional($.String()),pendingInteraction:$.Optional(S4),messageCount:$.Number(),firstMessageTime:$.String(),lastMessageTime:$.String(),hasErrors:$.Boolean()})),D9=M($.Object({sessions:$.Array(S0),nextCursor:$.Optional($.String())})),_9=M($.Object({session:S0,archivedSessionIds:$.Array($.String())})),B9=M($.Object({session:S0,restoredSessionIds:$.Array($.String())})),H9=M($.Object({version:$.Literal(1),sessionId:$.String(),goalId:$.String(),objective:$.String(),status:j(["active","paused","blocked","usage_limited","budget_limited","complete"]),tokenBudget:$.Optional($.Number()),tokensUsed:$.Number(),timeUsedSeconds:$.Number(),continuationCount:$.Number(),statusReason:$.Optional($.String()),createdAt:$.String(),updatedAt:$.String()})),P$=M($.Object({role:MO,content:k$,metadata:$.Optional($.Unknown()),reasoningContent:$.Optional($.String()),thinkingContent:$.Optional($.String()),tool_call_id:$.Optional($.String()),name:$.Optional($.String()),tool_calls:$.Optional($.Unknown())})),w9=M($.Object({session:S0,messages:$.Array(P$)})),h$=M(j(["conversation","code","both"])),h4=M($.Object({messageId:$.String(),preview:$.String(),createdAt:$.String(),fileCount:$.Integer({minimum:0})})),m$=M($.Object({targetMessageId:$.String({minLength:1}),mode:e0(h$,"conversation")})),L9=M($.Object({checkpoint:h4,mode:h$,removedTurns:$.Integer({minimum:1}),restoredFiles:$.Array($.String()),messages:$.Array(P$)})),m4=j(["running","completed","failed","cancelled"]),C$=M($.Object({id:$.String(),subagentType:$.String(),description:$.String(),status:m4,rootAgentId:$.String(),resumedFrom:$.Optional($.String()),resumeDepth:$.Integer({minimum:0}),createdAt:$.Number(),lastActiveAt:$.Number(),completedAt:$.Optional($.Number()),result:$.Optional($.Object({success:$.Boolean(),message:$.String(),error:$.Optional($.String()),verificationCommands:$.Optional($.Array($.String())),verificationVerdict:$.Optional(j(["pass","fail","partial"])),modifiedFiles:$.Optional($.Array($.String()))})),stats:$.Optional($.Object({tokens:$.Optional($.Number()),toolCalls:$.Optional($.Number()),duration:$.Optional($.Number())}))})),v$=M($.Object({prompt:$.String({minLength:1,maxLength:32000,pattern:"\\S"})})),A9=M($.Object({source:C$,session:C$})),E9=M($.Object({sessionId:$.String(),projectPath:$.String()})),q9=M($.Object({path:$.String(),name:$.String(),gitBranch:$.Optional($.String()),available:$.Boolean(),isCurrent:$.Boolean(),boundAt:$.String()})),M9=M($.Union([$.Object({cancelled:$.Literal(!0)}),$.Object({cancelled:$.Literal(!1),path:$.String({minLength:1})})])),b9=M($.Object({type:$.String(),seq:$.Optional($.Number()),properties:$.Record($.String(),$.Unknown())})),d$=$.Object({type:j(["file","image","url"]),path:$.Optional($.String()),url:$.Optional($.String()),content:$.Optional($.String({maxLength:g0})),mimeType:$.Optional($.String()),name:$.Optional($.String())}),T$=M($.Object({prompt:$.String({minLength:1,maxLength:32000,pattern:"\\S"}),title:$.Optional($.String({minLength:1,maxLength:200})),projectPath:$.Optional($.String()),modelId:$.Optional($.String({minLength:1,maxLength:500})),reasoningEffort:$.Optional(bO),serviceTier:$.Optional(RO),responseVerbosity:$.Optional(jO),communicationStyle:$.Optional(OO),isolation:e0(f$,"worktree"),permissionMode:e0(KO,"default"),attachments:$.Optional($.Array(d$,{maxItems:qO}))})),CO=M($.Object({session:S0,runId:$.String(),messageId:$.String(),status:j(["queued","running"]),queuePosition:$.Optional($.Integer({minimum:1})),queueDepth:$.Optional($.Integer({minimum:0})),maxConcurrentTasks:$.Optional($.Integer({minimum:1}))})),u$=M($.Object({action:j(["apply","discard"])})),g$=M($.Object({content:$.String({maxLength:I$}),projectPath:$.Optional($.String()),modelId:$.Optional($.String({minLength:1,maxLength:500})),reasoningEffort:$.Optional(bO),serviceTier:$.Optional(RO),responseVerbosity:$.Optional(jO),communicationStyle:$.Optional(OO),permissionMode:$.Optional(KO),attachments:$.Optional($.Array(d$,{maxItems:qO}))})),v4=j(["completed","failed","aborted","timed_out","spawn_error"]),d4=M($.Object({version:$.Literal(1),command:$.String(),status:v4,exitCode:$.Union([$.Integer(),$.Null()]),durationMs:$.Number({minimum:0}),stdout:$.String(),stderr:$.String(),stdoutOmittedBytes:$.Integer({minimum:0}),stderrOmittedBytes:$.Integer({minimum:0}),binaryOutput:$.Boolean(),truncated:$.Boolean()})),y$=M($.Object({command:$.String({minLength:1,maxLength:32768,pattern:"^(?![\\s\\S]*\\u0000)(?=[\\s\\S]*\\S)[\\s\\S]*$"}),projectPath:$.Optional($.String())})),R9=M($.Object({executionId:$.String(),messageId:$.String(),record:d4,auxiliary:$.Boolean(),delivery:$.Optional(j(["current_turn","next_turn"])),queued:$.Optional($.Integer({minimum:0}))})),j9=M($.Object({messageId:$.String(),role:MO,content:$.String(),timestamp:$.String()})),C9=M($.Object({approved:$.Boolean(),remember:$.Optional($.Boolean()),scope:$.Optional(j(["once","session","project"])),targetMode:$.Optional(KO),feedback:$.Optional($.String()),answers:$.Optional($.Record($.String(),$.Union([$.String(),$.Array($.String())]))),elicitation:$.Optional($.Object({action:j(["accept","decline","cancel"]),content:$.Optional($.Record($.String(),$.Union([$.String({maxLength:4000}),$.Number(),$.Boolean(),$.Array($.String({maxLength:1000}),{maxItems:100})]),{maxProperties:32}))}))})),T4=M($.Object({id:OO,name:$.String({minLength:1,maxLength:80}),description:$.String({minLength:1,maxLength:256}),source:j(["built-in","user","project","plugin"]),contentSha256:$.Optional($.String({pattern:"^[a-f0-9]{64}$"}))})),I9=M($.Object({id:$.String(),displayName:$.Optional($.String()),provider:$.String(),model:$.String(),contextWindow:$.Optional($.Number()),maxTokens:$.Optional($.Number()),reasoning:$.Optional($.Boolean()),supportedReasoningEfforts:$.Optional($.Array(j(["off","minimal","low","medium","high","xhigh","max"]))),supportedServiceTiers:$.Optional($.Array(j(["standard","fast","flex"]))),supportedResponseVerbosities:$.Optional($.Array(j(["low","medium","high"]))),communicationStyles:$.Optional($.Array(T4,{maxItems:36})),input:$.Optional($.Array(j(["text","image"]))),overrides:$.Optional($.Object({baseUrl:$.Optional($.String()),temperature:$.Optional($.Number()),maxOutputTokens:$.Optional($.Number()),timeout:$.Optional($.Number()),streamIdleTimeout:$.Optional($.Number({minimum:1000}))}))})),k9=M(j(["vs-dark","vs-light","hc-black"])),u4=M(j(["light","dark","system"])),g4=M($.Object({language:$.String(),theme:$.String(),uiTheme:u4,autoSaveSessions:$.Boolean(),notifyBuild:$.Boolean(),notifyErrors:$.Boolean(),notifySounds:$.Boolean(),privacyTelemetry:$.Boolean(),privacyCrash:$.Boolean(),communicationStyle:$.Optional(OO)})),f9=M($.Partial(g4));var P=p("Service"),i4=$.Object({title:$.Optional($.String()),projectPath:$.Optional($.String())}),p4=g$,a4=$.Object({title:$.Optional($.String()),projectPath:$.Optional($.String())}),o4=$.Object({projectPath:$.String()}),n4=$.Object({objective:$.String({minLength:1}),tokenBudget:$.Optional($.Integer({minimum:1})),permissionMode:$.Optional(j(["default","autoEdit","plan","yolo"]))}),t4=$.Union([$.Object({action:$.Literal("pause")}),$.Object({action:$.Literal("resume")}),$.Object({action:$.Literal("edit"),objective:$.String({minLength:1})})]),n=new Map,q0=new Map,c0=new Map,_O=new c4({max:100,ttl:1800000});function i$(O){return{sessionId:O.sessionId,projectPath:O.projectPath}}function G0(O){if(!O)return;return q0.get(O)??_O.get(O)}function s4(O){if(q0.get(O.id)!==O)return;q0.delete(O.id),_O.set(O.id,O)}function r4(O){q0.delete(O),_O.delete(O)}function W0(O){return O?.status==="queued"||O?.status==="running"||O?.status==="waiting_permission"}function UO(O,J="user-cancel"){if(O.status==="cancelled"||O.status==="completed"||O.status==="failed")return!1;let Z=O.pendingPermission;if(O.pendingPermission=void 0,Z?.resolve({approved:!1,reason:s$}),Z)k.publish(i$(O),"interaction.resolved",{requestId:Z.permissionId});return O.abortController.abort(J),O.status="cancelled",k.publish(i$(O),"run.cancelled",{runId:O.id}),!0}function x1(O,J=!1){let{permissionId:Z,details:Y}=O;if(Y.type==="askUserQuestion"&&Y.questions)return{type:"question.required",properties:{requestId:Z,toolCallId:Z,questions:Y.questions,details:Y,...J?{replayed:!0}:{}}};if(Y.type==="mcpElicitation"&&Y.mcpElicitation)return{type:"elicitation.required",properties:{requestId:Z,toolCallId:Z,elicitation:Y.mcpElicitation,...J?{replayed:!0}:{}}};return{type:"permission.asked",properties:{requestId:Z,toolName:Y.toolName,description:Y.message,args:Y.args,details:Y,...J?{replayed:!0}:{}}}}function e4(){for(let O of q0.values())UO(O,"route-reset");q0.clear();for(let O of c0.values())O.controller.abort("route-reset");c0.clear(),_O.clear(),n.clear()}var z1=(O)=>{if(!O||typeof O!=="object")return O;let J={...O},Z=200000,Y=(z,N)=>typeof z==="number"&&Number.isSafeInteger(z)&&z>=0&&z<=N?z:0;if(typeof J.oldContent==="string"&&J.oldContent.length>Z)delete J.oldContent;if(typeof J.newContent==="string"&&J.newContent.length>Z)delete J.newContent;if(J.mcpResult&&typeof J.mcpResult==="object"&&!Array.isArray(J.mcpResult)){let z=J.mcpResult,N=Array.isArray(z.artifacts)?z.artifacts.slice(0,64).flatMap((X)=>{if(!X||typeof X!=="object"||Array.isArray(X))return[];let K=X,W=new Set(["text","image","audio","resource"]);if(typeof K.id!=="string"||!/^[a-f0-9]{64}$/.test(K.id)||typeof K.sha256!=="string"||K.sha256!==K.id||typeof K.kind!=="string"||!W.has(K.kind)||Y(K.size,67108864)!==K.size||typeof K.persisted!=="boolean")return[];return[{id:K.id.slice(0,128),sha256:K.sha256.slice(0,128),kind:K.kind,size:K.size,persisted:K.persisted,...typeof K.mimeType==="string"?{mimeType:K.mimeType.slice(0,256)}:{},...typeof K.sourceUri==="string"?{sourceUri:K.sourceUri.slice(0,8192)}:{},...typeof K.path==="string"?{path:K.path.slice(0,8192)}:{}}]}):[];J.mcpResult={isError:z.isError===!0,contentCount:Y(z.contentCount,64),textBytes:Y(z.textBytes,4194304),structuredBytes:Y(z.structuredBytes,4194304),artifactCount:Y(z.artifactCount,64),truncated:z.truncated===!0,binaryOmitted:z.binaryOmitted===!0,artifacts:N}}else delete J.mcpResult;return J};function O2(O,J,Z){switch(Z.kind){case"tool_start":if("function"in Z.toolCall)k.publish(O,"subagent.update",{subagentSessionId:J,toolName:Z.toolCall.function.name}),k.publish(O,"subagent.tool.start",{subagentSessionId:J,toolCallId:Z.toolCall.id,toolName:Z.toolCall.function.name,arguments:Z.toolCall.function.arguments,toolKind:Z.toolKind});break;case"tool_result":if("function"in Z.toolCall)k.publish(O,"subagent.tool.result",{subagentSessionId:J,toolCallId:Z.toolCall.id,toolName:Z.toolCall.function.name,success:!Z.result.error,summary:Z.result.metadata?.summary,output:yO(gO(Z.toolCall.function.name,Z.result)),metadata:z1(Z.result.metadata)});break;case"tool_progress":if("function"in Z.toolCall)k.publish(O,"subagent.tool.progress",{subagentSessionId:J,toolCallId:Z.toolCall.id,toolName:Z.toolCall.function.name,...Z.update});break;case"content_delta":k.publish(O,"subagent.delta",{subagentSessionId:J,delta:Z.delta});break;case"thinking_delta":k.publish(O,"subagent.thinking.delta",{subagentSessionId:J,delta:Z.delta});break;case"stream_end":k.publish(O,"subagent.stream.end",{subagentSessionId:J});break;case"mcp_catalog_changed":k.publish(O,"subagent.mcp.catalog.changed",{subagentSessionId:J,revision:Z.revision,serverName:Z.serverName,added:Z.added,removed:Z.removed,updated:Z.updated});break;case"mcp_content_changed":k.publish(O,"subagent.mcp.content.changed",{subagentSessionId:J,revision:Z.revision,serverName:Z.serverName,contentKind:Z.contentKind,added:Z.added,removed:Z.removed,updated:Z.updated});break;case"mcp_resource_updated":k.publish(O,"subagent.mcp.resource.updated",{subagentSessionId:J,revision:Z.revision,serverName:Z.serverName,uri:Z.uri});break;case"mcp_connection_changed":k.publish(O,"subagent.mcp.connection.changed",{subagentSessionId:J,revision:Z.revision,serverName:Z.serverName,phase:Z.phase,reason:Z.reason,attempt:Z.attempt,maxAttempts:Z.maxAttempts,nextRetryAt:Z.nextRetryAt,error:Z.error});break;case"mcp_log":k.publish(O,"subagent.mcp.log",{subagentSessionId:J,revision:Z.revision,serverName:Z.serverName,level:Z.level,logger:Z.logger,message:Z.message,projectedBytes:Z.projectedBytes,dataSha256:Z.dataSha256,truncated:Z.truncated,detailsOmitted:Z.detailsOmitted,timestamp:Z.timestamp,synthetic:Z.synthetic});break;case"mcp_instructions_changed":k.publish(O,"subagent.mcp.instructions.changed",{subagentSessionId:J,revision:Z.revision,serverName:Z.serverName,action:Z.action,reason:Z.reason,text:Z.text,sourceBytes:Z.sourceBytes,projectedBytes:Z.projectedBytes,sha256:Z.sha256,truncated:Z.truncated,detailsOmitted:Z.detailsOmitted});break;case"mcp_task_changed":k.publish(O,"subagent.mcp.task.changed",{subagentSessionId:J,revision:Z.revision,taskId:Z.taskId,serverName:Z.serverName,toolName:Z.toolName,status:Z.status,statusMessage:Z.statusMessage,createdAt:Z.createdAt,updatedAt:Z.updatedAt,completedAt:Z.completedAt,hasResult:Z.hasResult,error:Z.error});break;case"project_rules_loaded":k.publish(O,"subagent.project.rules.loaded",{subagentSessionId:J,files:Z.files,triggerPaths:Z.triggerPaths,blockedWrite:Z.blockedWrite});break;default:break}}function $O(O,J="projectPath"){if(!c$.isAbsolute(O))throw new _(`${J} must be absolute`);return c$.resolve(O)}function TO(O){try{QO(O)}catch(J){throw new _(J instanceof Error?J.message:`Invalid session ID: ${O}`)}}function $0(O){return{sessionId:O.id,projectPath:O.projectPath}}function VO(O,J,Z){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,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:Z,messages:J}}function IO(O){return O.filter((J)=>J.role!=="system").map((J)=>{let Z=e$(J.metadata);return Z?{...J,content:r$(Z)}:J})}function DO(O,J){O.taskStatus=J.taskStatus,O.taskStatusReason=J.taskStatusReason,O.taskFailure=J.taskFailure,O.taskStartedAt=J.taskStartedAt,O.taskCompletedAt=J.taskCompletedAt,O.taskPromptSummary=J.taskPromptSummary,O.taskModelId=J.taskModelId,O.selectedModelId=J.selectedModelId,O.permissionMode=J.permissionMode,O.reasoningEffort=J.reasoningEffort,O.serviceTier=J.serviceTier,O.responseVerbosity=J.responseVerbosity,O.communicationStyle=J.communicationStyle,O.communicationStyleDigest=J.communicationStyleDigest,O.projectInstructionsDigest=J.projectInstructionsDigest,O.taskRetryAvailable=J.taskRetryAvailable,O.taskRetriedFrom=J.taskRetriedFrom,O.taskDelivery=J.taskDelivery,O.taskIsolation=J.taskIsolation,O.taskSourceProjectPath=J.taskSourceProjectPath,O.taskWorktreePath=J.taskWorktreePath,O.taskWorktreeBranch=J.taskWorktreeBranch,O.taskBaseCommit=J.taskBaseCommit,O.taskDiffStat=J.taskDiffStat,O.taskQueuePosition=J.taskQueuePosition,O.taskQueueDepth=J.taskQueueDepth,O.taskConcurrencyLimit=J.taskConcurrencyLimit,O.archivedAt=J.archivedAt,O.archivedBySessionId=J.archivedBySessionId,O.updatedAt=new Date(J.lastMessageTime)}async function kO(O){let J=await f.findSessionMetadata(O.id,O.projectPath);if(J)DO(O,J)}function y0(O){let J=G0(O.currentRunId),Z=J?.status==="waiting_permission"?"running":J?.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:Z,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:J?.status==="queued"?J.taskQueuePosition:Z==="queued"?O.taskQueuePosition:void 0,taskQueueDepth:J?.status==="queued"?J.taskQueueDepth:Z==="queued"?O.taskQueueDepth:void 0,taskConcurrencyLimit:J?.taskConcurrencyLimit??O.taskConcurrencyLimit,archivedAt:O.archivedAt,archivedBySessionId:O.archivedBySessionId,pendingInteraction:J?.pendingPermission?{type:J.pendingPermission.details.type==="askUserQuestion"?"question":J.pendingPermission.details.type==="mcpElicitation"?"elicitation":"permission",requestId:J.pendingPermission.permissionId}:void 0,agentType:void 0,model:void 0,messageCount:O.messages.length,firstMessageTime:O.createdAt.toISOString(),lastMessageTime:O.updatedAt.toISOString(),hasErrors:!1,isActive:!0}}async function z0(O,J){if(TO(O),J!==void 0){let Y=R0({sessionId:O,projectPath:$O(J)});if(n.has(d(Y)))return Y;let z=await f.findSessionMetadata(Y.sessionId,Y.projectPath);if(!z)throw new v("Session",O);return R0({sessionId:z.sessionId,projectPath:z.projectPath})}let Z=new Map;for(let Y of n.values()){if(Y.id!==O)continue;let z=$0(Y);Z.set(d(z),z)}for(let Y of await f.listSessions()){if(Y.sessionId!==O)continue;let z=R0({sessionId:Y.sessionId,projectPath:Y.projectPath});Z.set(d(z),z)}if(Z.size===0)try{let Y=await f.findSessionMetadata(O);if(!Y)throw new v("Session",O);return R0({sessionId:Y.sessionId,projectPath:Y.projectPath})}catch(Y){if(Y instanceof v)throw Y;if(Y instanceof Error&&Y.message.startsWith("Ambiguous session ID:"))throw new V0;throw Y}if(Z.size>1)throw new V0;return Z.values().next().value}function uO(O){if(typeof O==="string")return O;return O.filter((J)=>J.type==="text").map((J)=>J.text).join(`
2
- `)}function p$(O,J){let Z=(J??[]).filter((z)=>z.type==="image"&&typeof z.content==="string").map((z)=>({type:"image_url",image_url:{url:z.content}}));if(Z.length===0)return O;let Y=[];if(O.trim())Y.push({type:"text",text:O});return Y.push(...Z),Y}var Q1=()=>{e4();let O=new y4;O.onError((Q,V)=>{if(Q instanceof Z0)return V.json(Q.toObject(),Q.statusCode);return P.error("[SessionRoutes] Unhandled route error:",Q),V.json({error:{code:"INTERNAL_ERROR",message:"Internal server error"}},500)});let J=new Map,Z=new Map,Y=new Map,z=new Map,N=new Map,X=new Map,K=(Q)=>{let V=d(Q),x=N.get(V);if(!x)x=new l$,N.set(V,x);return x},W=(Q)=>{let V=d(Q),x=X.get(V);if(!x)x=new l$,X.set(V,x);return x},H=async(Q,V={})=>{let x=d($0(Q));await Y.get(x);let G=J.get(x);if(G)return G;let F=Z.get(x);if(!F){let U=V.communicationStyle??Q.communicationStyle;F=dO.create({sessionId:Q.id,workspaceRoot:Q.projectPath,...Q.selectedModelId??Q.taskModelId?{modelId:Q.selectedModelId??Q.taskModelId}:{},permissionMode:V.permissionMode??Q.permissionMode??"default",...Q.reasoningEffort?{reasoningEffort:Q.reasoningEffort}:{},...Q.serviceTier?{serviceTier:Q.serviceTier}:{},...Q.responseVerbosity?{responseVerbosity:Q.responseVerbosity}:{},...U?{communicationStyle:U}:{},...U===Q.communicationStyle&&Q.communicationStyleDigest?{communicationStyleDigest:Q.communicationStyleDigest}:{},...Q.projectInstructionsDigest?{projectInstructionsDigest:Q.projectInstructionsDigest}:{},...Q.taskWorktree?{taskWorktree:Q.taskWorktree}:{},...Q.taskIsolation?{taskIsolation:Q.taskIsolation}:{},...Q.messages.length>0?{sessionStart:{isResume:!0,resumeSessionId:Q.id}}:{}}),Z.set(x,F)}try{let U=await F;return J.set(x,U),U}finally{if(Z.get(x)===F)Z.delete(x)}},E=async(Q,V)=>{let x=d($0(Q)),G=Y.get(x);if(!G)G=(async()=>{let F=Z.get(x);if(F)await F.catch(()=>{return});Z.delete(x);let U=V??J.get(x);if(J.delete(x),U){for(let[D,w]of J)if(w===U)J.delete(D)}await U?.dispose()})().finally(()=>{if(Y.get(x)===G)Y.delete(x)}),Y.set(x,G);await G},R=async(Q)=>{let V=d(Q),x=n.get(V);if(x)return x;let G=z.get(V);if(!G)G=(async()=>{let F=await f.findSessionMetadata(Q.sessionId,Q.projectPath);if(!F)throw new v("Session",Q.sessionId);let[U,D]=await Promise.all([f.loadSession(Q.sessionId,Q.projectPath),f.findSessionTaskWorktree(Q.sessionId,Q.projectPath)]),w=VO(F,U,D);return n.set(V,w),w})(),z.set(V,G);try{return await G}finally{if(z.get(V)===G)z.delete(V)}},C=async(Q,V)=>{let x=await z0(Q,V);try{await f.assertSessionWritable(x.sessionId,x.projectPath)}catch(G){if(G instanceof SO)throw new I(G.message);throw G}return R(x)},t=async(Q,V)=>{if(Q.permissionMode===V)return;let x=await f.setSessionPermissionMode(Q.id,Q.projectPath,V);Q.permissionMode=x.permissionMode,Q.updatedAt=new Date(x.lastMessageTime),k.publish($0(Q),"session.updated",{permissionMode:V})},Y0=(Q,V,x,G={})=>{let F=l0(12),U={id:F,sessionId:Q.id,projectPath:Q.projectPath,status:"running",abortController:new AbortController,disposeRuntimeOnSettle:G.taskRuntime!==void 0,createdAt:new Date};if(G.taskRuntime){let D=G.taskRuntime,w=T0.admit({key:`${Q.projectPath}\x00${Q.id}`,...D.getTaskAdmissionLimits(),signal:U.abortController.signal,onUpdate:(B)=>{U.status=B.state,U.taskQueuePosition=B.queuePosition,U.taskQueueDepth=B.queueDepth,U.taskConcurrencyLimit=B.maxConcurrent,Q.taskStatus=B.state,Q.taskQueuePosition=B.queuePosition,Q.taskQueueDepth=B.queueDepth,Q.taskConcurrencyLimit=B.maxConcurrent,U.taskAdmissionUpdate=(U.taskAdmissionUpdate??Promise.resolve()).then(async()=>{await D.setTaskAdmission(B)}).catch((b)=>{P.warn(`[SessionRoutes] Failed to persist admission for ${Q.id}:`,b)})}});U.taskAdmission=w;let A=w.getSnapshot();U.status=A.state,U.taskQueuePosition=A.queuePosition,U.taskQueueDepth=A.queueDepth,U.taskConcurrencyLimit=A.maxConcurrent}return q0.set(F,U),Q.currentRunId=F,U.completion=$2(U,Q,V,x,H,{pendingInputOnly:G.pendingInputOnly,preparedInputTurn:G.preparedInputTurn,goalContinuationOnly:G.goalContinuationOnly,taskAdmission:U.taskAdmission,disposeRuntime:E}).catch((D)=>{P.error(`[SessionRoutes] Run ${F} failed:`,D)}),U},L=async(Q)=>{let V=fO("task",12),x=$O(Q.sourceProjectPath),G=Q.modelId?.trim(),F=o();if(!F)throw new _("Config not initialized");let[U,D]=await Promise.all([GO(x,F),N0(x)]);if(G&&!U.config.models.some((S)=>S.id===G))throw new _(`Task model not found: ${G}`);let w=G||U.config.models.find((S)=>S.id===U.config.currentModelId)?.id||U.config.models[0]?.id;if(!w)throw new _("No model is configured. Add or select a model before dispatching a task.");let A=U.config.models.find((S)=>S.id===w);if(!A)throw new _(`Task model not found: ${w}`);let B=Q.reasoningEffort??"off",b=Q.serviceTier??"auto",e=Q.responseVerbosity??"auto",h0=Q.communicationStyle??"auto",i,y=D.projectRules?.staticRules(x),l=y&&y.files.length>0?y.provenanceSha256:void 0;try{let S=U.catalog.resolveConfig(A);n$(S,B),o$(S,b),a$(S,e);let u=t$(h0,D.communicationStyles);i=u.source==="built-in"?void 0:u.contentSha256}catch(S){throw new _(S instanceof Error?S.message:"Invalid reasoning effort")}let K0={version:1,prompt:Q.prompt,...Q.title?{title:Q.title}:{},sourceProjectPath:x,isolation:Q.isolation,permissionMode:Q.permissionMode,modelId:w,reasoningEffort:B,serviceTier:b,responseVerbosity:e,communicationStyle:h0,...i?{communicationStyleDigest:i}:{},...l?{projectInstructionsDigest:l}:{},...Q.attachments?{attachments:Q.attachments.map((S)=>({...S}))}:{}},_0,q;try{let S=await Y1.createSessionTask({sessionId:V,prompt:Q.prompt,title:Q.title,sourceProjectPath:x,isolation:Q.isolation,dispatch:K0,retriedFrom:Q.retriedFrom}),{metadata:u}=S;_0=S.taskWorktree,q=VO(u,[],_0);let s=$0(q);n.set(d(s),q),k.publish(s,"task.status",{taskStatus:u.taskStatus,updatedAt:u.lastMessageTime});let c=p$(Q.prompt,Q.attachments),B0=await H(q),M0=await B0.prepareInputTurn(c);if(!M0.accepted)throw new I(`Task prompt was not accepted: ${M0.reason}`);let E0=Y0(q,c,Q.permissionMode,{preparedInputTurn:M0,taskRuntime:B0});return await E0.taskAdmissionUpdate,{session:y0(q),runId:E0.id,messageId:M0.messageId,status:E0.status==="queued"?"queued":"running",queuePosition:E0.taskQueuePosition,queueDepth:E0.taskQueueDepth,maxConcurrentTasks:E0.taskConcurrencyLimit}}catch(S){if(S instanceof vO&&q){let u=$0(q),s=d(u);if(_0)await A0.exit({sessionId:q.id,action:"remove",discardChanges:!0}).catch(()=>{return});throw await J.get(s)?.dispose().catch(()=>{return}),J.delete(s),await f.deleteSession(q.id,q.projectPath).catch(()=>{return}),n.delete(s),new v0("Task admission queue is full")}if(q){let u=await f.findSessionMetadata(q.id,q.projectPath).catch(()=>{return});if(!u||u.taskStatus==="queued"){let s=WO(S),c=await f.updateSessionMetadata(q.id,q.projectPath,{taskStatus:"failed",taskStatusReason:s.message,taskFailure:s,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null}).catch(()=>{return});q.taskStatus=c?.taskStatus??"failed",q.taskStatusReason=c?.taskStatusReason??s.message,q.taskFailure=c?.taskFailure??s,q.taskCompletedAt=c?.taskCompletedAt}else q.taskStatus=u.taskStatus,q.taskStatusReason=u.taskStatusReason,q.taskFailure=u.taskFailure,q.taskCompletedAt=u.taskCompletedAt}throw S}},O0=async(Q,V)=>{let x=await z0(Q,V),G=await f.findSessionMetadata(x.sessionId,x.projectPath);if(!G)throw new v("Session",x.sessionId);if(!["failed","interrupted","cancelled"].includes(G.taskStatus))throw new I(`Task cannot be retried while status is ${G.taskStatus}`);let F=await f.findSessionTaskDispatch(x.sessionId,x.projectPath);if(!F)throw new I("Task retry payload is unavailable");return L({prompt:F.prompt,title:F.title,sourceProjectPath:F.sourceProjectPath,isolation:F.isolation,permissionMode:F.permissionMode,modelId:F.modelId,reasoningEffort:F.reasoningEffort,serviceTier:F.serviceTier,responseVerbosity:F.responseVerbosity,communicationStyle:F.communicationStyle,attachments:F.attachments,retriedFrom:x})},m=async(Q,V)=>{let x=await C(Q,V);if(!x.taskWorktree)throw new _("Session does not have a task worktree");try{await A0.restoreSession(x.taskWorktree);let G=await A0.getDiffArtifact(x.id);if(!G)throw new I("Task diff artifact is unavailable");return{sessionId:x.id,projectPath:x.projectPath,...G}}catch(G){if(G instanceof I)throw G;throw P.error("[SessionRoutes] Failed to load task diff artifact:",G),new I("Task diff artifact is unavailable")}},J0=async(Q,V,x)=>{let G=await z0(Q,x);return W(G).runExclusive(async()=>{let F=await C(G.sessionId,G.projectPath);if(["queued","running"].includes(F.taskStatus))throw new I(`Task artifacts cannot be delivered while status is ${F.taskStatus}`);if(F.taskDelivery?.status==="applied")throw new I("Task changes have already been applied");if(F.taskDelivery?.status==="discarded")throw new I("Task changes have already been discarded");if(!F.taskWorktree)throw new I("Task worktree is unavailable");let U=async(D,w=!1)=>{let A=await f.updateSessionMetadata(F.id,F.projectPath,{taskDelivery:D,...w?{taskWorktree:null}:{}});if(DO(F,A),w)F.taskWorktree=void 0;return k.publish(G,"task.delivery",{taskDelivery:D,...w?{taskWorktreeRemoved:!0}:{},updatedAt:A.lastMessageTime}),y0(F)};try{if(V==="discard"){try{await A0.restoreSession(F.taskWorktree)}catch(A){return P.warn(`[SessionRoutes] Abandoning unavailable task worktree for ${F.id}:`,A),U({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:F.taskDiffStat?.changedFiles??0,message:"Task artifact discarded; worktree was unavailable"},!0)}let w=await A0.exit({sessionId:F.id,action:"remove",discardChanges:!0});return U({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:w.discardedFiles??0,message:"Task worktree removed"},!0)}try{await A0.restoreSession(F.taskWorktree)}catch(w){throw P.warn(`[SessionRoutes] Task worktree is unavailable for ${F.id}:`,w),new mO("artifact_unavailable","Task worktree is unavailable")}let D=await A0.apply(F.id);return U({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 mO)throw await U({status:"conflicted",updatedAt:new Date().toISOString(),message:D.message}),new I(D.message);throw D}})},x0=async(Q)=>{let V=G0(Q.currentRunId);if(W0(V))return;if(Q.taskIsolation&&Q.taskStatus!=="queued"&&Q.taskStatus!=="running")return;let x=await H(Q),G=G0(Q.currentRunId);if(W0(G))return;let F=x.getPendingSteeringCount()>0,D=(F?null:await x.getGoal())?.status==="active";if(!F&&!D||x.hasTurnOwner())return;Y0(Q,"",Q.permissionMode??"default",{pendingInputOnly:F,goalContinuationOnly:D,...Q.taskIsolation?{taskRuntime:x}:{}})},r=async()=>{let Q={scheduled:0,failed:0,deferred:0},V=(await f.listSessions()).filter((x)=>x.taskStatus==="queued"&&x.taskIsolation!==void 0).sort((x,G)=>x.firstMessageTime.localeCompare(G.firstMessageTime)||x.projectPath.localeCompare(G.projectPath)||x.sessionId.localeCompare(G.sessionId));for(let[x,G]of V.entries()){let F={sessionId:G.sessionId,projectPath:G.projectPath};try{if(!await dO.hasPendingInbox(G.projectPath,G.sessionId)){let D=WO("Queued task input is missing");await f.updateSessionMetadata(G.sessionId,G.projectPath,{taskStatus:"failed",taskStatusReason:D.message,taskFailure:D,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null}),Q.failed++;continue}let U=await R(F);if(await x0(U),U.currentRunId)Q.scheduled++}catch(U){if(U instanceof vO){Q.deferred+=V.length-x;break}P.warn(`[SessionRoutes] Failed to recover queued task ${G.sessionId}:`,U),Q.deferred++}}return Q};return O.get("/",async(Q)=>{try{let V=await f.listSessions(),x=new Set(V.filter((B)=>B.relationType==="subagent").map((B)=>d({sessionId:B.sessionId,projectPath:B.projectPath}))),G=Array.from(n.values()).filter((B)=>!x.has(d($0(B)))&&B.relationType!=="subagent").map((B)=>y0(B)),F=new Set(G.map((B)=>d({sessionId:B.sessionId,projectPath:B.projectPath}))),U=V.filter((B)=>{if(B.relationType==="subagent")return!1;return!F.has(d({sessionId:B.sessionId,projectPath:B.projectPath}))}),D=new Set(F),w=U.filter((B)=>{let b=d({sessionId:B.sessionId,projectPath:B.projectPath});if(D.has(b))return!1;return D.add(b),!0}),A=[...G,...w];return Q.json(A)}catch(V){throw P.error("[SessionRoutes] Failed to list sessions:",V),new a("Failed to list sessions")}}),O.get("/catalog",async(Q)=>{try{let V=Q.req.query("limit"),x=V===void 0?void 0:Number(V),G=Q.req.query("cursor"),F=Q.req.query("projectPath"),U=Q.req.query("archived");if(U!==void 0&&U!=="true"&&U!=="false")throw new _("archived must be true or false");let D=U==="true",w=await f.listSessionPage({...F?{cwd:$O(F)}:{},...G?{cursor:G}:{},...x===void 0?{}:{limit:x},includeSubagents:!1,archived:D}),A=new Map((D?[]:Array.from(n.values())).filter((B)=>B.relationType!=="subagent").map((B)=>[d($0(B)),y0(B)]));return Q.json({sessions:w.sessions.map((B)=>A.get(d({sessionId:B.sessionId,projectPath:B.projectPath}))??B),...w.nextCursor?{nextCursor:w.nextCursor}:{}})}catch(V){if(V instanceof _)throw V;if(V instanceof Error&&(V.message.startsWith("Invalid session cursor")||V.message.startsWith("Session cursor scope")||V.message.startsWith("Session catalog")))throw new _(V.message);throw P.error("[SessionRoutes] Failed to list session catalog:",V),new a("Failed to list session catalog")}}),O.post("/",async(Q)=>{try{let V=await Q.req.json(),x=h(i4,V);if(!x.success)throw new _("Invalid request body");let{title:G,projectPath:F}=x.data,U=fO("web",12),D=$O(F||Q.get("directory")||T(),F?"projectPath":"directory"),w=await f.createSessionMetadata(U,D,{title:G,taskStatus:"completed"}),A=VO(w,[]),B=$0(A);return n.set(d(B),A),k.publish(B,"session.created",{}),Q.json({...y0(A),status:void 0,agentType:void 0,model:void 0})}catch(V){if(P.error("[SessionRoutes] Failed to create session:",V),V instanceof _)throw V;throw new a("Failed to create session")}}),O.get("/:sessionId/export",async(Q)=>{let V=Q.req.param("sessionId");try{let x=Q.req.query("includeReasoning");if(x!==void 0&&x!=="true"&&x!=="false")throw new _("includeReasoning must be true or false");let G=await z0(V,Q.req.query("projectPath")),F=await f.exportSessionMarkdown(G.sessionId,G.projectPath,{includeReasoning:x==="true"});return Q.body(F.markdown,200,{"Cache-Control":"no-store","Content-Disposition":`attachment; filename="${F.filename}"`,"Content-Length":String(Buffer.byteLength(F.markdown,"utf8")),"Content-Type":"text/markdown; charset=utf-8","X-Blade-Content-Sha256":F.contentSha256,"X-Blade-Export-Activities":String(F.activityCount),"X-Blade-Export-Messages":String(F.messageCount),"X-Blade-Export-Redactions":String(F.redactionCount)})}catch(x){if(x instanceof _||x instanceof v||x instanceof V0)throw x;if(x instanceof Error&&x.message==="No conversation content to export")throw new I(x.message);throw P.error("[SessionRoutes] Failed to export session:",x),new a("Failed to export session")}}),O.post("/:sessionId/fork",async(Q)=>{let V=Q.req.param("sessionId");try{TO(V);let x=await Q.req.json(),G=h(o4,x);if(!G.success)throw new _("Invalid request body");let F=$O(G.data.projectPath),U=await f.findSessionMetadata(V,F);if(!U)throw new v("Session",V);let D=await f.forkSession(V,{sourceProjectPath:U.projectPath,targetProjectPath:U.projectPath}),w=VO(D.metadata,D.messages),A=$0(w);return n.set(d(A),w),k.publish(A,"task.status",{taskStatus:D.metadata.taskStatus,...D.metadata.taskCompletedAt?{taskCompletedAt:D.metadata.taskCompletedAt}:{},updatedAt:D.metadata.lastMessageTime}),Q.json({session:D.metadata,messages:IO(D.messages)},201)}catch(x){if(x instanceof _||x instanceof v||x instanceof I)throw x;if(x instanceof O1)throw new I("Session has no durable creation record");throw P.error("[SessionRoutes] Failed to fork session:",x),new a("Failed to fork session")}}),O.get("/:sessionId",async(Q)=>{let V=Q.req.param("sessionId");try{let x=await z0(V,Q.req.query("projectPath")),G=n.get(d(x));if(G)return Q.json(y0(G));let F=await f.findSessionMetadata(x.sessionId,x.projectPath);if(!F)throw new v("Session",V);return Q.json(F)}catch(x){if(x instanceof _||x instanceof v||x instanceof V0)throw x;throw P.error("[SessionRoutes] Failed to get session:",x),new a("Failed to get session")}}),O.patch("/:sessionId",async(Q)=>{let V=Q.req.param("sessionId");try{let x=await Q.req.json(),G=h(a4,x);if(!G.success)throw new _("Invalid request body");if(G.data.title===void 0)throw new _("title is required");let F=await z0(V,G.data.projectPath),U=await f.updateSessionMetadata(F.sessionId,F.projectPath,{title:G.data.title}),D=n.get(d(F));if(D)D.title=U.title??D.title,D.updatedAt=new Date(U.lastMessageTime);if(U.title)k.publish(F,"session.updated",{title:U.title});return Q.json({success:!0,title:U.title})}catch(x){if(P.error("[SessionRoutes] Failed to update session:",x),x instanceof _||x instanceof v||x instanceof V0)throw x;throw new a("Failed to update session")}}),O.get("/:sessionId/rewind",async(Q)=>{let V=await C(Q.req.param("sessionId"),Q.req.query("projectPath")),x=await H(V);return Q.json({checkpoints:await x.listRewindCheckpoints()})}),O.post("/:sessionId/rewind",async(Q)=>{let V=h(m$,await Q.req.json());if(!V.success)throw new _("Invalid rewind request");let x=await C(Q.req.param("sessionId"),Q.req.query("projectPath")),G=$0(x);return K(G).runExclusive(async()=>{let F=G0(x.currentRunId);if(W0(F))throw new I("Cannot rewind while a run is active");let U=await H(x),D;try{D=await U.rewindSession(V.data)}catch(A){if(A instanceof Error&&A.message.startsWith("Cannot rewind while"))throw new I(A.message);throw A}x.messages=[...D.messages],x.updatedAt=new Date;let w=IO(D.messages);return k.publish(G,"session.rewound",{targetMessageId:D.checkpoint.messageId,mode:D.mode,removedTurns:D.removedTurns,restoredFiles:D.restoredFiles,messages:w}),Q.json({...D,messages:w})})}),O.get("/:sessionId/subagents",async(Q)=>{let V=await C(Q.req.param("sessionId"),Q.req.query("projectPath")),x=await H(V);return Q.json({subagents:x.listSubagents().map(FO)})}),O.post("/:sessionId/subagents/:agentId/resume",async(Q)=>{TO(Q.req.param("agentId"));let V=v$.safeParse(await Q.req.json());if(!V.success)throw new _("Invalid subagent resume request");let x=await C(Q.req.param("sessionId"),Q.req.query("projectPath")),G=$0(x);return K(G).runExclusive(async()=>{let F=G0(x.currentRunId);if(W0(F))throw new I("Cannot resume a subagent while a parent run is active");let U=await H(x),D=!1,w,A=(b)=>{k.publish(G,"subagent.complete",{subagentSessionId:b.id,success:b.status==="completed",status:b.status,summary:b.result?.message?.slice(0,500),type:b.subagentType,verificationVerdict:b.result?.verificationVerdict,resumedFrom:b.resumedFrom,rootAgentId:b.rootAgentId,resumeDepth:b.resumeDepth})},B;try{B=U.resumeSubagent({agentId:Q.req.param("agentId"),prompt:V.data.prompt,onEvent:(b,e)=>{O2(G,e,b)},onCompleted:(b)=>{if(D)A(b);else w=b}})}catch(b){if(b instanceof Error&&(b.message.startsWith("Cannot resume")||b.message.startsWith("Subagent cannot")))throw new I(b.message);if(b instanceof Error&&b.message.startsWith("Subagent not found"))throw new v(b.message);throw b}if(k.publish(G,"subagent.start",{subagentSessionId:B.session.id,type:B.session.subagentType,description:B.session.description,resumedFrom:B.source.id,rootAgentId:B.session.rootAgentId,resumeDepth:B.session.resumeDepth}),D=!0,w)A(w);return Q.json({source:FO(B.source),session:FO(B.session)})})}),O.get("/:sessionId/goal",async(Q)=>{let V=await C(Q.req.param("sessionId"),Q.req.query("projectPath"));return Q.json({goal:await new $1(V.projectPath,V.id).get()})}),O.put("/:sessionId/goal",async(Q)=>{let V=h(n4,await Q.req.json());if(!V.success)throw new _("Invalid goal request");let x=await C(Q.req.param("sessionId"),Q.req.query("projectPath")),G=$0(x);return K(G).runExclusive(async()=>{let F=G0(x.currentRunId);if(W0(F))return Q.json({status:"rejected",reason:"run_active"},409);let D=V.data.permissionMode??x.permissionMode??"default";if(x.permissionMode!==D)await t(x,D);let w=await H(x),A=await w.createGoal(V.data);k.publish(G,"goal.updated",{goal:A});let B=Y0(x,"",D,{goalContinuationOnly:!0,...x.taskIsolation?{taskRuntime:w}:{}});return await B.taskAdmissionUpdate,Q.json({status:B.status==="queued"?"queued":"running",runId:B.id,goal:A,queuePosition:B.taskQueuePosition,queueDepth:B.taskQueueDepth,maxConcurrentTasks:B.taskConcurrencyLimit},202)})}),O.patch("/:sessionId/goal",async(Q)=>{let V=h(t4,await Q.req.json());if(!V.success)throw new _("Invalid goal update");let x=await C(Q.req.param("sessionId"),Q.req.query("projectPath")),G=$0(x);return K(G).runExclusive(async()=>{let F=await H(x),U;if(V.data.action==="pause")U=await F.pauseGoal();else if(V.data.action==="edit")U=await F.editGoal(V.data.objective);else U=await F.resumeGoal();if(k.publish(G,"goal.updated",{goal:U}),U.status==="active"&&!W0(G0(x.currentRunId))){let D=Y0(x,"","default",{goalContinuationOnly:!0,...x.taskIsolation?{taskRuntime:F}:{}});return await D.taskAdmissionUpdate,Q.json({status:D.status==="queued"?"queued":"running",runId:D.id,goal:U,queuePosition:D.taskQueuePosition,queueDepth:D.taskQueueDepth,maxConcurrentTasks:D.taskConcurrencyLimit},202)}return Q.json({status:U.status,goal:U})})}),O.delete("/:sessionId/goal",async(Q)=>{let V=await C(Q.req.param("sessionId"),Q.req.query("projectPath")),x=$0(V),F=await(await H(V)).clearGoal();if(F)k.publish(x,"goal.cleared",{});return Q.json({cleared:F})}),O.post("/:sessionId/archive",async(Q)=>{let V=Q.req.param("sessionId");try{let x=await z0(V,Q.req.query("projectPath")),G=await f.listSessionArchiveMembers(x.sessionId,x.projectPath);for(let U of G){let D=R0({sessionId:U.sessionId,projectPath:U.projectPath}),w=n.get(d(D));if(W0(G0(w?.currentRunId)))throw new I(`Stop session ${U.sessionId} before archiving this session tree`)}for(let U of G){let D=R0({sessionId:U.sessionId,projectPath:U.projectPath}),w=n.get(d(D));if(w)await E(w)}let F=await f.archiveSession(x.sessionId,x.projectPath);for(let U of G){let D=R0({sessionId:U.sessionId,projectPath:U.projectPath}),w=d(D);n.delete(w),z.delete(w),Z.delete(w),N.delete(w),k.publish(D,"session.archived",{archiveRootId:x.sessionId,archivedAt:F.archivedAt})}if(J.size===0)await X0.getInstance().disconnectAll();return Q.json({session:F,archivedSessionIds:G.map((U)=>U.sessionId)})}catch(x){if(x instanceof _||x instanceof v||x instanceof V0||x instanceof I)throw x;if(x instanceof PO)throw new I(x.message);throw P.error("[SessionRoutes] Failed to archive session:",x),new a("Failed to archive session")}}),O.post("/:sessionId/unarchive",async(Q)=>{let V=Q.req.param("sessionId");try{let x=await z0(V,Q.req.query("projectPath")),G=await f.listSessionArchiveMembers(x.sessionId,x.projectPath),F=await f.unarchiveSession(x.sessionId,x.projectPath),U=G.filter((D)=>D.sessionId===x.sessionId||D.archivedBySessionId===x.sessionId).map((D)=>D.sessionId);for(let D of U)k.publish({sessionId:D,projectPath:x.projectPath},"session.unarchived",{archiveRootId:x.sessionId});return Q.json({session:F,restoredSessionIds:U})}catch(x){if(x instanceof _||x instanceof v||x instanceof V0)throw x;if(x instanceof PO)throw new I(x.message);throw P.error("[SessionRoutes] Failed to unarchive session:",x),new a("Failed to unarchive session")}}),O.delete("/:sessionId",async(Q)=>{let V=Q.req.param("sessionId"),x=Q.req.query("projectPath");try{let G=await z0(V,x),F=d(G),U=n.get(F),D=J.get(F),w=U?.taskWorktree??await f.findSessionTaskWorktree(G.sessionId,G.projectPath),A;if(U?.currentRunId){let B=G0(U.currentRunId);if(B)UO(B),await B.completion,A=B.id}if(D)await D.clearGoal().catch((B)=>{P.warn("[SessionRoutes] Failed to clear session goal:",B)});if(await f.deleteSession(G.sessionId,G.projectPath),k.publish(G,"session.deleted",{}),A)r4(A);if(n.delete(F),z.delete(F),Z.delete(F),N.delete(F),D){if(await D.dispose(),J.delete(F),J.size===0)await X0.getInstance().disconnectAll()}if(w)try{await A0.restoreSession(w),await A0.exit({sessionId:G.sessionId,action:"remove",discardChanges:!0})}catch(B){P.warn(`[SessionRoutes] Failed to remove deleted task worktree ${G.sessionId}:`,B)}return Q.json({success:!0})}catch(G){if(P.error("[SessionRoutes] Failed to delete session:",G),G instanceof _||G instanceof v||G instanceof V0)throw G;throw new a("Failed to delete session")}}),O.get("/:sessionId/message",async(Q)=>{let V=Q.req.param("sessionId");try{let x=await z0(V,Q.req.query("projectPath")),G=n.get(d(x)),F=G?.messages?G.messages:await f.loadSession(x.sessionId,x.projectPath);return Q.json(IO(F))}catch(x){if(P.error("[SessionRoutes] Failed to get messages:",x),x instanceof _||x instanceof v||x instanceof V0)throw x;throw new a("Failed to get messages")}}),O.get("/:sessionId/events",async(Q)=>{let V=Q.req.param("sessionId"),x=await z0(V,Q.req.query("projectPath"));try{await f.assertSessionWritable(x.sessionId,x.projectPath)}catch(w){if(w instanceof SO)throw new I(w.message);throw w}let G=await R(x),F=Q.req.header("Last-Event-ID")??Q.req.query("lastEventId"),U=F?Number.parseInt(F,10):Number.NaN,D=Number.isInteger(U)?U+1:void 0;return l4(Q,async(w)=>{let B,b,e=!1,h0=()=>{if(b!==void 0)clearInterval(b),b=void 0;B?.(),B=void 0},i=()=>{if(e)return;e=!0,h0()},y=new Set;w.onAbort(i),B=k.subscribe((l)=>{if(l.sessionId!==x.sessionId||l.projectPath!==x.projectPath)return;let K0=l.properties.requestId;if((l.type==="permission.asked"||l.type==="question.required"||l.type==="elicitation.required")&&typeof K0==="string"){if(y.has(K0))return;y.add(K0)}w.writeSSE({...typeof l.seq==="number"?{id:String(l.seq)}:{},data:JSON.stringify({type:l.type,...typeof l.seq==="number"?{seq:l.seq}:{},properties:{...l.properties,sessionId:l.sessionId,projectPath:l.projectPath}})}).catch(i)});try{if(w.aborted||e)return;let l=G0(G.currentRunId),K0=W0(l)?await H(G):void 0,_0=K0?.getPendingSteeringCount()??0;if(await w.writeSSE({data:JSON.stringify({type:"connected",properties:{sessionId:x.sessionId,projectPath:x.projectPath,timestamp:Date.now(),status:W0(l)?l.status:"idle",runId:W0(l)?l.id:void 0,queued:_0,pendingInputDelivery:_0>0?K0?.hasActiveTurn()?"current_turn":"next_turn":null,recovered:K0?.getRecoveredSteeringCount()??0}})}).catch((S)=>{throw i(),S}),w.aborted||e)return;if(D!==void 0){if(await J1.for(x.sessionId,x.projectPath).replay({onCommitted:(u)=>{if(w.aborted||e)return;w.writeSSE({...typeof u.seq==="number"?{id:String(u.seq)}:{},data:JSON.stringify({type:`committed.${u.type}`,...typeof u.seq==="number"?{seq:u.seq}:{},properties:{event:u,sessionId:x.sessionId,projectPath:x.projectPath}})})}},D),w.aborted||e)return}let q=l?.pendingPermission;if(q){y.add(q.permissionId);let S=x1(q,!0);await w.writeSSE({data:JSON.stringify({type:S.type,properties:{...S.properties,sessionId:x.sessionId,projectPath:x.projectPath}})})}x0(G).catch((S)=>{P.error(`[SessionRoutes] Failed to resume pending input for ${V}:`,S)}),b=setInterval(()=>{if(!w.aborted)w.writeSSE({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})}).catch(i)},15000);while(!w.aborted&&!e)await new Promise((S)=>setTimeout(S,1000))}finally{i()}})}),O.post("/:sessionId/message",async(Q)=>{let V=Q.req.param("sessionId"),x=await Q.req.json(),G=h(p4,x);if(!G.success)throw new _("Invalid message format");let{content:F,attachments:U,modelId:D,reasoningEffort:w,serviceTier:A,responseVerbosity:B,communicationStyle:b,permissionMode:e,projectPath:h0}=G.data,i=b,y=D?.trim();if((U??[]).reduce((s,c)=>s+(typeof c.content==="string"?Buffer.byteLength(c.content):0),0)>g0)throw new _("Message attachments exceed the 5 MiB limit");let K0=e,_0=p$(F,U),q=await C(V,h0??Q.req.query("projectPath")),S=K0??q.permissionMode??"default",u=$0(q);return K(u).runExclusive(async()=>{let s=G0(q.currentRunId);if(W0(s)){let g=await H(q);if(y&&!g.getModelById(y))throw new _(`Model not found: ${y}`);if(y&&g.getCurrentModelId()!==y)throw new I("Wait for the active turn to finish before switching models");if(w&&g.getReasoningConfiguration().selection!==w)throw new I("Wait for the active turn to finish before switching reasoning effort");if(A&&g.getServiceTierConfiguration().selection!==A)throw new I("Wait for the active turn to finish before switching service tier");if(B&&g.getResponseVerbosityConfiguration().selection!==B)throw new I("Wait for the active turn to finish before switching response verbosity");if(i&&g.getCommunicationStyleConfiguration().selection!==i)throw new I("Wait for the active turn to finish before switching communication style");if(K0&&q.permissionMode!==K0)throw new I("Wait for the active turn to finish before switching permission mode");let H0=await g.enqueueSteering(_0,{allowBeforeTurn:!0});if(!H0.accepted)return Q.json({status:"rejected",reason:H0.reason??"turn_unavailable"},409);let LO=H0.messageId??l0(12),X$=H0.queued;k.publish(u,"message.created",{messageId:LO,role:"user",content:uO(_0)});let J4=H0.delivery==="next_turn"?"follow_up.queued":"steering.queued";if(k.publish(u,J4,{runId:s.id,messageId:LO,queued:X$}),H0.delivery==="next_turn"&&s.status!=="running"&&s.status!=="waiting_permission")x0(q).catch((Z4)=>{P.error(`[SessionRoutes] Failed to wake queued follow-up for ${V}:`,Z4)});if(H0.delivery==="next_turn")s.pendingFollowUpRequested=!0;return Q.json({runId:s.id,messageId:LO,status:H0.delivery==="next_turn"?"follow_up_queued":"steering_queued",queued:X$},202)}if(q.permissionMode!==S)await t(q,S);let c=await H(q,{permissionMode:S,...i&&!i.includes(":")?{communicationStyle:i}:{}});if(y&&!c.getModelById(y))throw new _(`Model not found: ${y}`);if(w)try{c.resolveReasoningConfiguration(w,y)}catch(g){throw new _(g instanceof Error?g.message:"Invalid reasoning effort")}if(A)try{c.resolveServiceTierConfiguration(A,y)}catch(g){throw new _(g instanceof Error?g.message:"Invalid service tier")}if(B)try{c.resolveResponseVerbosityConfiguration(B,y)}catch(g){throw new _(g instanceof Error?g.message:"Invalid response verbosity")}let B0=i?c.resolveCommunicationStyleConfiguration(i):void 0;if(B0?.source!==void 0&&B0.source!=="built-in"&&!B0.contentSha256)throw new _("Custom communication style has no provenance");let M0=c.getCurrentModelId(),E0=c.getReasoningConfiguration(),$$=c.getServiceTierConfiguration(),J$=c.getResponseVerbosityConfiguration(),Z$=c.getCommunicationStyleConfiguration(),Y$=Boolean(y)&&M0!==y,x$=Boolean(w)&&E0.selection!==w,z$=Boolean(A)&&$$.selection!==A,Q$=Boolean(B)&&J$.selection!==B,N$=Boolean(i)&&Z$.selection!==i;if(Y$||x$||z$||Q$||N$)await c.refresh({...y?{modelId:y}:{},...w?{reasoningEffort:w}:{},...A?{serviceTier:A}:{},...B?{responseVerbosity:B}:{},...i?{communicationStyle:i}:{}});let wO={...y&&q.selectedModelId!==y?{selectedModelId:y}:{},...w&&q.reasoningEffort!==w?{reasoningEffort:w}:{},...A&&q.serviceTier!==A?{serviceTier:A}:{},...B&&q.responseVerbosity!==B?{responseVerbosity:B}:{},...B0&&(q.communicationStyle!==i||q.communicationStyleDigest!==B0.contentSha256)?{communicationStyle:i,communicationStyleDigest:B0.source==="built-in"?null:B0.contentSha256}:{}};if(Object.keys(wO).length>0)try{let g=await f.updateSessionMetadata(q.id,q.projectPath,wO);q.permissionMode=g.permissionMode,q.selectedModelId=g.selectedModelId,q.reasoningEffort=g.reasoningEffort,q.serviceTier=g.serviceTier,q.responseVerbosity=g.responseVerbosity,q.communicationStyle=g.communicationStyle,q.communicationStyleDigest=g.communicationStyleDigest,q.updatedAt=new Date(g.lastMessageTime),k.publish(u,"session.updated",wO)}catch(g){if(Y$||x$||z$||Q$||N$)await c.refresh({...M0?{modelId:M0}:{},reasoningEffort:E0.selection,serviceTier:$$.selection,responseVerbosity:J$.selection,communicationStyle:Z$.selection}).catch((H0)=>P.error("[SessionRoutes] Failed to roll back non-durable model settings:",H0));throw g}let o0=await c.prepareInputTurn(_0);if(!o0.accepted)return Q.json({status:"rejected",reason:o0.reason},o0.reason==="queue_full"?429:409);let m0=Y0(q,_0,S,{preparedInputTurn:o0,...q.taskIsolation?{taskRuntime:c}:{}});return await m0.taskAdmissionUpdate,Q.json({runId:m0.id,messageId:o0.messageId,status:m0.status==="queued"?"queued":"running",queuePosition:m0.taskQueuePosition,queueDepth:m0.taskQueueDepth,maxConcurrentTasks:m0.taskConcurrencyLimit},202)})}),O.post("/:sessionId/shell",async(Q)=>{let V=Q.req.param("sessionId"),x=h(y$,await Q.req.json());if(!x.success)throw new _("Invalid user shell command");let G=await C(V,x.data.projectPath??Q.req.query("projectPath")),F=$0(G),U=d(F);return K(F).runExclusive(async()=>{if(c0.has(U))throw new I("A user shell command is already running in this Session");let D=await H(G),w=new AbortController,A,B=new Promise((b)=>{A=b});c0.set(U,{controller:w,completion:B});try{let b=await D.executeUserShellCommand(x.data.command,{signal:w.signal});G.messages=await f.loadSession(G.id,G.projectPath),G.updatedAt=new Date;let e=G0(G.currentRunId);if(b.delivery==="next_turn"&&W0(e))e.pendingFollowUpRequested=!0;return Q.json({executionId:b.executionId,messageId:b.messageId,record:b.record,auxiliary:b.auxiliary,...b.delivery?{delivery:b.delivery}:{},...b.queued!==void 0?{queued:b.queued}:{}})}finally{c0.delete(U),A()}})}),O.post("/:sessionId/abort",async(Q)=>{let V=Q.req.param("sessionId"),x=await z0(V,Q.req.query("projectPath")),G=n.get(d(x));if(G?.currentRunId){let U=G0(G.currentRunId);if(U)UO(U),await U.completion}let F=c0.get(d(x));if(F)F.controller.abort("user-cancel"),await F.completion;return Q.json({success:!0})}),O.get("/:sessionId/status",async(Q)=>{let V=Q.req.param("sessionId"),x=await z0(V,Q.req.query("projectPath")),G=n.get(d(x));if(!G?.currentRunId)return Q.json({sessionId:V,projectPath:x.projectPath,status:"idle"});let F=G0(G.currentRunId);return Q.json({sessionId:V,projectPath:x.projectPath,runId:G.currentRunId,status:F?.status||"idle"})}),{app:O,dispatchTask:L,retryTask:O0,getTaskDiff:m,deliverTask:J0,recoverQueuedTasks:r}};async function $2(O,J,Z,Y,z,N={}){let{abortController:X,sessionId:K,id:W}=O,H=N.preparedInputTurn?.messageId??l0(12),R=N.pendingInputOnly===!0||N.preparedInputTurn?.mode==="pending"||N.goalContinuationOnly===!0?void 0:l0(12),C,t,Y0=$0(J),L=(m,J0)=>{k.publish(Y0,m,J0)},O0=async()=>{let m=String(X.signal.reason||"Task run cancelled");if(J.taskIsolation){let J0=C??await z(J).catch(()=>{return});if(m==="user-cancel")await J0?.discardPendingInput().catch((r)=>{P.warn(`[SessionRoutes] Failed to discard cancelled input for ${J.id}:`,r)});let x0=await J0?.setTaskStatus("cancelled",m).catch(()=>{return});if(x0)DO(J,x0);else await kO(J).catch(()=>{return})}J.taskStatus="cancelled",J.taskStatusReason=m,J.taskCompletedAt??=new Date().toISOString()};try{if(N.taskAdmission){if(await N.taskAdmission.ready,await O.taskAdmissionUpdate,X.signal.aborted)throw Error(String(X.signal.reason||"Task run cancelled"))}if(J.taskStatus="running",J.taskStatusReason=void 0,J.taskStartedAt=new Date().toISOString(),J.taskCompletedAt=void 0,!N.pendingInputOnly&&!N.goalContinuationOnly)L("message.created",{messageId:H,role:"user",content:uO(Z)});if(L("session.status",{status:"running"}),R)L("message.created",{messageId:R,role:"assistant",content:""});C=await z(J);let m=C;t=await Z1.createWithRuntime(m,{sessionId:K,...J.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}});let J0=async(x)=>{let G=l0(12),F=300000;O.status="waiting_permission";let U=new Promise((B)=>{let b=setTimeout(()=>{P.warn(`[SessionRoutes] Permission ${G} timed out after 300000ms`),L("permission.timeout",{requestId:G}),B({approved:!1,reason:"timeout"})},300000);O.pendingPermission={permissionId:G,resolve:(e)=>{clearTimeout(b),B(e)},details:x}}),D=O.pendingPermission;if(!D)throw Error("Permission request was not registered");let w=x1(D);L(w.type,w.properties),P.info(`[SessionRoutes] Permission request created: ${G}, runId: ${W}`);let A=await U;if(P.info(`[SessionRoutes] Permission response received: ${G}, approved: ${A.approved}`),!X.signal.aborted)O.status="running";if(O.pendingPermission===D)O.pendingPermission=void 0;return L("interaction.resolved",{requestId:G}),A},x0={messages:[...J.messages],userId:"web-user",sessionId:K,workspaceRoot:J.projectPath,signal:X.signal,permissionMode:Y,onPermissionModeChange:async(x)=>{J.permissionMode=x,J.updatedAt=new Date,L("session.updated",{permissionMode:x})},...J.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:J0}},r=()=>{if(!R)R=l0(12),L("message.created",{messageId:R,role:"assistant",content:""});return R},Q=async(x)=>{switch(x.kind){case"content_delta":L("message.delta",{messageId:r(),delta:x.delta});break;case"thinking_delta":L("thinking.delta",{messageId:r(),delta:x.delta});break;case"tool_start":if("function"in x.toolCall)L("tool.start",{messageId:r(),toolName:x.toolCall.function.name,toolCallId:x.toolCall.id,arguments:x.toolCall.function.arguments,toolKind:x.toolKind});break;case"tool_result":if("function"in x.toolCall)L("tool.result",{messageId:r(),toolName:x.toolCall.function.name,toolCallId:x.toolCall.id,success:x.result.success,summary:x.result.metadata?.summary,output:yO(gO(x.toolCall.function.name,x.result)),metadata:z1(x.result.metadata)});break;case"tool_progress":if("function"in x.toolCall)L("tool.progress",{messageId:r(),toolName:x.toolCall.function.name,toolCallId:x.toolCall.id,...x.update});break;case"token_usage":L("token.usage",{...x.usage});break;case"turn_start":L("turn.started",{turn:x.turn,maxTurns:x.maxTurns});break;case"mcp_catalog_changed":L("mcp.catalog.changed",{messageId:r(),revision:x.revision,serverName:x.serverName,added:x.added,removed:x.removed,updated:x.updated});break;case"mcp_content_changed":L("mcp.content.changed",{messageId:r(),revision:x.revision,serverName:x.serverName,contentKind:x.contentKind,added:x.added,removed:x.removed,updated:x.updated});break;case"mcp_resource_updated":L("mcp.resource.updated",{messageId:r(),revision:x.revision,serverName:x.serverName,uri:x.uri});break;case"mcp_connection_changed":L("mcp.connection.changed",{messageId:r(),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":L("mcp.log",{messageId:r(),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":L("mcp.instructions.changed",{messageId:r(),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":L("mcp.task.changed",{messageId:r(),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":L("project.rules.loaded",{messageId:r(),files:x.files,triggerPaths:x.triggerPaths,blockedWrite:x.blockedWrite});break;case"steering_applied":L("steering.applied",{runId:W,messageIds:x.messageIds,count:x.count,recovered:x.recovered,delivery:x.delivery,queued:m.getPendingSteeringCount()});break;case"follow_up_started":{if(R)L("message.complete",{messageId:R}),R=void 0;for(let G of x.messages){if(!G.recovered||G.persisted)continue;L("message.created",{messageId:G.id,role:"user",content:uO(G.content),recovered:!0})}L("follow_up.started",{runId:W,queued:x.queued,recovered:x.recovered}),r();break}case"goal_updated":L("goal.updated",{goal:x.goal});break;case"goal_continuation_started":L("goal.continuation.started",{goal:x.goal,continuation:x.continuation}),r();break;case"compaction":L(x.phase==="start"?"compaction.started":"compaction.completed",{});break;case"model_fallback":L("model.fallback",{});break;case"task_update":L("task.updated",{tasks:x.tasks});break;default:break}},V=await hO(t.chatStream(Z,x0,{stream:!0,pendingInputOnly:N.pendingInputOnly,preparedInputTurn:N.preparedInputTurn,goalContinuationOnly:N.goalContinuationOnly,taskAdmission:N.taskAdmission}),Q);if(!V.success)throw Error(V.error?.message??"Agent run failed");for(let x=0;x<20;x++){let G=O.pendingFollowUpRequested===!0;if(O.pendingFollowUpRequested=!1,m.getPendingSteeringCount()===0){if(!G)break;continue}if(X.signal.aborted)break;if(V=await hO(t.chatStream("",x0,{stream:!0,pendingInputOnly:!0,taskAdmission:N.taskAdmission}),Q),!V.success)throw Error(V.error?.message??"Agent follow-up failed")}if(J.messages=[...x0.messages],J.updatedAt=new Date,await kO(J),X.signal.aborted||O.status==="cancelled"){await O0(),L("session.status",{status:"idle"});return}if(R)L("message.complete",{messageId:R});L("thinking.completed",{}),O.status="completed",J.taskStatus="completed",J.taskCompletedAt??=new Date().toISOString(),L("session.completed",{runId:W,outputTruncated:V.metadata?.outputTruncated??!1}),L("session.status",{status:"idle"})}catch(m){if(C&&N.preparedInputTurn)await C.finishTurn(N.preparedInputTurn.handle).catch(()=>{return});if(X.signal.aborted||O.status==="cancelled"){UO(O,"runtime-abort"),await O0(),L("session.status",{status:"idle"});return}await kO(J).catch(()=>{return}),P.error("[SessionRoutes] Agent execution error:",m),O.status="failed",J.taskStatus="failed",J.taskCompletedAt??=new Date().toISOString();let J0=WO(m);if(!J.taskFailure){let x0=C?await C.setTaskStatus("failed",m).catch(()=>{return}):await f.updateSessionMetadata(J.id,J.projectPath,{taskStatus:"failed",taskStatusReason:J0.message,taskFailure:J0,taskCompletedAt:J.taskCompletedAt,taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null}).catch(()=>{return});if(x0)DO(J,x0)}J.taskStatusReason??=J0.message,J.taskFailure??=J0,L("session.error",{error:J.taskFailure.message,taskFailure:J.taskFailure}),L("session.status",{status:"error"})}finally{if(N.taskAdmission?.release(),N.taskAdmission){let m=T0.getStats();L("task.status",{taskStatus:J.taskStatus,...J.taskStatusReason?{taskStatusReason:J.taskStatusReason}:{},...J.taskFailure?{taskFailure:J.taskFailure}:{},...J.taskStartedAt?{taskStartedAt:J.taskStartedAt}:{},...J.taskCompletedAt?{taskCompletedAt:J.taskCompletedAt}:{},...J.taskDiffStat?{taskDiffStat:J.taskDiffStat}:{},taskQueueDepth:m.queued,taskConcurrencyLimit:m.maxConcurrent,taskInFlight:m.inFlight,updatedAt:new Date().toISOString()})}if(await t?.destroy().catch(()=>{return}),O.disposeRuntimeOnSettle&&N.disposeRuntime)await N.disposeRuntime(J,C).catch((m)=>{P.warn(`[SessionRoutes] Failed to dispose terminal task runtime ${J.id}:`,m)});s4(O)}}function N1(O,J,Z){P.info(`[SessionRoutes] Looking for permission ${J} in session ${O.sessionId}`),P.info(`[SessionRoutes] Active runs: ${q0.size}`);for(let[Y,z]of q0.entries())if(P.info(`[SessionRoutes] Checking run ${Y}: sessionId=${z.sessionId}, projectPath=${z.projectPath}, pendingPermission=${z.pendingPermission?.permissionId}`),z.sessionId===O.sessionId&&z.projectPath===O.projectPath&&z.pendingPermission?.permissionId===J)return z.pendingPermission.resolve(Z),P.info(`[SessionRoutes] Permission ${J} responded, runId: ${z.id}`),!0;return P.error(`[SessionRoutes] Permission not found: ${J}`),!1}var lO=p("Service"),Z2=$.Object({approved:$.Boolean(),remember:$.Optional($.Boolean()),scope:$.Optional(j(["once","session","project"])),targetMode:$.Optional(j(["default","autoEdit","plan","yolo"])),feedback:$.Optional($.String()),answers:$.Optional($.Record($.String(),$.Union([$.String(),$.Array($.String())]))),elicitation:$.Optional($.Object({action:j(["accept","decline","cancel"]),content:$.Optional($.Record($.String(),$.Union([$.String({maxLength:4000}),$.Number(),$.Boolean(),$.Array($.String({maxLength:1000}),{maxItems:100})]),{maxProperties:32}))}))}),X1=()=>{let O=new J2;return O.post("/:permissionId",async(J)=>{let Z=J.req.param("permissionId"),Y=J.req.query("sessionId"),z=J.req.query("projectPath");lO.info(`[PermissionRoutes] Received permission response: permissionId=${Z}, sessionId=${Y}`);try{let N=await J.req.json(),X=h(Z2,N);if(!X.success)throw new _("Invalid permission response format");let{approved:K,remember:W,scope:H,targetMode:E,feedback:R,answers:C,elicitation:t}=X.data;if(!Y)throw new _("sessionId query parameter is required");let Y0=await z0(Y,z);if(!N1(Y0,Z,{approved:K,reason:R,scope:H,targetMode:E,feedback:R,answers:C,elicitation:t}))throw new v("Permission request",Z);return lO.info(`[PermissionRoutes] Permission ${Z} ${K?"approved":"denied"}`),J.json({success:!0,approved:K,remember:W})}catch(N){if(lO.error("[PermissionRoutes] Failed to respond to permission:",N),N instanceof _||N instanceof V0||N instanceof v||N instanceof Z0)throw N;throw N}}),O};import G1 from"node:path";import{Hono as Y2}from"hono";var x2=$.Object({projectPath:$.String({minLength:1}),enabled:$.Boolean(),scope:$.Optional(j(["local","project","global"]))}),z2=$.Object({projectPath:$.String({minLength:1})}),Q2=$.Object({projectPath:$.String({minLength:1}),source:$.String({minLength:1}),trust:$.Literal(!0),ref:$.Optional($.String({minLength:1}))}),N2=$.Object({projectPath:$.String({minLength:1}),trust:$.Literal(!0)}),X2=$.Object({projectPath:$.String({minLength:1}),confirm:$.Literal(!0)}),G2=$.Object({projectPath:$.String({minLength:1}),source:$.String({minLength:1}),ref:$.Optional($.String({minLength:1}))}),K1=$.Object({projectPath:$.String({minLength:1}),confirm:$.Optional($.Literal(!0))}),K2=$.Object({projectPath:$.String({minLength:1}),scope:$.Optional(j(["local","project","global"])),policy:$.Object({restrictToAllowedSources:$.Boolean(),requireGitCommitSha:$.Boolean(),allowedGitHosts:$.Array($.String()),allowedMarketplaces:$.Array($.String()),allowedLocalRoots:$.Array($.String())})});function U0(O){if(!O||!G1.isAbsolute(O))throw new _("projectPath must be absolute");return G1.resolve(O)}async function V1(O){let[J,Z]=await Promise.all([N0(O),t0.getInstance().loadWorkspacePluginSettingsResolution(O)]);return J.plugins.getAll().map((Y)=>({name:Y.manifest.name,description:Y.manifest.description,version:Y.manifest.version,source:Y.source,enabled:Y.status==="active",status:Y.status,commands:Y.commands.length,skills:Y.skills.length,agents:Y.agents.length,hooks:Y.hooks?Object.values(Y.hooks).reduce((z,N)=>z+(Array.isArray(N)?N.length:0),0):0,mcpServers:Object.keys(Y.mcpServers??{}).length,configurable:Y.source!=="cli",managed:Y.installation!==void 0,marketplace:Y.installation?.source.type==="marketplace"?Y.installation.source.marketplace:void 0,revision:Y.installation?.revision,installedAt:Y.installation?.installedAt,updatedAt:Y.installation?.updatedAt,compatibilityIssues:Y.compatibilityIssues??[],effectiveScope:Y.source==="cli"?"invocation":Z.settings[Y.manifest.name]?.effectiveScope??"default",settingLayers:Y.source==="cli"?{invocation:!0}:Z.settings[Y.manifest.name]?.layers??{}}))}async function V2(){let O=F1(),[J,Z]=await Promise.all([O.listCatalogs(),O.listInstallationRecords()]),Y=new Map(Z.map((z)=>[z.name,z]));return J.map(({marketplace:z,manifest:N})=>({name:z.name,description:N.description??N.metadata?.description??"",sourceType:z.source.type,revision:z.revision,updatedAt:z.updatedAt,plugins:N.plugins.map((X)=>{let K=Y.get(X.name);return{name:X.name,description:X.description??"",version:X.version,category:X.category,tags:X.tags??[],installed:K!==void 0,installedVersion:K?.version}})}))}function i0(O,J){if(!O.success)throw new _(O.error??J)}var E1=()=>{let O=new Y2;return O.get("/",async(J)=>{let Z=U0(J.req.query("projectPath"));return J.json(await V1(Z))}),O.post("/refresh",async(J)=>{let Z=h(z2,await J.req.json());if(!Z.success)throw new _("Invalid plugin refresh request");let Y=U0(Z.data.projectPath),z=await U1(Y);return J.json({plugins:await V1(Y),errors:z.discovery.errors.map((N)=>({code:N.code??"LOAD_ERROR",error:N.error}))})}),O.get("/catalog",async(J)=>{return U0(J.req.query("projectPath")),J.json(await V2())}),O.get("/policy",async(J)=>{let Z=U0(J.req.query("projectPath")),Y=await t0.getInstance().loadWorkspacePluginSourcePolicy(Z);return J.json({policy:Y,environmentRequiresSha:process.env.BLADE_PLUGIN_REQUIRE_SHA==="1"||process.env.BLADE_PLUGIN_REQUIRE_SHA==="true"})}),O.post("/policy",async(J)=>{let Z=h(K2,await J.req.json());if(!Z.success)throw new _("Invalid plugin source policy request");let Y=U0(Z.data.projectPath),z=await D1(Y,Z.data.policy,Z.data.scope??"global");return J.json({policy:z})}),O.post("/install",async(J)=>{let Z=h(Q2,await J.req.json());if(!Z.success)throw new _("Invalid plugin install request; explicit source trust is required");let Y=U0(Z.data.projectPath),{result:z}=await _1(Y,Z.data.source,{trusted:Z.data.trust,ref:Z.data.ref});return i0(z,"Plugin installation failed"),J.json({name:z.pluginName,version:z.manifest?.version,revision:z.installation?.revision,changed:z.changed,installedDependencies:z.installedDependencies??[]})}),O.post("/marketplaces",async(J)=>{let Z=h(G2,await J.req.json());if(!Z.success)throw new _("Invalid marketplace add request");let Y=U0(Z.data.projectPath),z=await w1(Y,Z.data.source,Z.data.ref);return i0(z,"Marketplace installation failed"),J.json({name:z.marketplace?.name,plugins:z.manifest?.plugins.length??0,revision:z.marketplace?.revision,changed:z.changed})}),O.post("/marketplaces/:name/refresh",async(J)=>{let Z=h(K1,await J.req.json());if(!Z.success)throw new _("Invalid marketplace refresh request");let Y=await L1(U0(Z.data.projectPath),J.req.param("name"));return i0(Y,"Marketplace refresh failed"),J.json({name:Y.marketplace?.name,plugins:Y.manifest?.plugins.length??0,revision:Y.marketplace?.revision,changed:Y.changed})}),O.post("/marketplaces/:name/remove",async(J)=>{let Z=h(K1,await J.req.json());if(!Z.success||Z.data.confirm!==!0)throw new _("Invalid marketplace removal request; explicit confirmation is required");U0(Z.data.projectPath);let Y=await A1(J.req.param("name"),!0);return i0(Y,"Marketplace removal failed"),J.json({name:Y.marketplace?.name,removed:!0})}),O.post("/:name/update",async(J)=>{let Z=h(N2,await J.req.json());if(!Z.success)throw new _("Invalid plugin update request; explicit source trust is required");let Y=U0(Z.data.projectPath),{result:z}=await B1(Y,J.req.param("name"),{trusted:Z.data.trust});return i0(z,"Plugin update failed"),J.json({name:z.pluginName,version:z.manifest?.version,revision:z.installation?.revision,changed:z.changed,updatedDependencies:z.updatedDependencies??[]})}),O.post("/:name/uninstall",async(J)=>{let Z=h(X2,await J.req.json());if(!Z.success)throw new _("Invalid plugin uninstall request; explicit confirmation is required");let Y=U0(Z.data.projectPath),{result:z}=await H1(Y,J.req.param("name"),Z.data.confirm);return i0(z,"Plugin uninstall failed"),J.json({name:z.pluginName,removed:!0})}),O.post("/:name/state",async(J)=>{let Z=h(x2,await J.req.json());if(!Z.success)throw new _("Invalid plugin state request");let Y=U0(Z.data.projectPath),z=J.req.param("name"),X=(await N0(Y)).plugins.get(z);if(!X)throw new v("Plugin",z);if(X.source==="cli")throw new _(`Plugin "${z}" was loaded with --plugin-dir and is invocation-scoped`);let K=await W1(Y,z,Z.data.enabled,Z.data.scope??"local");return J.json(K)}),O};import{Hono as _2}from"hono";import{execFile as F2}from"node:child_process";import W2 from"node:path";var pO="__BLADE_DIRECTORY_PICKER_CANCELLED__",U2=900000;function D2(O,J){return new Promise((Z)=>{F2(O,[...J],{timeout:U2,maxBuffer:65536,windowsHide:!0},(Y,z,N)=>{let X=Y?.code;Z({stdout:z,stderr:N,exitCode:typeof X==="number"?X:Y?1:0,...typeof X==="string"?{errorCode:X}:{}})})})}function cO(O){let J=O.replace(/[\r\n]+$/,"");if(!J||J===pO)return{cancelled:!0};if(!W2.isAbsolute(J))throw Error("The folder picker returned an invalid path");return{cancelled:!1,path:J}}function iO(O){return O.exitCode!==0||Boolean(O.errorCode)}class q1{platform;runCommand;activeSelection=null;constructor(O={}){this.platform=O.platform??process.platform,this.runCommand=O.runCommand??D2}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 "${pO}"`,"end try"].join(`
3
- `),J=await this.runCommand("osascript",["-e",O]);if(iO(J))throw Error("Unable to open the macOS folder picker");return cO(J.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("${pO}")`,"}"].join("; "),J=await this.runCommand("powershell.exe",["-NoProfile","-STA","-Command",O]);if(iO(J))throw Error("Unable to open the Windows folder picker");return cO(J.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 J of O){let Z=await this.runCommand(J.command,J.args);if(Z.errorCode==="ENOENT")continue;if(Z.exitCode===1&&!Z.stdout.trim()&&!Z.stderr.trim())return{cancelled:!0};if(iO(Z))throw Error("Unable to open the Linux folder picker");return cO(Z.stdout)}throw Error("Install zenity or kdialog to use native folder selection")}}var M1=new q1;var B2=$.Object({path:$.String({minLength:1})});function H2(O){if(!O)return!1;if(O==="tauri://localhost"||O==="http://tauri.localhost")return!0;try{let J=new URL(O).hostname;return J==="localhost"||J==="127.0.0.1"||J==="::1"||J==="[::1]"}catch{return!1}}var b1=(O={})=>{let J=new _2,Z=O.pickDirectory??(()=>M1.pick()),Y=O.allowDirectoryPickerRequest??H2;return J.get("/",async(z)=>{return z.json(await BO.list(T()))}),J.post("/",async(z)=>{let N;try{N=await z.req.json()}catch{throw new _("A valid JSON body is required")}let X=h(B2,N);if(!X.success)throw new _("A project path is required");try{let K=await BO.bind(X.data.path,T());return z.json(K,201)}catch(K){throw new _(K instanceof Error?K.message:"Failed to bind project")}}),J.post("/pick",async(z)=>{if(!Y(z.req.header("Origin")))throw new Z0("LOCAL_ACCESS_REQUIRED","Folder selection is only available from this machine",403);try{return z.json(await Z())}catch(N){throw new _(N instanceof Error?N.message:"Failed to select a folder")}}),J.delete("/",async(z)=>{let N=z.req.query("path");if(!N)throw new _("A project path is required");try{let X=await BO.unbind(N);return z.json({success:!0,removed:X})}catch(X){throw new _(X instanceof Error?X.message:"Failed to unbind project")}}),J};import{Hono as w2}from"hono";var R1=p("Service"),k1=()=>{let O=new w2;return O.get("/",async(J)=>{try{let Z=await C1();return J.json(Z)}catch(Z){return R1.error("[ProviderRoutes] Failed to list providers:",Z),J.json([])}}),O.get("/:provider/models",async(J)=>{let Z=J.req.param("provider");try{let Y=await I1(Z);return J.json(Y)}catch(Y){return R1.error("[ProviderRoutes] Failed to list models:",Y),J.json([])}}),O.put("/:provider/credential",async(J)=>{let Z=J.req.param("provider"),Y=await J.req.json();if(!Y.apiKey?.trim())throw new _("apiKey is required");return await f0().setApiKey(Z,Y.apiKey.trim()),J.json({success:!0})}),O.delete("/:provider/credential",async(J)=>{return await f0().clearCredential(J.req.param("provider")),J.json({success:!0})}),O.put("/:provider",async(J)=>{let Z=J.req.param("provider"),Y=o(),z=Y?.modelProviders[Z];if(!Y||!z)throw new v("Model provider",Z);let N=await J.req.json();if(!N.name||!N.baseUrl||!N.wireApi)throw new _("name, baseUrl and wireApi are required");let X="apiKeyEnv"in N?N.apiKeyEnv?.trim():z.apiKeyEnv,K={name:N.name,baseUrl:N.baseUrl,wireApi:N.wireApi,...X?{apiKeyEnv:X}:{}},W=f0(),H=N.apiKey?.trim()?await W.credentials.read(Z):void 0;if(N.apiKey?.trim())await W.setApiKey(Z,N.apiKey.trim());try{return await F0().updateModelProvider(Z,K),J.json({success:!0})}catch(E){if(N.apiKey?.trim())if(H)await W.credentials.modify(Z,async()=>H);else await W.credentials.delete(Z);if(E instanceof Error&&(E.message.includes("modelProviders.")||E.message.includes("built-in provider")))throw new _(E.message);throw E}}),O.delete("/:provider",async(J)=>{let Z=J.req.param("provider");if(!o()?.modelProviders[Z])throw new v("Model provider",Z);let z=J.req.query("removeModels");if(z!==void 0&&z!=="true"&&z!=="false")throw new _("removeModels must be true or false");try{let N=await F0().removeModelProvider(Z,{removeModels:z==="true"});return J.json({success:!0,...N})}catch(N){if(N instanceof Error&&(N.message.includes("still referenced")||N.message.includes("owns the only model")))throw new I(N.message);throw N}}),O.post("/:provider/probe",async(J)=>{let Z=J.req.param("provider"),Y=o();if(!Y?.modelProviders[Z])throw new v("Model provider",Z);let z=await J.req.json().catch(()=>({})),N=Y.models.filter((K)=>K.provider===Z),X=z.modelId?N.find((K)=>K.id===z.modelId):N[0];if(!X)throw new _(z.modelId?"modelId does not reference this provider":"Model provider has no configured model to probe");return J.json(await j1(X,Y))}),O};import*as C0 from"node:fs/promises";import{homedir as h1}from"node:os";import*as D0 from"node:path";import{Hono as L2}from"hono";var P0=p("Service"),f1=D0.join(h1(),".blade","skills"),aO=D0.join(h1(),".blade","skills-config.json");async function m1(){try{let O=await C0.readFile(aO,"utf-8");return JSON.parse(O)}catch{return{disabled:[]}}}async function A2(O){await C0.mkdir(D0.dirname(aO),{recursive:!0}),await C0.writeFile(aO,JSON.stringify(O,null,2))}async function E2(O,J){let Z=await m1();if(J)Z.disabled=Z.disabled.filter((Y)=>Y!==O);else if(!Z.disabled.includes(O))Z.disabled.push(O);await A2(Z)}var j0=null,q2=300000,M2=6;async function b2(){if(j0&&Date.now()-j0.timestamp<q2)return j0.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(P0.warn(`GitHub API returned ${O.status}`),j0)return j0.data;throw Error(`GitHub skills catalog returned ${O.status}`)}let Z=(await O.json()).filter((X)=>X.type==="dir"),Y=Array(Z.length),z=0,N=Math.min(M2,Z.length);return await Promise.all(Array.from({length:N},async()=>{while(z<Z.length){let X=z++,K=Z[X];if(!K)continue;let W=`Official ${K.name} skill`;try{let H=await fetch(`https://raw.githubusercontent.com/anthropics/skills/main/skills/${K.name}/SKILL.md`,{headers:{"User-Agent":"Blade-Skills-Catalog"}});if(H.ok){let R=(await H.text()).match(/^#[^\n]*\n+([^\n#]+)/);if(R)W=R[1].trim().slice(0,100)}}catch{}Y[X]={name:K.name,description:W,tag:"Official",author:"Anthropic"}}})),j0={data:Y,timestamp:Date.now()},Y}catch(O){if(P0.warn("Failed to fetch skills catalog from GitHub:",O),j0)return j0.data;throw O}}var v1=()=>{let O=new L2;return O.get("/",async(J)=>{try{let Z=J.get("directory")||T(),z=(await N0(Z)).skills.getAll(),N=await m1(),X=z.map((K)=>({id:K.name,name:K.name,enabled:!N.disabled.includes(K.name),description:K.description||"",version:K.version||"1.0.0",provider:"Local",location:K.source==="builtin"?"Built-in":K.basePath,removable:K.source==="user"&&D0.dirname(D0.resolve(K.basePath))===D0.resolve(f1),capabilities:["prompts"],allowedTools:K.allowedTools||[]}));return J.json(X)}catch(Z){return P0.error("[SkillsRoutes] Failed to get skills:",Z),J.json({error:Z instanceof Error?Z.message:"Failed to get skills"},500)}}),O.post("/:name/toggle",async(J)=>{try{let Z=J.req.param("name"),Y=await J.req.json();return await E2(Z,Y.enabled),J.json({success:!0,enabled:Y.enabled})}catch(Z){return P0.error("[SkillsRoutes] Failed to toggle skill:",Z),J.json({success:!1,error:Z.message},500)}}),O.delete("/:name",async(J)=>{try{let Z=J.req.param("name"),Y=J.get("directory")||T(),z=(await N0(Y)).skills,N=z.get(Z);if(!N)return J.json({success:!1,error:"Skill not found"},404);let X=D0.resolve(N.basePath),K=D0.resolve(f1);if(N.source!=="user"||D0.dirname(X)!==K)return J.json({success:!1,error:"Only Blade user skills can be uninstalled"},400);return await C0.rm(X,{recursive:!0,force:!0}),await z.refresh(),r0(Y),await s0(Y),J.json({success:!0})}catch(Z){return P0.error("[SkillsRoutes] Failed to uninstall skill:",Z),J.json({success:!1,error:Z.message},500)}}),O.post("/install",async(J)=>{try{let Z=await J.req.json(),Y=S1(),z=J.get("directory")||T(),N=P1({cwd:z}),X=!1;if(Z.source==="catalog"&&Z.name){if(X=await Y.installOfficialSkill(Z.name),!X)return J.json({success:!1,error:"Failed to install skill from catalog"},500)}else if(Z.source==="repo"&&Z.url){if(X=await Y.installFromRepo(Z.url,Z.name),!X)return J.json({success:!1,error:"Failed to install skill from repository. Make sure the repo contains a SKILL.md file."},500)}else if(Z.source==="local"&&Z.path){if(X=await Y.installFromLocal(Z.path,Z.name),!X)return J.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 J.json({success:!1,error:"Invalid install parameters. Required: source with corresponding url/path/name"},400);return await N.refresh(),r0(z),await s0(z),J.json({success:!0})}catch(Z){return P0.error("[SkillsRoutes] Failed to install skill:",Z),J.json({success:!1,error:Z.message},500)}}),O.get("/catalog",async(J)=>{try{let Z=await b2();return J.json(Z)}catch(Z){return P0.error("[SkillsRoutes] Failed to get catalog:",Z),J.json({error:Z instanceof Error?Z.message:"Failed to get skills catalog"},502)}}),O};import{execSync as R2}from"node:child_process";import{readdir as j2}from"node:fs/promises";import HO from"node:path";import C2 from"fast-glob";import{Hono as I2}from"hono";var JO=p("Service"),k2=(O)=>{try{return R2("git rev-parse --abbrev-ref HEAD",{cwd:O,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}},f2=[...p0.map((O)=>`${O}/**`),...p0,...p0.map((O)=>`**/${O}/**`),...p0.map((O)=>`**/${O}`),...oO.map((O)=>`**/${O}`)],S2=new Set(["/theme","/model","/permissions","/mcp","/skills","/exit","/resume","/ide","/login","/logout"]),u1=()=>{let O=new I2;return O.get("/commands",async(J)=>{try{let Z=J.req.query("q")||"",Y=J.get("directory")||T();await N0(Y);let z=T1(Z,Y).filter((N)=>!S2.has(N.command));return J.json(z)}catch(Z){return JO.error("[SuggestionsRoutes] Failed to get command suggestions:",Z),J.json([])}}),O.get("/files",async(J)=>{try{let Z=J.req.query("q")||"",Y=J.get("directory")||T(),z=Math.min(Number(J.req.query("limit"))||100,1000),N=J.req.query("type")==="file",K=(await C2("**/*",{cwd:Y,dot:!1,followSymbolicLinks:!1,onlyFiles:N,markDirectories:!0,unique:!0,ignore:f2})).map((E)=>E.replace(/\\/g,"/"));if(!Z)return J.json(K.slice(0,z));let W=Z.toLowerCase(),H=K.filter((E)=>E.toLowerCase().includes(W)).slice(0,z);return J.json(H)}catch(Z){return JO.error("[SuggestionsRoutes] Failed to get file suggestions:",Z),J.json([])}}),O.get("/files/tree",async(J)=>{try{let Z=J.get("directory")||T(),Y=J.req.query("path")||"",z=Y?HO.join(Z,Y):Z,X=(await j2(z,{withFileTypes:!0})).map((H)=>({name:H.name,path:Y?`${Y}/${H.name}`:H.name,type:H.isDirectory()?"dir":"file"}));X.sort((H,E)=>{if(H.type!==E.type)return H.type==="dir"?-1:1;return H.name.localeCompare(E.name)});let K=new Set(p0),W=X.filter((H)=>{let E=H.name;if(E.startsWith("."))return!1;if(K.has(E))return!1;for(let R of oO)if(E.match(new RegExp(R.replace("*",".*"))))return!1;return!0});return J.json(W)}catch(Z){return JO.error("[SuggestionsRoutes] Failed to get file tree:",Z),J.json([])}}),O.get("/files/content",async(J)=>{try{let Z=J.req.query("path");if(!Z)return J.json({error:"Missing file path"},400);let Y=J.get("directory")||T(),z=HO.resolve(Y,Z),N=HO.relative(Y,z);if(N.startsWith("..")||HO.isAbsolute(N))return J.json({error:"Invalid file path"},400);let X=d1(),K=await X.stat(z);if(!K?.isFile)return J.json({error:"File not found"},404);let W=200000,H=await X.readTextFile(z),E=H.length>W;return J.json({path:Z,content:E?H.slice(0,W):H,truncated:E,size:K.size})}catch(Z){return JO.error("[SuggestionsRoutes] Failed to get file content:",Z),J.json({error:"Failed to read file"},500)}}),O.get("/git-info",async(J)=>{try{let Z=J.get("directory")||T(),Y=k2(Z);return J.json({branch:Y})}catch(Z){return JO.error("[SuggestionsRoutes] Failed to get git info:",Z),J.json({branch:null})}}),O};import{Hono as P2}from"hono";var ZO=p("Service"),g1=(O)=>{let J=new P2;return J.onError((Z,Y)=>{if(Z instanceof Z0)return Y.json(Z.toObject(),Z.statusCode);return ZO.error("[TaskRoutes] Unhandled route error:",Z),Y.json(new a("Failed to dispatch task").toObject(),500)}),J.post("/",async(Z)=>{let Y;try{Y=await Z.req.json()}catch{throw new _("Invalid request body")}let z=h(T$,Y);if(!z.success)throw new _("Invalid task request");if((z.data.attachments??[]).reduce((X,K)=>X+(typeof K.content==="string"?Buffer.byteLength(K.content):0),0)>g0)throw new _("Task attachments exceed the 5 MiB limit");try{let X=await O.dispatchTask({prompt:z.data.prompt,title:z.data.title,sourceProjectPath:z.data.projectPath||Z.get("directory")||T(),isolation:z.data.isolation,permissionMode:z.data.permissionMode,modelId:z.data.modelId,reasoningEffort:z.data.reasoningEffort,serviceTier:z.data.serviceTier,responseVerbosity:z.data.responseVerbosity,communicationStyle:z.data.communicationStyle,attachments:z.data.attachments});return Z.json(CO.parse(X),202)}catch(X){if(X instanceof _||X instanceof I||X instanceof v0)throw X;throw ZO.error("[TaskRoutes] Failed to dispatch task:",X),new a("Failed to dispatch task")}}),J.post("/:sessionId/retry",async(Z)=>{try{let Y=await O.retryTask(Z.req.param("sessionId"),Z.req.query("projectPath"));return Z.json(CO.parse(Y),202)}catch(Y){if(Y instanceof _||Y instanceof v||Y instanceof I||Y instanceof v0)throw Y;throw ZO.error("[TaskRoutes] Failed to retry task:",Y),new a("Failed to retry task")}}),J.get("/:sessionId/diff",async(Z)=>{try{let Y=await O.getTaskDiff(Z.req.param("sessionId"),Z.req.query("projectPath"));return Z.json(S$.parse(Y))}catch(Y){if(Y instanceof _||Y instanceof v||Y instanceof I)throw Y;throw ZO.error("[TaskRoutes] Failed to load task diff:",Y),new a("Failed to load task diff")}}),J.post("/:sessionId/delivery",async(Z)=>{let Y;try{Y=await Z.req.json()}catch{throw new _("Invalid request body")}let z=h(u$,Y);if(!z.success)throw new _("Invalid task delivery request");try{let N=await O.deliverTask(Z.req.param("sessionId"),z.data.action,Z.req.query("projectPath"));return Z.json(S0.parse(N))}catch(N){if(N instanceof _||N instanceof v||N instanceof I)throw N;throw ZO.error("[TaskRoutes] Failed to deliver task:",N),new a("Failed to deliver task")}}),J};import{Hono as h2}from"hono";var I0=p("Service"),a0=new Map,y1=2097152,l1=65536;function c1(){return typeof globalThis.Bun<"u"}async function m2(O,J,Z){if(c1()){let{spawn:N}=await import("bun-pty"),X=N(O,J,{name:"xterm-256color",cwd:Z.cwd,env:Z.env});return{pid:X.pid,write:(K)=>X.write(K),resize:(K,W)=>X.resize(K,W),kill:()=>X.kill(),onData:(K)=>X.onData(K),onExit:(K)=>X.onExit(K)}}let z=(await import("node-pty")).spawn(O,J,{name:"xterm-256color",cwd:Z.cwd,env:Z.env,cols:80,rows:24});return{pid:z.pid,write:(N)=>z.write(N),resize:(N,X)=>z.resize(N,X),kill:()=>z.kill(),onData:(N)=>{z.onData(N)},onExit:(N)=>{z.onExit(N)}}}var sO=void 0,tO;if(c1())try{let{createBunWebSocket:O}=await import("hono/bun"),J=O();tO=J.upgradeWebSocket,sO=J.websocket}catch(O){I0.warn("[Terminal] Failed to initialize Bun WebSocket support:",O)}async function i1(O,J){let Z=`term-${Date.now()}`;I0.info(`[Terminal] New connection: ${Z}, cwd: ${O}`);let Y=process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/zsh",z=Y.endsWith("sh")?["-l"]:[],N=await m2(Y,z,{cwd:O,env:{...process.env,TERM:"xterm-256color",COLORTERM:"truecolor"}}),X={id:Z,process:N,cwd:O,buffer:"",subscribers:new Set};if(a0.set(Z,X),X.subscribers.add(J),N.onData((K)=>{let W=!1;for(let H of X.subscribers)try{H.send(K),W=!0}catch{X.subscribers.delete(H)}if(W)return;if(X.buffer+=K,X.buffer.length>y1)X.buffer=X.buffer.slice(-y1)}),N.onExit(({exitCode:K})=>{I0.info(`[Terminal] Process exited: ${Z}, code: ${K}`);for(let W of X.subscribers)try{W.close()}catch{}a0.delete(Z)}),X.buffer){let K=X.buffer;X.buffer="";for(let W=0;W<K.length;W+=l1)J.send(K.slice(W,W+l1))}return{session:X,cleanup:()=>{if(I0.info(`[Terminal] Connection closed: ${Z}`),X.subscribers.delete(J),X.subscribers.size===0){try{X.process.kill()}catch{}a0.delete(Z)}}}}function p1(O,J){O.on("connection",async(Z,Y)=>{let z=new URL(Y.url||"/",`http://${Y.headers.host}`);if(!z.pathname.endsWith("/terminal/ws")){Z.close();return}let N=z.searchParams.get("cwd")||J()||T();try{let{session:X,cleanup:K}=await i1(N,{send:(W)=>Z.send(W),close:()=>Z.close()});Z.on("message",(W)=>{try{X.process.write(String(W))}catch(H){I0.error("[Terminal] Failed to write to PTY:",H)}}),Z.on("close",K),Z.on("error",K)}catch(X){I0.error("[Terminal] Failed to spawn PTY:",X),Z.close()}})}var a1=()=>{let O=new h2;if(O.get("/status",(J)=>{let Z=Array.from(a0.values()).map((Y)=>({id:Y.id,cwd:Y.cwd}));return J.json({active:Z.length,terminals:Z})}),O.post("/kill/:terminalId",(J)=>{let Z=J.req.param("terminalId"),Y=a0.get(Z);if(Y){try{Y.process.kill()}catch{}for(let z of Y.subscribers)z.close();return a0.delete(Z),J.json({success:!0})}return J.json({success:!1,error:"Terminal not found"},404)}),tO)O.get("/ws",tO((J)=>{let Z=J.req.query("cwd")||J.get("directory")||T(),Y;return{async onOpen(z,N){try{Y=await i1(Z,{send:(X)=>N.send(X),close:()=>N.close()})}catch(X){I0.error("[Terminal] Failed to spawn PTY:",X),N.close()}},onMessage(z){if(!Y)return;try{Y.session.process.write(String(z.data))}catch(N){I0.error("[Terminal] Failed to write to PTY:",N)}},onClose(){Y?.cleanup()}}}));else O.get("/ws",(J)=>{return J.json({message:"WebSocket endpoint - connect via ws:// protocol",hint:"Use WebSocket client to connect to this endpoint"})});return O};import v2 from"node:path";import{Hono as d2}from"hono";var T2=$.Object({projectPath:$.String({minLength:1}),action:j(["trust","revoke"])});function o1(O){if(!v2.isAbsolute(O))throw new _("projectPath must be absolute")}var t1=()=>{let O=new d2;return O.get("/",async(J)=>{let Z=J.req.query("projectPath");if(!Z)throw new _("projectPath query parameter is required");return o1(Z),J.json(await rO.getInstance().getStatus(Z))}),O.post("/",async(J)=>{let Z=h(T2,await J.req.json());if(!Z.success)throw new _("Invalid workspace trust request");let{projectPath:Y,action:z}=Z.data;o1(Y);let N=rO.getInstance(),X=z==="trust"?await N.trust(Y):await N.revoke(Y);return await n1(),J.json({...X,reloadRequired:X.sensitiveSources>0})}),O};var Q0=p("Service"),O$=[],YO,s1=new Map,r1=new Map,s2=new Set([".css",".html",".js",".json",".svg"]),r2=1024;function e2(O,J){if(!O)return 0;let Z=O.split(",").map((Y)=>{let[z,...N]=Y.trim().toLowerCase().split(";"),X=N.find((W)=>W.trim().startsWith("q=")),K=X?Number(X.trim().slice(2)):1;return{name:z,quality:Number.isFinite(K)?Math.max(0,Math.min(1,K)):0}});return Z.find((Y)=>Y.name===J)?.quality??Z.find((Y)=>Y.name==="*")?.quality??0}function O5(O){return["br","gzip"].map((Z)=>({encoding:Z,quality:e2(O,Z)})).filter((Z)=>Z.quality>0).sort((Z,Y)=>Y.quality-Z.quality||(Z.encoding==="br"?-1:1))[0]?.encoding}function $5(O){let J=s1.get(O);if(J)return J;let Z=xO(O);return s1.set(O,Z),Z}function J5(O,J,Z){let Y=`${Z}:${O}`,z=r1.get(Y);if(z)return z;let N=Z==="br"?i2(J,{params:{[a2.BROTLI_PARAM_QUALITY]:5}}):p2(J,{level:6});return r1.set(Y,N),N}function Z5(){let O=y2(c2(import.meta.url)),J=[k0(O,"web"),k0(T(),"dist/web"),k0(T(),"packages/cli/dist/web")];for(let Z of J){let Y=k0(Z,"index.html");if(eO(Y)){if(xO(Y,"utf-8").includes("/assets/"))return Q0.debug(`[Server] Found web dist at: ${Z}`),Z}}return null}function Y5(){let O=new o2;O.onError((Y,z)=>{if(Q0.error("[Server] Request error:",Y),Y instanceof Z0)return z.json(Y.toObject(),Y.statusCode);let N=Y instanceof Error?Y.message:String(Y);return z.json({error:{code:"INTERNAL_ERROR",message:N}},500)}),O.use(async(Y,z)=>{let N=process.env.BLADE_SERVER_PASSWORD;if(!N)return z();let X=Y.req.path;if(X==="/"||X==="/favicon.svg"||X.startsWith("/assets/")||X.endsWith(".html")||X.endsWith(".js")||X.endsWith(".css"))return z();let K=Y.req.header("Authorization");if(!K?.startsWith("Basic "))return Y.header("WWW-Authenticate",'Basic realm="Blade Server"'),Y.json({error:{code:"UNAUTHORIZED",message:"Authentication required"}},401);let W=Buffer.from(K.slice(6),"base64").toString(),[H,E]=W.split(":"),R=process.env.BLADE_SERVER_USERNAME??"blade";if(H!==R||E!==N)return Y.json({error:{code:"UNAUTHORIZED",message:"Invalid credentials"}},401);return z()}),O.use(async(Y,z)=>{let N=Y.req.path==="/health"||Y.req.path==="/global/health"||Y.req.path.startsWith("/assets/");if(!N)Q0.debug(`[Server] ${Y.req.method} ${Y.req.path}`);let X=Date.now();if(await z(),!N){let K=Date.now()-X;Q0.debug(`[Server] ${Y.req.method} ${Y.req.path} - ${Y.res.status} (${K}ms)`)}}),O.use(n2({origin(Y){if(!Y)return;if(Y.startsWith("http://localhost:"))return Y;if(Y.startsWith("http://127.0.0.1:"))return Y;if(Y==="tauri://localhost"||Y==="http://tauri.localhost")return Y;if(O$.includes(Y))return Y;return}})),O.use(async(Y,z)=>{let N=Y.req.query("directory")||Y.req.header("x-blade-directory")||T();try{N=decodeURIComponent(N)}catch{}return Y.set("directory",N),z()});let J=Q1();YO=J.recoverQueuedTasks,O.route("/global",F$()),O.route("/events",K$()),O.route("/sessions",J.app),O.route("/tasks",g1(J)),O.route("/configs",G$()),O.route("/permissions",X1()),O.route("/plugins",E1()),O.route("/hooks",H$()),O.route("/workspace-trust",t1()),O.route("/providers",k1()),O.route("/models",j$()),O.route("/projects",b1()),O.route("/suggestions",u1()),O.route("/terminal",a1()),O.route("/mcp",A$()),O.route("/skills",v1()),O.get("/health",(Y)=>{return Y.json({healthy:!0,version:d0()})});let Z=Z5();if(Z)Q0.info(`[Server] Serving static files from ${Z}`),O.get("/favicon.svg",()=>{let Y=k0(Z,"favicon.svg");if(!eO(Y))return new Response(null,{status:404});return new Response(xO(Y),{headers:{"Content-Type":"image/svg+xml","Cache-Control":"public, max-age=86400"}})}),O.get("/assets/*",(Y)=>{let z=k0(Z,Y.req.path);if(!eO(z))return Y.json({error:{code:"NOT_FOUND",message:`File not found: ${Y.req.path}`}},404);let N=$5(z),X=l2(z).toLowerCase(),W={".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"}[X]||"application/octet-stream",H=s2.has(X)&&N.byteLength>=r2?O5(Y.req.header("Accept-Encoding")):void 0,E=H?J5(z,N,H):N;return new Response(new Uint8Array(E),{headers:{"Content-Type":W,"Content-Length":String(E.byteLength),"Cache-Control":"public, max-age=31536000, immutable",Vary:"Accept-Encoding",...H?{"Content-Encoding":H}:{}}})}),O.get("/",(Y)=>{let z=k0(Z,"index.html"),N=xO(z,"utf-8");return Y.html(N,200,{"Cache-Control":"no-cache"})}),O.get("*",(Y)=>{let z=Y.req.path;if(z.includes("."))return Y.json({error:{code:"NOT_FOUND",message:`File not found: ${z}`}},404);let N=k0(Z,"index.html"),X=xO(N,"utf-8");return Y.html(X,200,{"Cache-Control":"no-cache"})});else Q0.warn('[Server] Web UI not found. Run "cd packages/cli/web && bun run build" to enable web interface.'),O.get("/",(Y)=>{return Y.json({message:"Blade API Server",version:d0(),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("*",(Y)=>{return Y.json({error:{code:"NOT_FOUND",message:`Route not found: ${Y.req.path}`}},404)});return O}function x5(){let O=g2(),J=[];for(let Z of Object.keys(O)){let Y=O[Z];if(!Y)continue;for(let z of Y){if(z.internal||z.family!=="IPv4")continue;if(z.address.startsWith("172."))continue;J.push(z.address)}}return J}function e1(){return typeof globalThis.Bun<"u"}function O4(O,J){let Z=globalThis.Bun,Y=(N)=>{try{return Z.serve({hostname:J.hostname,port:N,fetch:O.fetch,idleTimeout:0,websocket:sO})}catch(X){Q0.error("Failed to start Bun server:",X);return}},z=J.port===0?Y(4096)??Y(0):Y(J.port);if(!z)throw Error(`Failed to start Bun server on port ${J.port}`);return{url:z.url,port:z.port,hostname:z.hostname,stop:async()=>{z.stop(!0)}}}function z5(O,J){return new Promise((Z,Y)=>{let z=u2(async(H,E)=>{let R=new URL(H.url||"/",`http://${H.headers.host}`),C=new Headers;for(let[L,O0]of Object.entries(H.headers))if(O0)if(Array.isArray(O0))for(let m of O0)C.append(L,m);else C.set(L,O0);let t;if(H.method!=="GET"&&H.method!=="HEAD")t=(await new Promise((O0)=>{let m=[];H.on("data",(J0)=>m.push(J0)),H.on("end",()=>O0(Buffer.concat(m)))})).toString();let Y0=new Request(R.toString(),{method:H.method,headers:C,body:t});try{let L=await O.fetch(Y0);if(E.statusCode=L.status,L.headers.forEach((O0,m)=>{E.setHeader(m,O0)}),L.body){let O0=L.body.getReader(),m=async()=>{let{done:J0,value:x0}=await O0.read();if(J0){E.end();return}return E.write(x0),m()};await m()}else{let O0=await L.text();E.end(O0)}}catch(L){Q0.error("[Server] Node request error:",L),E.statusCode=500,E.end(JSON.stringify({error:{code:"INTERNAL_ERROR",message:"Internal server error"}}))}}),N=new t2({noServer:!0}),X=T();p1(N,()=>X),z.on("upgrade",(H,E,R)=>{if(new URL(H.url||"/",`http://${H.headers.host}`).pathname==="/terminal/ws")N.handleUpgrade(H,E,R,(t)=>{N.emit("connection",t,H)});else E.destroy()});let K=(H)=>{return new Promise((E,R)=>{z.once("error",(C)=>{if(C.code==="EADDRINUSE")R(C);else R(C)}),z.listen(H,J.hostname,()=>{let C=z.address();if(C&&typeof C==="object")E(C.port);else E(H)})})};(async()=>{let H;if(J.port===0)try{H=await K(4096)}catch{H=await K(0)}else H=await K(J.port);let E=new URL(`http://${J.hostname==="0.0.0.0"?"localhost":J.hostname}:${H}`);Z({url:E,port:H,hostname:J.hostname,stop:async()=>{return new Promise((R)=>{N.close(()=>{z.close(()=>R())})})}})})().catch(Y)})}var $4;((D6)=>{let O,J;function Z(){if(!J)J=Y5();return J}D6.getApp=Z;function Y(X){O$=X.cors??[];let K=Z();if(e1())O=O4(K,X),Q0.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;return YO?.().catch((H)=>{Q0.warn("[Server] Failed to recover queued tasks:",H)}),{url:W.url,port:W.port,hostname:W.hostname,stop:async()=>{if(O)await O.stop(),O=void 0,J=void 0,YO=void 0,Q0.info("[Server] Blade server stopped")}}}D6.listen=Y;async function z(X){O$=X.cors??[];let K=Z();if(e1())O=O4(K,X),Q0.info(`[Server] Blade server listening on ${O.url} (Bun runtime)`);else O=await z5(K,X),Q0.info(`[Server] Blade server listening on ${O.url} (Node.js runtime)`);let W=O;try{await YO?.()}catch(H){Q0.warn("[Server] Failed to recover queued tasks:",H)}return{url:W.url,port:W.port,hostname:W.hostname,stop:async()=>{if(O)await O.stop(),O=void 0,J=void 0,YO=void 0,Q0.info("[Server] Blade server stopped")}}}D6.listenAsync=z;function N(){return O!==void 0}D6.isRunning=N})($4||={});export{Q5 as a,N5 as b,x5 as c,$4 as d};
@@ -1,22 +0,0 @@
1
- import{q as o}from"./chunk-xv0maezy.js";import{E as M,G as k,H as S,J as C,X as f,Y as u,Z as g,_ as c,t as K}from"./chunk-62881c2s.js";import{ia as n}from"./chunk-s645azsm.js";import{Aa as y,Da as I}from"./chunk-1m5r6mp2.js";import{Va as A}from"./chunk-jza1rsan.js";import{ib as E,jb as T,nb as V,qb as L}from"./chunk-417wefq7.js";import"./chunk-an96c54z.js";import"./chunk-drrdzmaa.js";import"./chunk-sanhjqpd.js";import"./chunk-g6h6h8xr.js";import{wc as i}from"./chunk-fvhc1yj8.js";import"./chunk-dqvcgwhe.js";import"./chunk-ea7wsges.js";import{Fc as r}from"./chunk-gxmrakrk.js";import"./chunk-yc53wz4r.js";import"./chunk-am8dtvff.js";import{ad as a}from"./chunk-35yktzm1.js";import"./chunk-63ysxybd.js";import"./chunk-vpj0sv73.js";import"./chunk-qm11hjd3.js";import{nd as R}from"./chunk-qda309d9.js";import"./chunk-rh7v814a.js";import"./chunk-tq52pbde.js";import{le as N,me as x,ne as P}from"./chunk-79s052sw.js";import{re as m}from"./chunk-epj56s0n.js";import"./chunk-gxzbv67r.js";import{Ae as l,xe as d}from"./chunk-bexgcc2d.js";import"./chunk-1vx4sf1y.js";import"./chunk-z906d5tb.js";import"./chunk-948qe2pp.js";import"./chunk-0n97186m.js";import"./chunk-9ffr01c3.js";import{Readable as zJ,Writable as WJ}from"node:stream";import*as O from"@agentclientprotocol/sdk";import{PROTOCOL_VERSION as $J}from"@agentclientprotocol/sdk";import p from"node:path";import{nanoid as q}from"nanoid";var X=R("Agent");function h(J){if(!J)return{};return Object.fromEntries(J.map((Z)=>[Z.name,Z.value]))}function e(J){if("command"in J)return{type:"stdio",command:J.command,args:J.args,env:h(J.env)};if("url"in J)return{type:J.type,url:J.url,headers:h("headers"in J?J.headers:void 0)};return null}function JJ(J){let Z={};for(let Q of J){let $=e(Q);if($)Z[Q.name]=$}return Z}function v(J){if(typeof J==="string")return J?[{type:"text",text:J}]:[];return J.flatMap((Z)=>{if(Z.type==="text")return Z.text?[{type:"text",text:Z.text}]:[];let Q=Z.image_url.url,$=/^data:([^;,]+);base64,(.+)$/s.exec(Q);if(!$)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:$[1]??"image/png",data:$[2]??""}]})}function QJ(J){let Z=T(J.metadata);return Z?[{type:"text",text:E(Z)}]:v(J.content)}function ZJ(J){return[`Status: ${J.status}`,`Exit code: ${J.exitCode??"null"}`,`Duration: ${(J.durationMs/1000).toFixed(3)} seconds`].join(`
2
- `)}class _{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingUserShell=null;pendingResumeRequested=!1;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;messages;mode;constructor(J,Z,Q,$,D={}){this.id=J;this.cwd=Z;this.connection=Q;this.clientCapabilities=$;this.options=D;this.messages=[...D.initialMessages??[]],this.mode=this.mapPermissionModeToMode(D.permissionMode)}mapPermissionModeToMode(J){switch(J){case"yolo":return"yolo";case"autoEdit":return"auto-edit";case"plan":return"plan";case"default":default:return"default"}}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return C.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){X.debug(`[AcpSession ${this.id}] Initializing...`),await L.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),K.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd),X.debug(`[AcpSession ${this.id}] ACP service context initialized`);let J=this.options.mcpServers?JJ(this.options.mcpServers):void 0,Z=K.getInstance().getTerminalService(this.id);this.runtime=await M.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($,D)=>{let Y=await Z.execute($,{cwd:D.cwd,env:D.env,timeout:D.timeoutMs,signal:D.signal,allowLocalFallback:!1,onOutput:(z)=>D.onOutput?.("stdout",z)});return{exitCode:Y.exitCode,stdout:Y.stdout,stderr:Y.stderr,...Y.error?{error:Y.error}:{},timedOut:Y.error==="Command timed out",aborted:Y.error==="Command was aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),this.agent=await this.createAgent(),await u(this.cwd),X.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=I.subscribe(($)=>{if($.sessionId!==this.id||$.projectPath!==this.cwd)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 Q=await this.runtime.getGoal();if(this.runtime.getPendingSteeringCount()>0||Q?.status==="active")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 Z=J.role==="user"?"user_message_chunk":J.role==="assistant"?"agent_message_chunk":void 0;if(!Z)continue;for(let Q of QJ(J)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:Z,content:Q}))return}}if(this.pendingResumeRequested)this.schedulePendingResume()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);X.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendAvailableCommands()},500)}async handleSlashCommand(J,Z){try{X.debug(`[AcpSession ${this.id}] Executing slash command: ${J}`);let Q={cwd:this.cwd,surface:"acp",workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.messages],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 W=await this.runtime.rewindSession(z);return this.messages=[...W.messages],await this.agent?.destroy(),this.agent=await this.createAgent(),W}},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,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let H=!1,F,j=(B)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:B.id,status:B.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:B.result?.message||B.result?.error||`Subagent ${B.status}`}}]})},G=this.runtime.resumeSubagent({agentId:z,prompt:W,onCompleted:(B)=>{if(H)j(B);else F=B}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:G.session.id,status:"in_progress",title:`Resuming ${G.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${G.source.id} at depth ${G.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),H=!0,F)j(F);return G}},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,W,H)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(z,W,H)},complete:async(z,W,H)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(z,W,H)},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,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(z,W)},getLogs:async(z,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(z,W)},setLoggingLevel:async(z,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(z,W)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},signal:Z,acp:{sendMessage:(z)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:z}})},sendToolStart:(z,W,H)=>{let F=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,j=this.mapToolKind(H);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:F,status:"in_progress",title:`${z}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(W,null,2)}}],kind:j})},sendToolResult:(z,W)=>{if(W.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W.summary}})}}},$=await g(J,Q),D=$.data?.action;if(D==="start_goal"||D==="resume_goal")this.schedulePendingResume();if(D==="rewind_session"&&Array.isArray($.data?.messages))this.messages=[...$.data.messages];if(($.message==="compact_completed"||$.message==="compact_fallback")&&$.data?.compactedMessages)this.messages=[...$.data.compactedMessages];let Y=$.content||$.message;if(Y)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Y}});if($.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${$.error}`}});return{stopReason:$.success?"end_turn":"cancelled"}}catch(Q){return X.error(`[AcpSession ${this.id}] Slash command error:`,Q),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${Q instanceof Error?Q.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async sendAvailableCommands(){try{let J=c(this.cwd),Z=["model","permissions","theme","config","exit","ide"],$=J.filter((D)=>!Z.includes(D.name)).map((D)=>{let Y;if(D.usage){let z=D.usage.replace(/^\/\w+\s*/,"").trim();if(z)Y=z}if(D.aliases?.length){let z=`Aliases: ${D.aliases.join(", ")}`;Y=Y?`${Y} | ${z}`:z}return{name:D.name,description:D.description,input:Y?{hint:Y}:void 0}});X.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify($.map((D)=>D.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:$}),X.info(`[AcpSession ${this.id}] Sent ${$.length} available commands`)}catch(J){X.error(`[AcpSession ${this.id}] Failed to send available commands:`,J)}}async prompt(J,Z={}){if(K.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let Q=this.resolvePrompt(J.prompt),$=Q.content,D=Q.displayText;if(D.trimStart().startsWith("!"))return this.handleUserShellCommand(D);if(this.pendingPrompt){if(/^\/goal(?:\s|$)/i.test(D.trim()))return this.handleSlashCommand(D,this.pendingPrompt.signal);let z=await this.runtime.enqueueSteering($,{allowBeforeTurn:!0});if(!z.accepted)throw Error(z.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(X.debug(`[AcpSession ${this.id}] Queued steering for active turn (${z.queued})`),z.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let Y=new AbortController;this.pendingPrompt=Y;try{if(X.debug(`[AcpSession ${this.id}] Received prompt: ${D.slice(0,100)}...`),f(D))return await this.handleSlashCommand(D,Y.signal);let z={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.messages],signal:Y.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async(W)=>{this.mode=this.mapPermissionModeToMode(W),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async(W)=>{return this.requestPermission(W)}}};if(await y(this.agent.chatStream($,z,{pendingInputOnly:Z.pendingInputOnly,goalContinuationOnly:Z.goalContinuationOnly}),async(W)=>{switch(W.kind){case"content_delta":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:W.delta}});break;case"tool_start":{let H=W.toolCall,F=H.function.name,j=this.mapToolKind(W.toolKind),G=`Executing ${F}`;if(F==="Task"&&"function"in H)try{let B=JSON.parse(H.function.arguments),U=B.resume_from??B.resume;if(typeof U==="string")G=`Resuming ${String(B.subagent_type||"subagent")} from ${U}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:H.id,status:"in_progress",title:G,content:[],kind:j});break}case"tool_progress":{let H=W.toolCall;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:H.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:W.update.message}}]});break}case"tool_result":{let{toolCall:H,result:F}=W,j=[],G=F.metadata;if(G?.kind==="patch"&&Array.isArray(G.changes))for(let U of G.changes){if(!U||typeof U!=="object"||!("path"in U)||typeof U.path!=="string")continue;j.push({type:"diff",path:U.path,oldText:"oldContent"in U&&typeof U.oldContent==="string"?U.oldContent:null,newText:"newContent"in U&&typeof U.newContent==="string"?U.newContent:null})}else if(G?.kind==="edit"&&typeof G.file_path==="string"&&typeof G.oldContent==="string"&&(typeof G.newContent==="string"||G.newContent===void 0))j.push({type:"diff",path:G.file_path,oldText:G.oldContent,newText:G.newContent??null});else{let U=H.function.name,t=S(k(U,F));j.push({type:"content",content:{type:"text",text:t}})}if(H.function.name==="Task"&&(G?.verificationVerdict==="pass"||G?.verificationVerdict==="fail"||G?.verificationVerdict==="partial"))j.unshift({type:"content",content:{type:"text",text:`Verification result: ${G.verificationVerdict.toUpperCase()}`}});let B=F.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:H.id,status:B,content:j});break}case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${W.revision} (${W.serverName}): +${W.added.length} -${W.removed.length} ~${W.updated.length}
3
- `}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${W.contentKind} r${W.revision} (${W.serverName}): +${W.added.length} -${W.removed.length} ~${W.updated.length}
4
- `}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${W.revision} (${W.serverName}): ${W.uri}
5
- `}});break;case"mcp_connection_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP connection r${W.revision} (${W.serverName}): ${W.phase} ${W.attempt}/${W.maxAttempts}
6
- `}});break;case"mcp_log":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP log r${W.revision} (${W.serverName}) ${W.level}${W.logger?` logger=${W.logger}`:""}: ${W.message}
7
- `}});break;case"mcp_instructions_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP instructions r${W.revision} (${W.serverName}): ${W.action}${W.detailsOmitted?" details-omitted":""}
8
- `}});break;case"mcp_task_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP task r${W.revision} ${W.taskId} (${W.serverName}/${W.toolName}): ${W.status}${W.hasResult?" result-available":""}
9
- `}});break;case"project_rules_loaded":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Project rules loaded: ${W.files.length}${W.blockedWrite?" (write retry required)":""}
10
- `}});break;case"task_update":this.sendPlanUpdate(W.tasks);break;case"steering_applied":break;case"follow_up_started":for(let H of W.messages){if(!H.recovered||H.persisted)continue;for(let F of v(H.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:F})}if(W.recovered>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${W.recovered} queued instruction${W.recovered===1?"":"s"} recovered after restart]
11
- `}});break;case"goal_updated":if(W.goal&&W.goal.status!=="active")this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Goal ${W.goal.status}: ${W.goal.objective}]
12
- `}});break;case"goal_continuation_started":break;default:break}}),this.messages=[...z.messages],Y.signal.aborted)return{stopReason:"cancelled"};return{stopReason:"end_turn"}}catch(z){if(Y.signal.aborted||z instanceof Error&&z.name==="AbortError")return{stopReason:"cancelled"};throw X.error(`[AcpSession ${this.id}] Prompt error:`,z),z}finally{if(this.pendingPrompt===Y){if(this.pendingPrompt=null,!this.destroyed&&this.pendingResumeRequested)this.schedulePendingResume()}}}async handleUserShellCommand(J){if(!this.runtime)throw Error("Session runtime is unavailable");if(this.pendingUserShell)throw Error("A user shell command is already running");let Z=J.trimStart().slice(1).trim();if(!Z)throw Error("User shell command cannot be empty");let Q=new AbortController;this.pendingUserShell=Q;let $,D="";try{let Y=await this.runtime.executeUserShellCommand(Z,{signal:Q.signal,onEvent:async(z)=>{if($=z.executionId,z.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:z.executionId,status:"in_progress",title:`! ${z.command}`,content:[],kind:"execute"});return}if(z.type==="output"){D+=z.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:z.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:z.chunk}}]});return}let W=E(z.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:z.executionId,status:z.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:D?ZJ(z.record):W}}]})}});if(this.messages.push({role:"user",content:Y.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify(Y.record))}}),Y.delivery==="next_turn")this.schedulePendingResume();return{stopReason:Y.record.status==="aborted"?"cancelled":"end_turn"}}catch(Y){if($)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:$,status:"failed",content:[{type:"content",content:{type:"text",text:Y instanceof Error?Y.message:String(Y)}}]});if(Q.signal.aborted)return{stopReason:"cancelled"};throw Y}finally{if(this.pendingUserShell===Q)this.pendingUserShell=null}}schedulePendingResume(){if(this.destroyed||this.connection.signal.aborted)return;this.pendingResumeRequested=!0,queueMicrotask(()=>{this.resumePendingIfIdle()})}async resumePendingIfIdle(){if(this.destroyed||this.connection.signal.aborted)return;if(this.pendingPrompt||this.pendingUserShell||!this.runtime||!this.agent)return;let J=this.runtime.getPendingSteeringCount()>0,Q=(J?null:await this.runtime.getGoal())?.status==="active";if(!J&&!Q){this.pendingResumeRequested=!1;return}this.pendingResumeRequested=!1,await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:J,goalContinuationOnly:Q}).catch(($)=>{X.error(`[AcpSession ${this.id}] Failed to resume pending input:`,$)})}cancel(){X.info(`[AcpSession ${this.id}] Cancel requested`),this.pendingResumeRequested=!1;let J=!1;if(this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,J=!0;if(this.pendingUserShell)this.pendingUserShell.abort(),this.pendingUserShell=null,J=!0;if(!J)X.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(J){let Q=["default","auto-edit","yolo","plan"].includes(J)?J:"default",$=this.mapModeIdToPermissionMode(Q);await L.setSessionPermissionMode(this.id,this.cwd,$),this.mode=Q,X.info(`[AcpSession ${this.id}] Mode set to: ${this.mode}`),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})}mapModeToPermissionMode(){return this.mapModeIdToPermissionMode(this.mode)}mapModeIdToPermissionMode(J){switch(J){case"yolo":return"yolo";case"auto-edit":return"autoEdit";case"plan":return"plan";case"default":default:return"default"}}shouldAutoApprove(J){switch(this.mode){case"yolo":return!0;case"auto-edit":return J==="readonly"||J==="write";case"plan":return J==="readonly";case"default":default:return!1}}async setModel(J){if(X.info(`[AcpSession ${this.id}] Model set to: ${J}`),this.pendingPrompt)throw Error("Cannot switch models while a prompt is active");if(!this.agent)throw Error("Session not initialized");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getCurrentModelId();await this.agent.switchModel(J);try{try{await L.updateSessionMetadata(this.id,this.cwd,{selectedModelId:J})}catch(Q){if(!(Q instanceof V)&&Q.code!=="ENOENT")throw Q;await L.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:J})}}catch(Q){if(Z&&Z!==J)await this.agent.switchModel(Z).catch(($)=>{X.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,$)});throw Q}}getCurrentModelId(){return this.runtime?.getCurrentModelId()}async setReasoningEffort(J){if(this.pendingPrompt)throw Error("Cannot switch reasoning effort while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getReasoningConfiguration();try{this.runtime.resolveReasoningConfiguration(J)}catch(Q){throw Error(Q instanceof Error?Q.message:"Invalid reasoning effort")}if(Z.selection===J)return;await this.runtime.refresh({reasoningEffort:J});try{try{await L.updateSessionMetadata(this.id,this.cwd,{reasoningEffort:J})}catch(Q){if(!(Q instanceof V)&&Q.code!=="ENOENT")throw Q;await L.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),reasoningEffort:J})}}catch(Q){throw await this.runtime.refresh({reasoningEffort:Z.selection}),Q}}async setServiceTier(J){if(this.pendingPrompt)throw Error("Cannot switch service tier while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getServiceTierConfiguration();try{this.runtime.resolveServiceTierConfiguration(J)}catch(Q){throw Error(Q instanceof Error?Q.message:"Invalid service tier")}if(Z.selection===J)return;await this.runtime.refresh({serviceTier:J});try{try{await L.updateSessionMetadata(this.id,this.cwd,{serviceTier:J})}catch(Q){if(!(Q instanceof V)&&Q.code!=="ENOENT")throw Q;await L.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),serviceTier:J})}}catch(Q){throw await this.runtime.refresh({serviceTier:Z.selection}),Q}}async setResponseVerbosity(J){if(this.pendingPrompt)throw Error("Cannot switch response verbosity while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getResponseVerbosityConfiguration();try{this.runtime.resolveResponseVerbosityConfiguration(J)}catch(Q){throw Error(Q instanceof Error?Q.message:"Invalid response verbosity")}if(Z.selection===J)return;await this.runtime.refresh({responseVerbosity:J});try{try{await L.updateSessionMetadata(this.id,this.cwd,{responseVerbosity:J})}catch(Q){if(!(Q instanceof V)&&Q.code!=="ENOENT")throw Q;await L.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),responseVerbosity:J})}}catch(Q){throw await this.runtime.refresh({responseVerbosity:Z.selection}),Q}}async setCommunicationStyle(J){if(this.pendingPrompt)throw Error("Cannot switch communication style while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getCommunicationStyleConfiguration(),Q=this.runtime.resolveCommunicationStyleConfiguration(J);if(Q.source!=="built-in"&&!Q.contentSha256)throw Error("Custom communication style has no provenance");if(Z.selection===J)return;await this.runtime.refresh({communicationStyle:J});try{try{await L.updateSessionMetadata(this.id,this.cwd,{communicationStyle:J,communicationStyleDigest:Q.source==="built-in"?null:Q.contentSha256})}catch($){if(!($ instanceof V)&&$.code!=="ENOENT")throw $;await L.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:J,...Q.source!=="built-in"&&Q.contentSha256?{communicationStyleDigest:Q.contentSha256}:{}})}}catch($){throw await this.runtime.refresh({communicationStyle:Z.selection}),$}}getModelConfiguration(){if(!this.runtime)return;let J=this.runtime.getConfig();return{currentModelId:this.runtime.getCurrentModelId()??J.currentModelId,models:J.models.map((Z)=>structuredClone(Z)),modelProviders:structuredClone(J.modelProviders),reasoning:this.runtime.getReasoningConfiguration(),serviceTier:this.runtime.getServiceTierConfiguration(),responseVerbosity:this.runtime.getResponseVerbosityConfiguration(),communicationStyle:this.runtime.getCommunicationStyleConfiguration()}}getMode(){return this.mode}async destroy(){if(this.destroyed)return;if(this.destroyed=!0,this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let J=this.agent,Z=this.runtime;this.agent=null,this.runtime=null;let Q,$=async(D)=>{try{await D()}catch(Y){Q??=Y}};if(await $(()=>this.cancel()),J)await $(()=>J.destroy());if(Z)await $(()=>Z.dispose());if(await $(()=>K.destroySession(this.id)),X.debug(`[AcpSession ${this.id}] Destroyed`),Q!==void 0)throw Q}resolvePrompt(J){let Z=[],Q=[],$=0,D=0,Y=0,z=(H)=>{if(Q.length>0)Q.push({type:"text",text:`
13
- `}),Y+=1;if(Q.push(H),H.type==="text")Y+=H.text.length};for(let H of J)if(H.type==="text")Z.push(H.text),z({type:"text",text:H.text});else if(H.type==="image"){let F=`data:${H.mimeType};base64,${H.data}`;$+=1,D+=F.length,Z.push(`[Image: ${H.mimeType}]`),z({type:"image_url",image_url:{url:F}})}else if(H.type==="resource"){let F=H.resource;if("text"in F){let j=`<file path="${F.uri}">
14
- ${F.text}
15
- </file>`;Z.push(j),z({type:"text",text:j})}}else if(H.type==="resource_link"){let F=`[Resource: ${H.uri}]`;Z.push(F),z({type:"text",text:F})}if($>N)throw Error(`ACP prompt contains more than ${N} images`);if(D>x)throw Error("ACP prompt images exceed the 5 MiB limit");if(Y>P)throw Error(`ACP prompt text exceeds ${P} characters`);let W=Z.join(`
16
- `);return{content:$>0?Q:W,displayText:W}}canSendUpdates(){return!this.destroyed&&!this.connection.signal.aborted}async sendUpdateAndWait(J){if(!this.canSendUpdates())return!1;return await this.connection.sessionUpdate({sessionId:this.id,update:J}),this.canSendUpdates()}sendUpdate(J){if(!this.canSendUpdates())return;let Z={sessionId:this.id,update:J};this.connection.sessionUpdate(Z).catch((Q)=>{X.warn(`[AcpSession ${this.id}] Failed to send update:`,Q)})}sendPlanUpdate(J){let Z=J.map((Q)=>({content:Q.subject,priority:Q.priority,status:Q.status}));X.debug(`[AcpSession ${this.id}] Sending plan update with ${Z.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:Z})}async requestPermission(J){let Z=this.pendingPrompt?.signal;if(J.type==="askUserQuestion")return this.requestUserQuestions(J,Z);if(J.type==="mcpElicitation")return this.requestMcpElicitation(J,Z);let Q=J.kind?.toLowerCase()||"execute";if(J.type!=="mcpSampling"&&this.shouldAutoApprove(Q))return X.debug(`[AcpSession ${this.id}] Auto-approving ${Q} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(Q==="write"||Q==="execute"))return X.debug(`[AcpSession ${this.id}] Rejecting ${Q} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};try{let $=q(),D=[];if(J.message)D.push({type:"content",content:{type:"text",text:J.message}});if(J.details)D.push({type:"content",content:{type:"text",text:J.details}});if(J.risks&&J.risks.length>0)D.push({type:"content",content:{type:"text",text:`Risks:
17
- - ${J.risks.join(`
18
- - `)}`}});let Y=this.mapToolKind(Q),z={sessionId:this.id,options:J.type==="mcpSampling"?[{optionId:"allow_once",name:"Allow this sampling request",kind:"allow_once"},{optionId:"reject_once",name:"Deny",kind:"reject_once"}]:[{optionId:"allow_once",name:"Allow once",kind:"allow_once"},{optionId:"allow_always",name:"Always allow",kind:"allow_always"},{optionId:"reject_once",name:"Deny once",kind:"reject_once"},{optionId:"reject_always",name:"Always deny",kind:"reject_always"}],toolCall:{toolCallId:$,status:"pending",title:J.title||"Permission Required",content:D,kind:Y}},W=await this.waitForClientInteraction(this.connection.requestPermission(z),Z);if(!W)return{approved:!1,reason:A};let H=W.outcome;if(H.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let F=H.optionId;if(F==="allow_always")return{approved:!0,scope:"project"};if(F==="reject_always")return{approved:!1,scope:"project",reason:"User permanently denied the permission request"};let j=F==="allow_once";return{approved:j,scope:"once",reason:j?void 0:"User denied the operation"}}catch($){return X.warn(`[AcpSession ${this.id}] Permission request failed:`,$),{approved:!1,reason:"Permission request failed"}}}async requestUserQuestions(J,Z){let Q=J.questions??[];if(Q.length===0)return{approved:!1,reason:"No structured questions were provided"};if(Q.some((D)=>D.multiSelect))return{approved:!1,reason:"ACP does not support multi-select question responses"};let $={};try{for(let[D,Y]of Q.entries()){let z=Y.options.map((j,G)=>`answer:${D}:${G}`),W=`answer:${D}:cancel`,H=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...Y.options.map((j,G)=>({optionId:z[G],name:j.label,kind:"allow_once"})),{optionId:W,name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:q(),status:"pending",title:Y.header,kind:"think",content:[{type:"content",content:{type:"text",text:[Y.question,...Y.options.map((j)=>`${j.label}: ${j.description}`)].join(`
19
- `)}}]}}),Z);if(!H)return{approved:!1,reason:A};if(H.outcome.outcome!=="selected")return{approved:!1,reason:"User cancelled the question prompt"};let F=z.indexOf(H.outcome.optionId);if(F<0)return{approved:!1,reason:"User cancelled the question prompt"};$[Y.header]=Y.options[F].label}return{approved:!0,answers:$}}catch(D){return X.warn(`[AcpSession ${this.id}] Question request failed:`,D),{approved:!1,reason:"Question request failed"}}}async requestMcpElicitation(J,Z){let Q=J.mcpElicitation;if(!Q)return{approved:!1,reason:"MCP elicitation details are missing",elicitation:{action:"cancel"}};try{if(Q.mode==="url"){let D=await this.requestElicitationChoice("MCP external authorization",[Q.message,`Server: ${Q.serverName}`,`Domain: ${Q.domain??"unknown"}`,`URL: ${Q.url??""}`,"Open this URL yourself only if you trust the MCP server."].join(`
20
- `),[{id:"accept",label:"I will open this URL"},{id:"decline",label:"Decline"}],Z);if(D==="accept")return{approved:!0,elicitation:{action:"accept"}};return{approved:!1,reason:D==="decline"?"User declined URL":"User cancelled",elicitation:{action:D==="decline"?"decline":"cancel"}}}let $=Object.create(null);for(let D of Q.fields??[]){let Y=await this.collectAcpElicitationField(D,Z);if(Y.cancelled)return{approved:!1,reason:Y.reason,elicitation:{action:"cancel"}};if(Y.value!==void 0)$[D.name]=Y.value}return{approved:!0,elicitation:{action:"accept",content:$}}}catch($){return X.warn(`[AcpSession ${this.id}] MCP elicitation failed:`,$),{approved:!1,reason:"MCP elicitation failed",elicitation:{action:"cancel"}}}}async collectAcpElicitationField(J,Z){if(J.type==="select"||J.type==="boolean"){let Q=J.type==="boolean"?[{id:"true",label:"Yes",value:!0},{id:"false",label:"No",value:!1}]:(J.options??[]).map((Y,z)=>({id:`option:${z}`,label:Y.label,value:Y.value})),$=await this.requestElicitationChoice(J.title,[J.description,J.required?"Required":"Optional"].filter(Boolean).join(`
21
- `),[...Q.map((Y)=>({id:Y.id,label:Y.label})),...!J.required?[{id:"skip",label:"Skip"}]:[]],Z);if($==="skip")return{cancelled:!1};let D=Q.find((Y)=>Y.id===$);if(!D)return{cancelled:!0,reason:"User cancelled MCP elicitation"};return{cancelled:!1,value:D.value}}if(J.defaultValue!==void 0){let Q=await this.requestElicitationChoice(J.title,[J.description,`ACP cannot collect ${J.type} input. Use the server default: ${String(J.defaultValue)}?`].filter(Boolean).join(`
22
- `),[{id:"default",label:"Use default"},...!J.required?[{id:"skip",label:"Skip"}]:[]],Z);if(Q==="default")return{cancelled:!1,value:J.defaultValue};if(Q==="skip")return{cancelled:!1};return{cancelled:!0,reason:"User cancelled MCP elicitation"}}if(!J.required)return{cancelled:!1};return{cancelled:!0,reason:`ACP cannot collect required ${J.type} field "${J.name}"`}}async requestElicitationChoice(J,Z,Q,$){let D=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...Q.map((Y)=>({optionId:Y.id,name:Y.label,kind:"allow_once"})),{optionId:"cancel",name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:q(),status:"pending",title:J,kind:"think",content:[{type:"content",content:{type:"text",text:Z}}]}}),$);return D?.outcome.outcome==="selected"?D.outcome.optionId:void 0}async waitForClientInteraction(J,Z){if(!Z)return J;if(Z.aborted)return;return new Promise((Q,$)=>{let D=!1,Y=(W)=>{if(D)return;D=!0,Z.removeEventListener("abort",z),W()},z=()=>Y(()=>Q(void 0));if(Z.addEventListener("abort",z,{once:!0}),Z.aborted)z();J.then((W)=>Y(()=>Q(W)),(W)=>Y(()=>$(W)))})}mapToolKind(J){return{readonly:"read",write:"edit",execute:"execute",read:"read",edit:"edit",delete:"delete",move:"move",search:"search",think:"think",fetch:"fetch"}[J||""]||"other"}}var w=R("Agent");class b{connection;sessions=new Map;sessionLoadQueues=new Map;clientCapabilities;destroyed=!1;constructor(J){this.connection=J}async initialize(J){return w.info("[BladeAgent] Initializing ACP connection"),w.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(J.clientCapabilities)}`),this.clientCapabilities=J.clientCapabilities,{protocolVersion:$J,agentCapabilities:{loadSession:!0,sessionCapabilities:{list:{},fork:{}},promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0}}}}async authenticate(J){return}async newSession(J){this.assertNotDestroyed();let Z=i("acp"),Q=J.cwd||m(),$=J._meta?.["blade/taskIsolation"],D=$==="local"||$==="worktree"?$:void 0,Y=J._meta?.["blade/taskPrompt"],z=D?await o.createSessionTask({sessionId:Z,prompt:typeof Y==="string"&&Y.trim()?Y:"ACP task session",sourceProjectPath:Q,isolation:D}):void 0,W=z?.metadata.projectPath??Q;w.info(`[BladeAgent] Creating new session: ${Z}`),w.debug(`[BladeAgent] Session cwd: ${W}`);let H=new _(Z,W,this.connection,this.clientCapabilities,{mcpServers:J.mcpServers,...z?.taskWorktree?{taskWorktree:z.taskWorktree}:{},...z?.metadata.taskIsolation?{taskIsolation:z.metadata.taskIsolation}:{}});try{await H.initialize(),this.assertNotDestroyed()}catch(F){throw await H.destroy().catch(()=>{return}),F}return this.sessions.set(Z,H),w.info(`[BladeAgent] Session ${Z} created, scheduling available commands update`),H.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Z,z?.metadata,H.getModelConfiguration())}async listSessions(J){if(J.cwd!=null&&!p.isAbsolute(J.cwd))throw Error("ACP session list cwd must be absolute");let Z=await L.listSessionPage({cwd:J.cwd??void 0,cursor:J.cursor??void 0,limit:50,includeSubagents:!1});return{sessions:Z.sessions.map((Q)=>({sessionId:Q.sessionId,cwd:Q.projectPath,title:Q.title??null,updatedAt:Q.lastMessageTime,_meta:{"blade/taskStatus":Q.taskStatus,...Q.taskStatusReason?{"blade/taskStatusReason":Q.taskStatusReason}:{},...Q.taskFailure?{"blade/taskFailure":Q.taskFailure}:{},...Q.taskStartedAt?{"blade/taskStartedAt":Q.taskStartedAt}:{},...Q.taskCompletedAt?{"blade/taskCompletedAt":Q.taskCompletedAt}:{},...Q.taskModelId?{"blade/taskModelId":Q.taskModelId}:{},...Q.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...Q.taskRetriedFrom?{"blade/taskRetriedFrom":Q.taskRetriedFrom}:{},...Q.taskDelivery?{"blade/taskDelivery":Q.taskDelivery}:{},...Q.taskIsolation?{"blade/taskIsolation":Q.taskIsolation}:{},...Q.taskSourceProjectPath?{"blade/taskSourceProjectPath":Q.taskSourceProjectPath}:{},...Q.taskWorktreeBranch?{"blade/taskWorktreeBranch":Q.taskWorktreeBranch}:{},...Q.taskBaseCommit?{"blade/taskBaseCommit":Q.taskBaseCommit}:{},...Q.taskDiffStat?{"blade/taskDiffStat":Q.taskDiffStat}:{},...Q.taskQueuePosition?{"blade/taskQueuePosition":Q.taskQueuePosition}:{},...Q.taskQueueDepth!==void 0?{"blade/taskQueueDepth":Q.taskQueueDepth}:{},...Q.taskConcurrencyLimit!==void 0?{"blade/taskConcurrencyLimit":Q.taskConcurrencyLimit}:{}}})),nextCursor:Z.nextCursor}}async unstable_forkSession(J){if(this.assertNotDestroyed(),!p.isAbsolute(J.cwd))throw Error("ACP session fork cwd must be absolute");let Z=await L.forkSession(J.sessionId,{sourceProjectPath:J.cwd,targetProjectPath:J.cwd});this.assertNotDestroyed();let Q=new _(Z.sessionId,J.cwd,this.connection,this.clientCapabilities,{initialMessages:Z.messages,permissionMode:Z.metadata.permissionMode,mcpServers:J.mcpServers});try{await Q.initialize(),this.assertNotDestroyed()}catch($){throw await Q.destroy().catch(()=>{return}),$}return this.sessions.set(Z.sessionId,Q),Q.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Z.sessionId,Z.metadata,Q.getModelConfiguration())}async loadSession(J){this.assertNotDestroyed(),w.info(`[BladeAgent] Loading session: ${J.sessionId}`);let Q=(this.sessionLoadQueues.get(J.sessionId)??Promise.resolve()).then(()=>this.replaceSession(J)),$=Q.then(()=>{return},()=>{return});this.sessionLoadQueues.set(J.sessionId,$);try{return await Q}finally{if(this.sessionLoadQueues.get(J.sessionId)===$)this.sessionLoadQueues.delete(J.sessionId)}}async replaceSession(J){this.assertNotDestroyed(),await L.assertSessionWritable(J.sessionId,J.cwd);let Z=this.sessions.get(J.sessionId);if(Z)try{await Z.destroy()}finally{if(this.sessions.get(J.sessionId)===Z)this.sessions.delete(J.sessionId)}let[Q,$]=await Promise.all([L.loadSession(J.sessionId,J.cwd),L.findSessionMetadata(J.sessionId,J.cwd)]);if(!$)throw Error(`Session not found: ${J.sessionId}`);let D=new _(J.sessionId,J.cwd,this.connection,this.clientCapabilities,{initialMessages:Q,permissionMode:$.permissionMode,mcpServers:J.mcpServers});try{await D.initialize(),await D.replayHistory(),this.assertNotDestroyed()}catch(Y){throw await D.destroy().catch(()=>{return}),Y}return this.sessions.set(J.sessionId,D),D.sendAvailableCommandsDelayed(),this.buildSessionSetup(D.getModelConfiguration(),D.getMode())}buildChildSessionResponse(J,Z,Q){return{sessionId:J,...this.buildSessionSetup(Q,Z?.permissionMode==="autoEdit"?"auto-edit":Z?.permissionMode),...Z?{_meta:{"blade/taskIsolation":Z.taskIsolation,"blade/taskSourceProjectPath":Z.taskSourceProjectPath,"blade/taskProjectPath":Z.projectPath,...Z.taskModelId?{"blade/taskModelId":Z.taskModelId}:{},...Z.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...Z.taskRetriedFrom?{"blade/taskRetriedFrom":Z.taskRetriedFrom}:{},...Z.taskDelivery?{"blade/taskDelivery":Z.taskDelivery}:{},...Z.taskWorktreeBranch?{"blade/taskWorktreeBranch":Z.taskWorktreeBranch}:{},...Z.taskBaseCommit?{"blade/taskBaseCommit":Z.taskBaseCommit}:{}}}:{}}}assertNotDestroyed(){if(this.destroyed)throw Error("BladeAgent is destroyed")}buildSessionSetup(J,Z="default"){let Q=J?.models??[],$=(J?.currentModelId&&Q.some((z)=>z.id===J.currentModelId)?J.currentModelId:void 0)??Q[0]?.id,D=[{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"}],Y=[];if(Q.length>0)Y.push({type:"select",id:"model",name:"Model",description:"Active language model",category:"model",currentValue:$,options:Q.map((z)=>({value:z.id,name:z.displayName??z.model,description:`${J?.modelProviders[z.provider]?.name??z.provider} · ${z.model}`}))});if(J?.reasoning)Y.push({type:"select",id:"reasoning_effort",name:"Reasoning effort",description:"Session-owned model reasoning intensity",category:"model",currentValue:J.reasoning.selection,options:[{value:"auto",name:"Auto",description:`Resolve near high for this model (currently ${J.reasoning.effective})`},...J.reasoning.supported.map((z)=>({value:z,name:z[0].toUpperCase()+z.slice(1),description:z==="off"?"Disable model reasoning":`Use ${z} reasoning effort`}))]});if(J?.serviceTier)Y.push({type:"select",id:"service_tier",name:"Service tier",description:"Session-owned provider latency and pricing tier",category:"model",currentValue:J.serviceTier.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default tier"},...J.serviceTier.supported.map((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(J?.responseVerbosity)Y.push({type:"select",id:"response_verbosity",name:"Response verbosity",description:"Session-owned model response detail",category:"model",currentValue:J.responseVerbosity.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default verbosity"},...J.responseVerbosity.supported.map((z)=>({value:z,name:z[0].toUpperCase()+z.slice(1),description:`Use ${z} response verbosity`}))]});if(J?.communicationStyle)Y.push({type:"select",id:"communication_style",name:"Communication style",description:"Session-owned tone and explanatory framing",category:"model",currentValue:J.communicationStyle.selection,options:J.communicationStyle.supported.map((z)=>({value:z.id,name:z.name,description:`${z.description} · ${z.source}`}))});return{modes:{availableModes:D,currentModeId:Z},configOptions:Y.length>0?Y:void 0}}async prompt(J){let Z=this.sessions.get(J.sessionId);if(!Z)throw Error(`Session not found: ${J.sessionId}`);return Z.prompt(J)}async cancel(J){w.info(`[BladeAgent] Cancel notification received for session: ${J.sessionId}`);let Z=this.sessions.get(J.sessionId);if(Z)w.info("[BladeAgent] Found session, calling session.cancel()"),Z.cancel();else w.warn(`[BladeAgent] Session not found for cancel: ${J.sessionId}`)}async setSessionMode(J){w.info(`[BladeAgent] Setting session mode: ${J.modeId}`);let Z=this.sessions.get(J.sessionId);if(Z)await Z.setMode(J.modeId);return{}}async setSessionConfigOption(J){let Z=this.sessions.get(J.sessionId);if(!Z)throw Error(`Session not found: ${J.sessionId}`);if(J.configId==="model"&&"value"in J&&typeof J.value==="string")w.info(`[BladeAgent] Setting session model: ${J.value}`),await Z.setModel(J.value);else if(J.configId==="reasoning_effort"&&"value"in J&&r(J.value))w.info(`[BladeAgent] Setting reasoning effort: ${J.value}`),await Z.setReasoningEffort(J.value);else if(J.configId==="service_tier"&&"value"in J&&l(J.value))w.info(`[BladeAgent] Setting service tier: ${J.value}`),await Z.setServiceTier(J.value);else if(J.configId==="response_verbosity"&&"value"in J&&d(J.value))w.info(`[BladeAgent] Setting response verbosity: ${J.value}`),await Z.setResponseVerbosity(J.value);else if(J.configId==="communication_style"&&"value"in J&&a(J.value))w.info(`[BladeAgent] Setting communication style: ${J.value}`),await Z.setCommunicationStyle(J.value);else throw Error(`Invalid session config option: ${J.configId}`);return{configOptions:this.buildSessionSetup(Z.getModelConfiguration(),Z.getMode()).configOptions??[]}}async destroy(){this.destroyed=!0,await Promise.all([...this.sessionLoadQueues.values()]),this.sessionLoadQueues.clear();let J;for(let Z of this.sessions.values())try{await Z.destroy()}catch(Q){J??=Q}this.sessions.clear();try{await n.getInstance().disconnectAll()}catch(Z){J??=Z}if(J!==void 0)throw J}}async function uJ(){let J=WJ.toWeb(process.stdout),Z=zJ.toWeb(process.stdin),Q=O.ndJsonStream(J,Z);await new O.AgentSideConnection((D)=>new b(D),Q).closed}export{uJ as runAcpIntegration};
@@ -1 +0,0 @@
1
- import{Bb as a,Cb as b,Db as c,Eb as d,Fb as e,Gb as f,Hb as g,Ib as h}from"./chunk-an96c54z.js";import"./chunk-qda309d9.js";import"./chunk-0n97186m.js";import"./chunk-9ffr01c3.js";export{d as syncSession,e as syncAll,h as searchProjectionText,c as resetProjectionDbCache,f as removeSessionFromProjection,g as rebuildProjectionIndex,b as getProjectionDb,a as getIndexDbPath};
@@ -1 +0,0 @@
1
- import{$c as e,Xc as a,Yc as b,Zc as c,_c as d}from"./chunk-am8dtvff.js";import"./chunk-35yktzm1.js";import"./chunk-63ysxybd.js";import"./chunk-vpj0sv73.js";import"./chunk-qm11hjd3.js";import"./chunk-qda309d9.js";import"./chunk-rh7v814a.js";import"./chunk-tq52pbde.js";import"./chunk-79s052sw.js";import"./chunk-epj56s0n.js";import"./chunk-gxzbv67r.js";import"./chunk-bexgcc2d.js";import"./chunk-1vx4sf1y.js";import"./chunk-z906d5tb.js";import"./chunk-948qe2pp.js";import"./chunk-0n97186m.js";import"./chunk-9ffr01c3.js";export{d as snapshotWorkspaceAgentResources,c as resolveWorkspaceAgentResources,e as resetWorkspaceAgentResources,a as refreshWorkspaceCommunicationStyles,b as configureInvocationPluginDirs};
@@ -1 +0,0 @@
1
- import{lb as a,mb as b,nb as c,ob as d,pb as e,qb as f}from"./chunk-417wefq7.js";import"./chunk-an96c54z.js";import"./chunk-gxmrakrk.js";import"./chunk-35yktzm1.js";import"./chunk-qm11hjd3.js";import"./chunk-qda309d9.js";import"./chunk-79s052sw.js";import"./chunk-epj56s0n.js";import"./chunk-bexgcc2d.js";import"./chunk-1vx4sf1y.js";import"./chunk-0n97186m.js";import"./chunk-9ffr01c3.js";export{a as __setSessionSnapshotIOForTesting,b as __resetSessionSnapshotIOForTesting,f as SessionService,c as SessionMissingCreationError,d as SessionArchivedError,e as SessionArchiveConflictError};
@@ -1 +0,0 @@
1
- import{Bc as a}from"./chunk-dqvcgwhe.js";import"./chunk-qda309d9.js";import"./chunk-gxzbv67r.js";import"./chunk-bexgcc2d.js";import"./chunk-0n97186m.js";import"./chunk-9ffr01c3.js";export{a as createChatServiceAsync};