blade-code 0.10.174 → 0.10.176

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 (42) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-sx68f8yz.js → chunk-0yebb919.js} +1 -1
  3. package/dist/{chunk-adzzwn5t.js → chunk-1g9vwbv4.js} +1 -1
  4. package/dist/{chunk-fr0pnytg.js → chunk-1k1dkbpa.js} +1 -1
  5. package/dist/{chunk-a3ejtsq6.js → chunk-3gtj63ss.js} +1 -1
  6. package/dist/{chunk-6fqewq0m.js → chunk-3w1aqkz9.js} +2 -2
  7. package/dist/{chunk-38arrd1h.js → chunk-3zz9m825.js} +1 -1
  8. package/dist/chunk-49gfpqkn.js +1 -0
  9. package/dist/{chunk-12jy6zwj.js → chunk-578gfr58.js} +1 -1
  10. package/dist/{chunk-bjda9w4s.js → chunk-5rrvwesz.js} +1 -1
  11. package/dist/{chunk-f69mpn2r.js → chunk-5y536ycm.js} +1 -1
  12. package/dist/{chunk-rejsff7v.js → chunk-6ke6p47w.js} +1 -1
  13. package/dist/{chunk-mw0xx44s.js → chunk-9wq0504z.js} +1 -1
  14. package/dist/{chunk-26g3nrdr.js → chunk-adjtgsqe.js} +273 -273
  15. package/dist/{chunk-5s7dzv39.js → chunk-arc5mz9q.js} +1 -1
  16. package/dist/{chunk-vep4e9bn.js → chunk-bf9ek9cw.js} +1 -1
  17. package/dist/{chunk-7ytweagc.js → chunk-d0rwtkvt.js} +1 -1
  18. package/dist/{chunk-0qtf9sss.js → chunk-e5qpgfa8.js} +1 -1
  19. package/dist/{chunk-5h0xq9f7.js → chunk-g58z5vrv.js} +1 -1
  20. package/dist/{chunk-1ajrbxsv.js → chunk-gwfz0qrr.js} +1 -1
  21. package/dist/{chunk-hbhf4bnq.js → chunk-gznfyegp.js} +1 -1
  22. package/dist/{chunk-p3sgmn1h.js → chunk-h26667eb.js} +1 -1
  23. package/dist/{chunk-w95gvhvw.js → chunk-ha6btpqh.js} +1 -1
  24. package/dist/{chunk-dpv615sg.js → chunk-hcgw662n.js} +1 -1
  25. package/dist/{chunk-j2fb3jwe.js → chunk-jq7pcxpx.js} +1 -1
  26. package/dist/{chunk-962xet8h.js → chunk-jv8hwxj9.js} +1 -1
  27. package/dist/{chunk-m9jgeshx.js → chunk-k4agcfcy.js} +1 -1
  28. package/dist/{chunk-f2qs07mx.js → chunk-k6b013wk.js} +1 -1
  29. package/dist/{chunk-wjegeerz.js → chunk-pkn0mjed.js} +1 -1
  30. package/dist/{chunk-teth5343.js → chunk-q599m0dn.js} +1 -1
  31. package/dist/chunk-rkebq2gn.js +1 -0
  32. package/dist/{chunk-bx3d9jae.js → chunk-s7q2tqfc.js} +1 -1
  33. package/dist/{chunk-3rrcg0es.js → chunk-saky5ntj.js} +1 -1
  34. package/dist/{chunk-jn2j7fgw.js → chunk-txz3xnz5.js} +1 -1
  35. package/dist/{chunk-66d27d7t.js → chunk-vpb63htc.js} +1 -1
  36. package/dist/{chunk-c9cwxadd.js → chunk-ynfv949b.js} +1 -1
  37. package/dist/{chunk-20x62wa4.js → chunk-yt31g9xb.js} +1 -1
  38. package/dist/{chunk-0ba55nvt.js → chunk-z5s67ate.js} +1 -1
  39. package/dist/{chunk-3cvycxre.js → chunk-zxmy26da.js} +1 -1
  40. package/package.json +1 -1
  41. package/dist/chunk-42ec0wep.js +0 -1
  42. package/dist/chunk-x2h8hz5w.js +0 -1
@@ -1,4 +1,4 @@
1
- import{e as U3,f as H3,g as R3,h as s0,i as q3}from"./chunk-w95gvhvw.js";import{j as o1}from"./chunk-zj1g4nbq.js";import{v as a0,w as y2}from"./chunk-0qtf9sss.js";import{A as m0,x as g2,y as p2,z as v2}from"./chunk-jn2j7fgw.js";import{B as C2,C as U$,D as H$,E as F$,F as z0,G as N$}from"./chunk-mw0xx44s.js";import{$ as I2,Ea as u3,J as B2,K as u1,L as v3,O as D2,P as e0,Q as d4,R as i1,S as g$,T as A4,U as j4,V as K0,W as L2,X as M2,Y as D$,Z as w1,aa as R2,ba as b4,ca as j0,da as H0,ga as q1,ha as E1,ia as O5,ja as q2,ka as E2,la as r2,ma as e2,na as O3,oa as $3,pa as Q3,qa as Z3,ra as J3,sa as Y3,ta as X3,wa as w3,za as W5}from"./chunk-26g3nrdr.js";import{La as q$,Ra as uO}from"./chunk-teth5343.js";import{Ua as A2,Wa as j2,Xa as b2,Ya as T2,cb as V4,fb as c3,gb as c4,hb as S2,ib as f2,jb as i3,kb as l3,lb as i4,mb as a3,nb as g0,ob as N3,pb as B3,qb as D3,rb as P2,sb as k2,tb as m2,ub as h2,vb as W$,wb as r4}from"./chunk-30x3mcsb.js";import{Kb as dO,Lb as a,Nb as P,Ob as x2,Zb as M4,hc as y0}from"./chunk-f2qs07mx.js";import{sc as T4}from"./chunk-zzvs471p.js";import{$c as W2,$d as D4,Cd as w2,Ic as V2,Md as A1,Nd as h0,Sc as z2,Ud as I1,Vd as I4,Wd as R1,Yd as o0,Zc as G2,_c as B4,ad as D1,bd as K2,ed as U4,ee as N2,fe as x4,ge as L4,he as g,rd as _2}from"./chunk-3rrcg0es.js";import{Fe as U2,Me as H2,Ne as F2}from"./chunk-y5wngtz0.js";import{gf as L3,kf as M3,lf as A3,mf as j3,nf as b3,of as y4,pf as T3,qf as I3}from"./chunk-w33zjw8m.js";import{Pf as r3,Tf as MO,Xf as f$,cg as nO}from"./chunk-3cvycxre.js";import{dg as c1}from"./chunk-t0gm0pn1.js";import{wg as J2}from"./chunk-50vwafn5.js";import{yg as B1}from"./chunk-vep4e9bn.js";import{Hg as e3,Lg as s2,Pg as H1,Qg as F1,Ug as B5,Xg as eO,Yg as N1,_g as X2,ah as s4}from"./chunk-38arrd1h.js";import{th as P$,uh as Y2}from"./chunk-vbjgcn49.js";import{yh as b$,zh as l0}from"./chunk-m9jgeshx.js";import{Mi as T$,Rh as R$,Ri as U1,fi as s$,ii as r$,ki as e$,li as O2,mi as h$,ni as y$,oi as K$,ui as $2,xi as Q2,zi as Z2}from"./chunk-962xet8h.js";import{Ui as F4}from"./chunk-kv458q06.js";import{Wi as a1,Zi as N4}from"./chunk-5v0jcyea.js";import{bj as GO}from"./chunk-2f8d0km4.js";import{Dj as ZO,Fj as y,Hj as G,Ij as oO,Kj as zO}from"./chunk-2mk914vk.js";import{Pj as f0}from"./chunk-j8hbddjp.js";import{Rj as C$,Sj as o$,Uj as S$,Vj as t$}from"./chunk-4cdk4mds.js";import{Xj as i0}from"./chunk-rejsff7v.js";import{ck as t4}from"./chunk-rvs364rz.js";import{Bk as g1,Jk as L$,fk as l1,zk as wO}from"./chunk-4wx5sya5.js";import{Mk as a4}from"./chunk-eg3ms291.js";var H8={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 F8(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{existsSync as e4,readFileSync as f1}from"node:fs";import{createServer as c6}from"node:http";import{networkInterfaces as i6}from"node:os";import{dirname as l6,extname as a6,join as E0}from"node:path";import{fileURLToPath as n6}from"node:url";import{brotliCompressSync as o6,gzipSync as t6,constants as s6}from"node:zlib";import{Hono as r6}from"hono";import{cors as e6}from"hono/cors";import{WebSocketServer as O8}from"ws";var c0=ZO("Service"),f5=30000,P5=new Set(["completed","failed","cancelled","interrupted"]);class z4{dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor(O){this.dispatch=O.dispatch,this.store=O.store??W$.getInstance(),this.tickMs=O.tickMs??f5}start(){if(this.timer)return;c0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=P.subscribe((O)=>{if(O.type!=="task.status")return;let $=O.properties.taskStatus;if(typeof $!=="string"||!P5.has($))return;this.recordTerminalStatus(O.sessionId,$,typeof O.properties.taskStatusReason==="string"?O.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,c0.info("[TaskScheduler] Stopped scheduler tick loop")}async tick(O=new Date){if(this.ticking)return;this.ticking=!0;try{let $=await this.store.list();for(let Q of $)await this.evaluate(Q,O)}catch($){c0.warn("[TaskScheduler] Tick failed:",$)}finally{this.ticking=!1}}async evaluate(O,$){if(!O.enabled)return;if(this.inFlight.has(O.id))return;if(O.expiresAt&&new Date(O.expiresAt).getTime()<=$.getTime()){await this.store.update(O.id,{enabled:!1,nextRunAt:null}),c0.info(`[TaskScheduler] Schedule ${O.id} expired; disabled`);return}if(!O.nextRunAt)return;if(!(new Date(O.nextRunAt).getTime()<=$.getTime()))return;await this.fire(O,$)}async fire(O,$=new Date,Q={}){if(this.inFlight.has(O.id))throw Error(`Schedule ${O.id} is already dispatching`);this.inFlight.add(O.id);let Z=$.toISOString();try{let J=await this.dispatch({prompt:O.prompt,title:O.title??k5(O),sourceProjectPath:O.projectPath,isolation:O.dispatch.isolation??"worktree",permissionMode:O.dispatch.permissionMode??"default",modelId:O.dispatch.modelId,reasoningEffort:O.dispatch.reasoningEffort,serviceTier:O.dispatch.serviceTier,responseVerbosity:O.dispatch.responseVerbosity,communicationStyle:O.dispatch.communicationStyle}),X=O.trigger.kind==="once"?null:Q.manual?O.nextRunAt?new Date(O.nextRunAt):null:V4(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:Z,lastRunSessionId:J.session.sessionId,lastStatus:J.status,lastError:void 0,runCount:O.runCount+1,nextRunAt:X?X.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled}),P.publish({sessionId:J.session.sessionId,projectPath:O.projectPath},"schedule.fired",{scheduleId:O.id,firedAt:Z,sessionId:J.session.sessionId,runId:J.runId,status:J.status}),c0.info(`[TaskScheduler] Fired schedule ${O.id} -> session ${J.session.sessionId} (${J.status})`)}catch(J){let X=J instanceof Error?J.message:String(J);c0.warn(`[TaskScheduler] Schedule ${O.id} dispatch failed:`,J);let V=O.trigger.kind==="once"?null:Q.manual?O.nextRunAt?new Date(O.nextRunAt):null:V4(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:Z,lastStatus:"error",lastError:X,nextRunAt:V?V.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled})}finally{this.inFlight.delete(O.id)}}async recordTerminalStatus(O,$,Q){let J=(await this.store.list()).find((X)=>X.lastRunSessionId===O);if(!J)return;await this.store.update(J.id,{lastStatus:$,...Q?{lastError:Q}:{lastError:void 0}})}}function k5(O){return`Scheduled: ${O.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class _O extends Error{code;statusCode;details;constructor(O,$,Q=500,Z){super($);this.code=O;this.statusCode=Q;this.details=Z;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class i extends _O{constructor(O,$){super("NOT_FOUND",$?`${O} not found: ${$}`:`${O} not found`,404)}}class F extends _O{constructor(O){super("BAD_REQUEST",O,400)}}class v extends _O{constructor(O){super("CONFLICT",O,409)}}class rO extends _O{constructor(O,$){super("TOO_MANY_REQUESTS",O,429,$)}}class LO extends _O{constructor(O="Server is shutting down"){super("SERVICE_UNAVAILABLE",O,503)}}class A0 extends _O{constructor(O){super("SESSION_WORKSPACE_UNAVAILABLE","This session workspace is no longer available",409,{reason:O})}}class vO extends _O{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class VO extends _O{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var j8=G.Object({error:G.Object({code:G.String(),message:G.String(),details:G.Optional(G.Record(G.String(),G.Unknown()))})});import{Hono as m5}from"hono";var G4=ZO("Service"),h5=G.Object({updates:G.Record(G.String(),G.Any()),options:G.Optional(G.Object({scope:G.Optional(zO(["local","project","global"])),immediate:G.Optional(G.Boolean())}))});function y5(O){return{currentModelId:O.currentModelId,permissionMode:O.permissionMode,language:O.language,codeTheme:O.codeTheme,uiTheme:O.uiTheme,autoSaveSessions:O.autoSaveSessions,notifyBuild:O.notifyBuild,notifyErrors:O.notifyErrors,notifySounds:O.notifySounds,privacyTelemetry:O.privacyTelemetry,privacyCrash:O.privacyCrash,agentTeamsEnabled:O.agentTeamsEnabled===!0,communicationStyle:O.communicationStyle,maxConcurrentTasks:O.maxConcurrentTasks,maxQueuedTasks:O.maxQueuedTasks,maxQueuedTaskBytes:O.maxQueuedTaskBytes,maxResidentSessionRuntimes:O.maxResidentSessionRuntimes,sessionRuntimeIdleMs:O.sessionRuntimeIdleMs,maxResidentSessionProjections:O.maxResidentSessionProjections,sessionProjectionIdleMs:O.sessionProjectionIdleMs}}var _$=()=>{let O=new m5;return O.get("/",async($)=>{try{let Q=MO();return $.json(Q?y5(Q):{})}catch(Q){return G4.error("[ConfigRoutes] Failed to get config:",Q),$.json({})}}),O.put("/",async($)=>{try{let Q=await $.req.json(),Z=y(h5,Q);if(!Z.success)throw new F("Invalid config update format");let{updates:J,options:X}=Z.data;return await nO().updateConfig(J,X),$.json({success:!0,updates:J})}catch(Q){if(Q instanceof K$)throw new F(Q.message);throw G4.error("[ConfigRoutes] Failed to update config:",Q),Q}}),O.get("/permissions",async($)=>{try{let Q=MO();return $.json(Q?.permissions||{})}catch(Q){return G4.error("[ConfigRoutes] Failed to get permissions:",Q),$.json({})}}),O};import{Hono as g5}from"hono";import{streamSSE as p5}from"hono/streaming";function w$(O){let $="";if(O.id!==void 0)$+=`id: ${O.id}
1
+ import{e as U3,f as H3,g as R3,h as s0,i as q3}from"./chunk-ha6btpqh.js";import{j as o1}from"./chunk-zj1g4nbq.js";import{v as a0,w as y2}from"./chunk-e5qpgfa8.js";import{A as m0,x as g2,y as p2,z as v2}from"./chunk-txz3xnz5.js";import{B as C2,C as U$,D as H$,E as F$,F as z0,G as N$}from"./chunk-9wq0504z.js";import{$ as I2,Ea as u3,J as B2,K as u1,L as v3,O as D2,P as e0,Q as d4,R as i1,S as g$,T as A4,U as j4,V as K0,W as L2,X as M2,Y as D$,Z as w1,aa as R2,ba as b4,ca as j0,da as H0,ga as q1,ha as E1,ia as O5,ja as q2,ka as E2,la as r2,ma as e2,na as O3,oa as $3,pa as Q3,qa as Z3,ra as J3,sa as Y3,ta as X3,wa as w3,za as W5}from"./chunk-adjtgsqe.js";import{La as q$,Ra as uO}from"./chunk-q599m0dn.js";import{Ua as A2,Wa as j2,Xa as b2,Ya as T2,cb as V4,fb as c3,gb as c4,hb as S2,ib as f2,jb as i3,kb as l3,lb as i4,mb as a3,nb as g0,ob as N3,pb as B3,qb as D3,rb as P2,sb as k2,tb as m2,ub as h2,vb as W$,wb as r4}from"./chunk-30x3mcsb.js";import{Kb as dO,Lb as a,Nb as P,Ob as x2,Zb as M4,hc as y0}from"./chunk-k6b013wk.js";import{sc as T4}from"./chunk-zzvs471p.js";import{$c as W2,$d as D4,Cd as w2,Ic as V2,Md as A1,Nd as h0,Sc as z2,Ud as I1,Vd as I4,Wd as R1,Yd as o0,Zc as G2,_c as B4,ad as D1,bd as K2,ed as U4,ee as N2,fe as x4,ge as L4,he as g,rd as _2}from"./chunk-saky5ntj.js";import{Fe as U2,Me as H2,Ne as F2}from"./chunk-y5wngtz0.js";import{gf as L3,kf as M3,lf as A3,mf as j3,nf as b3,of as y4,pf as T3,qf as I3}from"./chunk-w33zjw8m.js";import{Pf as r3,Tf as MO,Xf as f$,cg as nO}from"./chunk-zxmy26da.js";import{dg as c1}from"./chunk-t0gm0pn1.js";import{wg as J2}from"./chunk-50vwafn5.js";import{yg as B1}from"./chunk-bf9ek9cw.js";import{Hg as e3,Lg as s2,Pg as H1,Qg as F1,Ug as B5,Xg as eO,Yg as N1,_g as X2,ah as s4}from"./chunk-3zz9m825.js";import{th as P$,uh as Y2}from"./chunk-vbjgcn49.js";import{yh as b$,zh as l0}from"./chunk-k4agcfcy.js";import{Mi as T$,Rh as R$,Ri as U1,fi as s$,ii as r$,ki as e$,li as O2,mi as h$,ni as y$,oi as K$,ui as $2,xi as Q2,zi as Z2}from"./chunk-jv8hwxj9.js";import{Ui as F4}from"./chunk-kv458q06.js";import{Wi as a1,Zi as N4}from"./chunk-5v0jcyea.js";import{bj as GO}from"./chunk-2f8d0km4.js";import{Dj as ZO,Fj as y,Hj as G,Ij as oO,Kj as zO}from"./chunk-2mk914vk.js";import{Pj as f0}from"./chunk-j8hbddjp.js";import{Rj as C$,Sj as o$,Uj as S$,Vj as t$}from"./chunk-4cdk4mds.js";import{Xj as i0}from"./chunk-6ke6p47w.js";import{ck as t4}from"./chunk-rvs364rz.js";import{Bk as g1,Jk as L$,fk as l1,zk as wO}from"./chunk-4wx5sya5.js";import{Mk as a4}from"./chunk-eg3ms291.js";var H8={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 F8(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{existsSync as e4,readFileSync as f1}from"node:fs";import{createServer as c6}from"node:http";import{networkInterfaces as i6}from"node:os";import{dirname as l6,extname as a6,join as E0}from"node:path";import{fileURLToPath as n6}from"node:url";import{brotliCompressSync as o6,gzipSync as t6,constants as s6}from"node:zlib";import{Hono as r6}from"hono";import{cors as e6}from"hono/cors";import{WebSocketServer as O8}from"ws";var c0=ZO("Service"),f5=30000,P5=new Set(["completed","failed","cancelled","interrupted"]);class z4{dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor(O){this.dispatch=O.dispatch,this.store=O.store??W$.getInstance(),this.tickMs=O.tickMs??f5}start(){if(this.timer)return;c0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=P.subscribe((O)=>{if(O.type!=="task.status")return;let $=O.properties.taskStatus;if(typeof $!=="string"||!P5.has($))return;this.recordTerminalStatus(O.sessionId,$,typeof O.properties.taskStatusReason==="string"?O.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,c0.info("[TaskScheduler] Stopped scheduler tick loop")}async tick(O=new Date){if(this.ticking)return;this.ticking=!0;try{let $=await this.store.list();for(let Q of $)await this.evaluate(Q,O)}catch($){c0.warn("[TaskScheduler] Tick failed:",$)}finally{this.ticking=!1}}async evaluate(O,$){if(!O.enabled)return;if(this.inFlight.has(O.id))return;if(O.expiresAt&&new Date(O.expiresAt).getTime()<=$.getTime()){await this.store.update(O.id,{enabled:!1,nextRunAt:null}),c0.info(`[TaskScheduler] Schedule ${O.id} expired; disabled`);return}if(!O.nextRunAt)return;if(!(new Date(O.nextRunAt).getTime()<=$.getTime()))return;await this.fire(O,$)}async fire(O,$=new Date,Q={}){if(this.inFlight.has(O.id))throw Error(`Schedule ${O.id} is already dispatching`);this.inFlight.add(O.id);let Z=$.toISOString();try{let J=await this.dispatch({prompt:O.prompt,title:O.title??k5(O),sourceProjectPath:O.projectPath,isolation:O.dispatch.isolation??"worktree",permissionMode:O.dispatch.permissionMode??"default",modelId:O.dispatch.modelId,reasoningEffort:O.dispatch.reasoningEffort,serviceTier:O.dispatch.serviceTier,responseVerbosity:O.dispatch.responseVerbosity,communicationStyle:O.dispatch.communicationStyle}),X=O.trigger.kind==="once"?null:Q.manual?O.nextRunAt?new Date(O.nextRunAt):null:V4(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:Z,lastRunSessionId:J.session.sessionId,lastStatus:J.status,lastError:void 0,runCount:O.runCount+1,nextRunAt:X?X.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled}),P.publish({sessionId:J.session.sessionId,projectPath:O.projectPath},"schedule.fired",{scheduleId:O.id,firedAt:Z,sessionId:J.session.sessionId,runId:J.runId,status:J.status}),c0.info(`[TaskScheduler] Fired schedule ${O.id} -> session ${J.session.sessionId} (${J.status})`)}catch(J){let X=J instanceof Error?J.message:String(J);c0.warn(`[TaskScheduler] Schedule ${O.id} dispatch failed:`,J);let V=O.trigger.kind==="once"?null:Q.manual?O.nextRunAt?new Date(O.nextRunAt):null:V4(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:Z,lastStatus:"error",lastError:X,nextRunAt:V?V.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled})}finally{this.inFlight.delete(O.id)}}async recordTerminalStatus(O,$,Q){let J=(await this.store.list()).find((X)=>X.lastRunSessionId===O);if(!J)return;await this.store.update(J.id,{lastStatus:$,...Q?{lastError:Q}:{lastError:void 0}})}}function k5(O){return`Scheduled: ${O.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class _O extends Error{code;statusCode;details;constructor(O,$,Q=500,Z){super($);this.code=O;this.statusCode=Q;this.details=Z;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class i extends _O{constructor(O,$){super("NOT_FOUND",$?`${O} not found: ${$}`:`${O} not found`,404)}}class F extends _O{constructor(O){super("BAD_REQUEST",O,400)}}class v extends _O{constructor(O){super("CONFLICT",O,409)}}class rO extends _O{constructor(O,$){super("TOO_MANY_REQUESTS",O,429,$)}}class LO extends _O{constructor(O="Server is shutting down"){super("SERVICE_UNAVAILABLE",O,503)}}class A0 extends _O{constructor(O){super("SESSION_WORKSPACE_UNAVAILABLE","This session workspace is no longer available",409,{reason:O})}}class vO extends _O{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class VO extends _O{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var j8=G.Object({error:G.Object({code:G.String(),message:G.String(),details:G.Optional(G.Record(G.String(),G.Unknown()))})});import{Hono as m5}from"hono";var G4=ZO("Service"),h5=G.Object({updates:G.Record(G.String(),G.Any()),options:G.Optional(G.Object({scope:G.Optional(zO(["local","project","global"])),immediate:G.Optional(G.Boolean())}))});function y5(O){return{currentModelId:O.currentModelId,permissionMode:O.permissionMode,language:O.language,codeTheme:O.codeTheme,uiTheme:O.uiTheme,autoSaveSessions:O.autoSaveSessions,notifyBuild:O.notifyBuild,notifyErrors:O.notifyErrors,notifySounds:O.notifySounds,privacyTelemetry:O.privacyTelemetry,privacyCrash:O.privacyCrash,agentTeamsEnabled:O.agentTeamsEnabled===!0,communicationStyle:O.communicationStyle,maxConcurrentTasks:O.maxConcurrentTasks,maxQueuedTasks:O.maxQueuedTasks,maxQueuedTaskBytes:O.maxQueuedTaskBytes,maxResidentSessionRuntimes:O.maxResidentSessionRuntimes,sessionRuntimeIdleMs:O.sessionRuntimeIdleMs,maxResidentSessionProjections:O.maxResidentSessionProjections,sessionProjectionIdleMs:O.sessionProjectionIdleMs}}var _$=()=>{let O=new m5;return O.get("/",async($)=>{try{let Q=MO();return $.json(Q?y5(Q):{})}catch(Q){return G4.error("[ConfigRoutes] Failed to get config:",Q),$.json({})}}),O.put("/",async($)=>{try{let Q=await $.req.json(),Z=y(h5,Q);if(!Z.success)throw new F("Invalid config update format");let{updates:J,options:X}=Z.data;return await nO().updateConfig(J,X),$.json({success:!0,updates:J})}catch(Q){if(Q instanceof K$)throw new F(Q.message);throw G4.error("[ConfigRoutes] Failed to update config:",Q),Q}}),O.get("/permissions",async($)=>{try{let Q=MO();return $.json(Q?.permissions||{})}catch(Q){return G4.error("[ConfigRoutes] Failed to get permissions:",Q),$.json({})}}),O};import{Hono as g5}from"hono";import{streamSSE as p5}from"hono/streaming";function w$(O){let $="";if(O.id!==void 0)$+=`id: ${O.id}
2
2
  `;if(O.event!==void 0)$+=`event: ${O.event}
3
3
  `;for(let Q of O.data.split(/\r\n|\r|\n/))$+=`data: ${Q}
4
4
  `;if(O.retry!==void 0)$+=`retry: ${O.retry}
@@ -1,2 +1,2 @@
1
- import{Ri as I}from"./chunk-962xet8h.js";import{Oj as G,Pj as H}from"./chunk-j8hbddjp.js";import B from"node:path";function A(b){if(Array.isArray(b))return b.map((q)=>A(q));if(b!==null&&typeof b==="object"&&Object.getPrototypeOf(b)===Object.prototype)return Object.fromEntries(Object.entries(b).map(([q,w])=>[q,A(w)]));return b}function D(b){return A(b)}function E(b,q){let w=new G(q?.credentials??H().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=B.resolve(b),x=I.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...D(q),...J,...K},F=E(z);return x.validateConfig(z,F),{projectRoot:w,config:z,catalog:F}}function T(b){let q=D(b.config);return{projectRoot:B.resolve(b.projectRoot),config:q,catalog:E(q,b.catalog)}}function U(b,q){let w=D(q);return{projectRoot:B.resolve(b),config:w,catalog:E(w)}}
1
+ import{Ri as I}from"./chunk-jv8hwxj9.js";import{Oj as G,Pj as H}from"./chunk-j8hbddjp.js";import B from"node:path";function A(b){if(Array.isArray(b))return b.map((q)=>A(q));if(b!==null&&typeof b==="object"&&Object.getPrototypeOf(b)===Object.prototype)return Object.fromEntries(Object.entries(b).map(([q,w])=>[q,A(w)]));return b}function D(b){return A(b)}function E(b,q){let w=new G(q?.credentials??H().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=B.resolve(b),x=I.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...D(q),...J,...K},F=E(z);return x.validateConfig(z,F),{projectRoot:w,config:z,catalog:F}}function T(b){let q=D(b.config);return{projectRoot:B.resolve(b.projectRoot),config:q,catalog:E(q,b.catalog)}}function U(b,q){let w=D(q);return{projectRoot:B.resolve(b),config:w,catalog:E(w)}}
2
2
  export{D as xg,Q as yg,T as zg,U as Ag};
@@ -1 +1 @@
1
- import{a,b as i,c as l,d as m}from"./chunk-5s7dzv39.js";import"./chunk-w95gvhvw.js";import"./chunk-zj1g4nbq.js";import"./chunk-0qtf9sss.js";import"./chunk-jn2j7fgw.js";import"./chunk-mw0xx44s.js";import"./chunk-26g3nrdr.js";import"./chunk-g01mth5d.js";import"./chunk-teth5343.js";import"./chunk-30x3mcsb.js";import"./chunk-f2qs07mx.js";import"./chunk-zzvs471p.js";import"./chunk-3rrcg0es.js";import"./chunk-53fc0yrq.js";import"./chunk-y5wngtz0.js";import"./chunk-w33zjw8m.js";import{yf as n}from"./chunk-20x62wa4.js";import"./chunk-jj4ggb04.js";import{Uf as s}from"./chunk-3cvycxre.js";import"./chunk-v508x7cg.js";import"./chunk-t0gm0pn1.js";import"./chunk-1yq72zb7.js";import"./chunk-kqvzmnja.js";import"./chunk-0mr8nexh.js";import"./chunk-50vwafn5.js";import"./chunk-vep4e9bn.js";import"./chunk-38arrd1h.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-m9jgeshx.js";import"./chunk-3y2x6fb6.js";import"./chunk-962xet8h.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-rejsff7v.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";import v from"chalk";var C={command:"serve",describe:"Start a headless Blade server (no browser)",builder:a,handler:async(p)=>{let r=i(p);if(await s(),!process.env.BLADE_SERVER_PASSWORD)console.log(v.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let e=await m.listenAsync(r);if(console.log(`Blade server listening on http://${e.hostname}:${e.port}`),r.hostname==="0.0.0.0"){let o=l();for(let g of o)console.log(` Network: http://${g}:${e.port}`)}let t,c=new Promise((o)=>{t=o}),d=n(async()=>{await e.stop(),t()});try{await c}finally{d(),await e.stop()}}};export{C as serveCommand};
1
+ import{a,b as i,c as l,d as m}from"./chunk-arc5mz9q.js";import"./chunk-ha6btpqh.js";import"./chunk-zj1g4nbq.js";import"./chunk-e5qpgfa8.js";import"./chunk-txz3xnz5.js";import"./chunk-9wq0504z.js";import"./chunk-adjtgsqe.js";import"./chunk-g01mth5d.js";import"./chunk-q599m0dn.js";import"./chunk-30x3mcsb.js";import"./chunk-k6b013wk.js";import"./chunk-zzvs471p.js";import"./chunk-saky5ntj.js";import"./chunk-53fc0yrq.js";import"./chunk-y5wngtz0.js";import"./chunk-w33zjw8m.js";import{yf as n}from"./chunk-yt31g9xb.js";import"./chunk-jj4ggb04.js";import{Uf as s}from"./chunk-zxmy26da.js";import"./chunk-v508x7cg.js";import"./chunk-t0gm0pn1.js";import"./chunk-1yq72zb7.js";import"./chunk-kqvzmnja.js";import"./chunk-0mr8nexh.js";import"./chunk-50vwafn5.js";import"./chunk-bf9ek9cw.js";import"./chunk-3zz9m825.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-k4agcfcy.js";import"./chunk-3y2x6fb6.js";import"./chunk-jv8hwxj9.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-6ke6p47w.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";import v from"chalk";var C={command:"serve",describe:"Start a headless Blade server (no browser)",builder:a,handler:async(p)=>{let r=i(p);if(await s(),!process.env.BLADE_SERVER_PASSWORD)console.log(v.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let e=await m.listenAsync(r);if(console.log(`Blade server listening on http://${e.hostname}:${e.port}`),r.hostname==="0.0.0.0"){let o=l();for(let g of o)console.log(` Network: http://${g}:${e.port}`)}let t,c=new Promise((o)=>{t=o}),d=n(async()=>{await e.stop(),t()});try{await c}finally{d(),await e.stop()}}};export{C as serveCommand};
@@ -1,2 +1,2 @@
1
- import{Ai as H,Bi as I}from"./chunk-962xet8h.js";import{Mutex as J}from"async-mutex";class B extends Error{limit;resource="resident_runtimes";retryable=!0;constructor(b){super("Session runtime capacity is full");this.limit=b;this.name="SessionRuntimeCapacityError"}}class D extends Error{constructor(){super("Session runtime residency is closed");this.name="SessionRuntimeResidencyClosedError"}}class A extends Error{constructor(b){super(`Session runtime residency already owns key: ${b}`);this.name="SessionRuntimeResidencyConflictError"}}class K{maxResident;idleMs;now;residents=new Map;reservations=new Map;operations=new J;nextGeneration=1;closed=!1;constructor(b){if(!H(b.maxResident))throw Error("Invalid max resident Session Runtime limit");if(!I(b.idleMs))throw Error("Invalid Session Runtime idle timeout");this.maxResident=b.maxResident,this.idleMs=b.idleMs,this.now=b.now??Date.now}acquire(b){let j=this.residents.get(b);if(!j||j.poisoned)return;return j.pins++,j.lastUsedAt=this.now(),this.createLease(j)}owns(b,j){let q=this.residents.get(b);return Boolean(q&&(j===void 0||q.value===j))}async reserve(b,j){if(!b.trim())throw Error("Session runtime residency key must not be blank");return this.operations.runExclusive(async()=>{if(this.closed)throw new D;if(this.residents.has(b)||this.reservations.has(b))throw new A(b);while(this.retainedCount()>=this.maxResident){if(!j.allowEviction)throw new B(this.maxResident);let z=this.oldestEvictableWebResident();if(!z)throw new B(this.maxResident);await this.disposeResident(z,!0)}let q={generation:this.allocateGeneration(),surface:j.surface};return this.reservations.set(b,q),this.createReservation(b,q)})}async remove(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j)return!1;if(q.pins>0)return!1;return await this.disposeResident(q,!0),!0})}async forget(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j||q.pins>0)return!1;return this.residents.delete(b),!0})}async sweepIdle(){return this.operations.runExclusive(async()=>{if(this.closed)return 0;let b=0;while(!0){let j=this.oldestIdleWebResident();if(!j)return b;await this.disposeResident(j,!0),b++}})}async disposeAll(){await this.operations.runExclusive(async()=>{this.closed=!0,this.reservations.clear();let b;for(let j of[...this.residents.values()])try{await this.disposeResident(j,!1)}catch(q){b??=q}if(this.residents.clear(),b!==void 0)throw b})}getStats(){let b=0;for(let j of this.residents.values())if(j.pins>0)b++;return{resident:this.residents.size,reserved:this.reservations.size,pinned:b,maxResident:this.maxResident}}retainedCount(){return this.residents.size+this.reservations.size}allocateGeneration(){let b=this.nextGeneration;return this.nextGeneration=this.nextGeneration===Number.MAX_SAFE_INTEGER?1:this.nextGeneration+1,b}createReservation(b,j){let q=!1;return{commit:(z)=>{if(q)throw new A(b);if(z.key!==b||z.surface!==j.surface||this.reservations.get(b)!==j||this.closed)throw this.reservations.delete(b),q=!0,this.closed?new D:new A(b);this.reservations.delete(b);let G={...z,generation:j.generation,pins:1,lastUsedAt:this.now(),poisoned:!1};return this.residents.set(b,G),q=!0,this.createLease(G)},cancel:()=>{if(q)return;if(this.reservations.get(b)===j)this.reservations.delete(b);q=!0}}}createLease(b){let j=!1;return{value:b.value,release:()=>{if(j)return;j=!0;let q=this.residents.get(b.key);if(q!==b||q.generation!==b.generation)return;q.pins=Math.max(0,q.pins-1),q.lastUsedAt=this.now()}}}oldestEvictableWebResident(){return this.sortedWebResidents().find((b)=>this.canEvict(b))}oldestIdleWebResident(){let b=this.now();return this.sortedWebResidents().find((j)=>b-j.lastUsedAt>=this.idleMs&&this.canEvict(j))}sortedWebResidents(){return[...this.residents.values()].filter((b)=>b.surface==="web").sort((b,j)=>b.lastUsedAt-j.lastUsedAt||b.generation-j.generation)}canEvict(b){if(b.pins>0||b.poisoned)return!1;try{return b.canEvict()}catch{return!1}}async disposeResident(b,j){if(this.residents.get(b.key)!==b)return;this.residents.delete(b.key);try{await b.dispose()}catch(q){if(j&&!this.closed&&!this.residents.has(b.key))b.lastUsedAt=this.now(),b.poisoned=!0,this.residents.set(b.key,b);throw q}}}
1
+ import{Ai as H,Bi as I}from"./chunk-jv8hwxj9.js";import{Mutex as J}from"async-mutex";class B extends Error{limit;resource="resident_runtimes";retryable=!0;constructor(b){super("Session runtime capacity is full");this.limit=b;this.name="SessionRuntimeCapacityError"}}class D extends Error{constructor(){super("Session runtime residency is closed");this.name="SessionRuntimeResidencyClosedError"}}class A extends Error{constructor(b){super(`Session runtime residency already owns key: ${b}`);this.name="SessionRuntimeResidencyConflictError"}}class K{maxResident;idleMs;now;residents=new Map;reservations=new Map;operations=new J;nextGeneration=1;closed=!1;constructor(b){if(!H(b.maxResident))throw Error("Invalid max resident Session Runtime limit");if(!I(b.idleMs))throw Error("Invalid Session Runtime idle timeout");this.maxResident=b.maxResident,this.idleMs=b.idleMs,this.now=b.now??Date.now}acquire(b){let j=this.residents.get(b);if(!j||j.poisoned)return;return j.pins++,j.lastUsedAt=this.now(),this.createLease(j)}owns(b,j){let q=this.residents.get(b);return Boolean(q&&(j===void 0||q.value===j))}async reserve(b,j){if(!b.trim())throw Error("Session runtime residency key must not be blank");return this.operations.runExclusive(async()=>{if(this.closed)throw new D;if(this.residents.has(b)||this.reservations.has(b))throw new A(b);while(this.retainedCount()>=this.maxResident){if(!j.allowEviction)throw new B(this.maxResident);let z=this.oldestEvictableWebResident();if(!z)throw new B(this.maxResident);await this.disposeResident(z,!0)}let q={generation:this.allocateGeneration(),surface:j.surface};return this.reservations.set(b,q),this.createReservation(b,q)})}async remove(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j)return!1;if(q.pins>0)return!1;return await this.disposeResident(q,!0),!0})}async forget(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j||q.pins>0)return!1;return this.residents.delete(b),!0})}async sweepIdle(){return this.operations.runExclusive(async()=>{if(this.closed)return 0;let b=0;while(!0){let j=this.oldestIdleWebResident();if(!j)return b;await this.disposeResident(j,!0),b++}})}async disposeAll(){await this.operations.runExclusive(async()=>{this.closed=!0,this.reservations.clear();let b;for(let j of[...this.residents.values()])try{await this.disposeResident(j,!1)}catch(q){b??=q}if(this.residents.clear(),b!==void 0)throw b})}getStats(){let b=0;for(let j of this.residents.values())if(j.pins>0)b++;return{resident:this.residents.size,reserved:this.reservations.size,pinned:b,maxResident:this.maxResident}}retainedCount(){return this.residents.size+this.reservations.size}allocateGeneration(){let b=this.nextGeneration;return this.nextGeneration=this.nextGeneration===Number.MAX_SAFE_INTEGER?1:this.nextGeneration+1,b}createReservation(b,j){let q=!1;return{commit:(z)=>{if(q)throw new A(b);if(z.key!==b||z.surface!==j.surface||this.reservations.get(b)!==j||this.closed)throw this.reservations.delete(b),q=!0,this.closed?new D:new A(b);this.reservations.delete(b);let G={...z,generation:j.generation,pins:1,lastUsedAt:this.now(),poisoned:!1};return this.residents.set(b,G),q=!0,this.createLease(G)},cancel:()=>{if(q)return;if(this.reservations.get(b)===j)this.reservations.delete(b);q=!0}}}createLease(b){let j=!1;return{value:b.value,release:()=>{if(j)return;j=!0;let q=this.residents.get(b.key);if(q!==b||q.generation!==b.generation)return;q.pins=Math.max(0,q.pins-1),q.lastUsedAt=this.now()}}}oldestEvictableWebResident(){return this.sortedWebResidents().find((b)=>this.canEvict(b))}oldestIdleWebResident(){let b=this.now();return this.sortedWebResidents().find((j)=>b-j.lastUsedAt>=this.idleMs&&this.canEvict(j))}sortedWebResidents(){return[...this.residents.values()].filter((b)=>b.surface==="web").sort((b,j)=>b.lastUsedAt-j.lastUsedAt||b.generation-j.generation)}canEvict(b){if(b.pins>0||b.poisoned)return!1;try{return b.canEvict()}catch{return!1}}async disposeResident(b,j){if(this.residents.get(b.key)!==b)return;this.residents.delete(b.key);try{await b.dispose()}catch(q){if(j&&!this.closed&&!this.residents.has(b.key))b.lastUsedAt=this.now(),b.poisoned=!0,this.residents.set(b.key,b);throw q}}}
2
2
  export{B as v,K as w};
@@ -1 +1 @@
1
- import{k as o}from"./chunk-hbhf4bnq.js";import"./chunk-rejsff7v.js";import"./chunk-eg3ms291.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
1
+ import{k as o}from"./chunk-gznfyegp.js";import"./chunk-6ke6p47w.js";import"./chunk-eg3ms291.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
@@ -1 +1 @@
1
- import{$f as n,Of as a,Pf as b,Qf as c,Rf as d,Sf as e,Tf as f,Uf as g,Vf as h,Wf as i,Xf as j,Yf as k,Zf as l,_f as m,ag as o,bg as p,cg as q}from"./chunk-3cvycxre.js";import"./chunk-v508x7cg.js";import"./chunk-t0gm0pn1.js";import"./chunk-962xet8h.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-rejsff7v.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};
1
+ import{$f as n,Of as a,Pf as b,Qf as c,Rf as d,Sf as e,Tf as f,Uf as g,Vf as h,Wf as i,Xf as j,Yf as k,Zf as l,_f as m,ag as o,bg as p,cg as q}from"./chunk-zxmy26da.js";import"./chunk-v508x7cg.js";import"./chunk-t0gm0pn1.js";import"./chunk-jv8hwxj9.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-6ke6p47w.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};
@@ -1,2 +1,2 @@
1
- import{Xj as I}from"./chunk-rejsff7v.js";import{Mk as f}from"./chunk-eg3ms291.js";import*as j from"fs/promises";import*as S from"path";import X from"semver";import{ProxyAgent as R,fetch as k}from"undici";function x(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function L(){let z=x();if(z)try{return new R(z)}catch(q){console.warn(`[proxyFetch] Invalid proxy URL: ${z}`)}return}async function F(z,q,Z){let{timeout:W=30000,signal:J,...Q}=q;if(J?.aborted)throw new DOMException("The operation was aborted.","AbortError");let Y=L(),$=new AbortController,w=!1,y=setTimeout(()=>{w=!0,$.abort()},W),T=()=>$.abort();J?.addEventListener("abort",T);let D;try{let B={method:Q.method,headers:Q.headers,body:Q.body,signal:$.signal,dispatcher:Y};return D=await k(z.toString(),B),await Z(D)}catch(B){if(B instanceof Error&&B.name==="AbortError"){if(w)throw Error(`Request timeout after ${W}ms`);throw B}throw B}finally{if(clearTimeout(y),J?.removeEventListener("abort",T),$.abort(),D?.body&&!D.body.locked)await D.body.cancel().catch(()=>{return});await Y?.destroy?.().catch(()=>{return})}}var O="blade-code",G="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",H=S.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),N=S.join(H,"version-cache.json"),_=3600000,g=`https://registry.npmjs.org/${O}/latest`,M=null;async function P(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;return I()}catch{return"unknown"}}async function b(){try{let z=await j.readFile(N,"utf-8"),q=JSON.parse(z);if(Date.now()-q.checkedAt<_)return q;return{...q,checkedAt:0}}catch{return null}}async function K(z){try{await j.mkdir(H,{recursive:!0,mode:493}),await j.writeFile(N,JSON.stringify(z,null,2))}catch{}}async function E(){try{return await F(g,{timeout:5000,headers:{Accept:"application/json"}},async(z)=>{if(!z.ok)return null;let q=await z.json();if(!q||typeof q!=="object"||!("version"in q))return null;return typeof q.version==="string"&&X.valid(q.version)?q.version:null})}catch{return null}}async function A(z=!1){let q=await P(),Z=G;if(q==="unknown")return{currentVersion:q,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:Z,error:"Unable to determine current version"};let W=await b(),J=W?.skipUntilVersion,Q=null;if(!z&&W?.latestVersion&&W.checkedAt>0)Q=W.latestVersion;else if(Q=await E(),J=(await b())?.skipUntilVersion??J,Q)await K({latestVersion:Q,checkedAt:Date.now(),skipUntilVersion:J});else if(W?.latestVersion)await K({checkedAt:0,skipUntilVersion:J});if(!Q||!X.valid(Q))return{currentVersion:q,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:Z,error:"Unable to check for updates"};if(X.lt(Q,q))Q=q,await K({latestVersion:Q,checkedAt:Date.now(),skipUntilVersion:J});let Y=X.gt(Q,q),$=Y;if(Y&&J)$=X.gt(Q,J);return{currentVersion:q,latestVersion:Q,hasUpdate:Y,shouldPrompt:$,releaseNotesUrl:Z}}async function V(z){let q=await b();await K({latestVersion:q?.latestVersion??z,checkedAt:q?.checkedAt||Date.now(),skipUntilVersion:z})}function v(){return`npm install -g ${O}@latest --registry https://registry.npmjs.org`}async function p(){let{spawn:z}=await import("child_process");return new Promise((q)=>{let Z=v(),W=z(Z,{stdio:"inherit",shell:!0});W.on("close",(J)=>{if(J===0)q({success:!0,message:"Upgrade successful! Please restart blade."});else q({success:!1,message:`Upgrade failed (exit code: ${J})`})}),W.on("error",(J)=>{q({success:!1,message:`Upgrade failed: ${J.message}`})})})}async function h(){try{let z=await b();if(!z?.latestVersion||!X.valid(z.latestVersion)||!z.checkedAt){if(!M)M=A(!0).then(()=>{return},()=>{return}).finally(()=>{M=null});return null}let q=await P();if(!X.valid(q)||!X.gt(z.latestVersion,q)||z.skipUntilVersion&&X.valid(z.skipUntilVersion)&&!X.gt(z.latestVersion,z.skipUntilVersion))return null;return{currentVersion:q,latestVersion:z.latestVersion,hasUpdate:!0,shouldPrompt:!0,releaseNotesUrl:G}}catch{return null}}
1
+ import{Xj as I}from"./chunk-6ke6p47w.js";import{Mk as f}from"./chunk-eg3ms291.js";import*as j from"fs/promises";import*as S from"path";import X from"semver";import{ProxyAgent as R,fetch as k}from"undici";function x(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function L(){let z=x();if(z)try{return new R(z)}catch(q){console.warn(`[proxyFetch] Invalid proxy URL: ${z}`)}return}async function F(z,q,Z){let{timeout:W=30000,signal:J,...Q}=q;if(J?.aborted)throw new DOMException("The operation was aborted.","AbortError");let Y=L(),$=new AbortController,w=!1,y=setTimeout(()=>{w=!0,$.abort()},W),T=()=>$.abort();J?.addEventListener("abort",T);let D;try{let B={method:Q.method,headers:Q.headers,body:Q.body,signal:$.signal,dispatcher:Y};return D=await k(z.toString(),B),await Z(D)}catch(B){if(B instanceof Error&&B.name==="AbortError"){if(w)throw Error(`Request timeout after ${W}ms`);throw B}throw B}finally{if(clearTimeout(y),J?.removeEventListener("abort",T),$.abort(),D?.body&&!D.body.locked)await D.body.cancel().catch(()=>{return});await Y?.destroy?.().catch(()=>{return})}}var O="blade-code",G="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",H=S.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),N=S.join(H,"version-cache.json"),_=3600000,g=`https://registry.npmjs.org/${O}/latest`,M=null;async function P(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;return I()}catch{return"unknown"}}async function b(){try{let z=await j.readFile(N,"utf-8"),q=JSON.parse(z);if(Date.now()-q.checkedAt<_)return q;return{...q,checkedAt:0}}catch{return null}}async function K(z){try{await j.mkdir(H,{recursive:!0,mode:493}),await j.writeFile(N,JSON.stringify(z,null,2))}catch{}}async function E(){try{return await F(g,{timeout:5000,headers:{Accept:"application/json"}},async(z)=>{if(!z.ok)return null;let q=await z.json();if(!q||typeof q!=="object"||!("version"in q))return null;return typeof q.version==="string"&&X.valid(q.version)?q.version:null})}catch{return null}}async function A(z=!1){let q=await P(),Z=G;if(q==="unknown")return{currentVersion:q,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:Z,error:"Unable to determine current version"};let W=await b(),J=W?.skipUntilVersion,Q=null;if(!z&&W?.latestVersion&&W.checkedAt>0)Q=W.latestVersion;else if(Q=await E(),J=(await b())?.skipUntilVersion??J,Q)await K({latestVersion:Q,checkedAt:Date.now(),skipUntilVersion:J});else if(W?.latestVersion)await K({checkedAt:0,skipUntilVersion:J});if(!Q||!X.valid(Q))return{currentVersion:q,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:Z,error:"Unable to check for updates"};if(X.lt(Q,q))Q=q,await K({latestVersion:Q,checkedAt:Date.now(),skipUntilVersion:J});let Y=X.gt(Q,q),$=Y;if(Y&&J)$=X.gt(Q,J);return{currentVersion:q,latestVersion:Q,hasUpdate:Y,shouldPrompt:$,releaseNotesUrl:Z}}async function V(z){let q=await b();await K({latestVersion:q?.latestVersion??z,checkedAt:q?.checkedAt||Date.now(),skipUntilVersion:z})}function v(){return`npm install -g ${O}@latest --registry https://registry.npmjs.org`}async function p(){let{spawn:z}=await import("child_process");return new Promise((q)=>{let Z=v(),W=z(Z,{stdio:"inherit",shell:!0});W.on("close",(J)=>{if(J===0)q({success:!0,message:"Upgrade successful! Please restart blade."});else q({success:!1,message:`Upgrade failed (exit code: ${J})`})}),W.on("error",(J)=>{q({success:!1,message:`Upgrade failed: ${J.message}`})})})}async function h(){try{let z=await b();if(!z?.latestVersion||!X.valid(z.latestVersion)||!z.checkedAt){if(!M)M=A(!0).then(()=>{return},()=>{return}).finally(()=>{M=null});return null}let q=await P();if(!X.valid(q)||!X.gt(z.latestVersion,q)||z.skipUntilVersion&&X.valid(z.skipUntilVersion)&&!X.gt(z.latestVersion,z.skipUntilVersion))return null;return{currentVersion:q,latestVersion:z.latestVersion,hasUpdate:!0,shouldPrompt:!0,releaseNotesUrl:G}}catch{return null}}
2
2
  export{A as k,V as l,v as m,p as n,h as o};
@@ -1,4 +1,4 @@
1
- import{wf as v}from"./chunk-nheny8xp.js";import{Pf as e}from"./chunk-3cvycxre.js";import{Ci as S,Di as m,Ei as c,Fi as p,Hi as u,Ii as d,Mi as l,Ri as i,Si as t,ei as y,gi as D,hi as h,ji as A,qi as P,ri as T,ti as E,vi as _,wi as f,yi as C}from"./chunk-962xet8h.js";import{Ti as Y}from"./chunk-kv458q06.js";import{$i as X}from"./chunk-2f8d0km4.js";import{dj as U,ej as L,kj as M,lj as O,nj as $,oj as I,pj as G,rj as N,sj as j,uj as F,vj as R}from"./chunk-ddvdc2p0.js";import{Dj as s,Fj as x,Hj as k,Kj as Z}from"./chunk-2mk914vk.js";import{promises as a}from"node:fs";import g from"node:path";var r=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],kk=new Set([...Object.keys(l),...r,"providerRequestConcurrency","providerGlobalConcurrency","providerOwnerConcurrency"]),W=k.Number({exclusiveMinimum:0}),z=k.String({minLength:1}),b=k.Array(k.String()),qk=k.Object({currentModelId:k.Optional(k.String()),modelProviders:k.Optional(k.Record(z,k.Object({name:z,baseUrl:z,wireApi:Z(["openai-completions","anthropic-messages"]),apiKeyEnv:k.Optional(z)}))),models:k.Optional(k.Array(k.Object({id:z,displayName:k.Optional(z),provider:z,model:z,overrides:k.Optional(k.Object({baseUrl:k.Optional(k.String()),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),timeout:k.Optional(W),streamIdleTimeout:k.Optional(k.Number({minimum:1000})),apiVersion:k.Optional(k.String()),customHeaders:k.Optional(k.Record(k.String(),k.String())),maxRetries:k.Optional(k.Integer({minimum:0})),enablePromptCaching:k.Optional(k.Boolean())})),fallbackModels:k.Optional(k.Array(k.Object({provider:z,model:z,configId:k.Optional(z)})))}))),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),stream:k.Optional(k.Boolean()),topP:k.Optional(k.Number()),topK:k.Optional(k.Number()),timeout:k.Optional(W),bashForegroundHandoffMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:P,maximum:T})])),providerForegroundRecoveryMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:U,maximum:L})])),providerCircuitBreakerOpenMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:M,maximum:O})])),providerRequestConcurrency:k.Optional(k.Integer({minimum:$,maximum:I})),providerGlobalConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerOwnerConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerRequestAdmissionMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:N,maximum:j})])),providerRequestPendingBytes:k.Optional(k.Integer({minimum:F,maximum:R})),agentTeamsEnabled:k.Optional(k.Boolean()),codeTheme:k.Optional(k.String()),uiTheme:k.Optional(Z(["light","dark","system"])),language:k.Optional(k.String()),fontSize:k.Optional(W),autoSaveSessions:k.Optional(k.Boolean()),notifyBuild:k.Optional(k.Boolean()),notifyErrors:k.Optional(k.Boolean()),notifySounds:k.Optional(k.Boolean()),privacyTelemetry:k.Optional(k.Boolean()),privacyCrash:k.Optional(k.Boolean()),debug:k.Optional(k.Union([k.Boolean(),k.String()])),mcpEnabled:k.Optional(k.Boolean()),mcpServers:k.Optional(k.Record(k.String(),k.Record(k.String(),k.Unknown()))),lspServers:k.Optional(k.Record(z,k.Object({command:z,args:k.Optional(k.Array(k.String())),extensionToLanguage:k.Record(z,z),env:k.Optional(k.Record(k.String(),k.String())),initializationOptions:k.Optional(k.Unknown()),settings:k.Optional(k.Unknown()),enabled:k.Optional(k.Boolean()),priority:k.Optional(k.Integer()),startupTimeout:k.Optional(k.Integer({minimum:100})),shutdownTimeout:k.Optional(k.Integer({minimum:100})),requestTimeout:k.Optional(k.Integer({minimum:100})),diagnosticWaitTimeout:k.Optional(k.Integer({minimum:0})),maxRestarts:k.Optional(k.Integer({minimum:0,maximum:10}))}))),permissionMode:k.Optional(k.Enum(Y)),maxTurns:k.Optional(k.Integer({minimum:-1})),maxConcurrentTasks:k.Optional(k.Integer({minimum:S,maximum:m})),maxQueuedTasks:k.Optional(k.Integer({minimum:c,maximum:p})),maxQueuedTaskBytes:k.Optional(k.Integer({minimum:u,maximum:d})),maxResidentSessionRuntimes:k.Optional(k.Integer({minimum:E,maximum:_})),sessionRuntimeIdleMs:k.Optional(k.Integer({minimum:f,maximum:C})),maxResidentSessionProjections:k.Optional(k.Integer({minimum:y,maximum:D})),sessionProjectionIdleMs:k.Optional(k.Integer({minimum:h,maximum:A})),systemPrompt:k.Optional(k.String()),appendSystemPrompt:k.Optional(k.String()),initialMessage:k.Optional(k.String()),resumeSessionId:k.Optional(k.String()),forkSession:k.Optional(k.Boolean()),allowedTools:k.Optional(k.Array(z)),disallowedTools:k.Optional(k.Array(z)),mcpConfigPaths:k.Optional(k.Array(z)),strictMcpConfig:k.Optional(k.Boolean()),model:k.Optional(z),addDirs:k.Optional(k.Array(z)),outputFormat:k.Optional(Z(["text","json","stream-json","jsonl"])),inputFormat:k.Optional(Z(["text","stream-json"])),print:k.Optional(k.Boolean()),includePartialMessages:k.Optional(k.Boolean()),replayUserMessages:k.Optional(k.Boolean()),agentsConfig:k.Optional(k.String()),settingSources:k.Optional(k.String()),permissions:k.Optional(k.Object({allow:k.Optional(b),ask:k.Optional(b),deny:k.Optional(b)})),env:k.Optional(k.Record(k.String(),k.String())),hooks:k.Optional(k.Record(k.String(),k.Unknown())),enabledPlugins:k.Optional(k.Record(z,k.Boolean())),pluginSourcePolicy:k.Optional(k.Object({restrictToAllowedSources:k.Optional(k.Boolean()),requireGitCommitSha:k.Optional(k.Boolean()),allowedGitHosts:k.Optional(k.Array(z)),allowedMarketplaces:k.Optional(k.Array(z)),allowedLocalRoots:k.Optional(k.Array(z))})),disableAllHooks:k.Optional(k.Boolean())}),wk=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"],["maxConcurrentTasks","maxConcurrentTasks"],["maxQueuedTasks","maxQueuedTasks"],["maxQueuedTaskBytes","maxQueuedTaskBytes"],["maxResidentSessionRuntimes","maxResidentSessionRuntimes"],["sessionRuntimeIdleMs","sessionRuntimeIdleMs"],["maxResidentSessionProjections","maxResidentSessionProjections"],["sessionProjectionIdleMs","sessionProjectionIdleMs"]];function V(q,B){let w;try{w=JSON.parse(q)}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Invalid JSON provided to --settings (${B})${K}`)}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("--settings must contain a JSON object");for(let H of Object.keys(w))if(!kk.has(H))throw Error(`Unknown --settings field: ${H}`);let J=x(qk,w);if(!J.success){let H=J.error.issues.map((K)=>`${K.path.join(".")||"settings"}: ${K.message}`).join("; ");throw Error(`Invalid --settings value: ${H}`)}return J.data}async function n(q){if(q===void 0)return;let B=q.trim();if(!B)throw Error("--settings requires a JSON object or file path");if(B.startsWith("{"))return V(B,"inline JSON");let w=g.resolve(X(),B),J;try{J=await a.readFile(w,"utf8")}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Unable to read --settings file ${w}${K}`)}return V(J,w)}function o(q,B){if(!B)return;let w=B;for(let[J,H]of wk){if(J==="permissionMode"&&q.yolo===!0)continue;if(q[H]===void 0&&w[J]!==void 0)q[H]=w[J]}}var Q=s("General"),Uk=(q)=>{if(q.yolo){if(q.permissionMode&&q.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");q.permissionMode="yolo"}if(Array.isArray(q.allowedTools))q.allowedTools=q.allowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.disallowedTools))q.disallowedTools=q.disallowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.allowedTools)&&Array.isArray(q.disallowedTools)){let B=q.allowedTools.filter((w)=>q.disallowedTools.includes(w));if(B.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${B.join(", ")}`)}},Lk=async(q)=>{let B=await n(typeof q.settings==="string"?q.settings:void 0);if(o(q,B),typeof q.agents==="string")v(q.agents);zk(q);try{let J=await i.getInstance().initialize(B),H=t(J,q);if(e().config.actions.setConfig(H),q.debug)Q.info("[CLI] 配置已加载到 Store")}catch(w){Q.error("[CLI] [FAIL] 配置初始化失败",w instanceof Error?w.message:w),console.error(`
1
+ import{wf as v}from"./chunk-nheny8xp.js";import{Pf as e}from"./chunk-zxmy26da.js";import{Ci as S,Di as m,Ei as c,Fi as p,Hi as u,Ii as d,Mi as l,Ri as i,Si as t,ei as y,gi as D,hi as h,ji as A,qi as P,ri as T,ti as E,vi as _,wi as f,yi as C}from"./chunk-jv8hwxj9.js";import{Ti as Y}from"./chunk-kv458q06.js";import{$i as X}from"./chunk-2f8d0km4.js";import{dj as U,ej as L,kj as M,lj as O,nj as $,oj as I,pj as G,rj as N,sj as j,uj as F,vj as R}from"./chunk-ddvdc2p0.js";import{Dj as s,Fj as x,Hj as k,Kj as Z}from"./chunk-2mk914vk.js";import{promises as a}from"node:fs";import g from"node:path";var r=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],kk=new Set([...Object.keys(l),...r,"providerRequestConcurrency","providerGlobalConcurrency","providerOwnerConcurrency"]),W=k.Number({exclusiveMinimum:0}),z=k.String({minLength:1}),b=k.Array(k.String()),qk=k.Object({currentModelId:k.Optional(k.String()),modelProviders:k.Optional(k.Record(z,k.Object({name:z,baseUrl:z,wireApi:Z(["openai-completions","anthropic-messages"]),apiKeyEnv:k.Optional(z)}))),models:k.Optional(k.Array(k.Object({id:z,displayName:k.Optional(z),provider:z,model:z,overrides:k.Optional(k.Object({baseUrl:k.Optional(k.String()),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),timeout:k.Optional(W),streamIdleTimeout:k.Optional(k.Number({minimum:1000})),apiVersion:k.Optional(k.String()),customHeaders:k.Optional(k.Record(k.String(),k.String())),maxRetries:k.Optional(k.Integer({minimum:0})),enablePromptCaching:k.Optional(k.Boolean())})),fallbackModels:k.Optional(k.Array(k.Object({provider:z,model:z,configId:k.Optional(z)})))}))),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),stream:k.Optional(k.Boolean()),topP:k.Optional(k.Number()),topK:k.Optional(k.Number()),timeout:k.Optional(W),bashForegroundHandoffMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:P,maximum:T})])),providerForegroundRecoveryMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:U,maximum:L})])),providerCircuitBreakerOpenMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:M,maximum:O})])),providerRequestConcurrency:k.Optional(k.Integer({minimum:$,maximum:I})),providerGlobalConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerOwnerConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerRequestAdmissionMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:N,maximum:j})])),providerRequestPendingBytes:k.Optional(k.Integer({minimum:F,maximum:R})),agentTeamsEnabled:k.Optional(k.Boolean()),codeTheme:k.Optional(k.String()),uiTheme:k.Optional(Z(["light","dark","system"])),language:k.Optional(k.String()),fontSize:k.Optional(W),autoSaveSessions:k.Optional(k.Boolean()),notifyBuild:k.Optional(k.Boolean()),notifyErrors:k.Optional(k.Boolean()),notifySounds:k.Optional(k.Boolean()),privacyTelemetry:k.Optional(k.Boolean()),privacyCrash:k.Optional(k.Boolean()),debug:k.Optional(k.Union([k.Boolean(),k.String()])),mcpEnabled:k.Optional(k.Boolean()),mcpServers:k.Optional(k.Record(k.String(),k.Record(k.String(),k.Unknown()))),lspServers:k.Optional(k.Record(z,k.Object({command:z,args:k.Optional(k.Array(k.String())),extensionToLanguage:k.Record(z,z),env:k.Optional(k.Record(k.String(),k.String())),initializationOptions:k.Optional(k.Unknown()),settings:k.Optional(k.Unknown()),enabled:k.Optional(k.Boolean()),priority:k.Optional(k.Integer()),startupTimeout:k.Optional(k.Integer({minimum:100})),shutdownTimeout:k.Optional(k.Integer({minimum:100})),requestTimeout:k.Optional(k.Integer({minimum:100})),diagnosticWaitTimeout:k.Optional(k.Integer({minimum:0})),maxRestarts:k.Optional(k.Integer({minimum:0,maximum:10}))}))),permissionMode:k.Optional(k.Enum(Y)),maxTurns:k.Optional(k.Integer({minimum:-1})),maxConcurrentTasks:k.Optional(k.Integer({minimum:S,maximum:m})),maxQueuedTasks:k.Optional(k.Integer({minimum:c,maximum:p})),maxQueuedTaskBytes:k.Optional(k.Integer({minimum:u,maximum:d})),maxResidentSessionRuntimes:k.Optional(k.Integer({minimum:E,maximum:_})),sessionRuntimeIdleMs:k.Optional(k.Integer({minimum:f,maximum:C})),maxResidentSessionProjections:k.Optional(k.Integer({minimum:y,maximum:D})),sessionProjectionIdleMs:k.Optional(k.Integer({minimum:h,maximum:A})),systemPrompt:k.Optional(k.String()),appendSystemPrompt:k.Optional(k.String()),initialMessage:k.Optional(k.String()),resumeSessionId:k.Optional(k.String()),forkSession:k.Optional(k.Boolean()),allowedTools:k.Optional(k.Array(z)),disallowedTools:k.Optional(k.Array(z)),mcpConfigPaths:k.Optional(k.Array(z)),strictMcpConfig:k.Optional(k.Boolean()),model:k.Optional(z),addDirs:k.Optional(k.Array(z)),outputFormat:k.Optional(Z(["text","json","stream-json","jsonl"])),inputFormat:k.Optional(Z(["text","stream-json"])),print:k.Optional(k.Boolean()),includePartialMessages:k.Optional(k.Boolean()),replayUserMessages:k.Optional(k.Boolean()),agentsConfig:k.Optional(k.String()),settingSources:k.Optional(k.String()),permissions:k.Optional(k.Object({allow:k.Optional(b),ask:k.Optional(b),deny:k.Optional(b)})),env:k.Optional(k.Record(k.String(),k.String())),hooks:k.Optional(k.Record(k.String(),k.Unknown())),enabledPlugins:k.Optional(k.Record(z,k.Boolean())),pluginSourcePolicy:k.Optional(k.Object({restrictToAllowedSources:k.Optional(k.Boolean()),requireGitCommitSha:k.Optional(k.Boolean()),allowedGitHosts:k.Optional(k.Array(z)),allowedMarketplaces:k.Optional(k.Array(z)),allowedLocalRoots:k.Optional(k.Array(z))})),disableAllHooks:k.Optional(k.Boolean())}),wk=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"],["maxConcurrentTasks","maxConcurrentTasks"],["maxQueuedTasks","maxQueuedTasks"],["maxQueuedTaskBytes","maxQueuedTaskBytes"],["maxResidentSessionRuntimes","maxResidentSessionRuntimes"],["sessionRuntimeIdleMs","sessionRuntimeIdleMs"],["maxResidentSessionProjections","maxResidentSessionProjections"],["sessionProjectionIdleMs","sessionProjectionIdleMs"]];function V(q,B){let w;try{w=JSON.parse(q)}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Invalid JSON provided to --settings (${B})${K}`)}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("--settings must contain a JSON object");for(let H of Object.keys(w))if(!kk.has(H))throw Error(`Unknown --settings field: ${H}`);let J=x(qk,w);if(!J.success){let H=J.error.issues.map((K)=>`${K.path.join(".")||"settings"}: ${K.message}`).join("; ");throw Error(`Invalid --settings value: ${H}`)}return J.data}async function n(q){if(q===void 0)return;let B=q.trim();if(!B)throw Error("--settings requires a JSON object or file path");if(B.startsWith("{"))return V(B,"inline JSON");let w=g.resolve(X(),B),J;try{J=await a.readFile(w,"utf8")}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Unable to read --settings file ${w}${K}`)}return V(J,w)}function o(q,B){if(!B)return;let w=B;for(let[J,H]of wk){if(J==="permissionMode"&&q.yolo===!0)continue;if(q[H]===void 0&&w[J]!==void 0)q[H]=w[J]}}var Q=s("General"),Uk=(q)=>{if(q.yolo){if(q.permissionMode&&q.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");q.permissionMode="yolo"}if(Array.isArray(q.allowedTools))q.allowedTools=q.allowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.disallowedTools))q.disallowedTools=q.disallowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.allowedTools)&&Array.isArray(q.disallowedTools)){let B=q.allowedTools.filter((w)=>q.disallowedTools.includes(w));if(B.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${B.join(", ")}`)}},Lk=async(q)=>{let B=await n(typeof q.settings==="string"?q.settings:void 0);if(o(q,B),typeof q.agents==="string")v(q.agents);zk(q);try{let J=await i.getInstance().initialize(B),H=t(J,q);if(e().config.actions.setConfig(H),q.debug)Q.info("[CLI] 配置已加载到 Store")}catch(w){Q.error("[CLI] [FAIL] 配置初始化失败",w instanceof Error?w.message:w),console.error(`
2
2
  [FAIL] 配置初始化失败
3
3
  `),console.error("原因:",w instanceof Error?w.message:"未知错误"),console.error(`
4
4
  请检查:`),console.error(" 1. 配置文件格式是否正确 (~/.blade/config.json)"),console.error(" 2. 是否需要运行 blade 进行首次配置"),console.error(` 3. 配置文件权限是否正确
@@ -1,2 +1,2 @@
1
- import{N as GP}from"./chunk-26g3nrdr.js";import{he as N}from"./chunk-3rrcg0es.js";import{$e as JP,Oe as r,Pe as e,Se as L,Ue as PP,Xe as d,Ze as l,bf as QP,cf as ZP,df as $P,ef as w}from"./chunk-y5wngtz0.js";import{gf as t,hf as a,jf as R,lf as y,mf as A,of as p}from"./chunk-w33zjw8m.js";import{Pj as q}from"./chunk-j8hbddjp.js";import{Ak as n,fk as o,zk as s}from"./chunk-4wx5sya5.js";async function qP(){return q().listProviders()}async function EP(P){return q().listModels(P)}import{randomBytes as XP}from"node:crypto";var NP=600000,OP=2048,jP=64,MP=32,HP=67108864,WP=4,D={catalog:"session-surface-catalog:",history:"session-surface-history:",snapshot:"session-surface-snapshot:"},c={session_surface_cursor_invalid:{message:"session surface cursor is invalid",retryable:!1},session_surface_snapshot_changed:{message:"session surface snapshot changed",retryable:!1},session_surface_capacity:{message:"session surface cursor capacity exceeded",retryable:!0},session_surface_unavailable:{message:"session surface cursor registry is unavailable",retryable:!0}};class U extends Error{code;retryable;constructor(P){super(c[P].message);this.code=P;this.name="SessionSurfaceCursorRegistryError",this.retryable=c[P].retryable}}class g{now;tokenSource;tokenCollisionRetries;limitsValue;entries=new Map;chains=new Map;closed=!1;closePromise;totalIssues=0;activeLoads=0;frozenSnapshotBytes=0;retainedPayloadBytes=0;constructor(P={}){if(this.now=P.now??(()=>Date.now()),this.tokenSource=P.tokenSource??(()=>XP(32).toString("base64url")),this.tokenCollisionRetries=P.tokenCollisionRetries??WP,this.limitsValue=_P(P.limits??{}),!Number.isSafeInteger(this.tokenCollisionRetries)||this.tokenCollisionRetries<0)throw Error("tokenCollisionRetries must be a non-negative safe integer")}issueCatalogCursor(P){this.assertAvailable(),this.cleanup();let J=m(P.boundary);if(J.value===void 0)throw new U("session_surface_cursor_invalid");let Q=T(P.request);this.ensureCapacity({requestedEntries:1,requestedRetainedBytes:J.bytes,chainId:P.chainId});let Z=this.createToken("catalog"),$=this.now(),G=this.ensureChain(P.chainId,$),Y={token:Z,chainId:P.chainId,kind:"catalog",expiresAt:$+this.limitsValue.idleTtlMs,lastAccessAt:$,scopeKey:P.scopeKey,epoch:P.epoch,revision:P.revision,boundary:J.value,boundaryBytes:J.bytes,requestHash:Q,cachedResultBytes:0};return this.storeEntry(G,Y),this.retainedPayloadBytes+=J.bytes,G.retainedPayloadBytes+=J.bytes,Z}issueHistoryCursor(P){this.assertAvailable(),this.cleanup();let J=T(P.request),Q=this.assertSnapshotIssuableForHistory(P);this.ensureCapacity({requestedEntries:1,requestedRetainedBytes:0,chainId:P.chainId});let Z=this.createToken("history"),$=this.now(),G=this.ensureChain(P.chainId,$);this.touch(Q);let Y={token:Z,chainId:P.chainId,kind:"history",expiresAt:$+this.limitsValue.idleTtlMs,lastAccessAt:$,locatorDigest:P.locatorDigest,transcriptFingerprint:P.transcriptFingerprint,nextSequence:P.nextSequence,snapshotToken:P.snapshotToken,requestHash:J,cachedResultBytes:0};return this.storeEntry(G,Y),Z}issueSnapshotToken(P){this.assertAvailable(),this.cleanup();let J=P.frozenSnapshot===void 0?{value:void 0,bytes:0}:m(P.frozenSnapshot);this.ensureCapacity({requestedEntries:1,requestedRetainedBytes:J.bytes,chainId:P.chainId});let Q=this.createToken("snapshot"),Z=this.now(),$=this.ensureChain(P.chainId,Z),G={token:Q,chainId:P.chainId,kind:"snapshot",expiresAt:Z+this.limitsValue.idleTtlMs,lastAccessAt:Z,locatorDigest:P.locatorDigest,transcriptFingerprint:P.transcriptFingerprint,frozenBytes:J.bytes,frozenSnapshot:J.value};return this.storeEntry($,G),this.frozenSnapshotBytes+=J.bytes,this.retainedPayloadBytes+=J.bytes,$.frozenSnapshotBytes+=J.bytes,$.retainedPayloadBytes+=J.bytes,Q}async redeemCatalogCursor(P){this.assertAvailable(),this.cleanup();let J=this.getEntry(P.token,"catalog");if(J.scopeKey!==P.scopeKey)throw new U("session_surface_cursor_invalid");if(J.epoch!==P.epoch||J.revision!==P.revision)throw new U("session_surface_snapshot_changed");if(J.requestHash!==T(P.request))throw new U("session_surface_cursor_invalid");if(this.touch(J),J.cachedResult!==void 0)return W(J.cachedResult);if(J.activeLoad)return this.cloneActiveLoadResult(J.activeLoad);return this.startCatalogLoad(J,P.loader)}async redeemHistoryCursor(P){this.assertAvailable(),this.cleanup();let J=this.getEntry(P.token,"history");if(J.locatorDigest!==P.locatorDigest)throw new U("session_surface_snapshot_changed");if(J.transcriptFingerprint!==P.transcriptFingerprint)throw new U("session_surface_snapshot_changed");if(J.requestHash!==T(P.request))throw new U("session_surface_cursor_invalid");let Q=this.resolveHistorySnapshot(J);if(this.touch(J),this.touch(Q),J.cachedResult!==void 0)return W(J.cachedResult);if(J.activeLoad)return this.cloneActiveLoadResult(J.activeLoad);return this.startHistoryLoad(J,Q,P.loader)}async assertSnapshotToken(P){this.assertAvailable(),this.cleanup();let J=this.getEntry(P.token,"snapshot");if(J.locatorDigest!==P.locatorDigest)throw new U("session_surface_cursor_invalid");if(J.transcriptFingerprint!==P.transcriptFingerprint)throw new U("session_surface_snapshot_changed");return this.touch(J),{chainId:J.chainId,locatorDigest:J.locatorDigest,transcriptFingerprint:J.transcriptFingerprint,frozenBytes:J.frozenBytes,frozenSnapshot:J.frozenSnapshot===void 0?void 0:W(J.frozenSnapshot)}}completeChain(P){this.cleanup();let J=this.chains.get(P);if(!J)return;J.completed=!0,J.lastAccessAt=this.now()}stats(){this.cleanup();let P=0;for(let J of this.chains.values())if(J.completed)P+=1;return{closed:this.closed,chainCount:this.chains.size,activeChains:this.chains.size-P,completedChains:P,entryCount:this.entries.size,activeLoads:this.activeLoads,frozenSnapshotBytes:this.frozenSnapshotBytes,retainedPayloadBytes:this.retainedPayloadBytes,totalIssues:this.totalIssues,limits:{...this.limitsValue}}}async close(P){if(this.closePromise)return this.closePromise;this.closed=!0;let J=[];for(let Q of this.entries.values())if((Q.kind==="catalog"||Q.kind==="history")&&Q.activeLoad)J.push(Q.activeLoad.promise),Q.activeLoad.controller.abort(_());return this.closePromise=Promise.allSettled(J).then(()=>{this.entries.clear(),this.chains.clear(),this.activeLoads=0,this.frozenSnapshotBytes=0,this.retainedPayloadBytes=0}),this.closePromise}startCatalogLoad(P,J){let Q=this.requireChain(P.chainId),Z=new AbortController;this.activeLoads+=1,Q.activeLoads+=1;let $=Promise.resolve().then(()=>J({boundary:W(P.boundary)},Z.signal)).then((G)=>{return this.assertLoadAvailable(Z.signal),this.admitCachedResult(P,G)}).catch((G)=>{if(this.closed||Z.signal.aborted)throw _();throw G}).finally(()=>{P.activeLoad=void 0,this.activeLoads-=1,Q.activeLoads-=1});return P.activeLoad={controller:Z,promise:$},this.cloneActiveLoadResult(P.activeLoad)}startHistoryLoad(P,J,Q){let Z=this.requireChain(P.chainId),$=new AbortController;this.activeLoads+=1,Z.activeLoads+=1;let G=Promise.resolve().then(()=>Q({nextSequence:P.nextSequence,frozenSnapshot:J.frozenSnapshot===void 0?void 0:W(J.frozenSnapshot)},$.signal)).then((Y)=>{return this.assertLoadAvailable($.signal),this.admitCachedResult(P,Y)}).catch((Y)=>{if(this.closed||$.signal.aborted)throw _();throw Y}).finally(()=>{P.activeLoad=void 0,this.activeLoads-=1,Z.activeLoads-=1});return P.activeLoad={controller:$,promise:G},this.cloneActiveLoadResult(P.activeLoad)}resolveHistorySnapshot(P){let J=P.snapshotToken;if(E(J)!=="snapshot")throw new U("session_surface_snapshot_changed");let Q=this.entries.get(J);if(!Q||Q.kind!=="snapshot")throw new U("session_surface_snapshot_changed");if(Q.expiresAt<=this.now())throw this.removeEntry(Q),new U("session_surface_snapshot_changed");if(Q.locatorDigest!==P.locatorDigest||Q.transcriptFingerprint!==P.transcriptFingerprint)throw new U("session_surface_snapshot_changed");return Q}assertSnapshotIssuableForHistory(P){let J=P.snapshotToken;if(E(J)!=="snapshot")throw new U("session_surface_snapshot_changed");let Q=this.entries.get(J);if(!Q||Q.kind!=="snapshot")throw new U("session_surface_snapshot_changed");if(Q.expiresAt<=this.now())throw this.removeEntry(Q),new U("session_surface_snapshot_changed");if(Q.chainId!==P.chainId||Q.locatorDigest!==P.locatorDigest||Q.transcriptFingerprint!==P.transcriptFingerprint)throw new U("session_surface_snapshot_changed");return Q}requireChain(P){let J=this.chains.get(P);if(!J)throw new U("session_surface_cursor_invalid");return J}assertLoadAvailable(P){if(this.closed||P.aborted)throw _()}getEntry(P,J){if(E(P)!==J)throw new U("session_surface_cursor_invalid");let Z=this.entries.get(P);if(!Z)throw new U("session_surface_cursor_invalid");if(Z.kind!==J)throw new U("session_surface_cursor_invalid");if(Z.expiresAt<=this.now()&&!f(Z))throw this.removeEntry(Z),new U("session_surface_cursor_invalid");return Z}touch(P){let J=this.now();P.lastAccessAt=J,P.expiresAt=J+this.limitsValue.idleTtlMs;let Q=this.chains.get(P.chainId);if(Q)Q.lastAccessAt=J}storeEntry(P,J){if(P.tokens.size>=this.limitsValue.maxEntriesPerChain)throw new U("session_surface_capacity");this.entries.set(J.token,J),P.tokens.add(J.token),P.completed=!1,P.lastAccessAt=J.lastAccessAt,P.issueCount+=1,this.totalIssues+=1}ensureChain(P,J){let Q=this.chains.get(P);if(Q)return Q.lastAccessAt=J,Q;let Z={chainId:P,tokens:new Set,completed:!1,lastAccessAt:J,issueCount:0,activeLoads:0,frozenSnapshotBytes:0,retainedPayloadBytes:0};return this.chains.set(P,Z),Z}cloneActiveLoadResult(P){return P.promise.then((J)=>W(J))}admitCachedResult(P,J){let Q=m(J),Z=this.requireChain(P.chainId),$=Q.bytes-P.cachedResultBytes;if(this.ensureCapacity({requestedEntries:0,requestedRetainedBytes:Math.max(0,$),chainId:P.chainId}),this.releaseCachedResult(P,Z),Q.value===void 0)throw new U("session_surface_cursor_invalid");return P.cachedResult=Q.value,P.cachedResultBytes=Q.bytes,this.retainedPayloadBytes+=Q.bytes,Z.retainedPayloadBytes+=Q.bytes,P.cachedResult}createToken(P){let J=D[P];for(let Q=0;Q<=this.tokenCollisionRetries;Q+=1){this.assertAvailable();let Z=`${J}${this.tokenSource()}`;if(!this.entries.has(Z))return Z}throw new U("session_surface_capacity")}ensureCapacity(P){this.reclaimCompletedChains(P);let J=this.entries.size+P.requestedEntries,Q=this.chains.size+(this.chains.has(P.chainId)?0:1),Z=this.retainedPayloadBytes+P.requestedRetainedBytes,$=(this.chains.get(P.chainId)?.tokens.size??0)+P.requestedEntries;if(J>this.limitsValue.maxEntries||Q>this.limitsValue.maxChains||$>this.limitsValue.maxEntriesPerChain||Z>this.limitsValue.maxFrozenSnapshotBytes)throw new U("session_surface_capacity")}reclaimCompletedChains(P){let J=[...this.chains.values()].filter((Q)=>Q.completed&&Q.activeLoads===0).sort((Q,Z)=>Q.lastAccessAt-Z.lastAccessAt);for(let Q of J){if(!(this.entries.size+P.requestedEntries>this.limitsValue.maxEntries||this.chains.size+(P.chainId!==""&&this.chains.has(P.chainId)?0:1)>this.limitsValue.maxChains||this.retainedPayloadBytes+P.requestedRetainedBytes>this.limitsValue.maxFrozenSnapshotBytes))break;this.removeChain(Q.chainId)}}cleanup(){let P=this.now();for(let J of[...this.entries.values()]){if(J.expiresAt>P||f(J))continue;this.removeEntry(J)}for(let J of[...this.chains.values()])if(J.tokens.size===0&&J.activeLoads===0)this.chains.delete(J.chainId)}removeEntry(P){this.entries.delete(P.token);let J=this.chains.get(P.chainId);if(J){if(J.tokens.delete(P.token),this.releaseEntryRetainedPayload(P,J),J.tokens.size===0&&J.activeLoads===0)this.chains.delete(J.chainId)}else this.releaseEntryRetainedPayload(P)}removeChain(P){let J=this.chains.get(P);if(!J)return;for(let Q of J.tokens){let Z=this.entries.get(Q);if(!Z||f(Z))continue;this.entries.delete(Q),this.releaseEntryRetainedPayload(Z,J)}this.chains.delete(P)}releaseEntryRetainedPayload(P,J){if(P.kind==="snapshot"){if(this.frozenSnapshotBytes-=P.frozenBytes,this.retainedPayloadBytes-=P.frozenBytes,J)J.frozenSnapshotBytes-=P.frozenBytes,J.retainedPayloadBytes-=P.frozenBytes;return}if(P.kind==="catalog"){if(this.retainedPayloadBytes-=P.boundaryBytes,J)J.retainedPayloadBytes-=P.boundaryBytes}this.releaseCachedResult(P,J)}releaseCachedResult(P,J){if(P.cachedResultBytes===0){P.cachedResult=void 0;return}if(this.retainedPayloadBytes-=P.cachedResultBytes,J)J.retainedPayloadBytes-=P.cachedResultBytes;P.cachedResult=void 0,P.cachedResultBytes=0}assertAvailable(){if(this.closed)throw _()}}function E(P){if(P.startsWith(D.catalog))return"catalog";if(P.startsWith(D.history))return"history";if(P.startsWith(D.snapshot))return"snapshot";return}function f(P){return P.kind!=="snapshot"&&P.activeLoad!==void 0}function _P(P){let J={idleTtlMs:P.idleTtlMs??NP,maxEntries:P.maxEntries??OP,maxChains:P.maxChains??jP,maxEntriesPerChain:P.maxEntriesPerChain??MP,maxFrozenSnapshotBytes:P.maxFrozenSnapshotBytes??HP};for(let Q of Object.values(J))if(!Number.isSafeInteger(Q)||Q<=0)throw Error("session surface cursor registry limits must be positive safe integers");return J}function _(){return new U("session_surface_unavailable")}function T(P){return B(W(P))}function W(P){try{return S(P,new Set)}catch{throw new U("session_surface_cursor_invalid")}}function S(P,J){if(P===null)return null;if(typeof P==="string"||typeof P==="boolean")return P;if(typeof P==="number"){if(!Number.isFinite(P))throw Error("invalid number");return P}if(typeof P>"u"||typeof P==="function"||typeof P==="symbol"||typeof P==="bigint")throw Error("invalid JSON type");if(!P||typeof P!=="object")throw Error("invalid JSON value");if(J.has(P))throw Error("cycle");J.add(P);try{if(Array.isArray(P)){let $=[];for(let G=0;G<P.length;G+=1){if(!(G in P))throw Error("sparse array");$.push(S(P[G],J))}return $}if(Object.getOwnPropertySymbols(P).length>0)throw Error("symbol keys");let Q=Object.getPrototypeOf(P);if(Q!==Object.prototype&&Q!==null)throw Error("non-plain object");let Z={};for(let $ of Object.keys(P)){let G=Reflect.get(P,$);if(G===void 0)throw Error("undefined object value");Z[$]=S(G,J)}return Z}finally{J.delete(P)}}function B(P){if(P===null)return"null";if(typeof P==="string"||typeof P==="number")return JSON.stringify(P);if(typeof P==="boolean")return P?"true":"false";if(Array.isArray(P))return`[${P.map((Q)=>B(Q)).join(",")}]`;return`{${Object.keys(P).sort().map((Q)=>`${JSON.stringify(Q)}:${B(P[Q])}`).join(",")}}`}function m(P,J={}){if(P===void 0){if(J.allowUndefined)return{value:void 0,bytes:0};throw new U("session_surface_cursor_invalid")}let Q=W(P);return{value:Q,bytes:Buffer.byteLength(B(Q),"utf8")}}import{createHash as C,randomBytes as F}from"node:crypto";import FP from"node:path";var YP=50,zP=100,AP=16,TP=1e4,DP=16777216;class z extends Error{code;retryable;constructor(P){let J=CP(P);super(J.message);this.code=P;this.name="SessionSurfaceServiceError",this.retryable=J.retryable}}class BP{database;registry;epoch;maxConcurrentOperations;activeControllers=new Set;activeOperations=new Set;closed=!1;closePromise;concurrentOperations=0;constructor(P={}){if(this.database=P.database,this.registry=P.cursorRegistry??new g(P.cursorRegistryOptions),this.epoch=P.epochSource?.()??`session-surface-epoch:${F(32).toString("base64url")}`,this.maxConcurrentOperations=P.maxConcurrentOperations??AP,!Number.isSafeInteger(this.maxConcurrentOperations)||this.maxConcurrentOperations<1||this.maxConcurrentOperations>256)throw Error("maxConcurrentOperations must be an integer from 1 to 256")}async listPage(P={}){return this.runOperation(async(J)=>{let Q=K(P.limit),Z=P.archived??!1,$={archived:Z,limit:Q,workspaceKind:P.workspaceKind??null},G=JSON.stringify([Z,P.workspaceKind??null]),Y=await this.requireDatabase();if(J.throwIfAborted(),!Y)return this.listFallbackPage($,G,J,P.cursor);if(await this.syncAllSurfaces(Y,J),P.cursor){let V=String(ZP(Y));return this.registry.redeemCatalogCursor({token:P.cursor,scopeKey:G,epoch:this.epoch,revision:V,request:$,loader:async({boundary:X})=>{let O=KP(X);return this.loadCatalogPage(Y,$,G,V,O,O.chainId,J)}})}return this.loadCatalogPage(Y,$,G,void 0,void 0,void 0,J)})}async open(P,J={}){return this.runOperation((Q)=>this.openInternal(P,J,Q))}async historyPage(P,J){return this.runOperation(async(Q)=>{let Z=I(P),$=K(J.limit);if(!J.cursor||!J.expectedSnapshot)throw new z("invalid_session_surface_request");let G=await this.requireDatabase();if(!G)return this.readFallbackHistoryPage(Z,J,Q);await this.syncForLocator(G,Z,Q);let Y=await this.resolveFromProjection(G,Z,Q),V=w(G,{sourceKind:Y.candidate.sourceKind,projectPath:Y.candidate.projectPath,sessionId:Y.candidate.sessionId,limit:1}),X=x(Z);await this.registry.assertSnapshotToken({token:J.expectedSnapshot,locatorDigest:X,transcriptFingerprint:V.transcriptFingerprint});let O={expectedSnapshot:J.expectedSnapshot,limit:$},j=await this.registry.redeemHistoryCursor({token:J.cursor,locatorDigest:X,transcriptFingerprint:V.transcriptFingerprint,request:O,loader:async({nextSequence:M})=>{let H=w(G,{sourceKind:Y.candidate.sourceKind,projectPath:Y.candidate.projectPath,sessionId:Y.candidate.sessionId,beforeSequence:M,limit:$});return this.publicHistoryPage({history:H,snapshot:J.expectedSnapshot,chainId:(await this.registry.assertSnapshotToken({token:J.expectedSnapshot,locatorDigest:X,transcriptFingerprint:V.transcriptFingerprint})).chainId,locatorDigest:X,limit:$})}});return A.parse(j)})}async fork(P){return this.runOperation(async(J)=>{let Q=I(P),Z=await this.requireDatabase(),$=Z?await this.resolveFromProjectionAfterSync(Z,Q,J):await this.resolveFallback(Q,J);if($.candidate.summary.archivedAt)throw new z("session_surface_read_only");J.throwIfAborted();let G=await N.forkSession(Q.sessionId,{sourceProjectPath:$.candidate.projectPath,targetProjectPath:$.candidate.projectPath,...$.remoteCandidate?{remote:{expectedDescriptor:$.remoteCandidate.descriptor}}:{}}),Y=$.remoteCandidate?{version:2,sessionId:G.sessionId,workspace:{kind:"acp-remote",workspaceRef:$.candidate.publicWorkspaceRef}}:{version:2,sessionId:G.sessionId,workspace:{kind:"local",projectPath:$.candidate.projectPath}};return Z?this.openInternal(Y,{},J):this.openFallback(Y,YP,J)})}async resolveFromProjectionAfterSync(P,J,Q){return await this.syncForLocator(P,J,Q),this.resolveFromProjection(P,J,Q)}async close(P){if(this.closePromise)return this.closePromise;this.closed=!0;for(let J of this.activeControllers)J.abort(new z("session_surface_unavailable"));return this.closePromise=Promise.allSettled([...this.activeOperations,this.registry.close()]).then(()=>{return}),this.closePromise}async openInternal(P,J={},Q){let Z=I(P),$=K(J.limit);if(J.cursor!==void 0||J.expectedSnapshot!==void 0)throw new z("invalid_session_surface_request");let G=await this.requireDatabase();if(!G)return this.openFallback(Z,$,Q);await this.syncForLocator(G,Z,Q);let Y=await this.resolveFromProjection(G,Z,Q),V=w(G,{sourceKind:Y.candidate.sourceKind,projectPath:Y.candidate.projectPath,sessionId:Y.candidate.sessionId,limit:$}),X=`history-chain:${F(16).toString("base64url")}`,O=x(Z),j=this.registry.issueSnapshotToken({chainId:X,locatorDigest:O,transcriptFingerprint:V.transcriptFingerprint}),M={session:this.toSummary(Y),history:this.publicHistoryPage({history:V,snapshot:j,chainId:X,locatorDigest:O,limit:$})};return p.parse(M)}runOperation(P){if(this.assertAvailable(),this.concurrentOperations>=this.maxConcurrentOperations)throw new z("session_surface_capacity");let J=new AbortController;this.activeControllers.add(J),this.concurrentOperations+=1;let Q;return Q=Promise.resolve().then(()=>P(J.signal)).then((Z)=>{if(J.signal.aborted||this.closed)throw new z("session_surface_unavailable");return Z}).catch((Z)=>{if(J.signal.aborted||this.closed)throw new z("session_surface_unavailable");throw kP(Z)}).finally(()=>{this.activeControllers.delete(J),this.activeOperations.delete(Q),this.concurrentOperations-=1}),this.activeOperations.add(Q),Q}async loadCatalogPage(P,J,Q,Z,$,G,Y){let V=$P(P,{archived:J.archived,limit:J.limit,...J.workspaceKind?{workspaceKind:J.workspaceKind}:{},...$?{boundary:$}:{}}),X=String(V.revision);if(Z!==void 0&&Z!==X)throw new z("session_surface_snapshot_changed");let O=G??`catalog-chain:${F(16).toString("base64url")}`,j={sessions:await Promise.all(V.sessions.map(async(M)=>this.toSummary(await this.resolveCandidate(M,Y)))),...V.nextBoundary?{nextCursor:this.registry.issueCatalogCursor({chainId:O,scopeKey:Q,epoch:this.epoch,revision:X,boundary:{...V.nextBoundary,chainId:O},request:J})}:{}};if(!V.nextBoundary)this.registry.completeChain(O);return y.parse(j)}publicHistoryPage(P){let J=h(P.history.messages,L()),Q={messages:J.messages,snapshot:P.snapshot,truncated:P.history.hasOlder||J.truncated||J.messages.some((Z)=>Z.truncated===!0),...P.history.hasOlder&&P.history.nextSequence!==void 0?{olderCursor:this.registry.issueHistoryCursor({chainId:P.chainId,locatorDigest:P.locatorDigest,transcriptFingerprint:P.history.transcriptFingerprint,nextSequence:P.history.nextSequence,snapshotToken:P.snapshot,request:{expectedSnapshot:P.snapshot,limit:P.limit}})}:{}};if(!P.history.hasOlder)this.registry.completeChain(P.chainId);return A.parse(Q)}async syncForLocator(P,J,Q){if(Q?.throwIfAborted(),J.workspace.kind==="local"){await N.findSessionMetadata(J.sessionId,J.workspace.projectPath),Q?.throwIfAborted(),await d(P,J.sessionId,J.workspace.projectPath,N.projectionDeriverForSearch(),void 0,"local",Q);return}await N.listValidatedRemoteSurfaceCandidates(Q),await l(P,N.projectionDeriverForSearch(),Q)}async syncAllSurfaces(P,J){let Q=N.projectionDeriverForSearch(),Z=await N.listValidatedLocalSurfaceCandidates(J),$=new Set(Z.map((Y)=>`${Y.projectPath}\x00${Y.sessionId}`)),G=P.prepare("SELECT project_path, session_id FROM sessions WHERE source_kind='local'").all();for(let Y of G)if(!$.has(`${Y.project_path}\x00${Y.session_id}`))JP(P,Y.session_id,Y.project_path,"local");for(let Y of Z)J?.throwIfAborted(),await d(P,Y.sessionId,Y.projectPath,Q,void 0,"local",J);await N.listValidatedRemoteSurfaceCandidates(J),await l(P,Q,J)}async listFallbackPage(P,J,Q,Z){if(Z)return this.registry.redeemCatalogCursor({token:Z,scopeKey:J,epoch:this.epoch,revision:"fallback",request:P,loader:async({boundary:G})=>{let Y=LP(G);return this.pageFallbackCatalog(Y.entries,P,J,Y.chainId)}});let $=await this.loadFallbackCatalog(P,Q);return this.pageFallbackCatalog($,P,J,`catalog-fallback:${F(16).toString("base64url")}`)}async loadFallbackCatalog(P,J){let Q=[];if(P.workspaceKind!=="acp-remote")for(let $ of await N.listValidatedLocalSurfaceCandidates(J)){J?.throwIfAborted();let Y=(await N.readValidatedLocalSurfaceSnapshot($.sessionId,$.projectPath,J)).summary;if(Boolean(Y.archivedAt)!==P.archived)continue;Q.push({locator:{version:2,sessionId:$.sessionId,workspace:{kind:"local",projectPath:$.projectPath}},summary:Y})}if(P.workspaceKind!=="local")for(let $ of await N.listValidatedRemoteSurfaceCandidates(J)){J?.throwIfAborted();let Y=(await N.readValidatedRemoteSurfaceSnapshot($,J)).summary;if(Boolean(Y.archivedAt)!==P.archived)continue;Q.push({locator:{version:2,sessionId:$.sessionId,workspace:{kind:"acp-remote",workspaceRef:$.workspaceRef}},summary:Y})}Q.sort(IP);let Z=Buffer.byteLength(JSON.stringify(Q));if(Q.length>TP||Z>DP)throw new z("session_surface_capacity");return Q}async pageFallbackCatalog(P,J,Q,Z){let $=P.slice(0,J.limit),G=P.slice($.length),V={sessions:$.map((X)=>R.parse({locator:X.locator,...X.summary,capabilities:X.locator.workspace.kind==="local"?UP(Boolean(X.summary.archivedAt)):RP(Boolean(X.summary.archivedAt))})),...G.length>0?{nextCursor:this.registry.issueCatalogCursor({chainId:Z,scopeKey:Q,epoch:this.epoch,revision:"fallback",boundary:{chainId:Z,entries:G},request:J})}:{}};if(G.length===0)this.registry.completeChain(Z);return y.parse(V)}async openFallback(P,J,Q){let Z=await this.resolveFallback(P,Q),$=Z.remoteCandidate?await N.readValidatedRemoteSurfaceSnapshot(Z.remoteCandidate,Q):await N.readValidatedLocalSurfaceSnapshot(Z.candidate.sessionId,Z.candidate.projectPath,Q),G=e($.entries,{...Z.remoteCandidate?r(Z.remoteCandidate.hostStateRoot,Z.remoteCandidate.descriptor):{privateRoots:[]},bladeStorageRoots:[o()]}),Y=h(G.slice(-J),L()),V=`history-fallback:${F(16).toString("base64url")}`,X=x(P),O=C("sha256").update(JSON.stringify($.entries)).digest("hex"),j=this.registry.issueSnapshotToken({chainId:V,locatorDigest:X,transcriptFingerprint:O,frozenSnapshot:G}),M={session:this.toSummary(Z),history:A.parse({messages:Y.messages,snapshot:j,truncated:Y.messages.length<G.length||Y.truncated||Y.messages.some((H)=>H.truncated===!0),...G.length>Y.messages.length&&Y.messages[0]?{olderCursor:this.registry.issueHistoryCursor({chainId:V,locatorDigest:X,transcriptFingerprint:O,nextSequence:v(Y.messages[0].id),snapshotToken:j,request:{expectedSnapshot:j,limit:J}})}:{}})};if(G.length<=Y.messages.length)this.registry.completeChain(V);return p.parse(M)}async readFallbackHistoryPage(P,J,Q){let Z=K(J.limit);if(!J.cursor||!J.expectedSnapshot)throw new z("invalid_session_surface_request");let $=x(P),G=await this.resolveFallback(P,Q),Y=G.remoteCandidate?await N.readValidatedRemoteSurfaceSnapshot(G.remoteCandidate,Q):await N.readValidatedLocalSurfaceSnapshot(G.candidate.sessionId,G.candidate.projectPath,Q),V=C("sha256").update(JSON.stringify(Y.entries)).digest("hex");await this.registry.assertSnapshotToken({token:J.expectedSnapshot,locatorDigest:$,transcriptFingerprint:V});let X={expectedSnapshot:J.expectedSnapshot,limit:Z};return this.registry.redeemHistoryCursor({token:J.cursor,locatorDigest:$,transcriptFingerprint:V,request:X,loader:async({nextSequence:O,frozenSnapshot:j})=>{let M=xP(j).filter((b)=>v(b.id)<O),H=h(M.slice(-Z),L()),u=await this.registry.assertSnapshotToken({token:J.expectedSnapshot,locatorDigest:$,transcriptFingerprint:V}),k=H.messages.length<M.length,VP={messages:H.messages,snapshot:J.expectedSnapshot,truncated:k||H.truncated||H.messages.some((b)=>b.truncated===!0),...k&&H.messages[0]?{olderCursor:this.registry.issueHistoryCursor({chainId:u.chainId,locatorDigest:$,transcriptFingerprint:V,nextSequence:v(H.messages[0].id),snapshotToken:J.expectedSnapshot,request:X})}:{}};if(!k)this.registry.completeChain(u.chainId);return A.parse(VP)}})}async resolveFallback(P,J){let Q=[];for(let G of[!1,!0]){let Y={archived:G,limit:zP,workspaceKind:P.workspace.kind};Q.push(...(await this.loadFallbackCatalog(Y,J)).filter((V)=>JSON.stringify(V.locator)===JSON.stringify(P)))}if(Q.length!==1)throw new z("session_surface_not_found");let Z=Q[0],$;if(P.workspace.kind==="acp-remote"){let G=P.workspace.workspaceRef;if($=(await N.listValidatedRemoteSurfaceCandidates(J)).find((Y)=>Y.sessionId===P.sessionId&&Y.workspaceRef===G),!$)throw new z("workspace_binding_mismatch")}return{candidate:{sourceKind:P.workspace.kind,projectPath:P.workspace.kind==="local"?P.workspace.projectPath:$.hostStateRoot,sessionId:P.sessionId,...P.workspace.kind==="acp-remote"?{publicWorkspaceRef:P.workspace.workspaceRef}:{},publicWorkspaceSortKey:"",surfaceDigest:i(Z),transcriptFingerprint:i(Z),lastMessageTime:Z.summary.lastMessageTime,sessionSortKey:"",summary:Z.summary},...$?{remoteCandidate:$}:{}}}async resolveFromProjection(P,J,Q){let Z=QP(P,J.sessionId).filter((G)=>J.workspace.kind==="local"?G.sourceKind==="local"&&G.projectPath===FP.resolve(J.workspace.projectPath):G.sourceKind==="acp-remote"&&G.publicWorkspaceRef===J.workspace.workspaceRef);if(Z.length!==1)throw new z(Z.length===0?"session_surface_not_found":"workspace_binding_mismatch");let $;if(J.workspace.kind==="acp-remote"){let G=J.workspace.workspaceRef;if($=(await N.listValidatedRemoteSurfaceCandidates(Q)).filter((Y)=>Y.sessionId===J.sessionId&&Y.workspaceRef===G),$.length===0)throw new z("workspace_binding_mismatch");if($.length>1)throw new z("session_surface_state_invalid")}return $?{candidate:Z[0],remoteCandidate:$[0]}:{candidate:Z[0]}}async resolveCandidate(P,J){if(P.sourceKind==="local")return{candidate:P};let Q=(await N.listValidatedRemoteSurfaceCandidates(J)).filter((Z)=>Z.sessionId===P.sessionId&&Z.workspaceRef===P.publicWorkspaceRef);if(Q.length!==1)throw new z(Q.length===0?"workspace_binding_mismatch":"session_surface_state_invalid");return{candidate:P,remoteCandidate:Q[0]}}toSummary(P){let J=P.candidate,Q=J.sourceKind==="local"?{version:2,sessionId:J.sessionId,workspace:{kind:"local",projectPath:J.projectPath}}:{version:2,sessionId:J.sessionId,workspace:{kind:"acp-remote",workspaceRef:J.publicWorkspaceRef}};return R.parse({locator:Q,...J.summary,capabilities:this.capabilitiesFor(P)})}capabilitiesFor(P){let J=P.candidate.summary.archivedAt!==void 0;if(!P.remoteCandidate)return{connection:"local",history:{read:!0,fork:!J},turn:J?{start:!1,reason:"archived"}:{start:!0},files:J?{readText:!1,writeText:!1,browse:"none",reason:"archived"}:{readText:!0,writeText:!0,browse:"tree"},terminal:J?{mode:"none",owner:"none",reason:"archived"}:{mode:"interactive",owner:"local"}};return{connection:GP.getRemoteSurfaceOwnerSnapshot(P.candidate.sessionId,P.remoteCandidate.descriptor).connection,history:{read:!0,fork:!J},turn:{start:!1,reason:J?"archived":"history-only"},files:{readText:!1,writeText:!1,browse:"none",reason:J?"archived":"history-only"},terminal:{mode:"none",owner:"none",reason:J?"archived":"history-only"}}}async requireDatabase(){if(this.database===null)return null;return this.database??await PP()}assertAvailable(){if(this.closed)throw new z("session_surface_unavailable")}}function K(P){let J=P??YP;if(!Number.isSafeInteger(J)||J<1||J>zP)throw new z("invalid_session_surface_request");return J}function I(P){try{let J=t.parse(P);if(!n(J.sessionId))throw Error("invalid");if(J.workspace.kind==="local"){if(s(J.workspace.projectPath)!==J.workspace.projectPath)throw Error("invalid")}return J}catch{throw new z("invalid_session_locator")}}function x(P){return C("sha256").update("session-surface-locator-v2\x00").update(JSON.stringify(P)).digest("hex")}function KP(P){if(!P||typeof P!=="object"||Array.isArray(P))throw new z("session_surface_cursor_invalid");let J=P;if(typeof J.lastMessageTime!=="string"||J.sourceKind!=="local"&&J.sourceKind!=="acp-remote"||typeof J.publicWorkspaceSortKey!=="string"||typeof J.sessionSortKey!=="string"||typeof J.chainId!=="string"||!J.chainId)throw new z("session_surface_cursor_invalid");return{lastMessageTime:J.lastMessageTime,sourceKind:J.sourceKind,publicWorkspaceSortKey:J.publicWorkspaceSortKey,sessionSortKey:J.sessionSortKey,chainId:J.chainId}}function h(P,J){let Q=[];for(let Z=P.length-1;Z>=0;Z-=1){let $=P[Z];if(!$)continue;let G=[$,...Q];if(Q.length>0&&Buffer.byteLength(JSON.stringify(G))>J)break;Q.unshift($)}return{messages:Q,truncated:Q.length<P.length}}function v(P){let J=/^surface-message:([0-9]+):/.exec(P),Q=J?Number(J[1]):Number.NaN;if(!Number.isSafeInteger(Q)||Q<=0)throw new z("session_surface_state_invalid");return Q}function xP(P){if(!Array.isArray(P))throw new z("session_surface_snapshot_changed");return P.map((J)=>{try{return a.parse(J)}catch{throw new z("session_surface_snapshot_changed")}})}function LP(P){if(!P||typeof P!=="object"||Array.isArray(P))throw new z("session_surface_cursor_invalid");let J=P;if(typeof J.chainId!=="string"||J.chainId.length===0||!Array.isArray(J.entries))throw new z("session_surface_cursor_invalid");let Q=J.entries.map((Z)=>{if(!Z||typeof Z!=="object"||Array.isArray(Z))throw new z("session_surface_cursor_invalid");let $=Z;return{locator:I($.locator),summary:wP($.summary)}});return{chainId:J.chainId,entries:Q}}function wP(P){let J={version:2,sessionId:"placeholder",workspace:{kind:"local",projectPath:"/"}},Q=R.parse({...P&&typeof P==="object"&&!Array.isArray(P)?P:{},locator:J,capabilities:UP(!1)}),{locator:Z,capabilities:$,...G}=Q;return G}function IP(P,J){if(P.summary.lastMessageTime>J.summary.lastMessageTime)return-1;if(P.summary.lastMessageTime<J.summary.lastMessageTime)return 1;if(P.locator.workspace.kind!==J.locator.workspace.kind)return P.locator.workspace.kind==="local"?-1:1;let Q=P.locator.workspace.kind==="local"?P.locator.workspace.projectPath:P.locator.workspace.workspaceRef,Z=J.locator.workspace.kind==="local"?J.locator.workspace.projectPath:J.locator.workspace.workspaceRef;if(Q<Z)return-1;if(Q>Z)return 1;return P.locator.sessionId<J.locator.sessionId?-1:P.locator.sessionId>J.locator.sessionId?1:0}function i(P){return C("sha256").update("session-surface-fallback-entry\x00").update(JSON.stringify(P)).digest("hex")}function UP(P){return{connection:"local",history:{read:!0,fork:!P},turn:P?{start:!1,reason:"archived"}:{start:!0},files:P?{readText:!1,writeText:!1,browse:"none",reason:"archived"}:{readText:!0,writeText:!0,browse:"tree"},terminal:P?{mode:"none",owner:"none",reason:"archived"}:{mode:"interactive",owner:"local"}}}function RP(P){return{connection:"offline",history:{read:!0,fork:!P},turn:{start:!1,reason:P?"archived":"history-only"},files:{readText:!1,writeText:!1,browse:"none",reason:P?"archived":"history-only"},terminal:{mode:"none",owner:"none",reason:P?"archived":"history-only"}}}function CP(P){if(P==="session_surface_cursor_invalid")return{message:"Session surface cursor is invalid",retryable:!1};if(P==="session_surface_snapshot_changed")return{message:"Session surface snapshot changed",retryable:!1};if(P==="session_surface_state_invalid")return{message:"Session surface state is invalid",retryable:!1};if(P==="session_surface_capability_unavailable")return{message:"Session surface capability is unavailable",retryable:!1};if(P==="session_surface_unavailable")return{message:"Session surface is unavailable",retryable:!0};if(P==="session_surface_not_found")return{message:"Session surface was not found",retryable:!1};if(P==="workspace_binding_mismatch")return{message:"Session workspace binding changed",retryable:!1};if(P==="session_surface_read_only")return{message:"Session surface is read only",retryable:!1};if(P==="session_surface_capacity")return{message:"Session surface capacity is exhausted",retryable:!0};if(P==="invalid_session_locator")return{message:"Session locator is invalid",retryable:!1};return{message:"Session surface request is invalid",retryable:!1}}function kP(P){if(P instanceof z)return P;if(P&&typeof P==="object"&&"code"in P&&typeof P.code==="string"){let J=P.code;if(J==="session_surface_cursor_invalid"||J==="session_surface_snapshot_changed"||J==="session_surface_capacity"||J==="session_surface_unavailable"||J==="session_surface_state_invalid")return new z(J);if(J==="acp_remote_workspace_state_invalid")return new z("session_surface_state_invalid")}return P instanceof Error?P:new z("session_surface_state_invalid")}
1
+ import{N as GP}from"./chunk-adjtgsqe.js";import{he as N}from"./chunk-saky5ntj.js";import{$e as JP,Oe as r,Pe as e,Se as L,Ue as PP,Xe as d,Ze as l,bf as QP,cf as ZP,df as $P,ef as w}from"./chunk-y5wngtz0.js";import{gf as t,hf as a,jf as R,lf as y,mf as A,of as p}from"./chunk-w33zjw8m.js";import{Pj as q}from"./chunk-j8hbddjp.js";import{Ak as n,fk as o,zk as s}from"./chunk-4wx5sya5.js";async function qP(){return q().listProviders()}async function EP(P){return q().listModels(P)}import{randomBytes as XP}from"node:crypto";var NP=600000,OP=2048,jP=64,MP=32,HP=67108864,WP=4,D={catalog:"session-surface-catalog:",history:"session-surface-history:",snapshot:"session-surface-snapshot:"},c={session_surface_cursor_invalid:{message:"session surface cursor is invalid",retryable:!1},session_surface_snapshot_changed:{message:"session surface snapshot changed",retryable:!1},session_surface_capacity:{message:"session surface cursor capacity exceeded",retryable:!0},session_surface_unavailable:{message:"session surface cursor registry is unavailable",retryable:!0}};class U extends Error{code;retryable;constructor(P){super(c[P].message);this.code=P;this.name="SessionSurfaceCursorRegistryError",this.retryable=c[P].retryable}}class g{now;tokenSource;tokenCollisionRetries;limitsValue;entries=new Map;chains=new Map;closed=!1;closePromise;totalIssues=0;activeLoads=0;frozenSnapshotBytes=0;retainedPayloadBytes=0;constructor(P={}){if(this.now=P.now??(()=>Date.now()),this.tokenSource=P.tokenSource??(()=>XP(32).toString("base64url")),this.tokenCollisionRetries=P.tokenCollisionRetries??WP,this.limitsValue=_P(P.limits??{}),!Number.isSafeInteger(this.tokenCollisionRetries)||this.tokenCollisionRetries<0)throw Error("tokenCollisionRetries must be a non-negative safe integer")}issueCatalogCursor(P){this.assertAvailable(),this.cleanup();let J=m(P.boundary);if(J.value===void 0)throw new U("session_surface_cursor_invalid");let Q=T(P.request);this.ensureCapacity({requestedEntries:1,requestedRetainedBytes:J.bytes,chainId:P.chainId});let Z=this.createToken("catalog"),$=this.now(),G=this.ensureChain(P.chainId,$),Y={token:Z,chainId:P.chainId,kind:"catalog",expiresAt:$+this.limitsValue.idleTtlMs,lastAccessAt:$,scopeKey:P.scopeKey,epoch:P.epoch,revision:P.revision,boundary:J.value,boundaryBytes:J.bytes,requestHash:Q,cachedResultBytes:0};return this.storeEntry(G,Y),this.retainedPayloadBytes+=J.bytes,G.retainedPayloadBytes+=J.bytes,Z}issueHistoryCursor(P){this.assertAvailable(),this.cleanup();let J=T(P.request),Q=this.assertSnapshotIssuableForHistory(P);this.ensureCapacity({requestedEntries:1,requestedRetainedBytes:0,chainId:P.chainId});let Z=this.createToken("history"),$=this.now(),G=this.ensureChain(P.chainId,$);this.touch(Q);let Y={token:Z,chainId:P.chainId,kind:"history",expiresAt:$+this.limitsValue.idleTtlMs,lastAccessAt:$,locatorDigest:P.locatorDigest,transcriptFingerprint:P.transcriptFingerprint,nextSequence:P.nextSequence,snapshotToken:P.snapshotToken,requestHash:J,cachedResultBytes:0};return this.storeEntry(G,Y),Z}issueSnapshotToken(P){this.assertAvailable(),this.cleanup();let J=P.frozenSnapshot===void 0?{value:void 0,bytes:0}:m(P.frozenSnapshot);this.ensureCapacity({requestedEntries:1,requestedRetainedBytes:J.bytes,chainId:P.chainId});let Q=this.createToken("snapshot"),Z=this.now(),$=this.ensureChain(P.chainId,Z),G={token:Q,chainId:P.chainId,kind:"snapshot",expiresAt:Z+this.limitsValue.idleTtlMs,lastAccessAt:Z,locatorDigest:P.locatorDigest,transcriptFingerprint:P.transcriptFingerprint,frozenBytes:J.bytes,frozenSnapshot:J.value};return this.storeEntry($,G),this.frozenSnapshotBytes+=J.bytes,this.retainedPayloadBytes+=J.bytes,$.frozenSnapshotBytes+=J.bytes,$.retainedPayloadBytes+=J.bytes,Q}async redeemCatalogCursor(P){this.assertAvailable(),this.cleanup();let J=this.getEntry(P.token,"catalog");if(J.scopeKey!==P.scopeKey)throw new U("session_surface_cursor_invalid");if(J.epoch!==P.epoch||J.revision!==P.revision)throw new U("session_surface_snapshot_changed");if(J.requestHash!==T(P.request))throw new U("session_surface_cursor_invalid");if(this.touch(J),J.cachedResult!==void 0)return W(J.cachedResult);if(J.activeLoad)return this.cloneActiveLoadResult(J.activeLoad);return this.startCatalogLoad(J,P.loader)}async redeemHistoryCursor(P){this.assertAvailable(),this.cleanup();let J=this.getEntry(P.token,"history");if(J.locatorDigest!==P.locatorDigest)throw new U("session_surface_snapshot_changed");if(J.transcriptFingerprint!==P.transcriptFingerprint)throw new U("session_surface_snapshot_changed");if(J.requestHash!==T(P.request))throw new U("session_surface_cursor_invalid");let Q=this.resolveHistorySnapshot(J);if(this.touch(J),this.touch(Q),J.cachedResult!==void 0)return W(J.cachedResult);if(J.activeLoad)return this.cloneActiveLoadResult(J.activeLoad);return this.startHistoryLoad(J,Q,P.loader)}async assertSnapshotToken(P){this.assertAvailable(),this.cleanup();let J=this.getEntry(P.token,"snapshot");if(J.locatorDigest!==P.locatorDigest)throw new U("session_surface_cursor_invalid");if(J.transcriptFingerprint!==P.transcriptFingerprint)throw new U("session_surface_snapshot_changed");return this.touch(J),{chainId:J.chainId,locatorDigest:J.locatorDigest,transcriptFingerprint:J.transcriptFingerprint,frozenBytes:J.frozenBytes,frozenSnapshot:J.frozenSnapshot===void 0?void 0:W(J.frozenSnapshot)}}completeChain(P){this.cleanup();let J=this.chains.get(P);if(!J)return;J.completed=!0,J.lastAccessAt=this.now()}stats(){this.cleanup();let P=0;for(let J of this.chains.values())if(J.completed)P+=1;return{closed:this.closed,chainCount:this.chains.size,activeChains:this.chains.size-P,completedChains:P,entryCount:this.entries.size,activeLoads:this.activeLoads,frozenSnapshotBytes:this.frozenSnapshotBytes,retainedPayloadBytes:this.retainedPayloadBytes,totalIssues:this.totalIssues,limits:{...this.limitsValue}}}async close(P){if(this.closePromise)return this.closePromise;this.closed=!0;let J=[];for(let Q of this.entries.values())if((Q.kind==="catalog"||Q.kind==="history")&&Q.activeLoad)J.push(Q.activeLoad.promise),Q.activeLoad.controller.abort(_());return this.closePromise=Promise.allSettled(J).then(()=>{this.entries.clear(),this.chains.clear(),this.activeLoads=0,this.frozenSnapshotBytes=0,this.retainedPayloadBytes=0}),this.closePromise}startCatalogLoad(P,J){let Q=this.requireChain(P.chainId),Z=new AbortController;this.activeLoads+=1,Q.activeLoads+=1;let $=Promise.resolve().then(()=>J({boundary:W(P.boundary)},Z.signal)).then((G)=>{return this.assertLoadAvailable(Z.signal),this.admitCachedResult(P,G)}).catch((G)=>{if(this.closed||Z.signal.aborted)throw _();throw G}).finally(()=>{P.activeLoad=void 0,this.activeLoads-=1,Q.activeLoads-=1});return P.activeLoad={controller:Z,promise:$},this.cloneActiveLoadResult(P.activeLoad)}startHistoryLoad(P,J,Q){let Z=this.requireChain(P.chainId),$=new AbortController;this.activeLoads+=1,Z.activeLoads+=1;let G=Promise.resolve().then(()=>Q({nextSequence:P.nextSequence,frozenSnapshot:J.frozenSnapshot===void 0?void 0:W(J.frozenSnapshot)},$.signal)).then((Y)=>{return this.assertLoadAvailable($.signal),this.admitCachedResult(P,Y)}).catch((Y)=>{if(this.closed||$.signal.aborted)throw _();throw Y}).finally(()=>{P.activeLoad=void 0,this.activeLoads-=1,Z.activeLoads-=1});return P.activeLoad={controller:$,promise:G},this.cloneActiveLoadResult(P.activeLoad)}resolveHistorySnapshot(P){let J=P.snapshotToken;if(E(J)!=="snapshot")throw new U("session_surface_snapshot_changed");let Q=this.entries.get(J);if(!Q||Q.kind!=="snapshot")throw new U("session_surface_snapshot_changed");if(Q.expiresAt<=this.now())throw this.removeEntry(Q),new U("session_surface_snapshot_changed");if(Q.locatorDigest!==P.locatorDigest||Q.transcriptFingerprint!==P.transcriptFingerprint)throw new U("session_surface_snapshot_changed");return Q}assertSnapshotIssuableForHistory(P){let J=P.snapshotToken;if(E(J)!=="snapshot")throw new U("session_surface_snapshot_changed");let Q=this.entries.get(J);if(!Q||Q.kind!=="snapshot")throw new U("session_surface_snapshot_changed");if(Q.expiresAt<=this.now())throw this.removeEntry(Q),new U("session_surface_snapshot_changed");if(Q.chainId!==P.chainId||Q.locatorDigest!==P.locatorDigest||Q.transcriptFingerprint!==P.transcriptFingerprint)throw new U("session_surface_snapshot_changed");return Q}requireChain(P){let J=this.chains.get(P);if(!J)throw new U("session_surface_cursor_invalid");return J}assertLoadAvailable(P){if(this.closed||P.aborted)throw _()}getEntry(P,J){if(E(P)!==J)throw new U("session_surface_cursor_invalid");let Z=this.entries.get(P);if(!Z)throw new U("session_surface_cursor_invalid");if(Z.kind!==J)throw new U("session_surface_cursor_invalid");if(Z.expiresAt<=this.now()&&!f(Z))throw this.removeEntry(Z),new U("session_surface_cursor_invalid");return Z}touch(P){let J=this.now();P.lastAccessAt=J,P.expiresAt=J+this.limitsValue.idleTtlMs;let Q=this.chains.get(P.chainId);if(Q)Q.lastAccessAt=J}storeEntry(P,J){if(P.tokens.size>=this.limitsValue.maxEntriesPerChain)throw new U("session_surface_capacity");this.entries.set(J.token,J),P.tokens.add(J.token),P.completed=!1,P.lastAccessAt=J.lastAccessAt,P.issueCount+=1,this.totalIssues+=1}ensureChain(P,J){let Q=this.chains.get(P);if(Q)return Q.lastAccessAt=J,Q;let Z={chainId:P,tokens:new Set,completed:!1,lastAccessAt:J,issueCount:0,activeLoads:0,frozenSnapshotBytes:0,retainedPayloadBytes:0};return this.chains.set(P,Z),Z}cloneActiveLoadResult(P){return P.promise.then((J)=>W(J))}admitCachedResult(P,J){let Q=m(J),Z=this.requireChain(P.chainId),$=Q.bytes-P.cachedResultBytes;if(this.ensureCapacity({requestedEntries:0,requestedRetainedBytes:Math.max(0,$),chainId:P.chainId}),this.releaseCachedResult(P,Z),Q.value===void 0)throw new U("session_surface_cursor_invalid");return P.cachedResult=Q.value,P.cachedResultBytes=Q.bytes,this.retainedPayloadBytes+=Q.bytes,Z.retainedPayloadBytes+=Q.bytes,P.cachedResult}createToken(P){let J=D[P];for(let Q=0;Q<=this.tokenCollisionRetries;Q+=1){this.assertAvailable();let Z=`${J}${this.tokenSource()}`;if(!this.entries.has(Z))return Z}throw new U("session_surface_capacity")}ensureCapacity(P){this.reclaimCompletedChains(P);let J=this.entries.size+P.requestedEntries,Q=this.chains.size+(this.chains.has(P.chainId)?0:1),Z=this.retainedPayloadBytes+P.requestedRetainedBytes,$=(this.chains.get(P.chainId)?.tokens.size??0)+P.requestedEntries;if(J>this.limitsValue.maxEntries||Q>this.limitsValue.maxChains||$>this.limitsValue.maxEntriesPerChain||Z>this.limitsValue.maxFrozenSnapshotBytes)throw new U("session_surface_capacity")}reclaimCompletedChains(P){let J=[...this.chains.values()].filter((Q)=>Q.completed&&Q.activeLoads===0).sort((Q,Z)=>Q.lastAccessAt-Z.lastAccessAt);for(let Q of J){if(!(this.entries.size+P.requestedEntries>this.limitsValue.maxEntries||this.chains.size+(P.chainId!==""&&this.chains.has(P.chainId)?0:1)>this.limitsValue.maxChains||this.retainedPayloadBytes+P.requestedRetainedBytes>this.limitsValue.maxFrozenSnapshotBytes))break;this.removeChain(Q.chainId)}}cleanup(){let P=this.now();for(let J of[...this.entries.values()]){if(J.expiresAt>P||f(J))continue;this.removeEntry(J)}for(let J of[...this.chains.values()])if(J.tokens.size===0&&J.activeLoads===0)this.chains.delete(J.chainId)}removeEntry(P){this.entries.delete(P.token);let J=this.chains.get(P.chainId);if(J){if(J.tokens.delete(P.token),this.releaseEntryRetainedPayload(P,J),J.tokens.size===0&&J.activeLoads===0)this.chains.delete(J.chainId)}else this.releaseEntryRetainedPayload(P)}removeChain(P){let J=this.chains.get(P);if(!J)return;for(let Q of J.tokens){let Z=this.entries.get(Q);if(!Z||f(Z))continue;this.entries.delete(Q),this.releaseEntryRetainedPayload(Z,J)}this.chains.delete(P)}releaseEntryRetainedPayload(P,J){if(P.kind==="snapshot"){if(this.frozenSnapshotBytes-=P.frozenBytes,this.retainedPayloadBytes-=P.frozenBytes,J)J.frozenSnapshotBytes-=P.frozenBytes,J.retainedPayloadBytes-=P.frozenBytes;return}if(P.kind==="catalog"){if(this.retainedPayloadBytes-=P.boundaryBytes,J)J.retainedPayloadBytes-=P.boundaryBytes}this.releaseCachedResult(P,J)}releaseCachedResult(P,J){if(P.cachedResultBytes===0){P.cachedResult=void 0;return}if(this.retainedPayloadBytes-=P.cachedResultBytes,J)J.retainedPayloadBytes-=P.cachedResultBytes;P.cachedResult=void 0,P.cachedResultBytes=0}assertAvailable(){if(this.closed)throw _()}}function E(P){if(P.startsWith(D.catalog))return"catalog";if(P.startsWith(D.history))return"history";if(P.startsWith(D.snapshot))return"snapshot";return}function f(P){return P.kind!=="snapshot"&&P.activeLoad!==void 0}function _P(P){let J={idleTtlMs:P.idleTtlMs??NP,maxEntries:P.maxEntries??OP,maxChains:P.maxChains??jP,maxEntriesPerChain:P.maxEntriesPerChain??MP,maxFrozenSnapshotBytes:P.maxFrozenSnapshotBytes??HP};for(let Q of Object.values(J))if(!Number.isSafeInteger(Q)||Q<=0)throw Error("session surface cursor registry limits must be positive safe integers");return J}function _(){return new U("session_surface_unavailable")}function T(P){return B(W(P))}function W(P){try{return S(P,new Set)}catch{throw new U("session_surface_cursor_invalid")}}function S(P,J){if(P===null)return null;if(typeof P==="string"||typeof P==="boolean")return P;if(typeof P==="number"){if(!Number.isFinite(P))throw Error("invalid number");return P}if(typeof P>"u"||typeof P==="function"||typeof P==="symbol"||typeof P==="bigint")throw Error("invalid JSON type");if(!P||typeof P!=="object")throw Error("invalid JSON value");if(J.has(P))throw Error("cycle");J.add(P);try{if(Array.isArray(P)){let $=[];for(let G=0;G<P.length;G+=1){if(!(G in P))throw Error("sparse array");$.push(S(P[G],J))}return $}if(Object.getOwnPropertySymbols(P).length>0)throw Error("symbol keys");let Q=Object.getPrototypeOf(P);if(Q!==Object.prototype&&Q!==null)throw Error("non-plain object");let Z={};for(let $ of Object.keys(P)){let G=Reflect.get(P,$);if(G===void 0)throw Error("undefined object value");Z[$]=S(G,J)}return Z}finally{J.delete(P)}}function B(P){if(P===null)return"null";if(typeof P==="string"||typeof P==="number")return JSON.stringify(P);if(typeof P==="boolean")return P?"true":"false";if(Array.isArray(P))return`[${P.map((Q)=>B(Q)).join(",")}]`;return`{${Object.keys(P).sort().map((Q)=>`${JSON.stringify(Q)}:${B(P[Q])}`).join(",")}}`}function m(P,J={}){if(P===void 0){if(J.allowUndefined)return{value:void 0,bytes:0};throw new U("session_surface_cursor_invalid")}let Q=W(P);return{value:Q,bytes:Buffer.byteLength(B(Q),"utf8")}}import{createHash as C,randomBytes as F}from"node:crypto";import FP from"node:path";var YP=50,zP=100,AP=16,TP=1e4,DP=16777216;class z extends Error{code;retryable;constructor(P){let J=CP(P);super(J.message);this.code=P;this.name="SessionSurfaceServiceError",this.retryable=J.retryable}}class BP{database;registry;epoch;maxConcurrentOperations;activeControllers=new Set;activeOperations=new Set;closed=!1;closePromise;concurrentOperations=0;constructor(P={}){if(this.database=P.database,this.registry=P.cursorRegistry??new g(P.cursorRegistryOptions),this.epoch=P.epochSource?.()??`session-surface-epoch:${F(32).toString("base64url")}`,this.maxConcurrentOperations=P.maxConcurrentOperations??AP,!Number.isSafeInteger(this.maxConcurrentOperations)||this.maxConcurrentOperations<1||this.maxConcurrentOperations>256)throw Error("maxConcurrentOperations must be an integer from 1 to 256")}async listPage(P={}){return this.runOperation(async(J)=>{let Q=K(P.limit),Z=P.archived??!1,$={archived:Z,limit:Q,workspaceKind:P.workspaceKind??null},G=JSON.stringify([Z,P.workspaceKind??null]),Y=await this.requireDatabase();if(J.throwIfAborted(),!Y)return this.listFallbackPage($,G,J,P.cursor);if(await this.syncAllSurfaces(Y,J),P.cursor){let V=String(ZP(Y));return this.registry.redeemCatalogCursor({token:P.cursor,scopeKey:G,epoch:this.epoch,revision:V,request:$,loader:async({boundary:X})=>{let O=KP(X);return this.loadCatalogPage(Y,$,G,V,O,O.chainId,J)}})}return this.loadCatalogPage(Y,$,G,void 0,void 0,void 0,J)})}async open(P,J={}){return this.runOperation((Q)=>this.openInternal(P,J,Q))}async historyPage(P,J){return this.runOperation(async(Q)=>{let Z=I(P),$=K(J.limit);if(!J.cursor||!J.expectedSnapshot)throw new z("invalid_session_surface_request");let G=await this.requireDatabase();if(!G)return this.readFallbackHistoryPage(Z,J,Q);await this.syncForLocator(G,Z,Q);let Y=await this.resolveFromProjection(G,Z,Q),V=w(G,{sourceKind:Y.candidate.sourceKind,projectPath:Y.candidate.projectPath,sessionId:Y.candidate.sessionId,limit:1}),X=x(Z);await this.registry.assertSnapshotToken({token:J.expectedSnapshot,locatorDigest:X,transcriptFingerprint:V.transcriptFingerprint});let O={expectedSnapshot:J.expectedSnapshot,limit:$},j=await this.registry.redeemHistoryCursor({token:J.cursor,locatorDigest:X,transcriptFingerprint:V.transcriptFingerprint,request:O,loader:async({nextSequence:M})=>{let H=w(G,{sourceKind:Y.candidate.sourceKind,projectPath:Y.candidate.projectPath,sessionId:Y.candidate.sessionId,beforeSequence:M,limit:$});return this.publicHistoryPage({history:H,snapshot:J.expectedSnapshot,chainId:(await this.registry.assertSnapshotToken({token:J.expectedSnapshot,locatorDigest:X,transcriptFingerprint:V.transcriptFingerprint})).chainId,locatorDigest:X,limit:$})}});return A.parse(j)})}async fork(P){return this.runOperation(async(J)=>{let Q=I(P),Z=await this.requireDatabase(),$=Z?await this.resolveFromProjectionAfterSync(Z,Q,J):await this.resolveFallback(Q,J);if($.candidate.summary.archivedAt)throw new z("session_surface_read_only");J.throwIfAborted();let G=await N.forkSession(Q.sessionId,{sourceProjectPath:$.candidate.projectPath,targetProjectPath:$.candidate.projectPath,...$.remoteCandidate?{remote:{expectedDescriptor:$.remoteCandidate.descriptor}}:{}}),Y=$.remoteCandidate?{version:2,sessionId:G.sessionId,workspace:{kind:"acp-remote",workspaceRef:$.candidate.publicWorkspaceRef}}:{version:2,sessionId:G.sessionId,workspace:{kind:"local",projectPath:$.candidate.projectPath}};return Z?this.openInternal(Y,{},J):this.openFallback(Y,YP,J)})}async resolveFromProjectionAfterSync(P,J,Q){return await this.syncForLocator(P,J,Q),this.resolveFromProjection(P,J,Q)}async close(P){if(this.closePromise)return this.closePromise;this.closed=!0;for(let J of this.activeControllers)J.abort(new z("session_surface_unavailable"));return this.closePromise=Promise.allSettled([...this.activeOperations,this.registry.close()]).then(()=>{return}),this.closePromise}async openInternal(P,J={},Q){let Z=I(P),$=K(J.limit);if(J.cursor!==void 0||J.expectedSnapshot!==void 0)throw new z("invalid_session_surface_request");let G=await this.requireDatabase();if(!G)return this.openFallback(Z,$,Q);await this.syncForLocator(G,Z,Q);let Y=await this.resolveFromProjection(G,Z,Q),V=w(G,{sourceKind:Y.candidate.sourceKind,projectPath:Y.candidate.projectPath,sessionId:Y.candidate.sessionId,limit:$}),X=`history-chain:${F(16).toString("base64url")}`,O=x(Z),j=this.registry.issueSnapshotToken({chainId:X,locatorDigest:O,transcriptFingerprint:V.transcriptFingerprint}),M={session:this.toSummary(Y),history:this.publicHistoryPage({history:V,snapshot:j,chainId:X,locatorDigest:O,limit:$})};return p.parse(M)}runOperation(P){if(this.assertAvailable(),this.concurrentOperations>=this.maxConcurrentOperations)throw new z("session_surface_capacity");let J=new AbortController;this.activeControllers.add(J),this.concurrentOperations+=1;let Q;return Q=Promise.resolve().then(()=>P(J.signal)).then((Z)=>{if(J.signal.aborted||this.closed)throw new z("session_surface_unavailable");return Z}).catch((Z)=>{if(J.signal.aborted||this.closed)throw new z("session_surface_unavailable");throw kP(Z)}).finally(()=>{this.activeControllers.delete(J),this.activeOperations.delete(Q),this.concurrentOperations-=1}),this.activeOperations.add(Q),Q}async loadCatalogPage(P,J,Q,Z,$,G,Y){let V=$P(P,{archived:J.archived,limit:J.limit,...J.workspaceKind?{workspaceKind:J.workspaceKind}:{},...$?{boundary:$}:{}}),X=String(V.revision);if(Z!==void 0&&Z!==X)throw new z("session_surface_snapshot_changed");let O=G??`catalog-chain:${F(16).toString("base64url")}`,j={sessions:await Promise.all(V.sessions.map(async(M)=>this.toSummary(await this.resolveCandidate(M,Y)))),...V.nextBoundary?{nextCursor:this.registry.issueCatalogCursor({chainId:O,scopeKey:Q,epoch:this.epoch,revision:X,boundary:{...V.nextBoundary,chainId:O},request:J})}:{}};if(!V.nextBoundary)this.registry.completeChain(O);return y.parse(j)}publicHistoryPage(P){let J=h(P.history.messages,L()),Q={messages:J.messages,snapshot:P.snapshot,truncated:P.history.hasOlder||J.truncated||J.messages.some((Z)=>Z.truncated===!0),...P.history.hasOlder&&P.history.nextSequence!==void 0?{olderCursor:this.registry.issueHistoryCursor({chainId:P.chainId,locatorDigest:P.locatorDigest,transcriptFingerprint:P.history.transcriptFingerprint,nextSequence:P.history.nextSequence,snapshotToken:P.snapshot,request:{expectedSnapshot:P.snapshot,limit:P.limit}})}:{}};if(!P.history.hasOlder)this.registry.completeChain(P.chainId);return A.parse(Q)}async syncForLocator(P,J,Q){if(Q?.throwIfAborted(),J.workspace.kind==="local"){await N.findSessionMetadata(J.sessionId,J.workspace.projectPath),Q?.throwIfAborted(),await d(P,J.sessionId,J.workspace.projectPath,N.projectionDeriverForSearch(),void 0,"local",Q);return}await N.listValidatedRemoteSurfaceCandidates(Q),await l(P,N.projectionDeriverForSearch(),Q)}async syncAllSurfaces(P,J){let Q=N.projectionDeriverForSearch(),Z=await N.listValidatedLocalSurfaceCandidates(J),$=new Set(Z.map((Y)=>`${Y.projectPath}\x00${Y.sessionId}`)),G=P.prepare("SELECT project_path, session_id FROM sessions WHERE source_kind='local'").all();for(let Y of G)if(!$.has(`${Y.project_path}\x00${Y.session_id}`))JP(P,Y.session_id,Y.project_path,"local");for(let Y of Z)J?.throwIfAborted(),await d(P,Y.sessionId,Y.projectPath,Q,void 0,"local",J);await N.listValidatedRemoteSurfaceCandidates(J),await l(P,Q,J)}async listFallbackPage(P,J,Q,Z){if(Z)return this.registry.redeemCatalogCursor({token:Z,scopeKey:J,epoch:this.epoch,revision:"fallback",request:P,loader:async({boundary:G})=>{let Y=LP(G);return this.pageFallbackCatalog(Y.entries,P,J,Y.chainId)}});let $=await this.loadFallbackCatalog(P,Q);return this.pageFallbackCatalog($,P,J,`catalog-fallback:${F(16).toString("base64url")}`)}async loadFallbackCatalog(P,J){let Q=[];if(P.workspaceKind!=="acp-remote")for(let $ of await N.listValidatedLocalSurfaceCandidates(J)){J?.throwIfAborted();let Y=(await N.readValidatedLocalSurfaceSnapshot($.sessionId,$.projectPath,J)).summary;if(Boolean(Y.archivedAt)!==P.archived)continue;Q.push({locator:{version:2,sessionId:$.sessionId,workspace:{kind:"local",projectPath:$.projectPath}},summary:Y})}if(P.workspaceKind!=="local")for(let $ of await N.listValidatedRemoteSurfaceCandidates(J)){J?.throwIfAborted();let Y=(await N.readValidatedRemoteSurfaceSnapshot($,J)).summary;if(Boolean(Y.archivedAt)!==P.archived)continue;Q.push({locator:{version:2,sessionId:$.sessionId,workspace:{kind:"acp-remote",workspaceRef:$.workspaceRef}},summary:Y})}Q.sort(IP);let Z=Buffer.byteLength(JSON.stringify(Q));if(Q.length>TP||Z>DP)throw new z("session_surface_capacity");return Q}async pageFallbackCatalog(P,J,Q,Z){let $=P.slice(0,J.limit),G=P.slice($.length),V={sessions:$.map((X)=>R.parse({locator:X.locator,...X.summary,capabilities:X.locator.workspace.kind==="local"?UP(Boolean(X.summary.archivedAt)):RP(Boolean(X.summary.archivedAt))})),...G.length>0?{nextCursor:this.registry.issueCatalogCursor({chainId:Z,scopeKey:Q,epoch:this.epoch,revision:"fallback",boundary:{chainId:Z,entries:G},request:J})}:{}};if(G.length===0)this.registry.completeChain(Z);return y.parse(V)}async openFallback(P,J,Q){let Z=await this.resolveFallback(P,Q),$=Z.remoteCandidate?await N.readValidatedRemoteSurfaceSnapshot(Z.remoteCandidate,Q):await N.readValidatedLocalSurfaceSnapshot(Z.candidate.sessionId,Z.candidate.projectPath,Q),G=e($.entries,{...Z.remoteCandidate?r(Z.remoteCandidate.hostStateRoot,Z.remoteCandidate.descriptor):{privateRoots:[]},bladeStorageRoots:[o()]}),Y=h(G.slice(-J),L()),V=`history-fallback:${F(16).toString("base64url")}`,X=x(P),O=C("sha256").update(JSON.stringify($.entries)).digest("hex"),j=this.registry.issueSnapshotToken({chainId:V,locatorDigest:X,transcriptFingerprint:O,frozenSnapshot:G}),M={session:this.toSummary(Z),history:A.parse({messages:Y.messages,snapshot:j,truncated:Y.messages.length<G.length||Y.truncated||Y.messages.some((H)=>H.truncated===!0),...G.length>Y.messages.length&&Y.messages[0]?{olderCursor:this.registry.issueHistoryCursor({chainId:V,locatorDigest:X,transcriptFingerprint:O,nextSequence:v(Y.messages[0].id),snapshotToken:j,request:{expectedSnapshot:j,limit:J}})}:{}})};if(G.length<=Y.messages.length)this.registry.completeChain(V);return p.parse(M)}async readFallbackHistoryPage(P,J,Q){let Z=K(J.limit);if(!J.cursor||!J.expectedSnapshot)throw new z("invalid_session_surface_request");let $=x(P),G=await this.resolveFallback(P,Q),Y=G.remoteCandidate?await N.readValidatedRemoteSurfaceSnapshot(G.remoteCandidate,Q):await N.readValidatedLocalSurfaceSnapshot(G.candidate.sessionId,G.candidate.projectPath,Q),V=C("sha256").update(JSON.stringify(Y.entries)).digest("hex");await this.registry.assertSnapshotToken({token:J.expectedSnapshot,locatorDigest:$,transcriptFingerprint:V});let X={expectedSnapshot:J.expectedSnapshot,limit:Z};return this.registry.redeemHistoryCursor({token:J.cursor,locatorDigest:$,transcriptFingerprint:V,request:X,loader:async({nextSequence:O,frozenSnapshot:j})=>{let M=xP(j).filter((b)=>v(b.id)<O),H=h(M.slice(-Z),L()),u=await this.registry.assertSnapshotToken({token:J.expectedSnapshot,locatorDigest:$,transcriptFingerprint:V}),k=H.messages.length<M.length,VP={messages:H.messages,snapshot:J.expectedSnapshot,truncated:k||H.truncated||H.messages.some((b)=>b.truncated===!0),...k&&H.messages[0]?{olderCursor:this.registry.issueHistoryCursor({chainId:u.chainId,locatorDigest:$,transcriptFingerprint:V,nextSequence:v(H.messages[0].id),snapshotToken:J.expectedSnapshot,request:X})}:{}};if(!k)this.registry.completeChain(u.chainId);return A.parse(VP)}})}async resolveFallback(P,J){let Q=[];for(let G of[!1,!0]){let Y={archived:G,limit:zP,workspaceKind:P.workspace.kind};Q.push(...(await this.loadFallbackCatalog(Y,J)).filter((V)=>JSON.stringify(V.locator)===JSON.stringify(P)))}if(Q.length!==1)throw new z("session_surface_not_found");let Z=Q[0],$;if(P.workspace.kind==="acp-remote"){let G=P.workspace.workspaceRef;if($=(await N.listValidatedRemoteSurfaceCandidates(J)).find((Y)=>Y.sessionId===P.sessionId&&Y.workspaceRef===G),!$)throw new z("workspace_binding_mismatch")}return{candidate:{sourceKind:P.workspace.kind,projectPath:P.workspace.kind==="local"?P.workspace.projectPath:$.hostStateRoot,sessionId:P.sessionId,...P.workspace.kind==="acp-remote"?{publicWorkspaceRef:P.workspace.workspaceRef}:{},publicWorkspaceSortKey:"",surfaceDigest:i(Z),transcriptFingerprint:i(Z),lastMessageTime:Z.summary.lastMessageTime,sessionSortKey:"",summary:Z.summary},...$?{remoteCandidate:$}:{}}}async resolveFromProjection(P,J,Q){let Z=QP(P,J.sessionId).filter((G)=>J.workspace.kind==="local"?G.sourceKind==="local"&&G.projectPath===FP.resolve(J.workspace.projectPath):G.sourceKind==="acp-remote"&&G.publicWorkspaceRef===J.workspace.workspaceRef);if(Z.length!==1)throw new z(Z.length===0?"session_surface_not_found":"workspace_binding_mismatch");let $;if(J.workspace.kind==="acp-remote"){let G=J.workspace.workspaceRef;if($=(await N.listValidatedRemoteSurfaceCandidates(Q)).filter((Y)=>Y.sessionId===J.sessionId&&Y.workspaceRef===G),$.length===0)throw new z("workspace_binding_mismatch");if($.length>1)throw new z("session_surface_state_invalid")}return $?{candidate:Z[0],remoteCandidate:$[0]}:{candidate:Z[0]}}async resolveCandidate(P,J){if(P.sourceKind==="local")return{candidate:P};let Q=(await N.listValidatedRemoteSurfaceCandidates(J)).filter((Z)=>Z.sessionId===P.sessionId&&Z.workspaceRef===P.publicWorkspaceRef);if(Q.length!==1)throw new z(Q.length===0?"workspace_binding_mismatch":"session_surface_state_invalid");return{candidate:P,remoteCandidate:Q[0]}}toSummary(P){let J=P.candidate,Q=J.sourceKind==="local"?{version:2,sessionId:J.sessionId,workspace:{kind:"local",projectPath:J.projectPath}}:{version:2,sessionId:J.sessionId,workspace:{kind:"acp-remote",workspaceRef:J.publicWorkspaceRef}};return R.parse({locator:Q,...J.summary,capabilities:this.capabilitiesFor(P)})}capabilitiesFor(P){let J=P.candidate.summary.archivedAt!==void 0;if(!P.remoteCandidate)return{connection:"local",history:{read:!0,fork:!J},turn:J?{start:!1,reason:"archived"}:{start:!0},files:J?{readText:!1,writeText:!1,browse:"none",reason:"archived"}:{readText:!0,writeText:!0,browse:"tree"},terminal:J?{mode:"none",owner:"none",reason:"archived"}:{mode:"interactive",owner:"local"}};return{connection:GP.getRemoteSurfaceOwnerSnapshot(P.candidate.sessionId,P.remoteCandidate.descriptor).connection,history:{read:!0,fork:!J},turn:{start:!1,reason:J?"archived":"history-only"},files:{readText:!1,writeText:!1,browse:"none",reason:J?"archived":"history-only"},terminal:{mode:"none",owner:"none",reason:J?"archived":"history-only"}}}async requireDatabase(){if(this.database===null)return null;return this.database??await PP()}assertAvailable(){if(this.closed)throw new z("session_surface_unavailable")}}function K(P){let J=P??YP;if(!Number.isSafeInteger(J)||J<1||J>zP)throw new z("invalid_session_surface_request");return J}function I(P){try{let J=t.parse(P);if(!n(J.sessionId))throw Error("invalid");if(J.workspace.kind==="local"){if(s(J.workspace.projectPath)!==J.workspace.projectPath)throw Error("invalid")}return J}catch{throw new z("invalid_session_locator")}}function x(P){return C("sha256").update("session-surface-locator-v2\x00").update(JSON.stringify(P)).digest("hex")}function KP(P){if(!P||typeof P!=="object"||Array.isArray(P))throw new z("session_surface_cursor_invalid");let J=P;if(typeof J.lastMessageTime!=="string"||J.sourceKind!=="local"&&J.sourceKind!=="acp-remote"||typeof J.publicWorkspaceSortKey!=="string"||typeof J.sessionSortKey!=="string"||typeof J.chainId!=="string"||!J.chainId)throw new z("session_surface_cursor_invalid");return{lastMessageTime:J.lastMessageTime,sourceKind:J.sourceKind,publicWorkspaceSortKey:J.publicWorkspaceSortKey,sessionSortKey:J.sessionSortKey,chainId:J.chainId}}function h(P,J){let Q=[];for(let Z=P.length-1;Z>=0;Z-=1){let $=P[Z];if(!$)continue;let G=[$,...Q];if(Q.length>0&&Buffer.byteLength(JSON.stringify(G))>J)break;Q.unshift($)}return{messages:Q,truncated:Q.length<P.length}}function v(P){let J=/^surface-message:([0-9]+):/.exec(P),Q=J?Number(J[1]):Number.NaN;if(!Number.isSafeInteger(Q)||Q<=0)throw new z("session_surface_state_invalid");return Q}function xP(P){if(!Array.isArray(P))throw new z("session_surface_snapshot_changed");return P.map((J)=>{try{return a.parse(J)}catch{throw new z("session_surface_snapshot_changed")}})}function LP(P){if(!P||typeof P!=="object"||Array.isArray(P))throw new z("session_surface_cursor_invalid");let J=P;if(typeof J.chainId!=="string"||J.chainId.length===0||!Array.isArray(J.entries))throw new z("session_surface_cursor_invalid");let Q=J.entries.map((Z)=>{if(!Z||typeof Z!=="object"||Array.isArray(Z))throw new z("session_surface_cursor_invalid");let $=Z;return{locator:I($.locator),summary:wP($.summary)}});return{chainId:J.chainId,entries:Q}}function wP(P){let J={version:2,sessionId:"placeholder",workspace:{kind:"local",projectPath:"/"}},Q=R.parse({...P&&typeof P==="object"&&!Array.isArray(P)?P:{},locator:J,capabilities:UP(!1)}),{locator:Z,capabilities:$,...G}=Q;return G}function IP(P,J){if(P.summary.lastMessageTime>J.summary.lastMessageTime)return-1;if(P.summary.lastMessageTime<J.summary.lastMessageTime)return 1;if(P.locator.workspace.kind!==J.locator.workspace.kind)return P.locator.workspace.kind==="local"?-1:1;let Q=P.locator.workspace.kind==="local"?P.locator.workspace.projectPath:P.locator.workspace.workspaceRef,Z=J.locator.workspace.kind==="local"?J.locator.workspace.projectPath:J.locator.workspace.workspaceRef;if(Q<Z)return-1;if(Q>Z)return 1;return P.locator.sessionId<J.locator.sessionId?-1:P.locator.sessionId>J.locator.sessionId?1:0}function i(P){return C("sha256").update("session-surface-fallback-entry\x00").update(JSON.stringify(P)).digest("hex")}function UP(P){return{connection:"local",history:{read:!0,fork:!P},turn:P?{start:!1,reason:"archived"}:{start:!0},files:P?{readText:!1,writeText:!1,browse:"none",reason:"archived"}:{readText:!0,writeText:!0,browse:"tree"},terminal:P?{mode:"none",owner:"none",reason:"archived"}:{mode:"interactive",owner:"local"}}}function RP(P){return{connection:"offline",history:{read:!0,fork:!P},turn:{start:!1,reason:P?"archived":"history-only"},files:{readText:!1,writeText:!1,browse:"none",reason:P?"archived":"history-only"},terminal:{mode:"none",owner:"none",reason:P?"archived":"history-only"}}}function CP(P){if(P==="session_surface_cursor_invalid")return{message:"Session surface cursor is invalid",retryable:!1};if(P==="session_surface_snapshot_changed")return{message:"Session surface snapshot changed",retryable:!1};if(P==="session_surface_state_invalid")return{message:"Session surface state is invalid",retryable:!1};if(P==="session_surface_capability_unavailable")return{message:"Session surface capability is unavailable",retryable:!1};if(P==="session_surface_unavailable")return{message:"Session surface is unavailable",retryable:!0};if(P==="session_surface_not_found")return{message:"Session surface was not found",retryable:!1};if(P==="workspace_binding_mismatch")return{message:"Session workspace binding changed",retryable:!1};if(P==="session_surface_read_only")return{message:"Session surface is read only",retryable:!1};if(P==="session_surface_capacity")return{message:"Session surface capacity is exhausted",retryable:!0};if(P==="invalid_session_locator")return{message:"Session locator is invalid",retryable:!1};return{message:"Session surface request is invalid",retryable:!1}}function kP(P){if(P instanceof z)return P;if(P&&typeof P==="object"&&"code"in P&&typeof P.code==="string"){let J=P.code;if(J==="session_surface_cursor_invalid"||J==="session_surface_snapshot_changed"||J==="session_surface_capacity"||J==="session_surface_unavailable"||J==="session_surface_state_invalid")return new z(J);if(J==="acp_remote_workspace_state_invalid")return new z("session_surface_state_invalid")}return P instanceof Error?P:new z("session_surface_state_invalid")}
2
2
  export{qP as e,EP as f,g,z as h,BP as i};
@@ -1,2 +1,2 @@
1
- import{Xj as d,Zj as h}from"./chunk-rejsff7v.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"max-queued-task-bytes":{alias:["maxQueuedTaskBytes"],type:"number",describe:"Maximum retained bytes across queued top-level tasks",group:"AI Options:",default:void 0},"max-resident-session-runtimes":{alias:["maxResidentSessionRuntimes"],type:"number",describe:"Maximum initialized Session runtimes resident in this process",group:"AI Options:",default:void 0},"session-runtime-idle-ms":{alias:["sessionRuntimeIdleMs"],type:"number",describe:"Idle time before an evictable Web Session runtime is evicted",group:"AI Options:",default:void 0},"max-resident-session-projections":{alias:["maxResidentSessionProjections"],type:"number",describe:"Maximum resident Session projections retained in this process",group:"AI Options:",default:void 0},"session-projection-idle-ms":{alias:["sessionProjectionIdleMs"],type:"number",describe:"Idle time before an evictable Session projection is evicted",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
1
+ import{Xj as d,Zj as h}from"./chunk-6ke6p47w.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"max-queued-task-bytes":{alias:["maxQueuedTaskBytes"],type:"number",describe:"Maximum retained bytes across queued top-level tasks",group:"AI Options:",default:void 0},"max-resident-session-runtimes":{alias:["maxResidentSessionRuntimes"],type:"number",describe:"Maximum initialized Session runtimes resident in this process",group:"AI Options:",default:void 0},"session-runtime-idle-ms":{alias:["sessionRuntimeIdleMs"],type:"number",describe:"Idle time before an evictable Web Session runtime is evicted",group:"AI Options:",default:void 0},"max-resident-session-projections":{alias:["maxResidentSessionProjections"],type:"number",describe:"Maximum resident Session projections retained in this process",group:"AI Options:",default:void 0},"session-projection-idle-ms":{alias:["sessionProjectionIdleMs"],type:"number",describe:"Idle time before an evictable Session projection is evicted",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
2
2
  export{q as rf,w as sf};
@@ -1,4 +1,4 @@
1
- import{v as HH,w as JH}from"./chunk-0qtf9sss.js";import{A as S,x as Cz,y as fz,z as uz}from"./chunk-jn2j7fgw.js";import{B as zH,C as xz,D as bz,E as Rz,F as Sz,G as Mz}from"./chunk-mw0xx44s.js";import{Aa as Iz,Ba as yz,Ca as hz,Da as kz,N as R,W as Az,X as Oz,da as Ez,ga as qz,ha as Tz,ka as Pz}from"./chunk-26g3nrdr.js";import"./chunk-g01mth5d.js";import{Ra as ez}from"./chunk-teth5343.js";import{Ta as Nz,Xa as i,_a as a}from"./chunk-30x3mcsb.js";import{Nb as Kz,Zb as wz,hc as l}from"./chunk-f2qs07mx.js";import{sc as d}from"./chunk-zzvs471p.js";import{$d as Dz,Cd as Bz,Md as I,Nd as v,Od as Gz,Td as Vz,Wd as jz,Yd as M,ee as Fz,he as F}from"./chunk-3rrcg0es.js";import"./chunk-53fc0yrq.js";import{Fe as _z,Me as r,Ne as Uz}from"./chunk-y5wngtz0.js";import"./chunk-w33zjw8m.js";import{yf as LH}from"./chunk-20x62wa4.js";import"./chunk-jj4ggb04.js";import{Tf as oz,Uf as nz}from"./chunk-3cvycxre.js";import"./chunk-v508x7cg.js";import{dg as e}from"./chunk-t0gm0pn1.js";import{ig as Wz}from"./chunk-1yq72zb7.js";import{qg as m}from"./chunk-kqvzmnja.js";import"./chunk-0mr8nexh.js";import{vg as sz}from"./chunk-50vwafn5.js";import"./chunk-vep4e9bn.js";import"./chunk-38arrd1h.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import{rh as tz}from"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-m9jgeshx.js";import"./chunk-3y2x6fb6.js";import{ui as az,xi as rz}from"./chunk-962xet8h.js";import"./chunk-kv458q06.js";import{Vi as g,Wi as Xz,Yi as c,Zi as p}from"./chunk-5v0jcyea.js";import{bj as t}from"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import{Dj as y}from"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import{Qj as lz,Tj as iz}from"./chunk-4cdk4mds.js";import"./chunk-rejsff7v.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import{fk as $z,gk as dz,kk as zz,ok as Hz,pk as vz,qk as Jz}from"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";import{Readable as KH,Writable as wH}from"node:stream";import*as f from"@agentclientprotocol/sdk";import o from"node:path";import{PROTOCOL_VERSION as GH,RequestError as C}from"@agentclientprotocol/sdk";import{RequestError as gz}from"@agentclientprotocol/sdk";import{nanoid as u}from"nanoid";var G=y("Agent");function P(z){return Object.freeze({kind:"local",hostStateRoot:z,executionRoot:z,hostResourceRoot:z})}function Zz(z){if(!z)return{};return Object.fromEntries(z.map((H)=>[H.name,H.value]))}function ZH(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:Zz(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:Zz("headers"in z?z.headers:void 0)};return null}function $H(z){let H={};for(let L of z){let Y=ZH(L);if(Y)H[L.name]=Y}return H}function cz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((H)=>{if(H.type==="text")return H.text?[{type:"text",text:H.text}]:[];let L=H.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(L);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function XH(z){let H=Uz(z.metadata);return H?[{type:"text",text:r(H)}]:cz(z.content)}function WH(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
1
+ import{v as HH,w as JH}from"./chunk-e5qpgfa8.js";import{A as S,x as Cz,y as fz,z as uz}from"./chunk-txz3xnz5.js";import{B as zH,C as xz,D as bz,E as Rz,F as Sz,G as Mz}from"./chunk-9wq0504z.js";import{Aa as Iz,Ba as yz,Ca as hz,Da as kz,N as R,W as Az,X as Oz,da as Ez,ga as qz,ha as Tz,ka as Pz}from"./chunk-adjtgsqe.js";import"./chunk-g01mth5d.js";import{Ra as ez}from"./chunk-q599m0dn.js";import{Ta as Nz,Xa as i,_a as a}from"./chunk-30x3mcsb.js";import{Nb as Kz,Zb as wz,hc as l}from"./chunk-k6b013wk.js";import{sc as d}from"./chunk-zzvs471p.js";import{$d as Dz,Cd as Bz,Md as I,Nd as v,Od as Gz,Td as Vz,Wd as jz,Yd as M,ee as Fz,he as F}from"./chunk-saky5ntj.js";import"./chunk-53fc0yrq.js";import{Fe as _z,Me as r,Ne as Uz}from"./chunk-y5wngtz0.js";import"./chunk-w33zjw8m.js";import{yf as LH}from"./chunk-yt31g9xb.js";import"./chunk-jj4ggb04.js";import{Tf as oz,Uf as nz}from"./chunk-zxmy26da.js";import"./chunk-v508x7cg.js";import{dg as e}from"./chunk-t0gm0pn1.js";import{ig as Wz}from"./chunk-1yq72zb7.js";import{qg as m}from"./chunk-kqvzmnja.js";import"./chunk-0mr8nexh.js";import{vg as sz}from"./chunk-50vwafn5.js";import"./chunk-bf9ek9cw.js";import"./chunk-3zz9m825.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import{rh as tz}from"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-k4agcfcy.js";import"./chunk-3y2x6fb6.js";import{ui as az,xi as rz}from"./chunk-jv8hwxj9.js";import"./chunk-kv458q06.js";import{Vi as g,Wi as Xz,Yi as c,Zi as p}from"./chunk-5v0jcyea.js";import{bj as t}from"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import{Dj as y}from"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import{Qj as lz,Tj as iz}from"./chunk-4cdk4mds.js";import"./chunk-6ke6p47w.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import{fk as $z,gk as dz,kk as zz,ok as Hz,pk as vz,qk as Jz}from"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";import{Readable as KH,Writable as wH}from"node:stream";import*as f from"@agentclientprotocol/sdk";import o from"node:path";import{PROTOCOL_VERSION as GH,RequestError as C}from"@agentclientprotocol/sdk";import{RequestError as gz}from"@agentclientprotocol/sdk";import{nanoid as u}from"nanoid";var G=y("Agent");function P(z){return Object.freeze({kind:"local",hostStateRoot:z,executionRoot:z,hostResourceRoot:z})}function Zz(z){if(!z)return{};return Object.fromEntries(z.map((H)=>[H.name,H.value]))}function ZH(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:Zz(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:Zz("headers"in z?z.headers:void 0)};return null}function $H(z){let H={};for(let L of z){let Y=ZH(L);if(Y)H[L.name]=Y}return H}function cz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((H)=>{if(H.type==="text")return H.text?[{type:"text",text:H.text}]:[];let L=H.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(L);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function XH(z){let H=Uz(z.metadata);return H?[{type:"text",text:r(H)}]:cz(z.content)}function WH(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
2
2
  `)}function BH(z){if(!Wz(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...I("capacity"),resource:z.resource}}function _H(z){if(!(z instanceof gz)||!z.data||typeof z.data!=="object")return;let H=z.data;if(!Gz(H.taskFailure)||H.toolExecutionStarted!==!1||!Number.isInteger(H.toolCallsCount)||H.toolCallsCount<0||H.outputStarted!==!1)return;return{taskFailure:H.taskFailure,toolExecutionStarted:H.toolExecutionStarted,toolCallsCount:H.toolCallsCount,outputStarted:H.outputStarted}}function UH(z){return{version:z.version,pending:z.pending,mutable:z.mutable,locked:z.locked,internal:z.internal}}class x{id;roots;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingPromptCompletion=null;pendingUserShell=null;pendingUserShellCompletion=null;pendingSideConversation=null;pendingSideConversationCompletion=null;pendingResumeRequested=!1;pendingResumeAttempt=0;projectedPendingResumeInputIds=new Set;pendingResumeRecoveryStartedAt=0;pendingResumeInFlight=!1;pendingResumeScheduled=!1;pendingResumeGeneration=0;pendingResumeTimer=null;pendingResumeCompletion=null;pendingResumeNextDelayMs=null;availableCommandsTimer=null;taskStatusUnsubscribe;lastTurnActivityGeneration;lastTurnActivityRevision=-1;destroyed=!1;destroyFinished=!1;destroyPromise;serviceRegistration;messages;contextMessages;mode;updateEgress;constructor(z,H,L,Y,$={}){this.id=z;this.roots=H;this.connection=L;this.clientCapabilities=Y;this.options=$;this.messages=[...$.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode($.permissionMode),this.updateEgress=new Mz({maxPendingItems:xz,maxPendingBytes:bz,writeTimeoutMs:Rz,signal:L.signal,sizeOf:(X)=>Buffer.byteLength(JSON.stringify(X)),write:async(X)=>{await L.sessionUpdate(X)},onFailure:(X)=>this.handleUpdateEgressFailure(X)})}async refreshPersistedMessages(){let[z,H]=await Promise.all([this.loadPersistedMessages(),this.loadPersistedModelContext()]);if(z.length>0)this.messages=z;if(H.length>0)this.contextMessages=H}async loadModelContextOr(z){let H=await this.loadPersistedModelContext();return H.length>0?H:[...z]}loadPersistedMessages(){return this.roots.kind==="acp-remote"?F.loadRemoteSession(this.id,this.roots.hostStateRoot,this.roots.descriptor):F.loadSession(this.id,this.roots.hostStateRoot)}loadPersistedModelContext(){return this.roots.kind==="acp-remote"?F.loadRemoteSessionModelContext(this.id,this.roots.hostStateRoot,this.roots.descriptor):F.loadSessionModelContext(this.id,this.roots.hostStateRoot)}async persistMetadataUpdate(z,H=z){if(this.roots.kind==="acp-remote"){await F.updateRemoteSessionMetadata(this.id,this.roots.hostStateRoot,this.roots.descriptor,z);return}try{await F.updateSessionMetadata(this.id,this.roots.hostStateRoot,z)}catch(L){if(!(L instanceof Fz)&&L.code!=="ENOENT")throw L;await F.createSessionMetadata(this.id,this.roots.hostStateRoot,{taskStatus:"completed",...H})}}async persistPermissionMode(z){if(this.roots.kind==="acp-remote"){await F.updateRemoteSessionMetadata(this.id,this.roots.hostStateRoot,this.roots.descriptor,{permissionMode:z});return}await F.setSessionPermissionMode(this.id,this.roots.hostStateRoot,z)}mapPermissionModeToMode(z){switch(z){case"yolo":return"yolo";case"autoEdit":return"auto-edit";case"plan":return"plan";case"default":default:return"default"}}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return Pz.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){G.debug(`[AcpSession ${this.id}] Initializing...`),await this.persistPermissionMode(this.mapModeToPermissionMode()??"default");let z=R.initializeSession(this.connection,this.id,this.clientCapabilities,this.roots.executionRoot,async(Z)=>{await this.sendUpdateAndWait(Z)},this.roots.kind==="acp-remote"?this.roots.profile:void 0);if(z)this.serviceRegistration=z;if(G.debug(`[AcpSession ${this.id}] ACP service context initialized`),this.roots.kind==="local"?await l.resolvePendingWithHandler(this.roots.hostStateRoot,this.id,{requestConfirmation:(Z)=>this.requestPermission(Z)}):!1)await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let L=this.options.mcpServers?$H(this.options.mcpServers):void 0,Y=R.getInstance().getTerminalService(this.id),$=this.roots.kind==="acp-remote"?{kind:"acp-remote",executionRoot:this.roots.executionRoot,resourceRoot:this.roots.hostResourceRoot,readTextFile:this.clientCapabilities?.fs?.readTextFile===!0,writeTextFile:this.clientCapabilities?.fs?.writeTextFile===!0,terminal:this.clientCapabilities?.terminal===!0,descriptor:this.roots.descriptor}:void 0;if(this.runtime=await Ez.create({sessionId:this.id,workspaceRoot:this.roots.hostStateRoot,...$?{workspace:$}:{},permissionMode:this.mapModeToPermissionMode(),...L?{mcpServers:L}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async(Z,_)=>{let U=await Y.execute(Z,{cwd:_.cwd,env:_.env,timeout:_.timeoutMs,signal:_.signal,allowLocalFallback:!1,onOutput:(V)=>_.onOutput?.("stdout",V)});return{exitCode:U.exitCode,stdout:U.stdout,stderr:U.stderr,...U.error?{error:U.error}:{},timedOut:U.failureKind==="timeout",aborted:U.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),this.roots.kind==="local"?await S.recoverInterrupted(this.roots.hostStateRoot,this.id,this.runtime):!1)await this.refreshPersistedMessages();if(this.agent=await this.createAgent(),this.roots.kind==="local")await yz(this.roots.hostStateRoot);G.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=Kz.subscribe((Z)=>{if(Z.sessionId!==this.id||Z.projectPath!==this.roots.hostStateRoot)return;if(Z.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":Z.properties}}),this.requestPendingResume();return}if(Z.type==="follow_up.queue.changed"){let _=i.safeParse(Z.properties.queue);if(_.success)this.sendFollowUpQueueSnapshot(_.data);return}if(Z.type==="provider.recovery"){let _=m.safeParse(Z.properties.recovery);if(!_.success)return;this.sendProviderRecoveryProjection(_.data);return}if(Z.type==="turn.activity"){let _=a.safeParse(Z.properties.activity);if(!_.success)return;this.sendTurnActivityProjection(_.data);return}if(Z.type==="task.delivery"){if(!Z.properties.taskDelivery||typeof Z.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof Z.properties.updatedAt==="string"?Z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":Z.properties.taskDelivery,...Z.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(Z.type.startsWith("team.")){let{teamName:_,messageId:U,content:V}=Z.properties,T=Z.properties.metadata;if(Z.type==="team.message.received"&&typeof _==="string"&&typeof U==="string"&&typeof V==="string"&&Oz(T,{messageId:U,teamName:_}))(async()=>{let E=await this.runtime?.enqueueSteering(V,{allowBeforeTurn:!0,messageId:U,origin:"team_message",metadata:T});if(!E?.accepted)return;if(E.queue)this.sendFollowUpQueueSnapshot(E.queue);if(await new Az(_,$z()).markDelivered([U]),E.delivery==="next_turn")this.requestPendingResume()})().catch((E)=>{G.warn(`[AcpSession ${this.id}] Failed to deliver teammate message`,E)});this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/teamEvent":{type:Z.type,...Z.properties}}});return}if(Z.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof Z.properties.updatedAt==="string"?Z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":Z.properties.taskStatus,...typeof Z.properties.taskStatusReason==="string"?{"blade/taskStatusReason":Z.properties.taskStatusReason}:{},...Z.properties.taskFailure&&typeof Z.properties.taskFailure==="object"?{"blade/taskFailure":Z.properties.taskFailure}:{},...typeof Z.properties.taskStartedAt==="string"?{"blade/taskStartedAt":Z.properties.taskStartedAt}:{},...typeof Z.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":Z.properties.taskCompletedAt}:{},...Z.properties.taskDiffStat&&typeof Z.properties.taskDiffStat==="object"?{"blade/taskDiffStat":Z.properties.taskDiffStat}:{},...typeof Z.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":Z.properties.taskQueuePosition}:{},...typeof Z.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":Z.properties.taskQueueDepth}:{},...typeof Z.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":Z.properties.taskConcurrencyLimit}:{},...typeof Z.properties.taskInFlight==="number"?{"blade/taskInFlight":Z.properties.taskInFlight}:{}}})});let Q=await this.runtime.getGoal(),W=this.runtime.getPendingSteeringCount()>0,B=Q?.status==="active"||Q?.status==="verifying";if(W||B)this.requestPendingResume({defer:this.options.initialMessages!==void 0});else{let Z=this.runtime.getTurnRecoveryAssessment();if(Z.state!=="none")this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":Z}})}}async replayHistory(){for(let H of this.messages){if(!this.canSendUpdates())return;if(!_z(H))continue;let L=H.role==="user"?"user_message_chunk":H.role==="assistant"?"agent_message_chunk":void 0;if(!L)continue;for(let Y of XH(H)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:L,content:Y}))return}}let z=await this.runtime?.getGoal();if(z&&!await this.sendUpdateAndWait(this.goalSessionUpdate(z)))return;if(this.pendingResumeRequested)this.ensurePendingResumeScheduled()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);G.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendInitialSessionUpdates()},500)}async sendInitialSessionUpdates(){try{let z=this.runtime;if(z)this.sendFollowUpQueueSnapshot(await z.getFollowUpQueueSnapshot()),this.sendProviderRecoveryProjection(z.getProviderRecoveryProjection()),this.sendTurnActivityProjection(z.getTurnActivityProjection())}catch{G.warn("[AcpSession "+this.id+"] Initial follow-up queue unavailable")}await this.sendAvailableCommands()}async handleSlashCommand(z,H){try{G.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let L={cwd:this.roots.hostStateRoot,workspaceKind:this.roots.kind,surface:"acp",workspaceRoot:this.roots.hostStateRoot,sessionId:this.id,messages:[...this.contextMessages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let W=await this.runtime.rewindSession(Q);return this.messages=[...W.messages],this.contextMessages=await this.loadModelContextOr(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(Q)=>{if(await this.setReasoningEffort(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()}},serviceTier:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()},set:async(Q)=>{if(await this.setServiceTier(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()}},responseVerbosity:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()},set:async(Q)=>{if(await this.setResponseVerbosity(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()}},communicationStyle:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()},set:async(Q)=>{if(await this.setCommunicationStyle(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()}},...this.roots.kind==="local"?{subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let B=!1,Z,_=(V)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:V.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:V.result?.message||V.result?.error||`Subagent ${V.status}`}}]})},U=this.runtime.resumeSubagent({agentId:Q,prompt:W,onCompleted:(V)=>{if(B)_(V);else Z=V}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:U.session.id,status:"in_progress",title:`Resuming ${U.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${U.source.id} at depth ${U.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),B=!0,Z)_(Z);return U}}}:{},...this.roots.kind==="local"?{mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs(Q)},getPrompt:async(Q,W,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Q,W,B)},complete:async(Q,W,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Q,W,B)},listTasks:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks(Q)},getTask:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask(Q)},cancelTask:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Q,W)},getLogs:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Q,W)},setLoggingLevel:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Q,W)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}}}:{},sideConversation:{ask:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.askSideQuestion(Q,{signal:W})}},...this.roots.kind==="local"?{codeReview:{run:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let B=await S.start({sessionId:this.id,projectPath:this.roots.hostStateRoot,runtime:this.runtime,request:Q,signal:W,onEvent:(U)=>{if(U.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:U.toolCall.id,status:"in_progress",title:`Review: ${U.toolCall.function.name}`,content:[],kind:this.mapToolKind(U.toolKind)});else if(U.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:U.toolCall.id,status:U.result.success?"completed":"failed",content:[]})}}),Z=await B.completion,_=(await S.list(this.roots.hostStateRoot,this.id)).find((U)=>U.start.reviewId===B.reviewId);if(!_)throw Error(`Review not found: ${B.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:B.reviewId,status:Z.status,findings:Z.findings.length,content:Bz(_.start,Z)}}}}:{},signal:H,acp:{sendMessage:(Q)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}})},sendToolStart:(Q,W,B)=>{let Z=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,_=this.mapToolKind(B);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:Z,status:"in_progress",title:`${Q}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(W,null,2)}}],kind:_})},sendToolResult:(Q,W)=>{if(W.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W.summary}})}}},Y=await hz(z,L),$=Y.data?.action;if($==="start_goal"||$==="resume_goal")this.requestPendingResume();if($==="rewind_session"&&Array.isArray(Y.data?.messages))this.messages=[...Y.data.messages],this.contextMessages=await this.loadModelContextOr(Y.data.messages);if((Y.message==="compact_completed"||Y.message==="compact_fallback")&&Y.data?.compactedMessages){this.contextMessages=[...Y.data.compactedMessages];let Q=await this.loadPersistedMessages();if(Q.length>0)this.messages=Q}let X=Y.content||Y.message;if(X)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:X}});if(Y.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Y.error}`}});return await this.flushUpdates(),{stopReason:Y.success?"end_turn":"cancelled"}}catch(L){if(H.aborted||L instanceof Error&&L.name==="AbortError")return{stopReason:"cancelled"};return G.error(`[AcpSession ${this.id}] Slash command error:`,L),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${L instanceof Error?L.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async handleSideConversationCommand(z){if(this.pendingSideConversation)throw Error("A side conversation is already running");let H=new AbortController,L,Y=new Promise(($)=>{L=$});this.pendingSideConversation=H,this.pendingSideConversationCompletion=Y;try{return await this.handleSlashCommand(z,H.signal)}catch($){if(H.signal.aborted||$ instanceof Error&&$.name==="AbortError")return{stopReason:"cancelled"};throw $}finally{if(L(),this.pendingSideConversationCompletion===Y)this.pendingSideConversationCompletion=null;if(this.pendingSideConversation===H){if(this.pendingSideConversation=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async sendAvailableCommands(){try{let z=kz(this.roots.hostStateRoot,this.runtime?.getAgentResources(),this.roots.kind),H=["model","permissions","theme","config","exit","ide"],Y=z.filter(($)=>!H.includes($.name)&&($.name!=="team"||this.runtime?.getConfig().agentTeamsEnabled===!0)).map(($)=>{let X;if($.usage){let Q=$.usage.replace(/^\/\w+\s*/,"").trim();if(Q)X=Q}if($.aliases?.length){let Q=`Aliases: ${$.aliases.join(", ")}`;X=X?`${X} | ${Q}`:Q}return{name:$.name,description:$.description,input:X?{hint:X}:void 0}});G.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map(($)=>$.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Y}),G.info(`[AcpSession ${this.id}] Sent ${Y.length} available commands`)}catch(z){G.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,H={}){if(R.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let L=this.resolvePrompt(z.prompt),Y=L.content,$=L.displayText,X=z._meta?.outputSchema??(H.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((j)=>j.outputSchema)?.outputSchema:void 0),Q;if(X!==void 0)Q=Dz(X).schema;if($.trimStart().startsWith("!")){if(Q)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand($)}let W=Nz($);if(W){if(Q)throw Error("Output schemas cannot be combined with slash commands");if(Array.isArray(Y)&&Y.some((j)=>j.type==="image_url"))throw Error("Side conversations do not accept image attachments");return this.handleSideConversationCommand(W.question?`/btw ${W.question}`:"/btw")}if(this.pendingPrompt){if(Q)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test($.trim()))return this.handleSlashCommand($,this.pendingPrompt.signal);let j=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!j.accepted)throw Error(j.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(G.debug(`[AcpSession ${this.id}] Queued steering for active turn (${j.queued})`),this.sendFollowUpQueueSnapshot(j.queue??await this.runtime.getFollowUpQueueSnapshot()),j.delivery==="next_turn")this.requestPendingResume();return{stopReason:"end_turn"}}let B=new AbortController,Z=()=>{B.abort(H.abortSignal?.reason)};if(H.abortSignal?.aborted)Z();else H.abortSignal?.addEventListener("abort",Z,{once:!0});let _=!1,U=!1,V=!1,T,E=new Promise((j)=>{T=j});this.pendingPrompt=B,this.pendingPromptCompletion=E;try{if(G.debug(`[AcpSession ${this.id}] Received prompt: ${$.slice(0,100)}...`),Iz($)){if(Q)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand($,B.signal)}let j={sessionId:this.id,userId:"acp-user",workspaceRoot:this.roots.hostStateRoot,executionRoot:this.roots.executionRoot,workspaceKind:this.roots.kind,messages:[...this.contextMessages],signal:B.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async(J)=>{this.mode=this.mapPermissionModeToMode(J),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async(J)=>{return this.requestPermission(J)}}},N=await wz(this.agent.chatStream(Y,j,{pendingInputOnly:H.pendingInputOnly,goalContinuationOnly:H.goalContinuationOnly,outputSchema:Q}),async(J)=>{switch(J.kind){case"content_delta":if(Q)break;if(J.delta.length>0)U=!0;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:J.delta}});break;case"thinking_delta":if(J.delta.length>0)U=!0;this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:J.delta}});break;case"tool_start":{V=!0;let D=J.toolCall,A=D.function.name;if(A===M)break;let q=this.mapToolKind(J.toolKind),K=`Executing ${A}`;if(A==="Task"&&"function"in D)try{let b=JSON.parse(D.function.arguments),w=b.resume_from??b.resume;if(typeof w==="string")K=`Resuming ${String(b.subagent_type||"subagent")} from ${w}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:D.id,status:"in_progress",title:K,content:[],kind:q});break}case"tool_progress":{V=!0;let D=J.toolCall;if(D.function.name===M)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:D.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:J.update.message}}]});break}case"tool_result":{V=!0;let D=J.toolCall;if(D.function.name===M)break;let A=J.result,q=[],K=A.metadata;if(K?.kind==="patch"&&Array.isArray(K.changes))for(let w of K.changes){if(!w||typeof w!=="object"||!("path"in w)||typeof w.path!=="string")continue;q.push({type:"diff",path:w.path,oldText:"oldContent"in w&&typeof w.oldContent==="string"?w.oldContent:null,newText:"newContent"in w&&typeof w.newContent==="string"?w.newContent:null})}else if(K?.kind==="edit"&&typeof K.file_path==="string"&&typeof K.oldContent==="string"&&(typeof K.newContent==="string"||K.newContent===void 0))q.push({type:"diff",path:K.file_path,oldText:K.oldContent,newText:K.newContent??null});else{let w=D.function.name,QH=Tz(jz(qz(w,A),Vz));q.push({type:"content",content:{type:"text",text:QH}})}if(D.function.name==="Task"&&(K?.verificationVerdict==="pass"||K?.verificationVerdict==="fail"||K?.verificationVerdict==="partial"))q.unshift({type:"content",content:{type:"text",text:`Verification result: ${K.verificationVerdict.toUpperCase()}`}});let b=A.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:D.id,status:b,content:q});break}case"structured_output":U=!0,this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify(J.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${J.revision} (${J.serverName}): +${J.added.length} -${J.removed.length} ~${J.updated.length}
3
3
  `}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${J.contentKind} r${J.revision} (${J.serverName}): +${J.added.length} -${J.removed.length} ~${J.updated.length}
4
4
  `}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${J.revision} (${J.serverName}): ${J.uri}
@@ -1,4 +1,4 @@
1
- import{Ui as K}from"./chunk-kv458q06.js";import{Vi as wt,Wi as ft}from"./chunk-5v0jcyea.js";import{bj as I}from"./chunk-2f8d0km4.js";import{cj as tt,dj as Dt,ej as Bt,ij as Gt,jj as et,kj as Kt,lj as Ht,mj as Yt,nj as cn,oj as Ft,pj as qt,qj as Mt,rj as Vt,sj as Jt,tj as _t,uj as Qt,vj as jt,wj as Wt,xj as Zt,yj as kt,zj as yt}from"./chunk-ddvdc2p0.js";import{Dj as Un,Fj as bn,Gj as _n,Hj as T}from"./chunk-2mk914vk.js";import{Mj as zt,Pj as v}from"./chunk-j8hbddjp.js";import{Xj as xn,Yj as Cn}from"./chunk-rejsff7v.js";import{ck as a}from"./chunk-rvs364rz.js";import{fk as Ln}from"./chunk-4wx5sya5.js";var lt=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function vt(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function p(n,t="MCP OAuth URL"){let e=new URL(n);if(e.username||e.password)throw Error(`${t} must not contain credentials`);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&vt(e.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return e}var B=async(n,t)=>{p(n,"MCP OAuth request URL");let e=await fetch(n,{...t,redirect:"manual"});if(e.status>=300&&e.status<400)throw await e.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return e};function nn(n){let t=n.oauth;if(!t)return;let e=t;for(let E of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(e[E]!==void 0)throw Error(`MCP OAuth "${E}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(p(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((E)=>E.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let _=t.clientId?.trim();if(_&&_.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let S=t.scopes?.map((E)=>E.trim());if(S){if(S.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(S.some((E)=>!E||E.length>128||!lt.test(E)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(S).size!==S.length)throw Error("MCP OAuth scopes must not contain duplicates")}let r=t.callbackPort;if(r!==void 0&&(!Number.isInteger(r)||r<1024||r>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,..._?{clientId:_}:{},...S?.length?{scopes:S}:{},...r!==void 0?{callbackPort:r}:{}}}import{randomUUID as Sn}from"node:crypto";import Te from"node:http";import{auth as dn}from"@modelcontextprotocol/sdk/client/auth.js";import se from"open";import{createHash as ne,randomUUID as te}from"node:crypto";import{constants as tn,promises as b}from"node:fs";import en from"node:path";import ee from"write-file-atomic";var Nn=1,Me=1048576,_e=5000,re=50,Se=/^[a-f0-9]{64}$/,Ee=T.Object({client_id:T.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),ue=T.Object({access_token:T.String({minLength:1,maxLength:65536}),token_type:T.String({minLength:1,maxLength:64}),expires_in:T.Optional(T.Number({minimum:0})),refresh_token:T.Optional(T.String({minLength:1,maxLength:65536})),scope:T.Optional(T.String({maxLength:16384})),id_token:T.Optional(T.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),oe=T.Unsafe({type:"object",properties:{authorizationServerUrl:T.String({format:"uri"}),resourceMetadataUrl:T.Optional(T.String({format:"uri"})),resourceMetadata:T.Optional(T.Unknown()),authorizationServerMetadata:T.Optional(T.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),an=T.Object({serverUrl:T.String({format:"uri"}),clientId:T.Optional(T.String({minLength:1,maxLength:4096})),clientInformation:T.Optional(Ee),tokens:T.Optional(ue),tokenExpiresAt:T.Optional(T.Number({minimum:0})),discoveryState:T.Optional(oe),updatedAt:T.String({format:"date-time"})},{additionalProperties:!1}),gn=T.Object({version:T.Literal(Nn),credentials:T.Record(T.String(),an)},{additionalProperties:!1});function G(n,t){return n instanceof Error&&"code"in n&&n.code===t}function me(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return G(t,"EPERM")}}function Mn(n){return structuredClone(n)}function In(n){if(Object.keys(n.credentials).some((t)=>!Se.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function H(n){let t=new URL(n);return t.hash="",t.toString()}function rn(n,t,e=[]){return ne("sha256").update(JSON.stringify({serverUrl:H(n),clientId:t?.trim()||null,scopes:[...e].sort()})).digest("hex")}class f{static locks=new K;stateRoot;tokenFilePath;constructor(n=Ln()){this.stateRoot=en.join(n,"mcp"),this.tokenFilePath=en.join(this.stateRoot,"oauth-credentials.json")}static coordinationStatsForTests(){return this.locks.getStats()}async getCredential(n){return f.locks.runExclusive(this.tokenFilePath,async()=>{let e=(await this.readStore()).credentials[n];return e?Mn(e):null})}async updateCredential(n,t){return this.runMutation(async(e)=>{let M=e.credentials[n],_=await t(M?Mn(M):null);if(_)e.credentials[n]=_n(an,_);else delete e.credentials[n];return _?Mn(e.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return f.locks.runExclusive(this.tokenFilePath,async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return f.locks.runExclusive(this.tokenFilePath,async()=>{let t=await this.acquireStoreLock();try{let e=await this.readStore(),M=await n(e);return await this.writeStore(e),M}finally{await t()}})}async ensureStateRoot(){await b.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await b.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await b.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>Me)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await b.readFile(this.tokenFilePath,"utf8")),e=bn(gn,t);if(!e.success)throw Error("MCP OAuth credential store has an invalid schema");return In(e.data),e.data}catch(n){if(G(n,"ENOENT"))return{version:Nn,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=_n(gn,n);In(t),await ee(this.tokenFilePath,`${JSON.stringify(t,null,2)}
1
+ import{Ui as K}from"./chunk-kv458q06.js";import{Vi as wt,Wi as ft}from"./chunk-5v0jcyea.js";import{bj as I}from"./chunk-2f8d0km4.js";import{cj as tt,dj as Dt,ej as Bt,ij as Gt,jj as et,kj as Kt,lj as Ht,mj as Yt,nj as cn,oj as Ft,pj as qt,qj as Mt,rj as Vt,sj as Jt,tj as _t,uj as Qt,vj as jt,wj as Wt,xj as Zt,yj as kt,zj as yt}from"./chunk-ddvdc2p0.js";import{Dj as Un,Fj as bn,Gj as _n,Hj as T}from"./chunk-2mk914vk.js";import{Mj as zt,Pj as v}from"./chunk-j8hbddjp.js";import{Xj as xn,Yj as Cn}from"./chunk-6ke6p47w.js";import{ck as a}from"./chunk-rvs364rz.js";import{fk as Ln}from"./chunk-4wx5sya5.js";var lt=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function vt(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function p(n,t="MCP OAuth URL"){let e=new URL(n);if(e.username||e.password)throw Error(`${t} must not contain credentials`);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&vt(e.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return e}var B=async(n,t)=>{p(n,"MCP OAuth request URL");let e=await fetch(n,{...t,redirect:"manual"});if(e.status>=300&&e.status<400)throw await e.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return e};function nn(n){let t=n.oauth;if(!t)return;let e=t;for(let E of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(e[E]!==void 0)throw Error(`MCP OAuth "${E}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(p(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((E)=>E.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let _=t.clientId?.trim();if(_&&_.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let S=t.scopes?.map((E)=>E.trim());if(S){if(S.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(S.some((E)=>!E||E.length>128||!lt.test(E)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(S).size!==S.length)throw Error("MCP OAuth scopes must not contain duplicates")}let r=t.callbackPort;if(r!==void 0&&(!Number.isInteger(r)||r<1024||r>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,..._?{clientId:_}:{},...S?.length?{scopes:S}:{},...r!==void 0?{callbackPort:r}:{}}}import{randomUUID as Sn}from"node:crypto";import Te from"node:http";import{auth as dn}from"@modelcontextprotocol/sdk/client/auth.js";import se from"open";import{createHash as ne,randomUUID as te}from"node:crypto";import{constants as tn,promises as b}from"node:fs";import en from"node:path";import ee from"write-file-atomic";var Nn=1,Me=1048576,_e=5000,re=50,Se=/^[a-f0-9]{64}$/,Ee=T.Object({client_id:T.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),ue=T.Object({access_token:T.String({minLength:1,maxLength:65536}),token_type:T.String({minLength:1,maxLength:64}),expires_in:T.Optional(T.Number({minimum:0})),refresh_token:T.Optional(T.String({minLength:1,maxLength:65536})),scope:T.Optional(T.String({maxLength:16384})),id_token:T.Optional(T.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),oe=T.Unsafe({type:"object",properties:{authorizationServerUrl:T.String({format:"uri"}),resourceMetadataUrl:T.Optional(T.String({format:"uri"})),resourceMetadata:T.Optional(T.Unknown()),authorizationServerMetadata:T.Optional(T.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),an=T.Object({serverUrl:T.String({format:"uri"}),clientId:T.Optional(T.String({minLength:1,maxLength:4096})),clientInformation:T.Optional(Ee),tokens:T.Optional(ue),tokenExpiresAt:T.Optional(T.Number({minimum:0})),discoveryState:T.Optional(oe),updatedAt:T.String({format:"date-time"})},{additionalProperties:!1}),gn=T.Object({version:T.Literal(Nn),credentials:T.Record(T.String(),an)},{additionalProperties:!1});function G(n,t){return n instanceof Error&&"code"in n&&n.code===t}function me(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return G(t,"EPERM")}}function Mn(n){return structuredClone(n)}function In(n){if(Object.keys(n.credentials).some((t)=>!Se.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function H(n){let t=new URL(n);return t.hash="",t.toString()}function rn(n,t,e=[]){return ne("sha256").update(JSON.stringify({serverUrl:H(n),clientId:t?.trim()||null,scopes:[...e].sort()})).digest("hex")}class f{static locks=new K;stateRoot;tokenFilePath;constructor(n=Ln()){this.stateRoot=en.join(n,"mcp"),this.tokenFilePath=en.join(this.stateRoot,"oauth-credentials.json")}static coordinationStatsForTests(){return this.locks.getStats()}async getCredential(n){return f.locks.runExclusive(this.tokenFilePath,async()=>{let e=(await this.readStore()).credentials[n];return e?Mn(e):null})}async updateCredential(n,t){return this.runMutation(async(e)=>{let M=e.credentials[n],_=await t(M?Mn(M):null);if(_)e.credentials[n]=_n(an,_);else delete e.credentials[n];return _?Mn(e.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return f.locks.runExclusive(this.tokenFilePath,async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return f.locks.runExclusive(this.tokenFilePath,async()=>{let t=await this.acquireStoreLock();try{let e=await this.readStore(),M=await n(e);return await this.writeStore(e),M}finally{await t()}})}async ensureStateRoot(){await b.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await b.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await b.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>Me)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await b.readFile(this.tokenFilePath,"utf8")),e=bn(gn,t);if(!e.success)throw Error("MCP OAuth credential store has an invalid schema");return In(e.data),e.data}catch(n){if(G(n,"ENOENT"))return{version:Nn,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=_n(gn,n);In(t),await ee(this.tokenFilePath,`${JSON.stringify(t,null,2)}
2
2
  `,{mode:384,encoding:"utf8"}),await b.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let n=en.join(this.stateRoot,".oauth-credentials.lock"),t=te(),e=Date.now()+_e;while(Date.now()<e)try{let M=await b.open(n,tn.O_CREAT|tn.O_EXCL|tn.O_WRONLY,384);return await M.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:t,createdAt:new Date().toISOString()})}
3
3
  `,"utf8"),await M.close(),async()=>{try{if(JSON.parse(await b.readFile(n,"utf8")).token===t)await b.unlink(n)}catch(_){if(!G(_,"ENOENT"))throw _}}}catch(M){if(!G(M,"EEXIST"))throw M;await this.removeDeadLock(n),await new Promise((_)=>setTimeout(_,re))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(n){let t=await b.lstat(n);if(!t.isFile()||t.isSymbolicLink())throw Error("MCP OAuth credential lock must be a regular file");if(process.getuid&&t.uid!==process.getuid()||(t.mode&511)!==384)throw Error("MCP OAuth credential lock ownership or permissions are invalid");let e=JSON.parse(await b.readFile(n,"utf8"));if(typeof e.pid!=="number"||!Number.isInteger(e.pid)||e.pid<=0)throw Error("MCP OAuth credential lock owner is invalid");if(!me(e.pid))await b.unlink(n)}}var wn="127.0.0.1",fn=7777,Pn="/oauth/callback",Ae=300000;class En extends Error{constructor(n){super(`MCP server "${n}" requires OAuth authorization; run "blade mcp login ${n}" or use the Web MCP panel`);this.name="McpOAuthAuthorizationRequiredError"}}class hn extends Error{constructor(n){super(`MCP OAuth credentials are unavailable in this runtime for server "${n}"`);this.name="McpOAuthUnavailableError"}}function ce(n){let t=n?"Authentication complete":"Authentication failed";return`<!doctype html>
4
4
  <html lang="en">