blade-code 0.10.69 → 0.10.70
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/blade.js +2 -2
- package/dist/{chunk-g324ww9d.js → chunk-0kmrvxsz.js} +262 -263
- package/dist/{chunk-ypqp368c.js → chunk-0p0e70cy.js} +1 -1
- package/dist/{chunk-crkkpx3m.js → chunk-0p95nha3.js} +1 -1
- package/dist/{chunk-2da7j2sw.js → chunk-1bcp0qc4.js} +1 -1
- package/dist/{chunk-6pkyc8r6.js → chunk-1z9k5dmz.js} +1 -1
- package/dist/{chunk-bbcb9jzb.js → chunk-20vj0npz.js} +1 -1
- package/dist/chunk-2z75emht.js +1 -0
- package/dist/{chunk-2e7sedzn.js → chunk-31k6x4kn.js} +2 -2
- package/dist/chunk-3j413cgh.js +1 -0
- package/dist/chunk-4aam3qhk.js +8 -0
- package/dist/{chunk-efemjy9y.js → chunk-4md4sd4j.js} +1 -1
- package/dist/{chunk-kwv6vyst.js → chunk-5wnx38ze.js} +1 -1
- package/dist/{chunk-1z9wct9w.js → chunk-63121s4r.js} +1 -1
- package/dist/{chunk-n6rgqmf7.js → chunk-728anavt.js} +1 -1
- package/dist/{chunk-dfrgc84s.js → chunk-7b5s752s.js} +1 -1
- package/dist/{chunk-c8h3c8an.js → chunk-832va1mp.js} +1 -1
- package/dist/{chunk-b793bj62.js → chunk-83b4vfjs.js} +7 -7
- package/dist/chunk-8bsyhr4v.js +1 -0
- package/dist/{chunk-ppsvzgs5.js → chunk-8wea3qty.js} +2 -2
- package/dist/{chunk-yvg961q3.js → chunk-b2p4kd07.js} +1 -1
- package/dist/{chunk-kf070906.js → chunk-b39p4f5r.js} +1 -1
- package/dist/{chunk-7cm6tfnn.js → chunk-bkajr86v.js} +1 -1
- package/dist/{chunk-16n849z3.js → chunk-brdxkp0y.js} +1 -1
- package/dist/chunk-c0qm0wwk.js +1 -0
- package/dist/{chunk-xjse24zd.js → chunk-cmpj3a5a.js} +1 -1
- package/dist/chunk-cx5s0rf3.js +1 -0
- package/dist/{chunk-1xjzd1jn.js → chunk-d2vrbbvd.js} +1 -1
- package/dist/{chunk-98n2rxmq.js → chunk-d808m826.js} +1 -1
- package/dist/chunk-e3asq942.js +1 -0
- package/dist/{chunk-zdxxqchm.js → chunk-f7yfcw8s.js} +1 -1
- package/dist/{chunk-8gd0ksz7.js → chunk-ffym3kf3.js} +1 -1
- package/dist/{chunk-50jthhfq.js → chunk-g28pgqyn.js} +1 -1
- package/dist/{chunk-ftmbgtnk.js → chunk-h94vfh7s.js} +1 -1
- package/dist/{chunk-5d2cdvdy.js → chunk-jrr361h1.js} +1 -1
- package/dist/{chunk-hcv17986.js → chunk-k6shq7rk.js} +1 -1
- package/dist/chunk-nea4rcdf.js +1 -0
- package/dist/{chunk-qd9vk8t1.js → chunk-p9vaaayr.js} +6 -6
- package/dist/{chunk-68zek95f.js → chunk-pw87f92g.js} +1 -1
- package/dist/chunk-q919ypcz.js +5 -0
- package/dist/{chunk-asgyyv1s.js → chunk-qm5c9wew.js} +2 -2
- package/dist/{chunk-jj0b6n20.js → chunk-qstf0gpe.js} +1 -1
- package/dist/{chunk-nxek5ev2.js → chunk-r9n8y8m1.js} +1 -1
- package/dist/{chunk-qjg390mv.js → chunk-rpfa4a56.js} +1 -1
- package/dist/{chunk-v712dqde.js → chunk-sch01e04.js} +1 -1
- package/dist/{chunk-a0j0xwt1.js → chunk-sh17gjxv.js} +1 -1
- package/dist/{chunk-rpmmy3qs.js → chunk-smjkx71w.js} +1 -1
- package/dist/chunk-v3kkv21n.js +1 -0
- package/dist/{chunk-z9p0by31.js → chunk-w2gr97qt.js} +1 -1
- package/dist/{chunk-ptcb5fb7.js → chunk-wahhwjp9.js} +1 -1
- package/dist/{chunk-5147jh26.js → chunk-wepvrnmh.js} +1 -1
- package/dist/chunk-wj6t3tv2.js +3 -0
- package/dist/chunk-wkpacysr.js +166 -0
- package/dist/{chunk-4ge1jkf8.js → chunk-y9d9nqnn.js} +1 -1
- package/dist/{chunk-dktrankr.js → chunk-ypgjqg23.js} +1 -1
- package/dist/{chunk-kmarzy98.js → chunk-ysmqje92.js} +1 -1
- package/dist/{chunk-mgv3qr9b.js → chunk-z77c18j5.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-0f8nn2h1.js +0 -5
- package/dist/chunk-8gzm51m8.js +0 -1
- package/dist/chunk-bvyydst6.js +0 -166
- package/dist/chunk-e7pssnr9.js +0 -1
- package/dist/chunk-eym0bdee.js +0 -1
- package/dist/chunk-hsgcdk2a.js +0 -1
- package/dist/chunk-m65pse74.js +0 -1
- package/dist/chunk-q9y9hxnt.js +0 -1
- package/dist/chunk-qz0pe10c.js +0 -1
- package/dist/chunk-t2gq918a.js +0 -3
- package/dist/chunk-w3fy09rw.js +0 -8
- package/dist/chunk-w67k19a1.js +0 -1
package/dist/chunk-e7pssnr9.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{oh as a,ph as b}from"./chunk-t2gq918a.js";import"./chunk-5d2cdvdy.js";import"./chunk-ppsvzgs5.js";import"./chunk-hcv17986.js";export{b as WorkspaceTrustService,a as MAX_RESIDENT_WORKSPACE_TRUST_STATUSES};
|
package/dist/chunk-eym0bdee.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{ke as a,le as b,me as c}from"./chunk-c8h3c8an.js";import"./chunk-kf070906.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-98n2rxmq.js";import"./chunk-ypqp368c.js";import"./chunk-t8xmh4w2.js";import"./chunk-4ge1jkf8.js";import"./chunk-t2gq918a.js";import"./chunk-5d2cdvdy.js";import"./chunk-ppsvzgs5.js";import"./chunk-hcv17986.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,a as cloneWorkspaceModelConfig};
|
package/dist/chunk-hsgcdk2a.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b,c,d,e}from"./chunk-v712dqde.js";import"./chunk-4ge1jkf8.js";import"./chunk-hcv17986.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
|
package/dist/chunk-m65pse74.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{ld as a,md as b,nd as c}from"./chunk-nxek5ev2.js";import"./chunk-s7jsadnc.js";import"./chunk-qd9vk8t1.js";import"./chunk-v508x7cg.js";import"./chunk-0j22w4wh.js";import"./chunk-zvz2cnt4.js";import"./chunk-kf070906.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-98n2rxmq.js";import"./chunk-ypqp368c.js";import"./chunk-t8xmh4w2.js";import"./chunk-4ge1jkf8.js";import"./chunk-t2gq918a.js";import"./chunk-5d2cdvdy.js";import"./chunk-ppsvzgs5.js";import"./chunk-hcv17986.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
|
package/dist/chunk-q9y9hxnt.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{jd as a,kd as b}from"./chunk-7cm6tfnn.js";import"./chunk-4ge1jkf8.js";import"./chunk-hcv17986.js";export{a as globalOptions,b as cliConfig};
|
package/dist/chunk-qz0pe10c.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{f as a,g as i,h as l,i as m}from"./chunk-w3fy09rw.js";import"./chunk-dktrankr.js";import"./chunk-yvg961q3.js";import"./chunk-rpmmy3qs.js";import"./chunk-z9p0by31.js";import"./chunk-1xjzd1jn.js";import"./chunk-g324ww9d.js";import"./chunk-b793bj62.js";import"./chunk-5147jh26.js";import"./chunk-bvyydst6.js";import"./chunk-th4jjfgm.js";import"./chunk-6pkyc8r6.js";import"./chunk-0wxkymqv.js";import"./chunk-zdxxqchm.js";import{qd as n}from"./chunk-n6rgqmf7.js";import"./chunk-bjqjdw34.js";import{Md as s}from"./chunk-qd9vk8t1.js";import"./chunk-v508x7cg.js";import"./chunk-0j22w4wh.js";import"./chunk-0f8nn2h1.js";import"./chunk-efemjy9y.js";import"./chunk-yn51162x.js";import"./chunk-c8h3c8an.js";import"./chunk-ptcb5fb7.js";import"./chunk-hat9v5c5.js";import"./chunk-cdy9efgm.js";import"./chunk-zvz2cnt4.js";import"./chunk-asgyyv1s.js";import"./chunk-m57w4p91.js";import"./chunk-kf070906.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-98n2rxmq.js";import"./chunk-ypqp368c.js";import"./chunk-t8xmh4w2.js";import"./chunk-4ge1jkf8.js";import"./chunk-t2gq918a.js";import"./chunk-5d2cdvdy.js";import"./chunk-ppsvzgs5.js";import"./chunk-hcv17986.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};
|
package/dist/chunk-t2gq918a.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{qh as X}from"./chunk-5d2cdvdy.js";import{zh as T}from"./chunk-ppsvzgs5.js";import{createHash as _}from"node:crypto";import{constants as N,promises as B}from"node:fs";import A from"node:os";import F from"node:path";import{Mutex as w}from"async-mutex";import{LRUCache as k}from"lru-cache";import j from"write-file-atomic";var O=1,S=65536,D=1048576,U=100,R=64;function b(q){return q!==null&&typeof q==="object"&&!Array.isArray(q)}function C(q,Q=2048){return q.length<=Q?q:`${q.slice(0,Q-1)}…`}function M(q){if(typeof q!=="string"||!q.trim())return;try{let Q=new URL(q);return C(`${Q.origin}${Q.pathname}`)}catch{return C(q)}}function I(q){return Array.isArray(q)?q.filter((Q)=>typeof Q==="string"):[]}function m(q){if(!b(q))return[];return Object.entries(q).slice(0,U).map(([Q,Z])=>{let $=b(Z)?Z:{},H=typeof $.type==="string"?$.type:"unknown",G=typeof $.command==="string"?$.command:void 0,J=I($.args),L=H==="stdio"?C([G,...J].filter(Boolean).join(" ")):M($.url);return{kind:"mcp",name:`${Q} (${H})`,...L?{target:L}:{}}})}function E(q){if(!b(q))return[];return Object.entries(q).slice(0,U).map(([Q,Z])=>{let $=b(Z)?Z:{},H=typeof $.command==="string"?C($.command):void 0,G=b($.extensionToLanguage)?Object.keys($.extensionToLanguage).slice(0,12).join(", "):"unknown extensions";return{kind:"lsp",name:`${Q} (${G})`,...H?{target:H}:{}}})}function g(q){if(!Array.isArray(q))return[];return q.slice(0,U).flatMap((Q)=>{if(!b(Q))return[];let Z=typeof Q.id==="string"?Q.id:"unnamed",$=typeof Q.provider==="string"?Q.provider:"unknown",H=typeof Q.model==="string"?Q.model:"unknown",G=b(Q.overrides)?Q.overrides:{},J=M(G.baseUrl);return[{kind:"model",name:`${Z}: ${$}/${H}`,...J?{target:J}:{}}]})}function P(q){if(!b(q))return[];return Object.entries(q).slice(0,U).map(([Q,Z])=>{let $=b(Z)?Z:{},H=typeof $.wireApi==="string"?$.wireApi:"unknown",G=M($.baseUrl);return{kind:"model",name:`${Q} (${H})`,...G?{target:G}:{}}})}function y(q){if(!b(q))return[];let Q=[];for(let Z of["allow","ask","deny"])for(let $ of I(q[Z]).slice(0,U))Q.push({kind:"permission",name:`${Z}: ${C($,512)}`});return Q}function f(q){let Q=[...m(q.mcpServers),...E(q.lspServers),...g(q.models),...P(q.modelProviders),...y(q.permissions)];if(b(q.env))for(let Z of Object.keys(q.env).slice(0,U))Q.push({kind:"environment",name:Z});if(typeof q.permissionMode==="string")Q.push({kind:"permission",name:`permissionMode: ${q.permissionMode}`});return Q}function h(q){return q!=="hooks"&&q!=="disableAllHooks"}function v(q){return _("sha256").update(q).digest("hex")}function l(q,Q){let Z=F.relative(q,Q);return Z===""||!Z.startsWith(`..${F.sep}`)&&Z!==".."&&!F.isAbsolute(Z)}class x{storeDir;static instance=null;mutex=new w;statusCache=new k({max:R});constructor(q=F.join(T(),"workspace-trust")){this.storeDir=q}static getInstance(){if(!x.instance)x.instance=new x;return x.instance}static resetInstance(){x.instance=null}async getStatus(q){let Q=await X(q),Z;try{Z=await this.discoverSensitiveSources(Q.projectPath)}catch(Y){let V={...Q,state:"error",trusted:!1,sensitiveSources:0,sources:[],decision:"undecided",error:Y instanceof Error?Y.message:"Workspace trust review failed"};return this.cacheStatus(q,V),V}if(Z.length===0){let Y={...Q,state:"not_required",trusted:!0,sensitiveSources:0,sources:Z,decision:"undecided"};return this.cacheStatus(q,Y),Y}let $;try{$=await this.readDecisions()}catch(Y){let V={...Q,state:"error",trusted:!1,sensitiveSources:Z.length,sources:Z,decision:"undecided",error:Y instanceof Error?Y.message:"Workspace trust store is unavailable"};return this.cacheStatus(q,V),V}let H=$.filter((Y)=>l(Y.path,Q.trustRoot)),G=Math.max(-1,...H.map((Y)=>Y.path.split(F.sep).length)),J=H.filter((Y)=>Y.path.split(F.sep).length===G),L=J.length>0&&J.every((Y)=>Y.trusted),z=J[0],K=z?.path===Q.trustRoot,W={...Q,state:L?"trusted":"untrusted",trusted:L,sensitiveSources:Z.length,sources:Z,decision:z?K?z.trusted?"trusted":"untrusted":"inherited":"undecided",...z?.decidedAt?{decidedAt:z.decidedAt}:{},...!K&&z?.path?{inheritedFrom:z.path}:{}};return this.cacheStatus(q,W),W}cacheStatus(q,Q){this.statusCache.set(F.resolve(q),Q),this.statusCache.set(Q.projectPath,Q)}getCachedStatus(q){return this.statusCache.get(F.resolve(q))}isTrustedCached(q){return this.getCachedStatus(q)?.state==="trusted"}getCacheStats(){return{capacity:R,entries:this.statusCache.size}}async trust(q){return this.recordDecision(q,!0)}async revoke(q){return this.recordDecision(q,!1)}async recordDecision(q,Q){return this.mutex.runExclusive(async()=>{let Z=await X(q);await this.assertSafeTrustRoot(Z);let $={version:O,path:Z.trustRoot,trusted:Q,decidedAt:new Date().toISOString()};return await this.writeDecision($),this.statusCache.clear(),this.getStatus(q)})}async assertSafeTrustRoot(q){let Q=F.parse(q.trustRoot).root,Z=await B.realpath(A.homedir()).catch(()=>F.resolve(A.homedir()));if(!F.isAbsolute(q.trustRoot)||q.trustRoot===Q||q.trustRoot===Z)throw Error("Refusing to trust the filesystem root or user home directory")}async discoverSensitiveSources(q){let Q=[],Z=await this.reviewPackageScripts(q);if(Z)Q.push(Z);for(let[$,H]of[[".blade/config.json","config"],[".blade/settings.json","settings"],[".blade/settings.local.json","settings"]]){let G=await this.reviewConfigFile(q,$,H);if(G)Q.push(G)}for(let $ of[".blade/plugins",".claude/plugins"]){let H=await this.reviewResourceDirectory(q,$,"plugins","plugin");if(H)Q.push(H)}for(let $ of[".blade/commands",".claude/commands"]){let H=await this.reviewResourceDirectory(q,$,"commands","command");if(H)Q.push(H)}for(let[$,H,G]of[[".blade/skills","skills","skill"],[".claude/skills","skills","skill"],[".blade/agents","agents","agent"],[".claude/agents","agents","agent"]]){let J=await this.reviewResourceDirectory(q,$,H,G);if(J)Q.push(J)}for(let $ of["CLAUDE.md","AGENTS.md","BLADE.md"]){let H=await this.reviewInstructionFile(q,$);if(H)Q.push(H)}return Q}async reviewPackageScripts(q){let Q=F.join(q,"package.json"),Z;try{Z=await B.stat(Q)}catch(J){if(J.code==="ENOENT")return;throw J}if(!Z.isFile())return;if(Z.size>D)throw Error("package.json exceeds the 1 MiB workspace review limit");let $;try{$=JSON.parse(await B.readFile(Q,"utf8"))}catch{return{path:"package.json",kind:"package",keys:[],effects:[],warning:"Invalid package.json; project scripts will remain blocked"}}if(!b($)||!b($.scripts))return;let H=$.scripts,G=Object.keys(H).filter((J)=>typeof H[J]==="string").sort().slice(0,U);if(G.length===0)return;return{path:"package.json",kind:"package",keys:G,effects:G.map((J)=>({kind:"command",name:`package script: ${J}`}))}}async reviewInstructionFile(q,Q){try{if(!(await B.stat(F.join(q,Q))).isFile())return}catch(Z){if(Z.code==="ENOENT")return;throw Z}return{path:Q,kind:"instructions",keys:[Q],effects:[{kind:"instruction",name:Q}]}}async reviewConfigFile(q,Q,Z){let $=F.join(q,Q),H;try{H=await B.stat($)}catch(K){if(K.code==="ENOENT")return;throw K}if(!H.isFile())return;if(H.size>D)throw Error(`${Q} exceeds the 1 MiB workspace review limit`);let G;try{G=JSON.parse(await B.readFile($,"utf8"))}catch{return{path:Q,kind:Z,keys:[],effects:[],warning:"Invalid JSON; the file will remain blocked"}}if(!b(G))return{path:Q,kind:Z,keys:[],effects:[],warning:"Configuration root is not an object"};let J=Object.keys(G).filter(h).sort();if(J.length===0)return;let L=f(G),z=new Set(["mcpServers","lspServers","models","modelProviders","permissions","env","permissionMode"]);for(let K of J)if(!z.has(K))L.push({kind:"configuration",name:K});return{path:Q,kind:Z,keys:J,effects:L}}async reviewResourceDirectory(q,Q,Z,$){let H=F.join(q,Q),G;try{G=await B.readdir(H,{withFileTypes:!0})}catch(L){if(L.code==="ENOENT")return;throw L}let J=G.filter((L)=>Z==="plugins"||Z==="skills"?L.isDirectory()||L.isSymbolicLink():L.isFile()||L.isDirectory()||L.isSymbolicLink()).slice(0,U);if(J.length===0)return;return{path:Q,kind:Z,keys:J.map((L)=>L.name),effects:J.map((L)=>({kind:$,name:L.name}))}}async readDecisions(){let q;try{q=await B.lstat(this.storeDir)}catch($){if($.code==="ENOENT")return[];throw $}if(!q.isDirectory()||q.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&q.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((q.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700");let Q=await B.readdir(this.storeDir,{withFileTypes:!0}),Z=[];for(let $ of Q){if(!$.name.endsWith(".json"))continue;if(!$.isFile())throw Error("Workspace trust store entries must be regular files");Z.push(await this.readDecision(F.join(this.storeDir,$.name)))}return Z}async readDecision(q){let Q;try{Q=await B.open(q,N.O_RDONLY|N.O_NOFOLLOW)}catch{throw Error("Workspace trust decision must be a regular file")}try{let Z=await Q.stat();if(!Z.isFile()||Z.size>S)throw Error("Workspace trust decision is invalid");if(process.getuid&&Z.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((Z.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600");let $=JSON.parse(await Q.readFile("utf8"));if(!b($)||$.version!==O||typeof $.path!=="string"||!F.isAbsolute($.path)||typeof $.trusted!=="boolean"||typeof $.decidedAt!=="string"||!Number.isFinite(Date.parse($.decidedAt))||Object.keys($).some((H)=>H!=="version"&&H!=="path"&&H!=="trusted"&&H!=="decidedAt"))throw Error("Workspace trust decision schema is invalid");return{version:O,path:$.path,trusted:$.trusted,decidedAt:$.decidedAt}}finally{await Q.close()}}async writeDecision(q){await this.ensureStoreDirectoryForWrite();let Q=F.join(this.storeDir,`${v(q.path)}.json`);try{let Z=await B.lstat(Q);if(!Z.isFile()||Z.isSymbolicLink())throw Error("Workspace trust decision must be a regular file");if(process.getuid&&Z.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((Z.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600")}catch(Z){if(Z.code!=="ENOENT")throw Z}await j(Q,`${JSON.stringify(q,null,2)}
|
|
2
|
-
`,{mode:384}),await B.chmod(Q,384)}async ensureStoreDirectoryForWrite(){try{let q=await B.lstat(this.storeDir);if(!q.isDirectory()||q.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&q.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((q.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700")}catch(q){if(q.code!=="ENOENT")throw q;await B.mkdir(this.storeDir,{recursive:!0,mode:448}),await B.chmod(this.storeDir,448)}}}
|
|
3
|
-
export{R as oh,x as ph};
|
package/dist/chunk-w3fy09rw.js
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import{j as X4,k as V4}from"./chunk-dktrankr.js";import{l as tO}from"./chunk-yvg961q3.js";import{s as QO,t as g1}from"./chunk-rpmmy3qs.js";import{u as a0}from"./chunk-z9p0by31.js";import{A as a$,v as S1,w as l$,x as c$,y as i$,z as $O}from"./chunk-1xjzd1jn.js";import{$ as e1,C as w4,F as R1,G as VO,H as A$,I as iO,J as W$,K as E0,L as F$,M as f0,N as TO,Q as IO,R as SO,T as q1,U as k1,V as I1,W as o1,X as n1,Y as t1,Z as s1,_ as r1,aa as O4,ba as $4,ca as x4,fa as G4,ia as y4,na as M4}from"./chunk-g324ww9d.js";import{qa as Q1,wa as U0}from"./chunk-b793bj62.js";import{Ba as j4,Ca as j$,Da as P1,Ea as f1,Fa as T4,Ga as C4,Ha as T$,Ia as b4,Ja as t0,Ka as K4,La as W4,Ma as F4,Na as y1,Oa as m1,Pa as h1,Qa as u$,Ra as q$,ya as x$}from"./chunk-5147jh26.js";import{ab as m0,bb as g,db as R,eb as E1,pb as K$,yb as o0}from"./chunk-bvyydst6.js";import{Hb as M1}from"./chunk-th4jjfgm.js";import{Ac as C1,Cc as YO,Fc as X$,Kc as b1,Lc as V$,Mc as N$,Nc as E,_b as A1,jc as aO,pc as qO,qc as D$,rc as kO,tc as j1,zc as T1}from"./chunk-6pkyc8r6.js";import{Ld as J0,Pd as G1,Wd as L0}from"./chunk-qd9vk8t1.js";import{Xd as G$}from"./chunk-0j22w4wh.js";import{je as L1}from"./chunk-yn51162x.js";import{le as cO}from"./chunk-c8h3c8an.js";import{Be as MO,Ce as AO,Ge as d4,Je as T0,Ke as jO,Ne as l4,ue as D4,xe as a1}from"./chunk-ptcb5fb7.js";import{Ve as X1,We as w1}from"./chunk-cdy9efgm.js";import{$e as JO,_e as O1}from"./chunk-asgyyv1s.js";import{Lf as D1,Of as H1,Qf as B1,bg as $1,gg as wO,rf as J1}from"./chunk-kf070906.js";import{jg as z$}from"./chunk-h0ft81a3.js";import{kg as P,mg as U,pg as F0}from"./chunk-v0rsz1rt.js";import{rg as oO}from"./chunk-xz6y0w4n.js";import{wg as c}from"./chunk-k0pa8874.js";import{Xg as a}from"./chunk-98n2rxmq.js";import{bh as c0}from"./chunk-ypqp368c.js";import{dh as Y1,eh as U1,gh as z1,hh as _1}from"./chunk-t8xmh4w2.js";import{jh as xO}from"./chunk-4ge1jkf8.js";import{ph as E$}from"./chunk-t2gq918a.js";import{uh as pO,yh as n$}from"./chunk-ppsvzgs5.js";import{Bh as C$}from"./chunk-hcv17986.js";var a5={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 o5(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{existsSync as k$,readFileSync as yO}from"node:fs";import{createServer as j5}from"node:http";import{networkInterfaces as T5}from"node:os";import{dirname as C5,extname as b5,join as u0}from"node:path";import{fileURLToPath as R5}from"node:url";import{brotliCompressSync as E5,gzipSync as q5,constants as k5}from"node:zlib";import{Hono as I5}from"hono";import{cors as S5}from"hono/cors";import{WebSocketServer as P5}from"ws";var OO=a("Service"),a4=30000,o4=new Set(["completed","failed","cancelled","interrupted"]);class J${dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor(O){this.dispatch=O.dispatch,this.store=O.store??u$.getInstance(),this.tickMs=O.tickMs??a4}start(){if(this.timer)return;OO.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=R.subscribe((O)=>{if(O.type!=="task.status")return;let $=O.properties.taskStatus;if(typeof $!=="string"||!o4.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,OO.info("[TaskScheduler] Stopped scheduler tick loop")}async tick(O=new Date){if(this.ticking)return;this.ticking=!0;try{let $=await this.store.list();for(let x of $)await this.evaluate(x,O)}catch($){OO.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}),OO.info(`[TaskScheduler] Schedule ${O.id} expired; disabled`);return}if(!O.nextRunAt)return;if(!(new Date(O.nextRunAt).getTime()<=$.getTime()))return;await this.fire(O,$)}async fire(O,$=new Date,x={}){if(this.inFlight.has(O.id))throw Error(`Schedule ${O.id} is already dispatching`);this.inFlight.add(O.id);let J=$.toISOString();try{let Q=await this.dispatch({prompt:O.prompt,title:O.title??n4(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}),z=O.trigger.kind==="once"?null:x.manual?O.nextRunAt?new Date(O.nextRunAt):null:x$(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:J,lastRunSessionId:Q.session.sessionId,lastStatus:Q.status,lastError:void 0,runCount:O.runCount+1,nextRunAt:z?z.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled}),R.publish({sessionId:Q.session.sessionId,projectPath:O.projectPath},"schedule.fired",{scheduleId:O.id,firedAt:J,sessionId:Q.session.sessionId,runId:Q.runId,status:Q.status}),OO.info(`[TaskScheduler] Fired schedule ${O.id} -> session ${Q.session.sessionId} (${Q.status})`)}catch(Q){let z=Q instanceof Error?Q.message:String(Q);OO.warn(`[TaskScheduler] Schedule ${O.id} dispatch failed:`,Q);let Y=O.trigger.kind==="once"?null:x.manual?O.nextRunAt?new Date(O.nextRunAt):null:x$(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:J,lastStatus:"error",lastError:z,nextRunAt:Y?Y.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled})}finally{this.inFlight.delete(O.id)}}async recordTerminalStatus(O,$,x){let Q=(await this.store.list()).find((z)=>z.lastRunSessionId===O);if(!Q)return;await this.store.update(Q.id,{lastStatus:$,...x?{lastError:x}:{lastError:void 0}})}}function n4(O){return`Scheduled: ${O.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class Z0 extends Error{code;statusCode;details;constructor(O,$,x=500,J){super($);this.code=O;this.statusCode=x;this.details=J;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class S extends Z0{constructor(O,$){super("NOT_FOUND",$?`${O} not found: ${$}`:`${O} not found`,404)}}class H extends Z0{constructor(O){super("BAD_REQUEST",O,400)}}class q extends Z0{constructor(O){super("CONFLICT",O,409)}}class k0 extends Z0{constructor(O,$){super("TOO_MANY_REQUESTS",O,429,$)}}class l0 extends Z0{constructor(O="Server is shutting down"){super("SERVICE_UNAVAILABLE",O,503)}}class B0 extends Z0{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class r extends Z0{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var x3=U.Object({error:U.Object({code:U.String(),message:U.String(),details:U.Optional(U.Record(U.String(),U.Unknown()))})});import{Hono as t4}from"hono";var Q$=a("Service"),s4=U.Object({updates:U.Record(U.String(),U.Any()),options:U.Optional(U.Object({scope:U.Optional(F0(["local","project","global"])),immediate:U.Optional(U.Boolean())}))});function r4(O){return{currentModelId:O.currentModelId,permissionMode:O.permissionMode,language:O.language,codeTheme:O.codeTheme,uiTheme:O.uiTheme,autoSaveSessions:O.autoSaveSessions,notifyBuild:O.notifyBuild,notifyErrors:O.notifyErrors,notifySounds:O.notifySounds,privacyTelemetry:O.privacyTelemetry,privacyCrash:O.privacyCrash,communicationStyle:O.communicationStyle,maxConcurrentTasks:O.maxConcurrentTasks,maxQueuedTasks:O.maxQueuedTasks,maxQueuedTaskBytes:O.maxQueuedTaskBytes,maxResidentSessionRuntimes:O.maxResidentSessionRuntimes,sessionRuntimeIdleMs:O.sessionRuntimeIdleMs}}var p$=()=>{let O=new t4;return O.get("/",async($)=>{try{let x=J0();return $.json(x?r4(x):{})}catch(x){return Q$.error("[ConfigRoutes] Failed to get config:",x),$.json({})}}),O.put("/",async($)=>{try{let x=await $.req.json(),J=P(s4,x);if(!J.success)throw new H("Invalid config update format");let{updates:Q,options:z}=J.data;return await L0().updateConfig(Q,z),$.json({success:!0,updates:Q})}catch(x){throw Q$.error("[ConfigRoutes] Failed to update config:",x),x}}),O.get("/permissions",async($)=>{try{let x=J0();return $.json(x?.permissions||{})}catch(x){return Q$.error("[ConfigRoutes] Failed to get permissions:",x),$.json({})}}),O};import{Hono as e4}from"hono";import{streamSSE as O2}from"hono/streaming";function d$(O){let $="";if(O.id!==void 0)$+=`id: ${O.id}
|
|
2
|
-
`;if(O.event!==void 0)$+=`event: ${O.event}
|
|
3
|
-
`;for(let x of O.data.split(/\r\n|\r|\n/))$+=`data: ${x}
|
|
4
|
-
`;if(O.retry!==void 0)$+=`retry: ${O.retry}
|
|
5
|
-
`;return $+=`
|
|
6
|
-
`,Buffer.byteLength($)}class BO{serial;buffered=[];bufferedBytes=0;nextOrder=0;phase="buffering";highestDeliveredSequence=0;highestReplaySequence=0;failure;maxPendingItems;maxPendingBytes;constructor(O){this.maxPendingItems=O.maxPendingItems??l$,this.maxPendingBytes=O.maxPendingBytes??c$,this.serial=new a$({maxPendingItems:this.maxPendingItems,maxPendingBytes:this.maxPendingBytes,writeTimeoutMs:O.writeTimeoutMs??i$,sizeOf:d$,write:O.write,onFailure:($)=>{this.failure=$,this.phase="closed",this.buffered.length=0,this.bufferedBytes=0,O.onFailure?.($)}})}async writeInitial(O){await this.offerDirect(O)}observe(O,$){if(this.phase==="closed")return;if(this.phase==="buffering"){this.buffer(O,$);return}this.offerLive(O,$)}async writeReplay(O,$){if(!Number.isSafeInteger($)||$<=0)throw this.fail(new $O("invalid_size","SSE committed sequence must be a positive safe integer")),this.currentFailure();if($<=this.highestReplaySequence)return;await this.offerDirect(O),this.highestReplaySequence=$,this.highestDeliveredSequence=$}finishInitialization(O){if(this.phase!=="buffering")return;let $=this.buffered.splice(0);this.bufferedBytes=0,this.phase="live";let x=O.replayed?$.filter((Q)=>Q.sequence!==void 0&&Q.sequence>this.highestReplaySequence).sort((Q,z)=>Q.sequence-z.sequence||Q.order-z.order):$.sort((Q,z)=>Q.order-z.order),J;for(let Q of x){if(O.replayed&&Q.sequence!==void 0&&Q.sequence===J)continue;if(this.offerLive(Q.message,Q.sequence),this.serial.stats().closed)return;J=Q.sequence}}offerHeartbeat(O){if(this.phase!=="live"||this.buffered.length>0||this.serial.stats().pendingItems>0)return!1;return this.offerLive(O),!this.serial.stats().closed}async flush(){await this.serial.flush()}close(O){if(this.phase==="closed")return;this.phase="closed",this.buffered.length=0,this.bufferedBytes=0,this.serial.close(O)}stats(){let O=this.serial.stats();return{closed:this.phase==="closed",pendingItems:O.pendingItems+this.buffered.length,pendingBytes:O.pendingBytes+this.bufferedBytes,bufferedItems:this.buffered.length,bufferedBytes:this.bufferedBytes}}buffer(O,$){let x=d$(O),J=this.serial.stats();if(x>this.maxPendingBytes){this.fail(new $O("oversized",`SSE frame requires ${x} bytes; limit is ${this.maxPendingBytes}`,{pendingItems:J.pendingItems+this.buffered.length,pendingBytes:J.pendingBytes+this.bufferedBytes}));return}if(J.pendingItems+this.buffered.length>=this.maxPendingItems||J.pendingBytes+this.bufferedBytes+x>this.maxPendingBytes){this.fail(new $O("overflow","SSE initialization buffer limit exceeded",{pendingItems:J.pendingItems+this.buffered.length,pendingBytes:J.pendingBytes+this.bufferedBytes}));return}this.nextOrder+=1,this.buffered.push({message:O,bytes:x,sequence:$,order:this.nextOrder}),this.bufferedBytes+=x}offerLive(O,$){if($!==void 0){if($<=this.highestReplaySequence)return;if($<=this.highestDeliveredSequence){this.fail(new $O("write_failed","SSE committed sequence regressed"));return}this.highestDeliveredSequence=$}if(!this.serial.offer(O).accepted)this.phase="closed"}async offerDirect(O){if(this.phase==="closed")throw this.currentFailure();let $=this.serial.offer(O);if(!$.accepted)throw this.phase="closed",$.error;await $.completion}fail(O){this.serial.close(O)}currentFailure(){return this.failure??new $O("closed","SSE egress is closed")}}var $2=15000,x2=a("Service"),J2=new Set(["task.status","task.delivery","session.created","session.updated","session.deleted","schedule.fired","permission.asked","question.required","elicitation.required","interaction.resolved"]),Q2=new Set(["queued","running","completed","failed","cancelled","interrupted"]),Z2=new Set(["high","medium","low"]),Y2=new Set(["feature","bug","maintenance","research"]);function z2(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O,x=["changedFiles","additions","deletions","commits"];if(x.some((J)=>typeof $[J]!=="number"||!Number.isInteger($[J])||$[J]<0))return;return Object.fromEntries(x.map((J)=>[J,$[J]]))}function LO(O,$){return typeof O==="number"&&Number.isInteger(O)&&O>=$?O:void 0}function G2(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O;if(!["applied","discarded","conflicted"].includes(String($.status))||typeof $.updatedAt!=="string")return;return{status:$.status,updatedAt:$.updatedAt,...typeof $.sourceCommit==="string"?{sourceCommit:$.sourceCommit}:{},...LO($.changedFiles,0)!==void 0?{changedFiles:$.changedFiles}:{},...typeof $.message==="string"?{message:$.message}:{}}}var o$=()=>{let O=new e4;return O.get("/",($)=>O2($,async(x)=>{let J,Q,z=!1,Y,F,T=new Promise((W)=>{F=W}),B=()=>{if(Q!==void 0)clearInterval(Q),Q=void 0;J?.(),J=void 0},C=(W)=>{if(z)return;z=!0,B(),Y?.close(W),F()};x.onAbort(C),Y=new BO({write:async(W)=>{await x.writeSSE(W)},onFailure:(W)=>{x2.warn(`[EventRoutes] SSE egress closed: kind=${W.kind} pendingItems=${W.pendingItems??0} pendingBytes=${W.pendingBytes??0}`),C(W)}});let w=(W,I)=>{Y?.observe({data:JSON.stringify({type:W,properties:I})})};J=R.subscribe((W)=>{if(!J2.has(W.type))return;if(W.type==="permission.asked"||W.type==="question.required"||W.type==="elicitation.required"){let i=W.properties.requestId;if(typeof i!=="string"||!i)return;w("interaction.pending",{sessionId:W.sessionId,projectPath:W.projectPath,interactionType:W.type==="question.required"?"question":W.type==="elicitation.required"?"elicitation":"permission",requestId:i});return}if(W.type==="interaction.resolved"){let i=W.properties.requestId;if(typeof i!=="string"||!i)return;w(W.type,{sessionId:W.sessionId,projectPath:W.projectPath,requestId:i});return}if(W.type==="session.created"||W.type==="session.deleted"){w(W.type,{sessionId:W.sessionId,projectPath:W.projectPath});return}if(W.type==="session.updated"){let i=W.properties.title,x0=W.properties.taskPriority,S0=W.properties.taskKind,o=W.properties.taskDueAt,p0=typeof i==="string"&&Boolean(i.trim()),w0=Z2.has(String(x0)),V=Y2.has(String(S0)),V0=o===null||typeof o==="string"&&Number.isFinite(Date.parse(o));if(!p0&&!w0&&!V&&!V0)return;w(W.type,{sessionId:W.sessionId,projectPath:W.projectPath,...p0?{title:i}:{},...w0?{taskPriority:x0}:{},...V?{taskKind:S0}:{},...V0?{taskDueAt:o}:{}});return}if(W.type==="task.delivery"){let i=G2(W.properties.taskDelivery);if(!i)return;w(W.type,{sessionId:W.sessionId,projectPath:W.projectPath,taskDelivery:i,...W.properties.taskWorktreeRemoved===!0?{taskWorktreeRemoved:!0}:{},...typeof W.properties.updatedAt==="string"?{updatedAt:W.properties.updatedAt}:{}});return}if(W.type==="schedule.fired"){let i=W.properties.scheduleId,x0=W.properties.firedAt;if(typeof i!=="string"||typeof x0!=="string")return;w(W.type,{scheduleId:i,firedAt:x0,sessionId:W.sessionId,projectPath:W.projectPath,...typeof W.properties.runId==="string"?{runId:W.properties.runId}:{},...typeof W.properties.status==="string"?{status:W.properties.status}:{}});return}let I=W.properties.taskStatus;if(typeof I!=="string"||!Q2.has(I))return;let Q0=z2(W.properties.taskDiffStat),p=LO(W.properties.taskQueuePosition,1),b=LO(W.properties.taskQueueDepth,0),e=LO(W.properties.taskConcurrencyLimit,1),v=LO(W.properties.taskInFlight,0),Y0=typeof W.properties.taskAdmissionPaused==="boolean"?W.properties.taskAdmissionPaused:void 0;w(W.type,{sessionId:W.sessionId,projectPath:W.projectPath,taskStatus:I,...typeof W.properties.taskStatusReason==="string"?{taskStatusReason:W.properties.taskStatusReason}:{},...W.properties.taskFailure&&typeof W.properties.taskFailure==="object"?{taskFailure:W.properties.taskFailure}:{},...typeof W.properties.taskStartedAt==="string"?{taskStartedAt:W.properties.taskStartedAt}:{},...typeof W.properties.taskCompletedAt==="string"?{taskCompletedAt:W.properties.taskCompletedAt}:{},...typeof W.properties.updatedAt==="string"?{updatedAt:W.properties.updatedAt}:{},...Q0?{taskDiffStat:Q0}:{},...p!==void 0?{taskQueuePosition:p}:{},...b!==void 0?{taskQueueDepth:b}:{},...e!==void 0?{taskConcurrencyLimit:e}:{},...v!==void 0?{taskInFlight:v}:{},...Y0!==void 0?{taskAdmissionPaused:Y0}:{}})});try{if(x.aborted||z)return;if(await Y.writeInitial({data:JSON.stringify({type:"connected",properties:{timestamp:Date.now()}})}),x.aborted||z)return;if(Y.finishInitialization({replayed:!1}),x.aborted||z)return;Q=setInterval(()=>{if(x.aborted||z)return;Y?.offerHeartbeat({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})})},$2),await T}finally{C()}})),O};import{Hono as X2}from"hono";var V2=U.Object({paused:U.Boolean()}),t$=()=>{let O=new X2;return O.get("/health",($)=>{return $.json({healthy:!0,version:xO()})}),O.get("/info",($)=>{let x=c(),J=J0();if(J)f0.configure(J.maxConcurrentTasks,J.maxQueuedTasks,J.maxQueuedTaskBytes);let Q=f0.getStats();return $.json({version:xO(),platform:process.platform,arch:process.arch,nodeVersion:process.version,cwd:x,gitBranch:n$(x),taskAdmission:{inFlight:Q.inFlight,queued:Q.queued,maxConcurrent:Q.maxConcurrent,maxQueued:Q.maxQueued,paused:Q.paused}})}),O.put("/task-admission",async($)=>{let x;try{x=await $.req.json()}catch{throw new H("Invalid request body")}let J=P(V2,x);if(!J.success)throw new H("Invalid task admission control request");f0.setPaused(J.data.paused);let Q=f0.getStats();return $.json({inFlight:Q.inFlight,queued:Q.queued,maxConcurrent:Q.maxConcurrent,maxQueued:Q.maxQueued,paused:Q.paused})}),O};import s$ from"node:path";import{Hono as N2}from"hono";var K2=U.Object({projectPath:U.String({minLength:1}),action:F0(["trust","revoke"]),expectedDigest:U.Optional(U.String())}),W2=U.Object({projectPath:U.String({minLength:1}),sessionId:U.String({minLength:1}),enabled:U.Boolean()});function Z$(O){if(!O||!s$.isAbsolute(O))throw new H("projectPath must be absolute");return s$.resolve(O)}function r$(O){if(!O)throw new H("sessionId is required");try{pO(O)}catch($){throw new H($ instanceof Error?$.message:"sessionId is invalid")}return O}async function uO(O){let $=Z$(O),x=J0()?.hooks??$1.hooks,J=await wO.getInstance().loadWorkspaceHooks($,x,{includeBaseForCurrentWorkspace:!1});return jO($,async()=>{AO($);let Q=JO.getInstance();return Q.loadConfig(J,$),await MO($),Q.getConfig($)})}function e$(O,$){let x=JO.getInstance(),J=x.getConfig($).enabled,Q=x.isSessionPaused(O,$);return{sessionId:O,projectPath:$,enabled:x.isSessionEnabled(O,$),paused:Q,configEnabled:J}}var x1=()=>{let O=new N2;return O.get("/trust",async($)=>{let x=$.req.query("projectPath");if(!x)throw new H("projectPath query parameter is required");return await uO(x),$.json(await JO.getInstance().getTrustStatus(x))}),O.post("/trust",async($)=>{let x=P(K2,await $.req.json());if(!x.success)throw new H("Invalid hook trust request");let{projectPath:J,action:Q,expectedDigest:z}=x.data;await uO(J);let Y=JO.getInstance(),F;try{F=Q==="trust"?await Y.trustProject(J,z):await Y.revokeProjectTrust(J)}catch(T){if(T instanceof O1)throw new q(T.message);throw T}return $.json(F)}),O.get("/session",async($)=>{let x=Z$($.req.query("projectPath")),J=r$($.req.query("sessionId"));return await uO(x),$.json(e$(J,x))}),O.post("/session",async($)=>{let x=P(W2,await $.req.json());if(!x.success)throw new H("Invalid hook session request");let J=Z$(x.data.projectPath),Q=r$(x.data.sessionId);await uO(J);let z=JO.getInstance();if(x.data.enabled)z.enableSession(Q,J);else z.disableSession(Q,J);return $.json(e$(Q,J))}),O};import{Hono as F2}from"hono";var R0=a("Service");function U2(O){try{return Q1(O)}catch{return[]}}function _2(O){if(!dO(O)||!dO(O.reference)||!dO(O.argument))throw Error("Invalid MCP completion request");let $=O.reference.type,x=$==="prompt"&&typeof O.reference.name==="string"?{type:"prompt",name:O.reference.name}:$==="resource"&&typeof O.reference.uri==="string"?{type:"resource",uri:O.reference.uri}:void 0;if(!x||typeof O.argument.name!=="string"||typeof O.argument.value!=="string")throw Error("Invalid MCP completion request");let J;if(O.context!==void 0){if(!dO(O.context))throw Error("Invalid MCP completion context");J=Object.create(null);for(let[Q,z]of Object.entries(O.context)){if(typeof z!=="string")throw Error("Invalid MCP completion context");J[Q]=z}}return{reference:x,argument:{name:O.argument.name,value:O.argument.value},...J?{context:J}:{}}}function dO(O){return O!==null&&typeof O==="object"&&!Array.isArray(O)}async function y0(O,$){let x=J0()?.mcpServers??{};for(let[J,Q]of Object.entries(x)){if($&&J!==$)continue;if(!O.getServerStatus(J))await O.registerServer(J,Q,{connect:!1})}}var Z1=()=>{let O=new F2;return O.get("/",async($)=>{try{let x=U0.getInstance();await y0(x);let J=x.getAllServers(),Q=await Promise.all(Array.from(J.entries()).map(async([z,Y])=>({id:z,name:z,status:Y.status==="connected"?"connected":Y.status==="reconnecting"?"reconnecting":Y.status==="connecting"?"connecting":Y.lastError?"error":"offline",endpoint:Y.config.command?`${Y.config.command} ${(Y.config.args||[]).join(" ")}`.trim():Y.config.url||"Unknown",description:`MCP server: ${z}`,tools:Y.tools.map((F)=>F.name),completionSupported:Y.client.completionSupported,tasks:Y.client.tasks,resources:Y.contentCatalog.resources,resourceTemplates:Y.contentCatalog.resourceTemplates.map((F)=>({...F,variables:U2(F.uriTemplate)})),prompts:Y.contentCatalog.prompts,connectedAt:Y.connectedAt?.toISOString(),error:Y.lastError?.message,recovery:Y.recovery,logging:Y.logging,instructions:Y.instructions,oauthEnabled:Y.client.oauthEnabled,oauthStatus:await Y.client.getOAuthStatus()})));return $.json(Q)}catch(x){return R0.error("[McpRoutes] Failed to get MCP servers:",x),$.json({error:x instanceof Error?x.message:"Failed to get MCP servers"},500)}}),O.post("/:name/connect",async($)=>{try{let x=$.req.param("name"),J=U0.getInstance();return await y0(J,x),await J.connectServer(x),$.json({success:!0})}catch(x){return R0.error("[McpRoutes] Failed to connect MCP server:",x),$.json({success:!1,error:x.message},500)}}),O.post("/:name/disconnect",async($)=>{try{let x=$.req.param("name"),J=U0.getInstance();return await y0(J,x),await J.disconnectServer(x),$.json({success:!0})}catch(x){return R0.error("[McpRoutes] Failed to disconnect MCP server:",x),$.json({success:!1,error:x.message},500)}}),O.get("/:name/logs",async($)=>{try{let x=$.req.param("name"),J=Number($.req.query("limit")??20),Q=Number($.req.query("afterRevision")??0);if(!Number.isSafeInteger(J)||J<1||J>100||!Number.isSafeInteger(Q)||Q<0)return $.json({error:"Invalid MCP log pagination"},400);let z=U0.getInstance();return await y0(z,x),$.json(z.getLogSnapshot(x,{limit:J,afterRevision:Q}))}catch(x){return R0.error("[McpRoutes] Failed to get MCP logs:",x),$.json({error:x.message},500)}}),O.post("/:name/logging-level",async($)=>{try{let x=$.req.param("name"),J=await $.req.json();if(!J1(J.level))return $.json({success:!1,error:"Invalid MCP logging level"},400);let Q=U0.getInstance();return await y0(Q,x),await Q.setServerLoggingLevel(x,J.level),$.json({success:!0,level:J.level})}catch(x){return R0.error("[McpRoutes] Failed to set MCP logging level:",x),$.json({success:!1,error:x.message},400)}}),O.post("/:name/complete",async($)=>{try{let x=$.req.param("name"),J=_2(await $.req.json()),Q=U0.getInstance();await y0(Q,x);let z=await Q.complete(x,J);return $.json(z)}catch(x){return R0.error("[McpRoutes] Failed to complete MCP argument:",x),$.json({error:x.message},400)}}),O.post("/:name/oauth/login",async($)=>{try{let x=$.req.param("name"),J=U0.getInstance();await y0(J,x);let Q=await J.beginOAuthLogin(x);return $.json({success:!0,flowId:Q.flowId,authorizationUrl:Q.authorizationUrl},202)}catch(x){return R0.error("[McpRoutes] Failed to start MCP OAuth login:",x),$.json({success:!1,error:x.message},400)}}),O.post("/:name/oauth/logout",async($)=>{try{let x=$.req.param("name"),J=U0.getInstance();return await y0(J,x),await J.logoutOAuth(x),$.json({success:!0})}catch(x){return R0.error("[McpRoutes] Failed to log out MCP OAuth:",x),$.json({success:!1,error:x.message},400)}}),O.delete("/:name",async($)=>{try{let x=$.req.param("name");await U0.getInstance().unregisterServer(x);let Q=J0();if(Q?.mcpServers){let{[x]:z,...Y}=Q.mcpServers;await L0().updateConfig({mcpServers:Y})}return $.json({success:!0})}catch(x){return R0.error("[McpRoutes] Failed to delete MCP server:",x),$.json({success:!1,error:x.message},500)}}),O.post("/",async($)=>{try{let x=await $.req.json(),{name:J,config:Q}=x;if(!J||!Q)return $.json({success:!1,error:"Missing name or config"},400);await U0.getInstance().registerServer(J,Q);let Y=J0();return await L0().updateConfig({mcpServers:{...Y?.mcpServers,[J]:Q}}),$.json({success:!0})}catch(x){return R0.error("[McpRoutes] Failed to add MCP server:",x),$.json({success:!1,error:x.message},500)}}),O};import{getSupportedThinkingLevels as D2}from"@earendil-works/pi-ai";import{Hono as H2}from"hono";var lO=a("Service");function B2(O,$,x=X1.list()){return{id:O.id,displayName:O.displayName,provider:O.provider,model:O.model,overrides:O.overrides,fallbackModels:O.fallbackModels,contextWindow:$.contextWindow,maxTokens:$.maxTokens,reasoning:$.reasoning,supportedReasoningEfforts:D2($),supportedServiceTiers:z1($),supportedResponseVerbosities:Y1($),communicationStyles:x,input:$.input}}function L2(O){V1(O.overrides);let $={displayName:O.displayName||void 0,overrides:O.overrides||void 0};if(O.model)$.model=O.model;return $}function V1(O){let $=O?.streamIdleTimeout;if($!==void 0&&(!Number.isFinite($)||$<1000))throw new H("streamIdleTimeout must be at least 1000ms")}var N1=()=>{let O=new H2;return O.get("/",async($)=>{try{let x=J0();if(!x)throw Error("Config not initialized");let J=$.get("directory")||c(),[Q,z]=await Promise.all([cO(J,x),T0(J)]),Y=Q.config.models,F=Y.find((w)=>w.id===Q.config.currentModelId)??Y[0],T=Q.catalog,B=z.communicationStyles.list(),C=(w)=>B2(w,T.resolveConfig(w),B);return $.json({configured:Y.map(C),current:F?C(F):null})}catch(x){lO.error("[ModelsRoutes] Failed to get models:",x);let J=new r("Failed to get models");return $.json(J.toObject(),500)}}),O.post("/",async($)=>{let x=c0(),J,Q;try{let z=await $.req.json(),{provider:Y,displayName:F,model:T,overrides:B,apiKey:C,modelProvider:w}=z;if(!Y||!T)throw new H("provider and model are required");V1(B);let W;if(w){if(w.id!==Y)throw new H("modelProvider.id must match the model provider");if(J0()?.modelProviders[Y])throw new H(`model provider already exists: ${Y}`);W={name:w.name,baseUrl:w.baseUrl,wireApi:w.wireApi,...w.apiKeyEnv?{apiKeyEnv:w.apiKeyEnv}:{}};try{x.registerModelProvider(Y,W,[T]),Q=Y}catch(p){throw new H(p instanceof Error?p.message:"Invalid model provider")}}else x.getModel(Y,T);if(C?.trim()){if(await x.setApiKey(Y,C.trim()),W)J=Y}let I={provider:Y,displayName:F||void 0,model:T,overrides:B||void 0},Q0=W?await L0().addModelWithProvider(I,W):await L0().addModel(I);return $.json({success:!0,model:Q0})}catch(z){if(J)await x.credentials.delete(J);if(Q){let Y=J0();x.configureModelProviders(Y?.modelProviders??{},Y?.models??[])}throw lO.error("[ModelsRoutes] Failed to add model:",z),z}}),O.put("/:modelId",async($)=>{try{let x=$.req.param("modelId"),J=await $.req.json(),{displayName:Q,overrides:z,model:Y}=J,F=G1(x);if(!F)throw new H("model config not found");if(Y)c0().getModel(F.provider,Y);return await L0().updateModel(x,L2({displayName:Q,overrides:z,model:Y})),$.json({success:!0})}catch(x){throw lO.error("[ModelsRoutes] Failed to update model:",x),x}}),O.delete("/:modelId",async($)=>{try{let x=$.req.param("modelId");return await L0().removeModel(x),$.json({success:!0})}catch(x){throw lO.error("[ModelsRoutes] Failed to delete model:",x),x}}),O};import{Hono as h2}from"hono";import K1 from"node:path";import{Hono as w2}from"hono";import{streamSSE as M2}from"hono/streaming";import{LRUCache as A2}from"lru-cache";import{nanoid as ZO}from"nanoid";var y=a("Service"),j2=U.Object({title:U.Optional(U.String()),projectPath:U.Optional(U.String())}),T2=y1,C2=U.Object({title:U.Optional(U.String()),projectPath:U.Optional(U.String())}),b2=U.Object({projectPath:U.String()}),R2=U.Object({objective:U.String({minLength:1}),tokenBudget:U.Optional(U.Integer({minimum:1})),permissionMode:U.Optional(F0(["default","autoEdit","plan","yolo"]))}),E2=U.Union([U.Object({action:U.Literal("pause")}),U.Object({action:U.Literal("resume")}),U.Object({action:U.Literal("edit"),objective:U.String({minLength:1})})]),t=new Map,zO,b0=new Map,I0=new Map,C0=new Map,nO=new A2({max:100,ttl:1800000});function W1(O){return{sessionId:O.sessionId,projectPath:O.projectPath}}function D0(O){if(!O)return;return b0.get(O)??nO.get(O)}function q2(O){if(b0.get(O.id)!==O)return;b0.delete(O.id),nO.set(O.id,O)}function k2(O){b0.delete(O),nO.delete(O)}function _0(O){return O?.status==="queued"||O?.status==="running"||O?.status==="waiting_permission"}function RO(O,$="user-cancel"){if(O.status==="cancelled"||O.status==="completed"||O.status==="failed")return!1;let x=O.pendingPermission;if(O.pendingPermission=void 0,x?.resolve({approved:!1,reason:M1}),x)R.publish(W1(O),"interaction.resolved",{requestId:x.permissionId});return O.abortController.abort($),O.status="cancelled",R.publish(W1(O),"run.cancelled",{runId:O.id}),!0}function v1(O,$=!1){let{permissionId:x,details:J}=O;if(J.type==="askUserQuestion"&&J.questions)return{type:"question.required",properties:{requestId:x,toolCallId:J.toolCallId??x,questions:J.questions,details:J,...$?{replayed:!0}:{}}};if(J.type==="mcpElicitation"&&J.mcpElicitation)return{type:"elicitation.required",properties:{requestId:x,toolCallId:J.toolCallId??x,elicitation:J.mcpElicitation,...$?{replayed:!0}:{}}};return{type:"permission.asked",properties:{requestId:x,toolName:J.toolName,description:J.message,args:J.args,details:J,...$?{replayed:!0}:{}}}}function I2(O){return{...typeof O.seq==="number"?{id:String(O.seq)}:{},data:JSON.stringify({type:O.type,...typeof O.seq==="number"?{seq:O.seq}:{},properties:{...O.properties,sessionId:O.sessionId,projectPath:O.projectPath}})}}function S2(){for(let O of b0.values())RO(O,"route-reset");b0.clear();for(let O of I0.values())O.controller.abort("route-reset");I0.clear(),nO.clear(),zO=void 0,t.clear()}function P2(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O,x=$.code,J=$.reason,Q=$.scope,z=$.kind,Y=$.limit;if(x!=="tool_busy"&&x!=="tool_batch_full"||J!=="queue_full"&&J!=="wait_timeout"&&J!=="turn_limit"||Q!=="global"&&Q!=="session"||typeof $.retryable!=="boolean"||!Number.isSafeInteger(Y)||Y<=0||z!==void 0&&z!=="readonly"&&z!=="write"&&z!=="execute")return;return{code:x,reason:J,scope:Q,retryable:$.retryable,...z===void 0?{}:{kind:z},limit:Y}}var EO=(O,$)=>{if(!$||typeof $!=="object")return $;let x={...$},J=P2(x.tool_admission);if(J)x.tool_admission=J;else delete x.tool_admission;if(O==="Bash"){let Y={},F=["message","signal","status","summary"],T=["aborted","acp_mode","admission_failed","auto_backgrounded","background","capture_truncated","finalization_failed","has_stderr","output_accounting_complete","output_truncated","projection_truncated","sandbox_required","sandboxed","stderr_projection_truncated","stdout_projection_truncated","terminal_output_merged","timeout"],B=["execution_time","foreground_budget_ms","pid","raw_output_bytes","stderr_length","stderr_omitted_bytes","stderr_retained_bytes","stderr_total_bytes","stdout_length","stdout_omitted_bytes","stdout_retained_bytes","stdout_total_bytes"];for(let w of F){let W=x[w];if(typeof W==="string")Y[w]=W.slice(0,8192)}for(let w of T){let W=x[w];if(typeof W==="boolean")Y[w]=W}for(let w of B){let W=x[w];if(typeof W==="number"&&Number.isSafeInteger(W)&&W>=0)Y[w]=W}if(x.exit_code===null||typeof x.exit_code==="number"&&Number.isSafeInteger(x.exit_code))Y.exit_code=x.exit_code;if(x.terminal_transport==="local"||x.terminal_transport==="acp"||x.terminal_transport==="local_fallback")Y.terminal_transport=x.terminal_transport;if(x.background_reason==="explicit"||x.background_reason==="foreground_budget")Y.background_reason=x.background_reason;for(let w of["bash_id","shell_id"]){let W=x[w];if(typeof W==="string"&&W.length<=128&&/^bash_[A-Za-z0-9-]+$/.test(W))Y[w]=W}if(J)Y.tool_admission=J;let C=x.background_shell_admission;if(C&&typeof C==="object"&&!Array.isArray(C)){let w=C;if(w.code==="background_shell_busy"&&(w.scope==="session"||w.scope==="global")&&w.retryable===!0&&Number.isSafeInteger(w.limit)&&w.limit>0)Y.background_shell_admission={code:w.code,scope:w.scope,retryable:w.retryable,limit:w.limit}}return Y}let Q=200000,z=(Y,F)=>typeof Y==="number"&&Number.isSafeInteger(Y)&&Y>=0&&Y<=F?Y:0;if(typeof x.oldContent==="string"&&x.oldContent.length>Q)delete x.oldContent;if(typeof x.newContent==="string"&&x.newContent.length>Q)delete x.newContent;if(x.mcpResult&&typeof x.mcpResult==="object"&&!Array.isArray(x.mcpResult)){let Y=x.mcpResult,F=Array.isArray(Y.artifacts)?Y.artifacts.slice(0,64).flatMap((T)=>{if(!T||typeof T!=="object"||Array.isArray(T))return[];let B=T,C=new Set(["text","image","audio","resource"]);if(typeof B.id!=="string"||!/^[a-f0-9]{64}$/.test(B.id)||typeof B.sha256!=="string"||B.sha256!==B.id||typeof B.kind!=="string"||!C.has(B.kind)||z(B.size,67108864)!==B.size||typeof B.persisted!=="boolean")return[];return[{id:B.id.slice(0,128),sha256:B.sha256.slice(0,128),kind:B.kind,size:B.size,persisted:B.persisted,...typeof B.mimeType==="string"?{mimeType:B.mimeType.slice(0,256)}:{},...typeof B.sourceUri==="string"?{sourceUri:B.sourceUri.slice(0,8192)}:{},...typeof B.path==="string"?{path:B.path.slice(0,8192)}:{}}]}):[];x.mcpResult={isError:Y.isError===!0,contentCount:z(Y.contentCount,64),textBytes:z(Y.textBytes,4194304),structuredBytes:z(Y.structuredBytes,4194304),artifactCount:z(Y.artifactCount,64),truncated:Y.truncated===!0,binaryOmitted:Y.binaryOmitted===!0,artifacts:F}}else delete x.mcpResult;return x};function f2(O){let $=typeof O.seq==="number"?{seq:O.seq}:{};if(O.type==="part_created"&&O.data.partType==="tool_call"){let x=O.data.payload;return{type:"tool.start",...$,properties:{messageId:O.data.messageId,toolCallId:x.toolCallId??O.data.partId,toolName:x.toolName??"unknown",arguments:JSON.stringify(x.input??{})}}}if(O.type==="part_created"&&O.data.partType==="tool_result"){let x=O.data.payload,J=x.toolName??"unknown",Q=D$(x),z=kO(IO(J,Q),qO);return{type:"tool.result",...$,properties:{messageId:O.data.messageId,toolCallId:x.toolCallId??O.data.partId,toolName:J,success:Q.success,status:Q.success?"completed":"failed",summary:Q.metadata?.summary,output:SO(z),metadata:EO(J,Q.metadata)}}}return{type:`committed.${O.type}`,...$,properties:{event:O}}}function y2(O,$,x){switch(x.kind){case"tool_start":if("function"in x.toolCall)R.publish(O,"subagent.update",{subagentSessionId:$,toolName:x.toolCall.function.name}),R.publish(O,"subagent.tool.start",{subagentSessionId:$,toolCallId:x.toolCall.id,toolName:x.toolCall.function.name,arguments:x.toolCall.function.arguments,toolKind:x.toolKind});break;case"tool_result":if("function"in x.toolCall)R.publish(O,"subagent.tool.result",{subagentSessionId:$,toolCallId:x.toolCall.id,toolName:x.toolCall.function.name,success:x.result.success,summary:x.result.metadata?.summary,output:SO(kO(IO(x.toolCall.function.name,x.result),qO)),metadata:EO(x.toolCall.function.name,x.result.metadata)});break;case"tool_progress":if("function"in x.toolCall)R.publish(O,"subagent.tool.progress",{subagentSessionId:$,toolCallId:x.toolCall.id,toolName:x.toolCall.function.name,...x.update});break;case"content_delta":R.publish(O,"subagent.delta",{subagentSessionId:$,delta:x.delta});break;case"thinking_delta":R.publish(O,"subagent.thinking.delta",{subagentSessionId:$,delta:x.delta});break;case"stream_end":R.publish(O,"subagent.stream.end",{subagentSessionId:$});break;case"provider_admission":R.publish(O,"subagent.provider.admission",{subagentSessionId:$,phase:x.phase,requestClass:x.requestClass,resource:x.resource,scope:x.scope,reason:x.reason,queuePosition:x.queuePosition,queueDepth:x.queueDepth,inFlight:x.inFlight,limit:x.limit,waitMs:x.waitMs,maxWaitMs:x.maxWaitMs,recoveryRemainingMs:x.recoveryRemainingMs});break;case"provider_circuit":R.publish(O,"subagent.provider.circuit",{subagentSessionId:$,phase:x.phase,reason:x.reason,statusCode:x.statusCode,retryAfterMs:x.retryAfterMs,nextProbeAt:x.nextProbeAt,openDurationMs:x.openDurationMs,sampleCount:x.sampleCount,failureCount:x.failureCount,recoveryRemainingMs:x.recoveryRemainingMs});break;case"provider_retry":R.publish(O,"subagent.provider.retry",{subagentSessionId:$,phase:x.phase,attempt:x.attempt,maxRetries:x.maxRetries,reason:x.reason,statusCode:x.statusCode,delayMs:x.delayMs,nextRetryAt:x.nextRetryAt,mode:x.mode,recoveryBudgetMs:x.recoveryBudgetMs,recoveryElapsedMs:x.recoveryElapsedMs,recoveryRemainingMs:x.recoveryRemainingMs,exhaustedBy:x.exhaustedBy});break;case"provider_stall":R.publish(O,"subagent.provider.stall",{subagentSessionId:$,phase:x.phase,stallCount:x.stallCount,durationMs:x.durationMs,warningAfterMs:x.warningAfterMs,timeoutMs:x.timeoutMs,outputStarted:x.outputStarted});break;case"action_stationarity":R.publish(O,"subagent.action.stationarity",{subagentSessionId:$,phase:x.phase,toolName:x.toolName,runLength:x.runLength,nudgeThreshold:x.nudgeThreshold,haltThreshold:x.haltThreshold,progressAware:x.progressAware});break;case"mcp_catalog_changed":R.publish(O,"subagent.mcp.catalog.changed",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,added:x.added,removed:x.removed,updated:x.updated});break;case"mcp_content_changed":R.publish(O,"subagent.mcp.content.changed",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,contentKind:x.contentKind,added:x.added,removed:x.removed,updated:x.updated});break;case"mcp_resource_updated":R.publish(O,"subagent.mcp.resource.updated",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,uri:x.uri});break;case"mcp_connection_changed":R.publish(O,"subagent.mcp.connection.changed",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,phase:x.phase,reason:x.reason,attempt:x.attempt,maxAttempts:x.maxAttempts,nextRetryAt:x.nextRetryAt,error:x.error});break;case"mcp_log":R.publish(O,"subagent.mcp.log",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,level:x.level,logger:x.logger,message:x.message,projectedBytes:x.projectedBytes,dataSha256:x.dataSha256,truncated:x.truncated,detailsOmitted:x.detailsOmitted,timestamp:x.timestamp,synthetic:x.synthetic});break;case"mcp_instructions_changed":R.publish(O,"subagent.mcp.instructions.changed",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,action:x.action,reason:x.reason,text:x.text,sourceBytes:x.sourceBytes,projectedBytes:x.projectedBytes,sha256:x.sha256,truncated:x.truncated,detailsOmitted:x.detailsOmitted});break;case"mcp_task_changed":R.publish(O,"subagent.mcp.task.changed",{subagentSessionId:$,revision:x.revision,taskId:x.taskId,serverName:x.serverName,toolName:x.toolName,status:x.status,statusMessage:x.statusMessage,createdAt:x.createdAt,updatedAt:x.updatedAt,completedAt:x.completedAt,hasResult:x.hasResult,error:x.error});break;case"project_rules_loaded":R.publish(O,"subagent.project.rules.loaded",{subagentSessionId:$,files:x.files,triggerPaths:x.triggerPaths,blockedWrite:x.blockedWrite});break;default:break}}function CO(O,$="projectPath"){if(!K1.isAbsolute(O))throw new H(`${$} must be absolute`);return K1.resolve(O)}function U$(O){try{pO(O)}catch($){throw new H($ instanceof Error?$.message:`Invalid session ID: ${O}`)}}function z0(O){return{sessionId:O.id,projectPath:O.projectPath}}function bO(O,$,x){return{id:O.sessionId,projectPath:O.projectPath,title:O.title??`Session ${O.sessionId.slice(0,6)}`,createdAt:new Date(O.firstMessageTime),updatedAt:new Date(O.lastMessageTime),rootId:O.rootId,parentId:O.parentId,relationType:O.relationType,taskStatus:O.taskStatus,taskStatusReason:O.taskStatusReason,taskFailure:O.taskFailure,taskStartedAt:O.taskStartedAt,taskCompletedAt:O.taskCompletedAt,taskPromptSummary:O.taskPromptSummary,taskPriority:O.taskPriority,taskKind:O.taskKind,taskDueAt:O.taskDueAt,taskModelId:O.taskModelId,selectedModelId:O.selectedModelId,permissionMode:O.permissionMode,reasoningEffort:O.reasoningEffort,serviceTier:O.serviceTier,responseVerbosity:O.responseVerbosity,communicationStyle:O.communicationStyle,communicationStyleDigest:O.communicationStyleDigest,projectInstructionsDigest:O.projectInstructionsDigest,pendingInteraction:O.pendingInteraction,taskRetryAvailable:O.taskRetryAvailable,taskRetriedFrom:O.taskRetriedFrom,taskDelivery:O.taskDelivery,taskIsolation:O.taskIsolation,taskSourceProjectPath:O.taskSourceProjectPath,taskWorktreePath:O.taskWorktreePath,taskWorktreeBranch:O.taskWorktreeBranch,taskBaseCommit:O.taskBaseCommit,taskDiffStat:O.taskDiffStat,taskQueuePosition:O.taskQueuePosition,taskQueueDepth:O.taskQueueDepth,taskConcurrencyLimit:O.taskConcurrencyLimit,archivedAt:O.archivedAt,archivedBySessionId:O.archivedBySessionId,taskWorktree:x,messages:$}}function Y$(O){return O.flatMap(($)=>{if(!j1($)||$.role==="system"||$.role==="tool"&&$.name===YO)return[];let x=$.tool_calls?.filter((Y)=>!("function"in Y)||Y.function.name!==YO),J=typeof $.content==="string"?$.content.trim():"";if($.role==="assistant"&&$.tool_calls?.length&&!x?.length&&!J&&!$.reasoningContent&&!$.metadata)return[];let Q={...$,...$.tool_calls?{tool_calls:x&&x.length>0?x:void 0}:{}};if($.role==="tool"){let Y=$.metadata&&typeof $.metadata==="object"&&!Array.isArray($.metadata)?$.metadata:void 0,F=$.name??(typeof Y?.toolName==="string"?Y.toolName:"unknown");if(Y!==void 0&&(Object.hasOwn(Y,"output")||Object.hasOwn(Y,"error"))){let B=D$(Y),C=kO(IO(F,B),qO);return[{...Q,name:F,content:SO(C),metadata:EO(F,{...B.metadata,status:B.success?"completed":"failed"})}]}return[{...Q,name:F,metadata:EO(F,Y)}]}let z=C1($.metadata);return[z?{...Q,content:T1(z)}:Q]})}function GO(O,$){O.title=$.title??O.title,O.taskStatus=$.taskStatus,O.taskStatusReason=$.taskStatusReason,O.taskFailure=$.taskFailure,O.taskStartedAt=$.taskStartedAt,O.taskCompletedAt=$.taskCompletedAt,O.taskPromptSummary=$.taskPromptSummary,O.taskPriority=$.taskPriority,O.taskKind=$.taskKind,O.taskDueAt=$.taskDueAt,O.taskModelId=$.taskModelId,O.selectedModelId=$.selectedModelId,O.permissionMode=$.permissionMode,O.reasoningEffort=$.reasoningEffort,O.serviceTier=$.serviceTier,O.responseVerbosity=$.responseVerbosity,O.communicationStyle=$.communicationStyle,O.communicationStyleDigest=$.communicationStyleDigest,O.projectInstructionsDigest=$.projectInstructionsDigest,O.pendingInteraction=$.pendingInteraction,O.taskRetryAvailable=$.taskRetryAvailable,O.taskRetriedFrom=$.taskRetriedFrom,O.taskDelivery=$.taskDelivery,O.taskIsolation=$.taskIsolation,O.taskSourceProjectPath=$.taskSourceProjectPath,O.taskWorktreePath=$.taskWorktreePath,O.taskWorktreeBranch=$.taskWorktreeBranch,O.taskBaseCommit=$.taskBaseCommit,O.taskDiffStat=$.taskDiffStat,O.taskQueuePosition=$.taskQueuePosition,O.taskQueueDepth=$.taskQueueDepth,O.taskConcurrencyLimit=$.taskConcurrencyLimit,O.archivedAt=$.archivedAt,O.archivedBySessionId=$.archivedBySessionId,O.updatedAt=new Date($.lastMessageTime)}async function n0(O){let $=await E.findSessionMetadata(O.id,O.projectPath);if($)GO(O,$)}function i0(O){let $=D0(O.currentRunId),x=$?.status==="waiting_permission"?"running":$?.status??O.taskStatus;return{sessionId:O.id,projectPath:O.projectPath,title:O.title,rootId:O.rootId,parentId:O.parentId,relationType:O.relationType,status:void 0,taskStatus:x,taskStatusReason:O.taskStatusReason,taskFailure:O.taskFailure,taskStartedAt:O.taskStartedAt,taskCompletedAt:O.taskCompletedAt,taskPromptSummary:O.taskPromptSummary,taskPriority:O.taskPriority,taskKind:O.taskKind,taskDueAt:O.taskDueAt,taskModelId:O.taskModelId,selectedModelId:O.selectedModelId,permissionMode:O.permissionMode,reasoningEffort:O.reasoningEffort,serviceTier:O.serviceTier,responseVerbosity:O.responseVerbosity,communicationStyle:O.communicationStyle,communicationStyleDigest:O.communicationStyleDigest,projectInstructionsDigest:O.projectInstructionsDigest,taskRetryAvailable:O.taskRetryAvailable,taskRetriedFrom:O.taskRetriedFrom,taskDelivery:O.taskDelivery,taskIsolation:O.taskIsolation,taskSourceProjectPath:O.taskSourceProjectPath,taskWorktreePath:O.taskWorktreePath,taskWorktreeBranch:O.taskWorktreeBranch,taskBaseCommit:O.taskBaseCommit,taskDiffStat:O.taskDiffStat,taskQueuePosition:$?.status==="queued"?$.taskQueuePosition:x==="queued"?O.taskQueuePosition:void 0,taskQueueDepth:$?.status==="queued"?$.taskQueueDepth:x==="queued"?O.taskQueueDepth:void 0,taskConcurrencyLimit:$?.taskConcurrencyLimit??O.taskConcurrencyLimit,archivedAt:O.archivedAt,archivedBySessionId:O.archivedBySessionId,pendingInteraction:$?.pendingPermission?{type:$.pendingPermission.details.type==="askUserQuestion"?"question":$.pendingPermission.details.type==="mcpElicitation"?"elicitation":"permission",requestId:$.pendingPermission.permissionId}:O.pendingInteraction,agentType:void 0,model:void 0,messageCount:O.messages.length,firstMessageTime:O.createdAt.toISOString(),lastMessageTime:O.updatedAt.toISOString(),hasErrors:!1,isActive:!0}}async function N0(O,$){if(U$(O),$!==void 0){let J=m0({sessionId:O,projectPath:CO($)});if(t.has(g(J)))return J;let Q=await E.findSessionMetadata(J.sessionId,J.projectPath);if(!Q)throw new S("Session",O);return m0({sessionId:Q.sessionId,projectPath:Q.projectPath})}let x=new Map;for(let J of t.values()){if(J.id!==O)continue;let Q=z0(J);x.set(g(Q),Q)}for(let J of await E.listSessions()){if(J.sessionId!==O)continue;let Q=m0({sessionId:J.sessionId,projectPath:J.projectPath});x.set(g(Q),Q)}if(x.size===0)try{let J=await E.findSessionMetadata(O);if(!J)throw new S("Session",O);return m0({sessionId:J.sessionId,projectPath:J.projectPath})}catch(J){if(J instanceof S)throw J;if(J instanceof Error&&J.message.startsWith("Ambiguous session ID:"))throw new B0;throw J}if(x.size>1)throw new B0;return x.values().next().value}function _$(O){if(typeof O==="string")return O;return O.filter(($)=>$.type==="text").map(($)=>$.text).join(`
|
|
7
|
-
`)}function F1(O,$){let x=($??[]).filter((Q)=>Q.type==="image"&&typeof Q.content==="string").map((Q)=>({type:"image_url",image_url:{url:Q.content}}));if(x.length===0)return O;let J=[];if(O.trim())J.push({type:"text",text:O});return J.push(...x),J}var u1=()=>{S2();let O=new w2;O.onError((Z,N)=>{if(Z instanceof QO){let G=new k0("Session runtime capacity is full",{resource:Z.resource,limit:Z.limit});return N.json(G.toObject(),429)}if(Z instanceof Z0)return N.json(Z.toObject(),Z.statusCode);return y.error("[SessionRoutes] Unhandled route error:",Z),N.json({error:{code:"INTERNAL_ERROR",message:"Internal server error"}},500)});let $=new Map,x=new Map,J=new Map,Q=new Map,z=new z$,Y=new z$,F=J0(),T=new g1({maxResident:F?.maxResidentSessionRuntimes??D1,idleMs:F?.sessionRuntimeIdleMs??H1}),B=new q1,C=setInterval(()=>{T.sweepIdle().catch((Z)=>{y.warn("[SessionRoutes] Session Runtime idle sweep failed:",Z)})},B1);C.unref?.();let w,W=async(Z)=>{let N;try{N=B.enter()}catch{throw new l0}try{return await Z()}finally{N.release()}};O.use("*",async(Z,N)=>{if(Z.req.method==="GET"||Z.req.method==="HEAD")return N();return W(N)});let I=(Z,N)=>z.runExclusive(g(Z),N),Q0=(Z,N)=>Y.runExclusive(g(Z),N),p=(Z)=>[...b0.values()].some((N)=>N.sessionId===Z.sessionId&&N.projectPath===Z.projectPath&&_0(N)),b=async(Z,N,G)=>{let X=J.get(N);if(!X)X=(async()=>{if($.get(N)===G)$.delete(N);for(let[_,D]of $)if(D===G)$.delete(_);let K=z0(Z);if(t.get(N)===Z&&!p(K)&&!I0.has(N)&&!C0.has(N))t.delete(N);if(await G.dispose(),$.size===0)await U0.getInstance().disconnectAll()})().finally(()=>{if(J.get(N)===X)J.delete(N)}),J.set(N,X);await X},e=async(Z,N={})=>{let G=z0(Z),X=g(G);await J.get(X);let K=T.acquire(X);if(K){if($.get(X)!==K.value)throw K.release(),Error("Session Runtime residency identity is inconsistent");return K}if(T.owns(X))throw new QO(T.getStats().maxResident);let _=x.get(X);if(!_){let D=N.communicationStyle??Z.communicationStyle;_=(async()=>{let L=await T.reserve(X,{surface:"web",allowEviction:!0});try{let A=await TO.create({sessionId:Z.id,workspaceRoot:Z.projectPath,...Z.selectedModelId??Z.taskModelId?{modelId:Z.selectedModelId??Z.taskModelId}:{},permissionMode:N.permissionMode??Z.permissionMode??"default",...Z.reasoningEffort?{reasoningEffort:Z.reasoningEffort}:{},...Z.serviceTier?{serviceTier:Z.serviceTier}:{},...Z.responseVerbosity?{responseVerbosity:Z.responseVerbosity}:{},...D?{communicationStyle:D}:{},...D===Z.communicationStyle&&Z.communicationStyleDigest?{communicationStyleDigest:Z.communicationStyleDigest}:{},...Z.projectInstructionsDigest?{projectInstructionsDigest:Z.projectInstructionsDigest}:{},...Z.taskWorktree?{taskWorktree:Z.taskWorktree}:{},...Z.taskIsolation?{taskIsolation:Z.taskIsolation}:{},...Z.messages.length>0?{sessionStart:{isResume:!0,resumeSessionId:Z.id}}:{}}),M=L.commit({key:X,surface:"web",value:A,canEvict:()=>!p(G)&&!I0.has(X)&&!C0.has(X)&&!x.has(X)&&!J.has(X)&&A.isIdleForResidency(),dispose:()=>b(Z,X,A)});return $.set(X,A),{runtime:A,claimLease:()=>{if(M){let k=M;return M=void 0,k}let j=T.acquire(X);if(!j||j.value!==A)throw Error("Initialized Session Runtime lost residency");return j}}}catch(A){throw L.cancel(),A}})(),x.set(X,_)}try{return(await _).claimLease()}finally{if(x.get(X)===_)x.delete(X)}},v=async(Z,N,G={})=>{let X=await e(Z,G);try{return await N(X.value)}finally{X.release()}},Y0=async(Z,N)=>{let G=g(z0(Z)),X=x.get(G);if(X)await X.catch(()=>{return});x.delete(G);let K=N??$.get(G);if(!K)return;if(!await T.remove(G,K))throw Error(`Session Runtime is pinned and cannot be disposed: ${G}`)},i=async(Z)=>{let N=g(Z),G=t.get(N);if(G)return G;let X=Q.get(N);if(!X)X=(async()=>{let K=await E.findSessionMetadata(Z.sessionId,Z.projectPath);if(!K)throw new S("Session",Z.sessionId);let[_,D]=await Promise.all([E.loadSession(Z.sessionId,Z.projectPath),E.findSessionTaskWorktree(Z.sessionId,Z.projectPath)]),L=bO(K,_,D);return t.set(N,L),L})(),Q.set(N,X);try{return await X}finally{if(Q.get(N)===X)Q.delete(N)}},x0=async(Z,N)=>{let G=await N0(Z,N);try{await E.assertSessionWritable(G.sessionId,G.projectPath)}catch(X){if(X instanceof V$)throw new q(X.message);throw X}return i(G)},S0=async(Z,N)=>{if(Z.permissionMode===N)return;let G=await E.setSessionPermissionMode(Z.id,Z.projectPath,N);Z.permissionMode=G.permissionMode,Z.updatedAt=new Date(G.lastMessageTime),R.publish(z0(Z),"session.updated",{permissionMode:N})},o=(Z,N,G,X={})=>{if(!B.stats().accepting)throw new l0;let K=ZO(12),_={id:K,sessionId:Z.id,projectPath:Z.projectPath,status:"running",abortController:new AbortController,disposeRuntimeOnSettle:Z.taskIsolation!==void 0&&X.runtimeLease!==void 0,createdAt:new Date};if(Z.taskIsolation&&X.runtimeLease){let D=X.runtimeLease.value,L=f0.admit({key:`${Z.projectPath}\x00${Z.id}`,...D.getTaskAdmissionLimits(),pendingBytes:k1({content:N,outputSchema:X.outputSchema,pendingMessages:D.getPendingSteeringMessages()}),signal:_.abortController.signal,onUpdate:(M)=>{_.status=M.state,_.taskQueuePosition=M.queuePosition,_.taskQueueDepth=M.queueDepth,_.taskConcurrencyLimit=M.maxConcurrent,Z.taskStatus=M.state,Z.taskQueuePosition=M.queuePosition,Z.taskQueueDepth=M.queueDepth,Z.taskConcurrencyLimit=M.maxConcurrent,_.taskAdmissionUpdate=(_.taskAdmissionUpdate??Promise.resolve()).then(async()=>{await D.setTaskAdmission(M)}).catch((j)=>{y.warn(`[SessionRoutes] Failed to persist admission for ${Z.id}:`,j)})}});_.taskAdmission=L;let A=L.getSnapshot();_.status=A.state,_.taskQueuePosition=A.queuePosition,_.taskQueueDepth=A.queueDepth,_.taskConcurrencyLimit=A.maxConcurrent}return b0.set(K,_),Z.currentRunId=K,_.completion=m2(_,Z,N,G,e,{pendingInputOnly:X.pendingInputOnly,preparedInputTurn:X.preparedInputTurn,goalContinuationOnly:X.goalContinuationOnly,outputSchema:X.outputSchema,taskAdmission:_.taskAdmission,runtimeLease:X.runtimeLease,disposeRuntime:Y0}).catch((D)=>{y.error(`[SessionRoutes] Run ${K} failed:`,D)}),_},p0=async(Z)=>{let N;if(Z.outputSchema)try{N=X$(Z.outputSchema).schema}catch(u){throw new H(u instanceof Error?u.message:"Invalid output schema")}let G=G$("task",12),X=CO(Z.sourceProjectPath),K=Z.modelId?.trim(),_=J0();if(!_)throw new H("Config not initialized");let[D,L]=await Promise.all([cO(X,_),T0(X)]);if(K&&!D.config.models.some((u)=>u.id===K))throw new H(`Task model not found: ${K}`);let A=K||D.config.models.find((u)=>u.id===D.config.currentModelId)?.id||D.config.models[0]?.id;if(!A)throw new H("No model is configured. Add or select a model before dispatching a task.");let M=D.config.models.find((u)=>u.id===A);if(!M)throw new H(`Task model not found: ${A}`);let j=Z.reasoningEffort??"off",k=Z.serviceTier??"auto",K0=Z.responseVerbosity??"auto",P0=Z.communicationStyle??"auto",j0,G0=L.projectRules?.staticRules(X),O0=G0&&G0.files.length>0?G0.provenanceSha256:void 0;try{let u=D.catalog.resolveConfig(M);L1(u,j),_1(u,k),U1(u,K0);let l=w1(P0,L.communicationStyles);j0=l.source==="built-in"?void 0:l.contentSha256}catch(u){throw new H(u instanceof Error?u.message:"Invalid reasoning effort")}let r0={version:1,prompt:Z.prompt,...Z.title?{title:Z.title}:{},...Z.taskPriority?{taskPriority:Z.taskPriority}:{},...Z.taskKind?{taskKind:Z.taskKind}:{},...Z.taskDueAt?{taskDueAt:Z.taskDueAt}:{},sourceProjectPath:X,isolation:Z.isolation,permissionMode:Z.permissionMode,modelId:A,reasoningEffort:j,serviceTier:k,responseVerbosity:K0,communicationStyle:P0,...j0?{communicationStyleDigest:j0}:{},...O0?{projectInstructionsDigest:O0}:{},...Z.attachments?{attachments:Z.attachments.map((u)=>({...u}))}:{},...N?{outputSchema:N}:{}},m,h,f;try{let u=await S1.createSessionTask({sessionId:G,prompt:Z.prompt,title:Z.title,taskPriority:Z.taskPriority,taskKind:Z.taskKind,taskDueAt:Z.taskDueAt,sourceProjectPath:X,isolation:Z.isolation,dispatch:r0,retriedFrom:Z.retriedFrom}),{metadata:l}=u;m=u.taskWorktree,h=bO(l,[],m);let d=z0(h);t.set(g(d),h),R.publish(d,"task.status",{taskStatus:l.taskStatus,updatedAt:l.lastMessageTime});let s=F1(Z.prompt,Z.attachments);f=await e(h);let _O=f.value,n=N?await _O.prepareInputTurn(s,{outputSchema:N}):await _O.prepareInputTurn(s);if(!n.accepted)throw new q(`Task prompt was not accepted: ${n.reason}`);let $0=o(h,s,Z.permissionMode,{preparedInputTurn:n,runtimeLease:f,outputSchema:N});return f=void 0,await $0.taskAdmissionUpdate,{session:i0(h),runId:$0.id,messageId:n.messageId,status:$0.status==="queued"?"queued":"running",queuePosition:$0.taskQueuePosition,queueDepth:$0.taskQueueDepth,maxConcurrentTasks:$0.taskConcurrencyLimit}}catch(u){if(f?.release(),f=void 0,(u instanceof F$||u instanceof QO)&&h){let l=z0(h),d=g(l);if(m)await E0.exit({sessionId:h.id,action:"remove",discardChanges:!0}).catch(()=>{return});throw await Y0(h).catch(()=>{return}),await E.deleteSession(h.id,h.projectPath).catch(()=>{return}),t.delete(d),new k0(u instanceof QO?"Session runtime capacity is full":"Task admission capacity is full",{resource:u.resource,limit:u.limit})}if(h){let l=await E.findSessionMetadata(h.id,h.projectPath).catch(()=>{return});if(!l||l.taskStatus==="queued"){let d=aO(u),s=await E.updateSessionMetadata(h.id,h.projectPath,{taskStatus:"failed",taskStatusReason:d.message,taskFailure:d,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null}).catch(()=>{return});h.taskStatus=s?.taskStatus??"failed",h.taskStatusReason=s?.taskStatusReason??d.message,h.taskFailure=s?.taskFailure??d,h.taskCompletedAt=s?.taskCompletedAt}else h.taskStatus=l.taskStatus,h.taskStatusReason=l.taskStatusReason,h.taskFailure=l.taskFailure,h.taskCompletedAt=l.taskCompletedAt}throw u}},w0=(Z)=>W(()=>p0(Z)),V=async(Z,N)=>{let G=await N0(Z,N),X=await E.findSessionMetadata(G.sessionId,G.projectPath);if(!X)throw new S("Session",G.sessionId);if(!["failed","interrupted","cancelled"].includes(X.taskStatus))throw new q(`Task cannot be retried while status is ${X.taskStatus}`);let K=await E.findSessionTaskDispatch(G.sessionId,G.projectPath);if(!K)throw new q("Task retry payload is unavailable");return w0({prompt:K.prompt,title:X.title??K.title,taskPriority:X.taskPriority??K.taskPriority,taskKind:X.taskKind??K.taskKind,taskDueAt:X.taskDueAt,sourceProjectPath:K.sourceProjectPath,isolation:K.isolation,permissionMode:K.permissionMode,modelId:K.modelId,reasoningEffort:K.reasoningEffort,serviceTier:K.serviceTier,responseVerbosity:K.responseVerbosity,communicationStyle:K.communicationStyle,attachments:K.attachments,outputSchema:K.outputSchema,retriedFrom:G})},V0=(Z,N)=>W(()=>V(Z,N)),S$=(Z,N,G)=>W(async()=>{let X=await N0(Z,G);if(!await E.findSessionMetadata(X.sessionId,X.projectPath))throw new S("Session",X.sessionId);let _=await E.updateSessionMetadata(X.sessionId,X.projectPath,N),D=t.get(g(X));if(D)GO(D,_);return R.publish(X,"session.updated",{..._.title?{title:_.title}:{},..._.taskPriority?{taskPriority:_.taskPriority}:{},..._.taskKind?{taskKind:_.taskKind}:{},taskDueAt:_.taskDueAt??null}),D?i0(D):{..._,isActive:!1}}),eO=async(Z,N)=>{let G=await x0(Z,N);if(!G.taskWorktree)throw new H("Session does not have a task worktree");try{await E0.restoreSession(G.taskWorktree);let X=await E0.getDiffArtifact(G.id);if(!X)throw new q("Task diff artifact is unavailable");return{sessionId:G.id,projectPath:G.projectPath,...X}}catch(X){if(X instanceof q)throw X;throw y.error("[SessionRoutes] Failed to load task diff artifact:",X),new q("Task diff artifact is unavailable")}},UO=async(Z,N,G)=>{let X=await N0(Z,G);return Q0(X,async()=>{let K=await x0(X.sessionId,X.projectPath);if(["queued","running"].includes(K.taskStatus))throw new q(`Task artifacts cannot be delivered while status is ${K.taskStatus}`);if(K.taskDelivery?.status==="applied")throw new q("Task changes have already been applied");if(K.taskDelivery?.status==="discarded")throw new q("Task changes have already been discarded");if(!K.taskWorktree)throw new q("Task worktree is unavailable");let _=async(D,L=!1)=>{let A=await E.updateSessionMetadata(K.id,K.projectPath,{taskDelivery:D,...L?{taskWorktree:null}:{}});if(GO(K,A),L)K.taskWorktree=void 0;return R.publish(X,"task.delivery",{taskDelivery:D,...L?{taskWorktreeRemoved:!0}:{},updatedAt:A.lastMessageTime}),i0(K)};try{if(N==="discard"){try{await E0.restoreSession(K.taskWorktree)}catch(A){return y.warn(`[SessionRoutes] Abandoning unavailable task worktree for ${K.id}:`,A),_({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:K.taskDiffStat?.changedFiles??0,message:"Task artifact discarded; worktree was unavailable"},!0)}let L=await E0.exit({sessionId:K.id,action:"remove",discardChanges:!0});return _({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:L.discardedFiles??0,message:"Task worktree removed"},!0)}try{await E0.restoreSession(K.taskWorktree)}catch(L){throw y.warn(`[SessionRoutes] Task worktree is unavailable for ${K.id}:`,L),new W$("artifact_unavailable","Task worktree is unavailable")}let D=await E0.apply(K.id);return _({status:"applied",updatedAt:new Date().toISOString(),sourceCommit:D.sourceCommit,changedFiles:D.changedFiles,message:"Task changes applied to the source workspace"})}catch(D){if(D instanceof W$)throw await _({status:"conflicted",updatedAt:new Date().toISOString(),message:D.message}),new q(D.message);throw D}})},mO=(Z,N,G)=>W(()=>UO(Z,N,G)),hO=async(Z)=>{let N=D0(Z.currentRunId);if(_0(N))return;if(Z.taskIsolation&&Z.taskStatus!=="queued"&&Z.taskStatus!=="running")return;let G=await TO.hasPendingInbox(Z.projectPath,Z.id),X=!G&&await TO.hasActiveGoal(Z.projectPath,Z.id);if(!G&&!X)return;let K=await e(Z),_=!1;try{let D=K.value,L=D0(Z.currentRunId);if(_0(L))return;if(G&&D.getPendingSteeringCount()===0)await D.reloadPendingInbox();let A=D.getPendingSteeringCount()>0,M=A?null:await D.getGoal(),j=M?.status==="active"||M?.status==="verifying";if(!A&&!j||D.hasTurnOwner())return;o(Z,"",Z.permissionMode??"default",{pendingInputOnly:A,goalContinuationOnly:j,runtimeLease:K}),_=!0}finally{if(!_)K.release()}},q0=async(Z)=>{let N;try{N=B.enter()}catch{return}try{await hO(Z)}finally{N.release()}};zO=q0;let O$=async()=>{let Z={scheduled:0,failed:0,deferred:0};if(!B.stats().accepting)return Z;let N=(await E.listSessions({taskStatus:"queued"})).filter((G)=>G.taskIsolation!==void 0).sort((G,X)=>G.firstMessageTime.localeCompare(X.firstMessageTime)||G.projectPath.localeCompare(X.projectPath)||G.sessionId.localeCompare(X.sessionId));for(let[G,X]of N.entries()){let K={sessionId:X.sessionId,projectPath:X.projectPath};try{if(!await TO.hasPendingInbox(X.projectPath,X.sessionId)){let D=aO("Queued task input is missing");await E.updateSessionMetadata(X.sessionId,X.projectPath,{taskStatus:"failed",taskStatusReason:D.message,taskFailure:D,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null}),Z.failed++;continue}let _=await i(K);if(await q0(_),_.currentRunId)Z.scheduled++}catch(_){if(_ instanceof F$||_ instanceof QO){Z.deferred+=N.length-G;break}y.warn(`[SessionRoutes] Failed to recover queued task ${X.sessionId}:`,_),Z.deferred++}}return Z};return O.get("/",async(Z)=>{try{let N=await E.listSessions(),G=new Set(N.filter((M)=>M.relationType==="subagent").map((M)=>g({sessionId:M.sessionId,projectPath:M.projectPath}))),X=Array.from(t.values()).filter((M)=>!G.has(g(z0(M)))&&M.relationType!=="subagent").map((M)=>i0(M)),K=new Set(X.map((M)=>g({sessionId:M.sessionId,projectPath:M.projectPath}))),_=N.filter((M)=>{if(M.relationType==="subagent")return!1;return!K.has(g({sessionId:M.sessionId,projectPath:M.projectPath}))}),D=new Set(K),L=_.filter((M)=>{let j=g({sessionId:M.sessionId,projectPath:M.projectPath});if(D.has(j))return!1;return D.add(j),!0}),A=[...X,...L];return Z.json(A)}catch(N){throw y.error("[SessionRoutes] Failed to list sessions:",N),new r("Failed to list sessions")}}),O.get("/catalog",async(Z)=>{try{let N=Z.req.query("limit"),G=N===void 0?void 0:Number(N),X=Z.req.query("cursor"),K=Z.req.query("projectPath"),_=Z.req.query("archived");if(_!==void 0&&_!=="true"&&_!=="false")throw new H("archived must be true or false");let D=_==="true",L=await E.listSessionPage({...K?{cwd:CO(K)}:{},...X?{cursor:X}:{},...G===void 0?{}:{limit:G},includeSubagents:!1,archived:D}),A=new Map((D?[]:Array.from(t.values())).filter((M)=>M.relationType!=="subagent").map((M)=>[g(z0(M)),i0(M)]));return Z.json({sessions:L.sessions.map((M)=>A.get(g({sessionId:M.sessionId,projectPath:M.projectPath}))??M),...L.nextCursor?{nextCursor:L.nextCursor}:{}})}catch(N){if(N instanceof H)throw N;if(N instanceof Error&&(N.message.startsWith("Invalid session cursor")||N.message.startsWith("Session cursor scope")||N.message.startsWith("Session catalog")))throw new H(N.message);throw y.error("[SessionRoutes] Failed to list session catalog:",N),new r("Failed to list session catalog")}}),O.post("/",async(Z)=>{try{let N=await Z.req.json(),G=P(j2,N);if(!G.success)throw new H("Invalid request body");let{title:X,projectPath:K}=G.data,_=G$("web",12),D=CO(K||Z.get("directory")||c(),K?"projectPath":"directory"),L=await E.createSessionMetadata(_,D,{title:X,taskStatus:"completed"}),A=bO(L,[]),M=z0(A);return t.set(g(M),A),R.publish(M,"session.created",{}),Z.json({...i0(A),status:void 0,agentType:void 0,model:void 0})}catch(N){if(y.error("[SessionRoutes] Failed to create session:",N),N instanceof H)throw N;throw new r("Failed to create session")}}),O.get("/:sessionId/export",async(Z)=>{let N=Z.req.param("sessionId");try{let G=Z.req.query("includeReasoning");if(G!==void 0&&G!=="true"&&G!=="false")throw new H("includeReasoning must be true or false");let X=await N0(N,Z.req.query("projectPath")),K=await E.exportSessionMarkdown(X.sessionId,X.projectPath,{includeReasoning:G==="true"});return Z.body(K.markdown,200,{"Cache-Control":"no-store","Content-Disposition":`attachment; filename="${K.filename}"`,"Content-Length":String(Buffer.byteLength(K.markdown,"utf8")),"Content-Type":"text/markdown; charset=utf-8","X-Blade-Content-Sha256":K.contentSha256,"X-Blade-Export-Activities":String(K.activityCount),"X-Blade-Export-Messages":String(K.messageCount),"X-Blade-Export-Redactions":String(K.redactionCount)})}catch(G){if(G instanceof H||G instanceof S||G instanceof B0)throw G;if(G instanceof Error&&G.message==="No conversation content to export")throw new q(G.message);throw y.error("[SessionRoutes] Failed to export session:",G),new r("Failed to export session")}}),O.post("/:sessionId/fork",async(Z)=>{let N=Z.req.param("sessionId");try{U$(N);let G=await Z.req.json(),X=P(b2,G);if(!X.success)throw new H("Invalid request body");let K=CO(X.data.projectPath),_=await E.findSessionMetadata(N,K);if(!_)throw new S("Session",N);let D=await E.forkSession(N,{sourceProjectPath:_.projectPath,targetProjectPath:_.projectPath}),L=bO(D.metadata,D.messages),A=z0(L);return t.set(g(A),L),R.publish(A,"task.status",{taskStatus:D.metadata.taskStatus,...D.metadata.taskCompletedAt?{taskCompletedAt:D.metadata.taskCompletedAt}:{},updatedAt:D.metadata.lastMessageTime}),Z.json({session:D.metadata,messages:Y$(D.messages)},201)}catch(G){if(G instanceof H||G instanceof S||G instanceof q)throw G;if(G instanceof b1)throw new q("Session has no durable creation record");throw y.error("[SessionRoutes] Failed to fork session:",G),new r("Failed to fork session")}}),O.get("/:sessionId",async(Z)=>{let N=Z.req.param("sessionId");try{let G=await N0(N,Z.req.query("projectPath")),X=t.get(g(G));if(X)return Z.json(i0(X));let K=await E.findSessionMetadata(G.sessionId,G.projectPath);if(!K)throw new S("Session",N);return Z.json(K)}catch(G){if(G instanceof H||G instanceof S||G instanceof B0)throw G;throw y.error("[SessionRoutes] Failed to get session:",G),new r("Failed to get session")}}),O.patch("/:sessionId",async(Z)=>{let N=Z.req.param("sessionId");try{let G=await Z.req.json(),X=P(C2,G);if(!X.success)throw new H("Invalid request body");if(X.data.title===void 0)throw new H("title is required");let K=await N0(N,X.data.projectPath),_=await E.updateSessionMetadata(K.sessionId,K.projectPath,{title:X.data.title}),D=t.get(g(K));if(D)D.title=_.title??D.title,D.updatedAt=new Date(_.lastMessageTime);if(_.title)R.publish(K,"session.updated",{title:_.title});return Z.json({success:!0,title:_.title})}catch(G){if(y.error("[SessionRoutes] Failed to update session:",G),G instanceof H||G instanceof S||G instanceof B0)throw G;throw new r("Failed to update session")}}),O.get("/:sessionId/rewind",async(Z)=>{let N=await x0(Z.req.param("sessionId"),Z.req.query("projectPath"));return v(N,async(G)=>Z.json({checkpoints:await G.listRewindCheckpoints()}))}),O.post("/:sessionId/rewind",async(Z)=>{let N=P(P1,await Z.req.json());if(!N.success)throw new H("Invalid rewind request");let G=await x0(Z.req.param("sessionId"),Z.req.query("projectPath")),X=z0(G);return I(X,async()=>{let K=D0(G.currentRunId);if(_0(K))throw new q("Cannot rewind while a run is active");return v(G,async(_)=>{let D;try{D=await _.rewindSession(N.data)}catch(A){if(A instanceof Error&&A.message.startsWith("Cannot rewind while"))throw new q(A.message);throw A}G.messages=[...D.messages],G.updatedAt=new Date;let L=Y$(D.messages);return R.publish(X,"session.rewound",{targetMessageId:D.checkpoint.messageId,mode:D.mode,removedTurns:D.removedTurns,restoredFiles:D.restoredFiles,messages:L}),Z.json({...D,messages:L})})})}),O.get("/:sessionId/review",async(Z)=>{let N=Z.req.param("sessionId"),G=await N0(N,Z.req.query("projectPath")),X=await a0.list(G.projectPath,G.sessionId);return Z.json({reviews:X.map((K)=>({...K,content:K.completion?A1(K.start,K.completion):void 0}))})}),O.post("/:sessionId/review",async(Z)=>{let N=Z.req.param("sessionId"),G=P(h1,await Z.req.json());if(!G.success)throw new H("Invalid code review request");let X=await x0(N,G.data.projectPath),K=z0(X),_=g(K);return I(K,async()=>{if(_0(D0(X.currentRunId)))throw new q("Cannot start a review during an active turn");if(C0.has(_))throw new q("Session already has an active review");return v(X,async(D)=>{if(await a0.recoverInterrupted(K.projectPath,K.sessionId,D),G.data.modelId&&!D.getModelById(G.data.modelId))throw new H(`Model not found: ${G.data.modelId}`);if(G.data.modelId&&D.getCurrentModelId()!==G.data.modelId)await D.refresh({modelId:G.data.modelId});if(G.data.modelId&&X.selectedModelId!==G.data.modelId){let j=await E.updateSessionMetadata(X.id,X.projectPath,{selectedModelId:G.data.modelId});GO(X,j)}let L=new AbortController,A;try{A=await a0.start({sessionId:K.sessionId,projectPath:K.projectPath,runtime:D,request:{kind:G.data.kind,...G.data.ref?{ref:G.data.ref}:{},...G.data.instructions?{instructions:G.data.instructions}:{}},signal:L.signal,onEvent:(j)=>{if(j.kind==="tool_start")R.publish(K,"review.tool.started",{reviewId:A?.reviewId,toolCallId:j.toolCall.id,toolName:j.toolCall.function.name});else if(j.kind==="tool_progress")R.publish(K,"review.tool.progress",{reviewId:A?.reviewId,toolCallId:j.toolCall.id,message:j.update.message.slice(0,1000)});else if(j.kind==="tool_result")R.publish(K,"review.tool.completed",{reviewId:A?.reviewId,toolCallId:j.toolCall.id,success:j.result.success})}})}catch(j){if(j instanceof Error&&(j.message.includes("active review")||j.message.includes("interrupted review")||j.message.includes("active turn")))throw new q(j.message);if(j instanceof Error&&(j.message.includes("review")||j.message.includes("Git")||j.message.includes("changes")||j.message.includes("ref")))throw new H(j.message);throw j}if(!A)throw new r("Code review failed to start");await n0(X),R.publish(K,"review.started",{reviewId:A.reviewId,kind:G.data.kind}),R.publish(K,"task.status",{taskStatus:X.taskStatus,...X.taskStatusReason?{taskStatusReason:X.taskStatusReason}:{},...X.taskStartedAt?{taskStartedAt:X.taskStartedAt}:{},...X.taskPromptSummary?{taskPromptSummary:X.taskPromptSummary}:{},updatedAt:new Date().toISOString()});let M=A.completion.then(async(j)=>{X.messages=await E.loadSession(K.sessionId,K.projectPath),await n0(X),R.publish(K,"task.status",{taskStatus:X.taskStatus,...X.taskStatusReason?{taskStatusReason:X.taskStatusReason}:{},...X.taskFailure?{taskFailure:X.taskFailure}:{},...X.taskStartedAt?{taskStartedAt:X.taskStartedAt}:{},...X.taskCompletedAt?{taskCompletedAt:X.taskCompletedAt}:{},...X.taskPromptSummary?{taskPromptSummary:X.taskPromptSummary}:{},updatedAt:new Date().toISOString()}),R.publish(K,"review.completed",{reviewId:A.reviewId,status:j.status,findings:j.findings.length})}).catch((j)=>{y.error(`[SessionRoutes] Code review ${A.reviewId} failed:`,j)}).finally(()=>{if(C0.get(_)?.reviewId===A.reviewId)C0.delete(_)});return C0.set(_,{reviewId:A.reviewId,controller:L,completion:M}),Z.json({reviewId:A.reviewId,status:"running"},202)})})}),O.get("/:sessionId/subagents",async(Z)=>{let N=await x0(Z.req.param("sessionId"),Z.req.query("projectPath"));return v(N,(G)=>Z.json({subagents:G.listSubagents().map(iO)}))}),O.post("/:sessionId/subagents/:agentId/resume",async(Z)=>{U$(Z.req.param("agentId"));let N=f1.safeParse(await Z.req.json());if(!N.success)throw new H("Invalid subagent resume request");let G=await x0(Z.req.param("sessionId"),Z.req.query("projectPath")),X=z0(G);return I(X,async()=>{let K=D0(G.currentRunId);if(_0(K))throw new q("Cannot resume a subagent while a parent run is active");return v(G,async(_)=>{let D=!1,L,A=(j)=>{R.publish(X,"subagent.complete",{subagentSessionId:j.id,success:j.status==="completed",status:j.status,summary:j.result?.message?.slice(0,500),type:j.subagentType,verificationVerdict:j.result?.verificationVerdict,resumedFrom:j.resumedFrom,rootAgentId:j.rootAgentId,resumeDepth:j.resumeDepth})},M;try{M=_.resumeSubagent({agentId:Z.req.param("agentId"),prompt:N.data.prompt,onEvent:(j,k)=>{y2(X,k,j)},onCompleted:(j)=>{if(D)A(j);else L=j}})}catch(j){if(j instanceof Error&&(j.message.startsWith("Cannot resume")||j.message.startsWith("Subagent cannot")))throw new q(j.message);if(j instanceof Error&&j.message.startsWith("Subagent not found"))throw new S(j.message);throw j}if(R.publish(X,"subagent.start",{subagentSessionId:M.session.id,type:M.session.subagentType,description:M.session.description,resumedFrom:M.source.id,rootAgentId:M.session.rootAgentId,resumeDepth:M.session.resumeDepth}),D=!0,L)A(L);return Z.json({source:iO(M.source),session:iO(M.session)})})})}),O.get("/:sessionId/goal",async(Z)=>{let N=await x0(Z.req.param("sessionId"),Z.req.query("projectPath"));return Z.json({goal:await new R1(N.projectPath,N.id).get()})}),O.put("/:sessionId/goal",async(Z)=>{let N=P(R2,await Z.req.json());if(!N.success)throw new H("Invalid goal request");let G=await x0(Z.req.param("sessionId"),Z.req.query("projectPath")),X=z0(G);return I(X,async()=>{let K=D0(G.currentRunId);if(_0(K))return Z.json({status:"rejected",reason:"run_active"},409);let D=N.data.permissionMode??G.permissionMode??"default";if(G.permissionMode!==D)await S0(G,D);let L=await e(G),A=!1;try{let M=await L.value.createGoal(N.data);R.publish(X,"goal.updated",{goal:M});let j=o(G,"",D,{goalContinuationOnly:!0,runtimeLease:L});return A=!0,await j.taskAdmissionUpdate,Z.json({status:j.status==="queued"?"queued":"running",runId:j.id,goal:M,queuePosition:j.taskQueuePosition,queueDepth:j.taskQueueDepth,maxConcurrentTasks:j.taskConcurrencyLimit},202)}finally{if(!A)L.release()}})}),O.patch("/:sessionId/goal",async(Z)=>{let N=P(E2,await Z.req.json());if(!N.success)throw new H("Invalid goal update");let G=await x0(Z.req.param("sessionId"),Z.req.query("projectPath")),X=z0(G);return I(X,async()=>{let K=await e(G),_=!1;try{let D=K.value,L;if(N.data.action==="pause")L=await D.pauseGoal();else if(N.data.action==="edit")L=await D.editGoal(N.data.objective);else L=await D.resumeGoal();if(R.publish(X,"goal.updated",{goal:L}),L.status==="active"&&!_0(D0(G.currentRunId))){let A=o(G,"","default",{goalContinuationOnly:!0,runtimeLease:K});return _=!0,await A.taskAdmissionUpdate,Z.json({status:A.status==="queued"?"queued":"running",runId:A.id,goal:L,queuePosition:A.taskQueuePosition,queueDepth:A.taskQueueDepth,maxConcurrentTasks:A.taskConcurrencyLimit},202)}return Z.json({status:L.status,goal:L})}finally{if(!_)K.release()}})}),O.delete("/:sessionId/goal",async(Z)=>{let N=await x0(Z.req.param("sessionId"),Z.req.query("projectPath")),G=z0(N);return v(N,async(X)=>{let K=await X.clearGoal();if(K)R.publish(G,"goal.cleared",{});return Z.json({cleared:K})})}),O.post("/:sessionId/archive",async(Z)=>{let N=Z.req.param("sessionId");try{let G=await N0(N,Z.req.query("projectPath")),X=await E.listSessionArchiveMembers(G.sessionId,G.projectPath);for(let _ of X){let D=m0({sessionId:_.sessionId,projectPath:_.projectPath}),L=t.get(g(D));if(_0(D0(L?.currentRunId)))throw new q(`Stop session ${_.sessionId} before archiving this session tree`)}for(let _ of X){let D=m0({sessionId:_.sessionId,projectPath:_.projectPath}),L=t.get(g(D));if(L)await Y0(L)}let K=await E.archiveSession(G.sessionId,G.projectPath);for(let _ of X){let D=m0({sessionId:_.sessionId,projectPath:_.projectPath}),L=g(D);t.delete(L),Q.delete(L),x.delete(L),R.publish(D,"session.archived",{archiveRootId:G.sessionId,archivedAt:K.archivedAt})}if($.size===0)await U0.getInstance().disconnectAll();return Z.json({session:K,archivedSessionIds:X.map((_)=>_.sessionId)})}catch(G){if(G instanceof H||G instanceof S||G instanceof B0||G instanceof q)throw G;if(G instanceof N$)throw new q(G.message);throw y.error("[SessionRoutes] Failed to archive session:",G),new r("Failed to archive session")}}),O.post("/:sessionId/unarchive",async(Z)=>{let N=Z.req.param("sessionId");try{let G=await N0(N,Z.req.query("projectPath")),X=await E.listSessionArchiveMembers(G.sessionId,G.projectPath),K=await E.unarchiveSession(G.sessionId,G.projectPath),_=X.filter((D)=>D.sessionId===G.sessionId||D.archivedBySessionId===G.sessionId).map((D)=>D.sessionId);for(let D of _)R.publish({sessionId:D,projectPath:G.projectPath},"session.unarchived",{archiveRootId:G.sessionId});return Z.json({session:K,restoredSessionIds:_})}catch(G){if(G instanceof H||G instanceof S||G instanceof B0)throw G;if(G instanceof N$)throw new q(G.message);throw y.error("[SessionRoutes] Failed to unarchive session:",G),new r("Failed to unarchive session")}}),O.delete("/:sessionId",async(Z)=>{let N=Z.req.param("sessionId"),G=Z.req.query("projectPath");try{let X=await N0(N,G),K=g(X),_=t.get(K),D=$.get(K),L=_?.taskWorktree??await E.findSessionTaskWorktree(X.sessionId,X.projectPath),A;if(_?.currentRunId){let k=D0(_.currentRunId);if(k)RO(k),await k.completion,A=k.id}let M=C0.get(K);if(M)M.controller.abort("session-delete"),await M.completion;if(D)await D.clearGoal().catch((k)=>{y.warn("[SessionRoutes] Failed to clear session goal:",k)});if(await E.deleteSession(X.sessionId,X.projectPath),R.publish(X,"session.deleted",{}),A)k2(A);t.delete(K),Q.delete(K),x.delete(K);let j=$.get(K);if(j){if(!await T.remove(K,j))throw new q("Session Runtime is still active and cannot be deleted")}if(L)try{await E0.restoreSession(L),await E0.exit({sessionId:X.sessionId,action:"remove",discardChanges:!0})}catch(k){y.warn(`[SessionRoutes] Failed to remove deleted task worktree ${X.sessionId}:`,k)}return Z.json({success:!0})}catch(X){if(y.error("[SessionRoutes] Failed to delete session:",X),X instanceof H||X instanceof S||X instanceof B0)throw X;throw new r("Failed to delete session")}}),O.get("/:sessionId/message",async(Z)=>{let N=Z.req.param("sessionId");try{let G=await N0(N,Z.req.query("projectPath")),X=t.get(g(G)),K=X?.messages?X.messages:await E.loadSession(G.sessionId,G.projectPath);return Z.json(Y$(K))}catch(G){if(y.error("[SessionRoutes] Failed to get messages:",G),G instanceof H||G instanceof S||G instanceof B0)throw G;throw new r("Failed to get messages")}}),O.get("/:sessionId/events",async(Z)=>{let N=Z.req.param("sessionId"),G=await N0(N,Z.req.query("projectPath"));try{await E.assertSessionWritable(G.sessionId,G.projectPath)}catch(L){if(L instanceof V$)throw new q(L.message);throw L}let X=await i(G),K=Z.req.header("Last-Event-ID")??Z.req.query("lastEventId"),_=K?Number.parseInt(K,10):Number.NaN,D=Number.isInteger(_)?_+1:void 0;return M2(Z,async(L)=>{let M,j,k=!1,K0,P0,j0=new Promise((m)=>{P0=m}),G0=()=>{if(j!==void 0)clearInterval(j),j=void 0;M?.(),M=void 0},O0=(m)=>{if(k)return;k=!0,G0(),K0?.close(m),P0()},r0=new Set;L.onAbort(O0),K0=new BO({write:async(m)=>{await L.writeSSE(m)},onFailure:(m)=>{y.warn(`[SessionRoutes] SSE egress closed for ${G.sessionId}: kind=${m.kind} pendingItems=${m.pendingItems??0} pendingBytes=${m.pendingBytes??0}`),O0(m)}}),M=R.subscribe((m)=>{if(m.sessionId!==G.sessionId||m.projectPath!==G.projectPath)return;let h=m.properties.requestId;if((m.type==="permission.asked"||m.type==="question.required"||m.type==="elicitation.required")&&typeof h==="string"){if(r0.has(h))return;r0.add(h)}if(m.type==="subagent.completion.queued")I(G,()=>q0(X)).catch((f)=>{y.error(`[SessionRoutes] Failed to wake background completion for ${X.id}:`,f)});K0?.observe(I2(m),m.seq)});try{if(L.aborted||k)return;let m=D0(X.currentRunId),h=_0(m)?await e(X):void 0;try{let l=h?.value,d=l?.getPendingSteeringCount()??0;await K0.writeInitial({data:JSON.stringify({type:"connected",properties:{sessionId:G.sessionId,projectPath:G.projectPath,timestamp:Date.now(),status:_0(m)?m.status:"idle",runId:_0(m)?m.id:void 0,queued:d,pendingInputDelivery:d>0?l?.hasActiveTurn()?"current_turn":"next_turn":null,recovered:l?.getRecoveredSteeringCount()??0}})})}finally{h?.release()}if(L.aborted||k)return;if(D!==void 0){if(await E1.for(G.sessionId,G.projectPath).replay({onCommitted:async(d)=>{if(L.aborted||k)return;let s=f2(d);if(s.seq===void 0)return;await K0.writeReplay({...typeof d.seq==="number"?{id:String(d.seq)}:{},data:JSON.stringify({type:s.type,...s.seq!==void 0?{seq:s.seq}:{},properties:{...s.properties,sessionId:G.sessionId,projectPath:G.projectPath}})},s.seq)}},D),L.aborted||k)return}if(K0.finishInitialization({replayed:D!==void 0}),L.aborted||k)return;if(!m&&!C0.has(g(G))){let d=(await a0.list(G.projectPath,G.sessionId)).some((s)=>s.completion===void 0)?await v(X,(s)=>a0.recoverInterrupted(G.projectPath,G.sessionId,s)):void 0;if(d)X.messages=await E.loadSession(G.sessionId,G.projectPath),await n0(X),R.publish(G,"review.completed",{reviewId:d.reviewId,status:d.status,findings:0,recovered:!0})}if(L.aborted||k)return;if(!m)await o0.recoverResponded(G.projectPath,G.sessionId);if(L.aborted||k)return;let f=m?void 0:await o0.findPending(G.projectPath,G.sessionId),u=m?.pendingPermission??(f?{permissionId:f.request.requestId,details:o0.confirmationDetails(f),resolve:()=>{return}}:void 0);if(u){r0.add(u.permissionId);let l=v1(u,!0);K0.observe({data:JSON.stringify({type:l.type,properties:{...l.properties,sessionId:G.sessionId,projectPath:G.projectPath}})})}if(L.aborted||k)return;if(q0(X).catch((l)=>{y.error(`[SessionRoutes] Failed to resume pending input for ${N}:`,l)}),L.aborted||k)return;j=setInterval(()=>{if(L.aborted||k)return;K0?.offerHeartbeat({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})})},15000),await j0}finally{O0()}})}),O.post("/:sessionId/message",async(Z)=>{let N=Z.req.param("sessionId"),G=await Z.req.json(),X=P(T2,G);if(!X.success)throw new H("Invalid message format");let{content:K,attachments:_,modelId:D,reasoningEffort:L,serviceTier:A,responseVerbosity:M,communicationStyle:j,permissionMode:k,projectPath:K0,outputSchema:P0}=X.data,j0;if(P0)try{j0=X$(P0).schema}catch(d){throw new H(d instanceof Error?d.message:"Invalid output schema")}let G0=j,O0=D?.trim();if((_??[]).reduce((d,s)=>d+(typeof s.content==="string"?Buffer.byteLength(s.content):0),0)>oO)throw new H("Message attachments exceed the 5 MiB limit");let m=k,h=F1(K,_),f=await x0(N,K0??Z.req.query("projectPath")),u=m??f.permissionMode??"default",l=z0(f);return I(l,async()=>{let d=D0(f.currentRunId);if(_0(d)){if(j0)throw new q("Wait for the active turn to finish before setting an output schema");return v(f,async(n)=>{if(O0&&!n.getModelById(O0))throw new H(`Model not found: ${O0}`);if(O0&&n.getCurrentModelId()!==O0)throw new q("Wait for the active turn to finish before switching models");if(L&&n.getReasoningConfiguration().selection!==L)throw new q("Wait for the active turn to finish before switching reasoning effort");if(A&&n.getServiceTierConfiguration().selection!==A)throw new q("Wait for the active turn to finish before switching service tier");if(M&&n.getResponseVerbosityConfiguration().selection!==M)throw new q("Wait for the active turn to finish before switching response verbosity");if(G0&&n.getCommunicationStyleConfiguration().selection!==G0)throw new q("Wait for the active turn to finish before switching communication style");if(m&&f.permissionMode!==m)throw new q("Wait for the active turn to finish before switching permission mode");let $0=await n.enqueueSteering(h,{allowBeforeTurn:!0});if(!$0.accepted)return Z.json({status:"rejected",reason:$0.reason??"turn_unavailable"},409);let d0=$0.messageId??ZO(12),DO=$0.queued;R.publish(l,"message.created",{messageId:d0,role:"user",content:_$(h)});let gO=$0.delivery==="next_turn"?"follow_up.queued":"steering.queued";if(R.publish(l,gO,{runId:d.id,messageId:d0,queued:DO}),$0.delivery==="next_turn"&&d.status!=="running"&&d.status!=="waiting_permission")q0(f).catch((vO)=>{y.error(`[SessionRoutes] Failed to wake queued follow-up for ${N}:`,vO)});if($0.delivery==="next_turn")d.pendingFollowUpRequested=!0;return Z.json({runId:d.id,messageId:d0,status:$0.delivery==="next_turn"?"follow_up_queued":"steering_queued",queued:DO},202)})}if(f.permissionMode!==u)await S0(f,u);let s=await e(f,{permissionMode:u,...G0&&!G0.includes(":")?{communicationStyle:G0}:{}}),_O=!1;try{let n=s.value;if(O0&&!n.getModelById(O0))throw new H(`Model not found: ${O0}`);if(L)try{n.resolveReasoningConfiguration(L,O0)}catch(X0){throw new H(X0 instanceof Error?X0.message:"Invalid reasoning effort")}if(A)try{n.resolveServiceTierConfiguration(A,O0)}catch(X0){throw new H(X0 instanceof Error?X0.message:"Invalid service tier")}if(M)try{n.resolveResponseVerbosityConfiguration(M,O0)}catch(X0){throw new H(X0 instanceof Error?X0.message:"Invalid response verbosity")}let $0=G0?n.resolveCommunicationStyleConfiguration(G0):void 0;if($0?.source!==void 0&&$0.source!=="built-in"&&!$0.contentSha256)throw new H("Custom communication style has no provenance");let d0=n.getCurrentModelId(),DO=n.getReasoningConfiguration(),gO=n.getServiceTierConfiguration(),vO=n.getResponseVerbosityConfiguration(),f$=n.getCommunicationStyleConfiguration(),y$=Boolean(O0)&&d0!==O0,m$=Boolean(L)&&DO.selection!==L,h$=Boolean(A)&&gO.selection!==A,g$=Boolean(M)&&vO.selection!==M,v$=Boolean(G0)&&f$.selection!==G0;if(y$||m$||h$||g$||v$)await n.refresh({...O0?{modelId:O0}:{},...L?{reasoningEffort:L}:{},...A?{serviceTier:A}:{},...M?{responseVerbosity:M}:{},...G0?{communicationStyle:G0}:{}});let $$={...O0&&f.selectedModelId!==O0?{selectedModelId:O0}:{},...L&&f.reasoningEffort!==L?{reasoningEffort:L}:{},...A&&f.serviceTier!==A?{serviceTier:A}:{},...M&&f.responseVerbosity!==M?{responseVerbosity:M}:{},...$0&&(f.communicationStyle!==G0||f.communicationStyleDigest!==$0.contentSha256)?{communicationStyle:G0,communicationStyleDigest:$0.source==="built-in"?null:$0.contentSha256}:{}};if(Object.keys($$).length>0)try{let X0=await E.updateSessionMetadata(f.id,f.projectPath,$$);f.permissionMode=X0.permissionMode,f.selectedModelId=X0.selectedModelId,f.reasoningEffort=X0.reasoningEffort,f.serviceTier=X0.serviceTier,f.responseVerbosity=X0.responseVerbosity,f.communicationStyle=X0.communicationStyle,f.communicationStyleDigest=X0.communicationStyleDigest,f.updatedAt=new Date(X0.lastMessageTime),R.publish(l,"session.updated",$$)}catch(X0){if(y$||m$||h$||g$||v$)await n.refresh({...d0?{modelId:d0}:{},reasoningEffort:DO.selection,serviceTier:gO.selection,responseVerbosity:vO.selection,communicationStyle:f$.selection}).catch((i4)=>y.error("[SessionRoutes] Failed to roll back non-durable model settings:",i4));throw X0}let HO=j0?await n.prepareInputTurn(h,{outputSchema:j0}):await n.prepareInputTurn(h);if(!HO.accepted)return Z.json({status:"rejected",reason:HO.reason},HO.reason==="queue_full"?429:409);let e0=o(f,h,u,{preparedInputTurn:HO,outputSchema:j0,runtimeLease:s});return _O=!0,await e0.taskAdmissionUpdate,Z.json({runId:e0.id,messageId:HO.messageId,status:e0.status==="queued"?"queued":"running",queuePosition:e0.taskQueuePosition,queueDepth:e0.taskQueueDepth,maxConcurrentTasks:e0.taskConcurrencyLimit},202)}finally{if(!_O)s.release()}})}),O.post("/:sessionId/shell",async(Z)=>{let N=Z.req.param("sessionId"),G=P(m1,await Z.req.json());if(!G.success)throw new H("Invalid user shell command");let X=await x0(N,G.data.projectPath??Z.req.query("projectPath")),K=z0(X),_=g(K);return I(K,async()=>{if(I0.has(_))throw new q("A user shell command is already running in this Session");let D=await e(X),L=D.value,A=new AbortController,M,j=new Promise((k)=>{M=k});I0.set(_,{controller:A,completion:j});try{let k=await L.executeUserShellCommand(G.data.command,{signal:A.signal});X.messages=await E.loadSession(X.id,X.projectPath),X.updatedAt=new Date;let K0=D0(X.currentRunId);if(k.delivery==="next_turn"&&_0(K0))K0.pendingFollowUpRequested=!0;return Z.json({executionId:k.executionId,messageId:k.messageId,record:k.record,auxiliary:k.auxiliary,...k.delivery?{delivery:k.delivery}:{},...k.queued!==void 0?{queued:k.queued}:{}})}finally{I0.delete(_),M(),D.release()}})}),O.post("/:sessionId/abort",async(Z)=>{let N=Z.req.param("sessionId"),G=await N0(N,Z.req.query("projectPath")),X=t.get(g(G));if(X?.currentRunId){let D=D0(X.currentRunId);if(D)RO(D),await D.completion}let K=I0.get(g(G));if(K)K.controller.abort("user-cancel"),await K.completion;let _=C0.get(g(G));if(_)_.controller.abort("user-cancel"),await _.completion;return Z.json({success:!0})}),O.get("/:sessionId/status",async(Z)=>{let N=Z.req.param("sessionId"),G=await N0(N,Z.req.query("projectPath")),X=t.get(g(G)),K=C0.get(g(G));if(K)return Z.json({sessionId:N,projectPath:G.projectPath,reviewId:K.reviewId,status:"reviewing"});if(!X?.currentRunId)return Z.json({sessionId:N,projectPath:G.projectPath,status:"idle"});let _=D0(X.currentRunId);return Z.json({sessionId:N,projectPath:G.projectPath,runId:X.currentRunId,status:_?.status||"idle"})}),{app:O,dispatchTask:w0,retryTask:V0,updateTask:S$,getTaskDiff:eO,deliverTask:mO,recoverQueuedTasks:O$,getRuntimeResidencyStats:()=>T.getStats(),getCoordinationStats:()=>({messageSubmissions:z.getStats(),taskDeliveries:Y.getStats()}),shutdown:(Z="server-shutdown")=>{if(w)return w;return B.close(Z),clearInterval(C),w=(async()=>{let N,G=async(L)=>{let A=await Promise.allSettled(L);for(let M of A)if(M.status==="rejected")N??=M.reason},X=new Set,K=()=>{for(let L of b0.values()){if(L.completion)X.add(L.completion);if(_0(L))RO(L,Z)}for(let L of I0.values())L.controller.abort(Z),X.add(L.completion);for(let L of C0.values())L.controller.abort(Z),X.add(L.completion)},_=B.waitForIdle(),D=!1;_.then(()=>{D=!0});while(!D)K(),await Promise.race([_,new Promise((L)=>setImmediate(L))]);if(await _,K(),await G([...X]),await G([...x.values()]),K(),await G([...X]),await G([T.disposeAll()]),$.clear(),await G([...J.values()]),await G([U0.getInstance().disconnectAll()]),x.clear(),J.clear(),Q.clear(),t.clear(),zO===q0)zO=void 0;if(N!==void 0)throw N})(),w}}};async function m2(O,$,x,J,Q,z={}){let{abortController:Y,sessionId:F,id:T}=O,B=z.preparedInputTurn?.messageId??ZO(12),w=z.pendingInputOnly===!0||z.preparedInputTurn?.mode==="pending"||z.goalContinuationOnly===!0?void 0:ZO(12),W=z.runtimeLease,I,Q0,p=z0($),b=(v,Y0)=>{R.publish(p,v,Y0)},e=async()=>{let v=String(Y.signal.reason||"Task run cancelled");if($.taskIsolation){if(!W)W=await Q($).catch(()=>{return});let Y0=I??W?.value;if(v==="user-cancel")await Y0?.discardPendingInput().catch((x0)=>{y.warn(`[SessionRoutes] Failed to discard cancelled input for ${$.id}:`,x0)});let i=await Y0?.setTaskStatus("cancelled",v).catch(()=>{return});if(i)GO($,i);else await n0($).catch(()=>{return})}$.taskStatus="cancelled",$.taskStatusReason=v,$.taskCompletedAt??=new Date().toISOString()};try{if(z.taskAdmission){if(await z.taskAdmission.ready,await O.taskAdmissionUpdate,Y.signal.aborted)throw Error(String(Y.signal.reason||"Task run cancelled"))}if($.taskStatus="running",$.taskStatusReason=void 0,$.taskStartedAt=new Date().toISOString(),$.taskCompletedAt=void 0,!z.pendingInputOnly&&!z.goalContinuationOnly)b("message.created",{messageId:B,role:"user",content:_$(x)});if(b("session.status",{status:"running"}),w)b("message.created",{messageId:w,role:"assistant",content:""});W??=await Q($),I=W.value;let v=I,Y0=Boolean(z.outputSchema??v.getPendingSteeringMessages().find((V)=>V.outputSchema)?.outputSchema);Q0=await I1.createWithRuntime(v,{sessionId:F,...$.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}});let i=async(V)=>{let V0=V.interactionRequestId??ZO(12),S$=300000;O.status="waiting_permission";let eO=new Promise((q0)=>{let O$=setTimeout(()=>{y.warn(`[SessionRoutes] Permission ${V0} timed out after 300000ms`),b("permission.timeout",{requestId:V0}),q0({approved:!1,reason:"timeout"})},300000);O.pendingPermission={permissionId:V0,resolve:(P$)=>{clearTimeout(O$),q0(P$)},details:V}}),UO=O.pendingPermission;if(!UO)throw Error("Permission request was not registered");let mO=v1(UO);b(mO.type,mO.properties),y.info(`[SessionRoutes] Permission request created: ${V0}, runId: ${T}`);let hO=await eO;if(y.info(`[SessionRoutes] Permission response received: ${V0}, approved: ${hO.approved}`),!Y.signal.aborted)O.status="running";if(O.pendingPermission===UO)O.pendingPermission=void 0;return b("interaction.resolved",{requestId:V0}),hO},S0={messages:await E.loadSessionModelContext($.id,$.projectPath),userId:"web-user",sessionId:F,workspaceRoot:$.projectPath,signal:Y.signal,permissionMode:J,onPermissionModeChange:async(V)=>{$.permissionMode=V,$.updatedAt=new Date,b("session.updated",{permissionMode:V})},...$.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:i}},o=()=>{if(!w)w=ZO(12),b("message.created",{messageId:w,role:"assistant",content:""});return w},p0=async(V)=>{switch(V.kind){case"content_delta":if(Y0)break;b("message.delta",{messageId:o(),delta:V.delta});break;case"structured_output":b("structured.output",{messageId:o(),output:V.output,schemaDigest:V.schemaDigest});break;case"thinking_delta":b("thinking.delta",{messageId:o(),delta:V.delta});break;case"tool_start":if("function"in V.toolCall){if(V.toolCall.function.name===YO)break;b("tool.start",{messageId:o(),toolName:V.toolCall.function.name,toolCallId:V.toolCall.id,arguments:V.toolCall.function.arguments,toolKind:V.toolKind})}break;case"tool_result":if("function"in V.toolCall){if(V.toolCall.function.name===YO)break;b("tool.result",{messageId:o(),toolName:V.toolCall.function.name,toolCallId:V.toolCall.id,success:V.result.success,summary:V.result.metadata?.summary,output:SO(kO(IO(V.toolCall.function.name,V.result),qO)),metadata:EO(V.toolCall.function.name,V.result.metadata)})}break;case"tool_progress":if("function"in V.toolCall){if(V.toolCall.function.name===YO)break;b("tool.progress",{messageId:o(),toolName:V.toolCall.function.name,toolCallId:V.toolCall.id,...V.update})}break;case"token_usage":b("token.usage",{...V.usage});break;case"turn_start":b("turn.started",{turn:V.turn,maxTurns:V.maxTurns});break;case"provider_admission":b("provider.admission",{phase:V.phase,requestClass:V.requestClass,resource:V.resource,scope:V.scope,reason:V.reason,queuePosition:V.queuePosition,queueDepth:V.queueDepth,inFlight:V.inFlight,limit:V.limit,waitMs:V.waitMs,maxWaitMs:V.maxWaitMs,recoveryRemainingMs:V.recoveryRemainingMs});break;case"provider_circuit":b("provider.circuit",{phase:V.phase,reason:V.reason,statusCode:V.statusCode,retryAfterMs:V.retryAfterMs,nextProbeAt:V.nextProbeAt,openDurationMs:V.openDurationMs,sampleCount:V.sampleCount,failureCount:V.failureCount,recoveryRemainingMs:V.recoveryRemainingMs});break;case"provider_retry":b("provider.retry",{phase:V.phase,attempt:V.attempt,maxRetries:V.maxRetries,reason:V.reason,statusCode:V.statusCode,delayMs:V.delayMs,nextRetryAt:V.nextRetryAt,mode:V.mode,recoveryBudgetMs:V.recoveryBudgetMs,recoveryElapsedMs:V.recoveryElapsedMs,recoveryRemainingMs:V.recoveryRemainingMs,exhaustedBy:V.exhaustedBy});break;case"provider_stall":b("provider.stall",{phase:V.phase,stallCount:V.stallCount,durationMs:V.durationMs,warningAfterMs:V.warningAfterMs,timeoutMs:V.timeoutMs,outputStarted:V.outputStarted});break;case"action_stationarity":b("action.stationarity",{phase:V.phase,toolName:V.toolName,runLength:V.runLength,nudgeThreshold:V.nudgeThreshold,haltThreshold:V.haltThreshold,progressAware:V.progressAware});break;case"mcp_catalog_changed":b("mcp.catalog.changed",{messageId:o(),revision:V.revision,serverName:V.serverName,added:V.added,removed:V.removed,updated:V.updated});break;case"mcp_content_changed":b("mcp.content.changed",{messageId:o(),revision:V.revision,serverName:V.serverName,contentKind:V.contentKind,added:V.added,removed:V.removed,updated:V.updated});break;case"mcp_resource_updated":b("mcp.resource.updated",{messageId:o(),revision:V.revision,serverName:V.serverName,uri:V.uri});break;case"mcp_connection_changed":b("mcp.connection.changed",{messageId:o(),revision:V.revision,serverName:V.serverName,phase:V.phase,reason:V.reason,attempt:V.attempt,maxAttempts:V.maxAttempts,nextRetryAt:V.nextRetryAt,error:V.error});break;case"mcp_log":b("mcp.log",{messageId:o(),revision:V.revision,serverName:V.serverName,level:V.level,logger:V.logger,message:V.message,projectedBytes:V.projectedBytes,dataSha256:V.dataSha256,truncated:V.truncated,detailsOmitted:V.detailsOmitted,timestamp:V.timestamp,synthetic:V.synthetic});break;case"mcp_instructions_changed":b("mcp.instructions.changed",{messageId:o(),revision:V.revision,serverName:V.serverName,action:V.action,reason:V.reason,text:V.text,sourceBytes:V.sourceBytes,projectedBytes:V.projectedBytes,sha256:V.sha256,truncated:V.truncated,detailsOmitted:V.detailsOmitted});break;case"mcp_task_changed":b("mcp.task.changed",{messageId:o(),revision:V.revision,taskId:V.taskId,serverName:V.serverName,toolName:V.toolName,status:V.status,statusMessage:V.statusMessage,createdAt:V.createdAt,updatedAt:V.updatedAt,completedAt:V.completedAt,hasResult:V.hasResult,error:V.error});break;case"project_rules_loaded":b("project.rules.loaded",{messageId:o(),files:V.files,triggerPaths:V.triggerPaths,blockedWrite:V.blockedWrite});break;case"steering_applied":b("steering.applied",{runId:T,messageIds:V.messageIds,count:V.count,recovered:V.recovered,delivery:V.delivery,queued:v.getPendingSteeringCount()});break;case"follow_up_started":{if(w)b("message.complete",{messageId:w}),w=void 0;for(let V0 of V.messages){if(!V0.recovered||V0.persisted)continue;b("message.created",{messageId:V0.id,role:"user",content:_$(V0.content),recovered:!0})}b("follow_up.started",{runId:T,queued:V.queued,recovered:V.recovered}),o();break}case"goal_updated":b("goal.updated",{goal:V.goal});break;case"goal_continuation_started":b("goal.continuation.started",{goal:V.goal,continuation:V.continuation}),o();break;case"compaction":b(V.phase==="start"?"compaction.started":"compaction.completed",{...V.reason?{reason:V.reason}:{},...V.strategy?{strategy:V.strategy}:{},...V.outcome?{outcome:V.outcome}:{},...V.preTokens!==void 0?{preTokens:V.preTokens}:{},...V.postTokens!==void 0?{postTokens:V.postTokens}:{}});break;case"model_fallback":b("model.fallback",{});break;case"task_update":b("task.updated",{tasks:V.tasks});break;default:break}},w0=await K$(Q0.chatStream(x,S0,{stream:!0,pendingInputOnly:z.pendingInputOnly,preparedInputTurn:z.preparedInputTurn,goalContinuationOnly:z.goalContinuationOnly,outputSchema:z.outputSchema,taskAdmission:z.taskAdmission}),p0);if(!w0.success)throw Error(w0.error?.message??"Agent run failed");for(let V=0;V<20;V++){let V0=O.pendingFollowUpRequested===!0;if(O.pendingFollowUpRequested=!1,v.getPendingSteeringCount()===0){if(!V0)break;continue}if(Y.signal.aborted)break;if(w0=await K$(Q0.chatStream("",S0,{stream:!0,pendingInputOnly:!0,taskAdmission:z.taskAdmission}),p0),!w0.success)throw Error(w0.error?.message??"Agent follow-up failed")}if($.messages=await E.loadSession($.id,$.projectPath),$.updatedAt=new Date,await n0($),Y.signal.aborted||O.status==="cancelled"){await e(),b("session.status",{status:"idle"});return}if(w)b("message.complete",{messageId:w});b("thinking.completed",{}),O.status="completed",$.taskStatus="completed",$.taskCompletedAt??=new Date().toISOString(),b("session.completed",{runId:T,outputTruncated:w0.metadata?.outputTruncated??!1}),b("session.status",{status:"idle"})}catch(v){if(I&&z.preparedInputTurn)await I.finishTurn(z.preparedInputTurn.handle).catch(()=>{return});if(Y.signal.aborted||O.status==="cancelled"){RO(O,"runtime-abort"),await e(),b("session.status",{status:"idle"});return}await n0($).catch(()=>{return}),y.error("[SessionRoutes] Agent execution error:",v),O.status="failed",$.taskStatus="failed",$.taskCompletedAt??=new Date().toISOString();let Y0=aO(v);if(!$.taskFailure){let i=I?await I.setTaskStatus("failed",v).catch(()=>{return}):await E.updateSessionMetadata($.id,$.projectPath,{taskStatus:"failed",taskStatusReason:Y0.message,taskFailure:Y0,taskCompletedAt:$.taskCompletedAt,taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null}).catch(()=>{return});if(i)GO($,i)}$.taskStatusReason??=Y0.message,$.taskFailure??=Y0,b("session.error",{error:$.taskFailure.message,taskFailure:$.taskFailure}),b("session.status",{status:"error"})}finally{if(z.taskAdmission?.release(),z.taskAdmission){let v=f0.getStats();b("task.status",{taskStatus:$.taskStatus,...$.taskStatusReason?{taskStatusReason:$.taskStatusReason}:{},...$.taskFailure?{taskFailure:$.taskFailure}:{},...$.taskStartedAt?{taskStartedAt:$.taskStartedAt}:{},...$.taskCompletedAt?{taskCompletedAt:$.taskCompletedAt}:{},...$.taskDiffStat?{taskDiffStat:$.taskDiffStat}:{},taskQueueDepth:v.queued,taskConcurrencyLimit:v.maxConcurrent,taskInFlight:v.inFlight,taskAdmissionPaused:v.paused,updatedAt:new Date().toISOString()})}if(await Q0?.destroy().catch(()=>{return}),W?.release(),O.disposeRuntimeOnSettle&&z.disposeRuntime)await z.disposeRuntime($,I).catch((v)=>{y.warn(`[SessionRoutes] Failed to dispose terminal task runtime ${$.id}:`,v)});q2(O)}}async function p1(O,$,x){y.info(`[SessionRoutes] Looking for permission ${$} in session ${O.sessionId}`),y.info(`[SessionRoutes] Active runs: ${b0.size}`);for(let[z,Y]of b0.entries())if(y.info(`[SessionRoutes] Checking run ${z}: sessionId=${Y.sessionId}, projectPath=${Y.projectPath}, pendingPermission=${Y.pendingPermission?.permissionId}`),Y.sessionId===O.sessionId&&Y.projectPath===O.projectPath&&Y.pendingPermission?.permissionId===$){if(Y.pendingPermission.details.interactionRequestId)await o0.respond(O.projectPath,O.sessionId,$,x);return Y.pendingPermission.resolve(x),y.info(`[SessionRoutes] Permission ${$} responded, runId: ${Y.id}`),!0}let J=await o0.findPending(O.projectPath,O.sessionId);if(!J||J.request.requestId!==$)return y.error(`[SessionRoutes] Permission not found: ${$}`),!1;await o0.respondAndRecover(O.projectPath,O.sessionId,$,x);let Q=t.get(g(O));if(!Q){let z=await E.findSessionMetadata(O.sessionId,O.projectPath);if(!z)return!1;let[Y,F]=await Promise.all([E.loadSession(O.sessionId,O.projectPath),E.findSessionTaskWorktree(O.sessionId,O.projectPath)]);Q=bO(z,Y,F),t.set(g(O),Q)}else await n0(Q);if(R.publish(O,"interaction.resolved",{requestId:$}),zO)zO(Q).catch((z)=>{y.error(`[SessionRoutes] Failed to resume recovered interaction ${$}:`,z)});return!0}var H$=a("Service"),g2=U.Object({approved:U.Boolean(),remember:U.Optional(U.Boolean()),scope:U.Optional(F0(["once","session","project"])),targetMode:U.Optional(F0(["default","autoEdit","plan","yolo"])),feedback:U.Optional(U.String({maxLength:4000})),answers:U.Optional(U.Record(U.String({maxLength:80}),U.Union([U.String({maxLength:4000}),U.Array(U.String({maxLength:1000}),{maxItems:4})]),{maxProperties:4})),elicitation:U.Optional(U.Object({action:F0(["accept","decline","cancel"]),content:U.Optional(U.Record(U.String(),U.Union([U.String({maxLength:4000}),U.Number(),U.Boolean(),U.Array(U.String({maxLength:1000}),{maxItems:100})]),{maxProperties:32}))}))}),d1=()=>{let O=new h2;return O.post("/:permissionId",async($)=>{let x=$.req.param("permissionId"),J=$.req.query("sessionId"),Q=$.req.query("projectPath");H$.info(`[PermissionRoutes] Received permission response: permissionId=${x}, sessionId=${J}`);try{let z=await $.req.json(),Y=P(g2,z);if(!Y.success)throw new H("Invalid permission response format");let{approved:F,remember:T,scope:B,targetMode:C,feedback:w,answers:W,elicitation:I}=Y.data;if(!J)throw new H("sessionId query parameter is required");let Q0=await N0(J,Q);if(!await p1(Q0,x,{approved:F,reason:w,scope:B,targetMode:C,feedback:w,answers:W,elicitation:I}))throw new S("Permission request",x);return H$.info(`[PermissionRoutes] Permission ${x} ${F?"approved":"denied"}`),$.json({success:!0,approved:F,remember:T})}catch(z){if(H$.error("[PermissionRoutes] Failed to respond to permission:",z),z instanceof H||z instanceof B0||z instanceof S||z instanceof Z0)throw z;throw z}}),O};import l1 from"node:path";import{Hono as v2}from"hono";var u2=U.Object({projectPath:U.String({minLength:1}),enabled:U.Boolean(),scope:U.Optional(F0(["local","project","global"]))}),p2=U.Object({projectPath:U.String({minLength:1})}),d2=U.Object({projectPath:U.String({minLength:1}),source:U.String({minLength:1}),trust:U.Literal(!0),ref:U.Optional(U.String({minLength:1}))}),l2=U.Object({projectPath:U.String({minLength:1}),trust:U.Literal(!0)}),c2=U.Object({projectPath:U.String({minLength:1}),confirm:U.Literal(!0)}),i2=U.Object({projectPath:U.String({minLength:1}),source:U.String({minLength:1}),ref:U.Optional(U.String({minLength:1}))}),c1=U.Object({projectPath:U.String({minLength:1}),confirm:U.Optional(U.Literal(!0))}),a2=U.Object({projectPath:U.String({minLength:1}),scope:U.Optional(F0(["local","project","global"])),policy:U.Object({restrictToAllowedSources:U.Boolean(),requireGitCommitSha:U.Boolean(),allowedGitHosts:U.Array(U.String()),allowedMarketplaces:U.Array(U.String()),allowedLocalRoots:U.Array(U.String())})});function M0(O){if(!O||!l1.isAbsolute(O))throw new H("projectPath must be absolute");return l1.resolve(O)}async function i1(O){let[$,x]=await Promise.all([T0(O),wO.getInstance().loadWorkspacePluginSettingsResolution(O)]);return $.plugins.getAll().map((J)=>({name:J.manifest.name,description:J.manifest.description,version:J.manifest.version,source:J.source,enabled:J.status==="active",status:J.status,commands:J.commands.length,skills:J.skills.length,agents:J.agents.length,hooks:J.hooks?Object.values(J.hooks).reduce((Q,z)=>Q+(Array.isArray(z)?z.length:0),0):0,mcpServers:Object.keys(J.mcpServers??{}).length,configurable:J.source!=="cli",managed:J.installation!==void 0,marketplace:J.installation?.source.type==="marketplace"?J.installation.source.marketplace:void 0,revision:J.installation?.revision,installedAt:J.installation?.installedAt,updatedAt:J.installation?.updatedAt,compatibilityIssues:J.compatibilityIssues??[],effectiveScope:J.source==="cli"?"invocation":x.settings[J.manifest.name]?.effectiveScope??"default",settingLayers:J.source==="cli"?{invocation:!0}:x.settings[J.manifest.name]?.layers??{}}))}async function o2(){let O=a1(),[$,x]=await Promise.all([O.listCatalogs(),O.listInstallationRecords()]),J=new Map(x.map((Q)=>[Q.name,Q]));return $.map(({marketplace:Q,manifest:z})=>({name:Q.name,description:z.description??z.metadata?.description??"",sourceType:Q.source.type,revision:Q.revision,updatedAt:Q.updatedAt,plugins:z.plugins.map((Y)=>{let F=J.get(Y.name);return{name:Y.name,description:Y.description??"",version:Y.version,category:Y.category,tags:Y.tags??[],installed:F!==void 0,installedVersion:F?.version}})}))}function XO(O,$){if(!O.success)throw new H(O.error??$)}var J4=()=>{let O=new v2;return O.get("/",async($)=>{let x=M0($.req.query("projectPath"));return $.json(await i1(x))}),O.post("/refresh",async($)=>{let x=P(p2,await $.req.json());if(!x.success)throw new H("Invalid plugin refresh request");let J=M0(x.data.projectPath),Q=await n1(J);return $.json({plugins:await i1(J),errors:Q.discovery.errors.map((z)=>({code:z.code??"LOAD_ERROR",error:z.error}))})}),O.get("/catalog",async($)=>{return M0($.req.query("projectPath")),$.json(await o2())}),O.get("/policy",async($)=>{let x=M0($.req.query("projectPath")),J=await wO.getInstance().loadWorkspacePluginSourcePolicy(x);return $.json({policy:J,environmentRequiresSha:process.env.BLADE_PLUGIN_REQUIRE_SHA==="1"||process.env.BLADE_PLUGIN_REQUIRE_SHA==="true"})}),O.post("/policy",async($)=>{let x=P(a2,await $.req.json());if(!x.success)throw new H("Invalid plugin source policy request");let J=M0(x.data.projectPath),Q=await t1(J,x.data.policy,x.data.scope??"global");return $.json({policy:Q})}),O.post("/install",async($)=>{let x=P(d2,await $.req.json());if(!x.success)throw new H("Invalid plugin install request; explicit source trust is required");let J=M0(x.data.projectPath),{result:Q}=await s1(J,x.data.source,{trusted:x.data.trust,ref:x.data.ref});return XO(Q,"Plugin installation failed"),$.json({name:Q.pluginName,version:Q.manifest?.version,revision:Q.installation?.revision,changed:Q.changed,installedDependencies:Q.installedDependencies??[]})}),O.post("/marketplaces",async($)=>{let x=P(i2,await $.req.json());if(!x.success)throw new H("Invalid marketplace add request");let J=M0(x.data.projectPath),Q=await O4(J,x.data.source,x.data.ref);return XO(Q,"Marketplace installation failed"),$.json({name:Q.marketplace?.name,plugins:Q.manifest?.plugins.length??0,revision:Q.marketplace?.revision,changed:Q.changed})}),O.post("/marketplaces/:name/refresh",async($)=>{let x=P(c1,await $.req.json());if(!x.success)throw new H("Invalid marketplace refresh request");let J=await $4(M0(x.data.projectPath),$.req.param("name"));return XO(J,"Marketplace refresh failed"),$.json({name:J.marketplace?.name,plugins:J.manifest?.plugins.length??0,revision:J.marketplace?.revision,changed:J.changed})}),O.post("/marketplaces/:name/remove",async($)=>{let x=P(c1,await $.req.json());if(!x.success||x.data.confirm!==!0)throw new H("Invalid marketplace removal request; explicit confirmation is required");M0(x.data.projectPath);let J=await x4($.req.param("name"),!0);return XO(J,"Marketplace removal failed"),$.json({name:J.marketplace?.name,removed:!0})}),O.post("/:name/update",async($)=>{let x=P(l2,await $.req.json());if(!x.success)throw new H("Invalid plugin update request; explicit source trust is required");let J=M0(x.data.projectPath),{result:Q}=await r1(J,$.req.param("name"),{trusted:x.data.trust});return XO(Q,"Plugin update failed"),$.json({name:Q.pluginName,version:Q.manifest?.version,revision:Q.installation?.revision,changed:Q.changed,updatedDependencies:Q.updatedDependencies??[]})}),O.post("/:name/uninstall",async($)=>{let x=P(c2,await $.req.json());if(!x.success)throw new H("Invalid plugin uninstall request; explicit confirmation is required");let J=M0(x.data.projectPath),{result:Q}=await e1(J,$.req.param("name"),x.data.confirm);return XO(Q,"Plugin uninstall failed"),$.json({name:Q.pluginName,removed:!0})}),O.post("/:name/state",async($)=>{let x=P(u2,await $.req.json());if(!x.success)throw new H("Invalid plugin state request");let J=M0(x.data.projectPath),Q=$.req.param("name"),Y=(await T0(J)).plugins.get(Q);if(!Y)throw new S("Plugin",Q);if(Y.source==="cli")throw new H(`Plugin "${Q}" was loaded with --plugin-dir and is invocation-scoped`);let F=await o1(J,Q,x.data.enabled,x.data.scope??"local");return $.json(F)}),O};import{Hono as e2}from"hono";import{execFile as n2}from"node:child_process";import t2 from"node:path";var w$="__BLADE_DIRECTORY_PICKER_CANCELLED__",s2=900000;function r2(O,$){return new Promise((x)=>{n2(O,[...$],{timeout:s2,maxBuffer:65536,windowsHide:!0},(J,Q,z)=>{let Y=J?.code;x({stdout:Q,stderr:z,exitCode:typeof Y==="number"?Y:J?1:0,...typeof Y==="string"?{errorCode:Y}:{}})})})}function B$(O){let $=O.replace(/[\r\n]+$/,"");if(!$||$===w$)return{cancelled:!0};if(!t2.isAbsolute($))throw Error("The folder picker returned an invalid path");return{cancelled:!1,path:$}}function L$(O){return O.exitCode!==0||Boolean(O.errorCode)}class Q4{platform;runCommand;activeSelection=null;constructor(O={}){this.platform=O.platform??process.platform,this.runCommand=O.runCommand??r2}pick(){if(this.activeSelection)return this.activeSelection;let O=this.pickForPlatform().finally(()=>{this.activeSelection=null});return this.activeSelection=O,O}async pickForPlatform(){switch(this.platform){case"darwin":return this.pickOnMac();case"win32":return this.pickOnWindows();case"linux":return this.pickOnLinux();default:throw Error("Native folder selection is unavailable on this system")}}async pickOnMac(){let O=["try",'set selectedFolder to choose folder with prompt "Choose a project folder"',"return POSIX path of selectedFolder","on error number -128",`return "${w$}"`,"end try"].join(`
|
|
8
|
-
`),$=await this.runCommand("osascript",["-e",O]);if(L$($))throw Error("Unable to open the macOS folder picker");return B$($.stdout)}async pickOnWindows(){let O=["Add-Type -AssemblyName System.Windows.Forms","$dialog = New-Object System.Windows.Forms.FolderBrowserDialog",'$dialog.Description = "Choose a project folder"',"$dialog.ShowNewFolderButton = $true","if ($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {"," [Console]::Out.Write($dialog.SelectedPath)","} else {",` [Console]::Out.Write("${w$}")`,"}"].join("; "),$=await this.runCommand("powershell.exe",["-NoProfile","-STA","-Command",O]);if(L$($))throw Error("Unable to open the Windows folder picker");return B$($.stdout)}async pickOnLinux(){let O=[{command:"zenity",args:["--file-selection","--directory","--title=Choose a project folder"]},{command:"kdialog",args:["--getexistingdirectory",".","--title","Choose a project folder"]}];for(let $ of O){let x=await this.runCommand($.command,$.args);if(x.errorCode==="ENOENT")continue;if(x.exitCode===1&&!x.stdout.trim()&&!x.stderr.trim())return{cancelled:!0};if(L$(x))throw Error("Unable to open the Linux folder picker");return B$(x.stdout)}throw Error("Install zenity or kdialog to use native folder selection")}}var Z4=new Q4;var O5=U.Object({path:U.String({minLength:1})});function $5(O){if(!O)return!1;if(O==="tauri://localhost"||O==="http://tauri.localhost")return!0;try{let $=new URL(O).hostname;return $==="localhost"||$==="127.0.0.1"||$==="::1"||$==="[::1]"}catch{return!1}}var Y4=(O={})=>{let $=new e2,x=O.pickDirectory??(()=>Z4.pick()),J=O.allowDirectoryPickerRequest??$5;return $.get("/",async(Q)=>{return Q.json(await tO.list(c()))}),$.post("/",async(Q)=>{let z;try{z=await Q.req.json()}catch{throw new H("A valid JSON body is required")}let Y=P(O5,z);if(!Y.success)throw new H("A project path is required");try{let F=await tO.bind(Y.data.path,c());return Q.json(F,201)}catch(F){throw new H(F instanceof Error?F.message:"Failed to bind project")}}),$.post("/pick",async(Q)=>{if(!J(Q.req.header("Origin")))throw new Z0("LOCAL_ACCESS_REQUIRED","Folder selection is only available from this machine",403);try{return Q.json(await x())}catch(z){throw new H(z instanceof Error?z.message:"Failed to select a folder")}}),$.delete("/",async(Q)=>{let z=Q.req.query("path");if(!z)throw new H("A project path is required");try{let Y=await tO.unbind(z);return Q.json({success:!0,removed:Y})}catch(Y){throw new H(Y instanceof Error?Y.message:"Failed to unbind project")}}),$};import{Hono as x5}from"hono";var z4=a("Service"),N4=()=>{let O=new x5;return O.get("/",async($)=>{try{let x=await X4();return $.json(x)}catch(x){return z4.error("[ProviderRoutes] Failed to list providers:",x),$.json([])}}),O.get("/:provider/models",async($)=>{let x=$.req.param("provider");try{let J=await V4(x);return $.json(J)}catch(J){return z4.error("[ProviderRoutes] Failed to list models:",J),$.json([])}}),O.put("/:provider/credential",async($)=>{let x=$.req.param("provider"),J=await $.req.json();if(!J.apiKey?.trim())throw new H("apiKey is required");return await c0().setApiKey(x,J.apiKey.trim()),$.json({success:!0})}),O.delete("/:provider/credential",async($)=>{return await c0().clearCredential($.req.param("provider")),$.json({success:!0})}),O.put("/:provider",async($)=>{let x=$.req.param("provider"),J=J0(),Q=J?.modelProviders[x];if(!J||!Q)throw new S("Model provider",x);let z=await $.req.json();if(!z.name||!z.baseUrl||!z.wireApi)throw new H("name, baseUrl and wireApi are required");let Y="apiKeyEnv"in z?z.apiKeyEnv?.trim():Q.apiKeyEnv,F={name:z.name,baseUrl:z.baseUrl,wireApi:z.wireApi,...Y?{apiKeyEnv:Y}:{}},T=c0(),B=z.apiKey?.trim()?await T.credentials.read(x):void 0;if(z.apiKey?.trim())await T.setApiKey(x,z.apiKey.trim());try{return await L0().updateModelProvider(x,F),$.json({success:!0})}catch(C){if(z.apiKey?.trim())if(B)await T.credentials.modify(x,async()=>B);else await T.credentials.delete(x);if(C instanceof Error&&(C.message.includes("modelProviders.")||C.message.includes("built-in provider")))throw new H(C.message);throw C}}),O.delete("/:provider",async($)=>{let x=$.req.param("provider");if(!J0()?.modelProviders[x])throw new S("Model provider",x);let Q=$.req.query("removeModels");if(Q!==void 0&&Q!=="true"&&Q!=="false")throw new H("removeModels must be true or false");try{let z=await L0().removeModelProvider(x,{removeModels:Q==="true"});return $.json({success:!0,...z})}catch(z){if(z instanceof Error&&(z.message.includes("still referenced")||z.message.includes("owns the only model")))throw new q(z.message);throw z}}),O.post("/:provider/probe",async($)=>{let x=$.req.param("provider"),J=J0();if(!J?.modelProviders[x])throw new S("Model provider",x);let Q=await $.req.json().catch(()=>({})),z=J.models.filter((F)=>F.provider===x),Y=Q.modelId?z.find((F)=>F.id===Q.modelId):z[0];if(!Y)throw new H(Q.modelId?"modelId does not reference this provider":"Model provider has no configured model to probe");return $.json(await G4(Y,J))}),O};import{Hono as J5}from"hono";var Q5=a("Service"),U4=(O,$)=>{let x=new J5;return x.onError((J,Q)=>{if(J instanceof Z0)return Q.json(J.toObject(),J.statusCode);return Q5.error("[ScheduleRoutes] Unhandled route error:",J),Q.json(new r("Schedule request failed").toObject(),500)}),x.get("/",async(J)=>{let Q=await O.list();return J.json(F4.parse({schedules:Q}))}),x.post("/",async(J)=>{let Q;try{Q=await J.req.json()}catch{throw new H("Invalid request body")}let z=P(K4,Q);if(!z.success)throw new H("Invalid schedule request");let Y=z.data.projectPath||J.get("directory")||c();try{let F=await O.create({...z.data,projectPath:Y});return J.json(t0.parse(F),201)}catch(F){throw new H(F instanceof Error?F.message:"Failed to create schedule")}}),x.get("/:id",async(J)=>{let Q=await O.get(J.req.param("id"));if(!Q)throw new S("Schedule not found");return J.json(t0.parse(Q))}),x.patch("/:id",async(J)=>{let Q;try{Q=await J.req.json()}catch{throw new H("Invalid request body")}let z=P(W4,Q);if(!z.success)throw new H("Invalid schedule update");let{modelId:Y,reasoningEffort:F,serviceTier:T,responseVerbosity:B,communicationStyle:C,isolation:w,permissionMode:W,...I}=z.data,Q0={...Y!==void 0?{modelId:Y}:{},...F!==void 0?{reasoningEffort:F}:{},...T!==void 0?{serviceTier:T}:{},...B!==void 0?{responseVerbosity:B}:{},...C!==void 0?{communicationStyle:C}:{},...w!==void 0?{isolation:w}:{},...W!==void 0?{permissionMode:W}:{}};try{let p=await O.update(J.req.param("id"),{...I,...Object.keys(Q0).length>0?{dispatch:Q0}:{}});if(!p)throw new S("Schedule not found");return J.json(t0.parse(p))}catch(p){if(p instanceof Z0)throw p;throw new H(p instanceof Error?p.message:"Failed to update schedule")}}),x.delete("/:id",async(J)=>{if(!await O.remove(J.req.param("id")))throw new S("Schedule not found");return J.json({ok:!0})}),x.post("/:id/enable",async(J)=>{let Q=await O.setEnabled(J.req.param("id"),!0);if(!Q)throw new S("Schedule not found");return J.json(t0.parse(Q))}),x.post("/:id/disable",async(J)=>{let Q=await O.setEnabled(J.req.param("id"),!1);if(!Q)throw new S("Schedule not found");return J.json(t0.parse(Q))}),x.post("/:id/run",async(J)=>{let Q=await O.get(J.req.param("id"));if(!Q)throw new S("Schedule not found");if(!$)throw new r("Scheduler is not running in this process");await $.fire(Q,new Date,{manual:!0});let z=await O.get(Q.id);return J.json(t0.parse(z??Q),202)}),x};import*as g0 from"node:fs/promises";import{homedir as H4}from"node:os";import*as A0 from"node:path";import{Hono as Z5}from"hono";var s0=a("Service"),_4=A0.join(H4(),".blade","skills"),M$=A0.join(H4(),".blade","skills-config.json");async function B4(){try{let O=await g0.readFile(M$,"utf-8");return JSON.parse(O)}catch{return{disabled:[]}}}async function Y5(O){await g0.mkdir(A0.dirname(M$),{recursive:!0}),await g0.writeFile(M$,JSON.stringify(O,null,2))}async function z5(O,$){let x=await B4();if($)x.disabled=x.disabled.filter((J)=>J!==O);else if(!x.disabled.includes(O))x.disabled.push(O);await Y5(x)}var h0=null,G5=300000,X5=6;async function V5(){if(h0&&Date.now()-h0.timestamp<G5)return h0.data;try{let O=await fetch("https://api.github.com/repos/anthropics/skills/contents/skills",{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"Blade-Skills-Catalog"}});if(!O.ok){if(s0.warn(`GitHub API returned ${O.status}`),h0)return h0.data;throw Error(`GitHub skills catalog returned ${O.status}`)}let x=(await O.json()).filter((Y)=>Y.type==="dir"),J=Array(x.length),Q=0,z=Math.min(X5,x.length);return await Promise.all(Array.from({length:z},async()=>{while(Q<x.length){let Y=Q++,F=x[Y];if(!F)continue;let T=`Official ${F.name} skill`;try{let B=await fetch(`https://raw.githubusercontent.com/anthropics/skills/main/skills/${F.name}/SKILL.md`,{headers:{"User-Agent":"Blade-Skills-Catalog"}});if(B.ok){let w=(await B.text()).match(/^#[^\n]*\n+([^\n#]+)/);if(w)T=w[1].trim().slice(0,100)}}catch{}J[Y]={name:F.name,description:T,tag:"Official",author:"Anthropic"}}})),h0={data:J,timestamp:Date.now()},J}catch(O){if(s0.warn("Failed to fetch skills catalog from GitHub:",O),h0)return h0.data;throw O}}var L4=()=>{let O=new Z5;return O.get("/",async($)=>{try{let x=$.get("directory")||c(),Q=(await T0(x)).skills.getAll(),z=await B4(),Y=Q.map((F)=>({id:F.name,name:F.name,enabled:!z.disabled.includes(F.name),description:F.description||"",version:F.version||"1.0.0",provider:"Local",location:F.source==="builtin"?"Built-in":F.basePath,removable:F.source==="user"&&A0.dirname(A0.resolve(F.basePath))===A0.resolve(_4),capabilities:["prompts"],allowedTools:F.allowedTools||[]}));return $.json(Y)}catch(x){return s0.error("[SkillsRoutes] Failed to get skills:",x),$.json({error:x instanceof Error?x.message:"Failed to get skills"},500)}}),O.post("/:name/toggle",async($)=>{try{let x=$.req.param("name"),J=await $.req.json();return await z5(x,J.enabled),$.json({success:!0,enabled:J.enabled})}catch(x){return s0.error("[SkillsRoutes] Failed to toggle skill:",x),$.json({success:!1,error:x.message},500)}}),O.delete("/:name",async($)=>{try{let x=$.req.param("name"),J=$.get("directory")||c();return jO(J,async(Q)=>{let z=Q.skills,Y=z.get(x);if(!Y)return $.json({success:!1,error:"Skill not found"},404);let F=A0.resolve(Y.basePath),T=A0.resolve(_4);if(Y.source!=="user"||A0.dirname(F)!==T)return $.json({success:!1,error:"Only Blade user skills can be uninstalled"},400);return await g0.rm(F,{recursive:!0,force:!0}),await z.refresh(),AO(J),await MO(J),$.json({success:!0})})}catch(x){return s0.error("[SkillsRoutes] Failed to uninstall skill:",x),$.json({success:!1,error:x.message},500)}}),O.post("/install",async($)=>{try{let x=await $.req.json(),J=D4(),Q=$.get("directory")||c();return jO(Q,async(z)=>{let Y=z.skills,F=!1;if(x.source==="catalog"&&x.name){if(F=await J.installOfficialSkill(x.name),!F)return $.json({success:!1,error:"Failed to install skill from catalog"},500)}else if(x.source==="repo"&&x.url){if(F=await J.installFromRepo(x.url,x.name),!F)return $.json({success:!1,error:"Failed to install skill from repository. Make sure the repo contains a SKILL.md file."},500)}else if(x.source==="local"&&x.path){if(F=await J.installFromLocal(x.path,x.name),!F)return $.json({success:!1,error:"Failed to install skill from local path. Make sure the path exists and contains a SKILL.md file."},500)}else return $.json({success:!1,error:"Invalid install parameters. Required: source with corresponding url/path/name"},400);return await Y.refresh(),AO(Q),await MO(Q),$.json({success:!0})})}catch(x){return s0.error("[SkillsRoutes] Failed to install skill:",x),$.json({success:!1,error:x.message},500)}}),O.get("/catalog",async($)=>{try{let x=await V5();return $.json(x)}catch(x){return s0.error("[SkillsRoutes] Failed to get catalog:",x),$.json({error:x instanceof Error?x.message:"Failed to get skills catalog"},502)}}),O};import{execSync as N5}from"node:child_process";import{readdir as K5}from"node:fs/promises";import sO from"node:path";import W5 from"fast-glob";import{Hono as F5}from"hono";var PO=a("Service"),U5=(O)=>{try{return N5("git rev-parse --abbrev-ref HEAD",{cwd:O,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}},_5=[...VO.map((O)=>`${O}/**`),...VO,...VO.map((O)=>`**/${O}/**`),...VO.map((O)=>`**/${O}`),...A$.map((O)=>`**/${O}`)],D5=new Set(["/theme","/model","/permissions","/mcp","/skills","/exit","/resume","/ide","/login","/logout"]),A4=()=>{let O=new F5;return O.get("/commands",async($)=>{try{let x=$.req.query("q")||"",J=$.get("directory")||c(),Q=await T0(J),z=M4(x,J,Q).filter((Y)=>!D5.has(Y.command));return $.json(z)}catch(x){return PO.error("[SuggestionsRoutes] Failed to get command suggestions:",x),$.json([])}}),O.get("/files",async($)=>{try{let x=$.req.query("q")||"",J=$.get("directory")||c(),Q=Math.min(Number($.req.query("limit"))||100,1000),z=$.req.query("type")==="file",F=(await W5("**/*",{cwd:J,dot:!1,followSymbolicLinks:!1,onlyFiles:z,markDirectories:!0,unique:!0,ignore:_5})).map((C)=>C.replace(/\\/g,"/"));if(!x)return $.json(F.slice(0,Q));let T=x.toLowerCase(),B=F.filter((C)=>C.toLowerCase().includes(T)).slice(0,Q);return $.json(B)}catch(x){return PO.error("[SuggestionsRoutes] Failed to get file suggestions:",x),$.json([])}}),O.get("/files/tree",async($)=>{try{let x=$.get("directory")||c(),J=$.req.query("path")||"",Q=J?sO.join(x,J):x,Y=(await K5(Q,{withFileTypes:!0})).map((B)=>({name:B.name,path:J?`${J}/${B.name}`:B.name,type:B.isDirectory()?"dir":"file"}));Y.sort((B,C)=>{if(B.type!==C.type)return B.type==="dir"?-1:1;return B.name.localeCompare(C.name)});let F=new Set(VO),T=Y.filter((B)=>{let C=B.name;if(C.startsWith("."))return!1;if(F.has(C))return!1;for(let w of A$)if(C.match(new RegExp(w.replace("*",".*"))))return!1;return!0});return $.json(T)}catch(x){return PO.error("[SuggestionsRoutes] Failed to get file tree:",x),$.json([])}}),O.get("/files/content",async($)=>{try{let x=$.req.query("path");if(!x)return $.json({error:"Missing file path"},400);let J=$.get("directory")||c(),Q=sO.resolve(J,x),z=sO.relative(J,Q);if(z.startsWith("..")||sO.isAbsolute(z))return $.json({error:"Invalid file path"},400);let Y=w4(),F=await Y.stat(Q);if(!F?.isFile)return $.json({error:"File not found"},404);let T=200000,B=await Y.readTextFile(Q),C=B.length>T;return $.json({path:x,content:C?B.slice(0,T):B,truncated:C,size:F.size})}catch(x){return PO.error("[SuggestionsRoutes] Failed to get file content:",x),$.json({error:"Failed to read file"},500)}}),O.get("/git-info",async($)=>{try{let x=$.get("directory")||c(),J=U5(x);return $.json({branch:J})}catch(x){return PO.error("[SuggestionsRoutes] Failed to get git info:",x),$.json({branch:null})}}),O};import{Hono as H5}from"hono";var NO=a("Service"),R4=(O)=>{let $=new H5;return $.onError((x,J)=>{if(x instanceof Z0)return J.json(x.toObject(),x.statusCode);return NO.error("[TaskRoutes] Unhandled route error:",x),J.json(new r("Failed to dispatch task").toObject(),500)}),$.post("/",async(x)=>{let J;try{J=await x.req.json()}catch{throw new H("Invalid request body")}let Q=P(T4,J);if(!Q.success)throw new H("Invalid task request");if((Q.data.attachments??[]).reduce((Y,F)=>Y+(typeof F.content==="string"?Buffer.byteLength(F.content):0),0)>oO)throw new H("Task attachments exceed the 5 MiB limit");if(Q.data.taskDueAt&&!Number.isFinite(Date.parse(Q.data.taskDueAt)))throw new H("Invalid task due date");try{let Y=await O.dispatchTask({prompt:Q.data.prompt,title:Q.data.title,taskPriority:Q.data.taskPriority,taskKind:Q.data.taskKind,taskDueAt:Q.data.taskDueAt?new Date(Q.data.taskDueAt).toISOString():void 0,sourceProjectPath:Q.data.projectPath||x.get("directory")||c(),isolation:Q.data.isolation,permissionMode:Q.data.permissionMode,modelId:Q.data.modelId,reasoningEffort:Q.data.reasoningEffort,serviceTier:Q.data.serviceTier,responseVerbosity:Q.data.responseVerbosity,communicationStyle:Q.data.communicationStyle,attachments:Q.data.attachments,outputSchema:Q.data.outputSchema});return x.json(T$.parse(Y),202)}catch(Y){if(Y instanceof H||Y instanceof q||Y instanceof l0||Y instanceof k0)throw Y;throw NO.error("[TaskRoutes] Failed to dispatch task:",Y),new r("Failed to dispatch task")}}),$.patch("/:sessionId",async(x)=>{let J;try{J=await x.req.json()}catch{throw new H("Invalid request body")}let Q=P(C4,J);if(!Q.success)throw new H("Invalid task update");if(Q.data.title===void 0&&Q.data.taskPriority===void 0&&Q.data.taskKind===void 0&&Q.data.taskDueAt===void 0)throw new H("Task update must include at least one field");if(typeof Q.data.taskDueAt==="string"&&!Number.isFinite(Date.parse(Q.data.taskDueAt)))throw new H("Invalid task due date");try{let z=await O.updateTask(x.req.param("sessionId"),{...Q.data,...typeof Q.data.taskDueAt==="string"?{taskDueAt:new Date(Q.data.taskDueAt).toISOString()}:{}},x.req.query("projectPath"));return x.json(j$.parse(z))}catch(z){if(z instanceof H||z instanceof S||z instanceof q)throw z;throw NO.error("[TaskRoutes] Failed to update task:",z),new r("Failed to update task")}}),$.post("/:sessionId/retry",async(x)=>{try{let J=await O.retryTask(x.req.param("sessionId"),x.req.query("projectPath"));return x.json(T$.parse(J),202)}catch(J){if(J instanceof H||J instanceof S||J instanceof q||J instanceof l0||J instanceof k0)throw J;throw NO.error("[TaskRoutes] Failed to retry task:",J),new r("Failed to retry task")}}),$.get("/:sessionId/diff",async(x)=>{try{let J=await O.getTaskDiff(x.req.param("sessionId"),x.req.query("projectPath"));return x.json(j4.parse(J))}catch(J){if(J instanceof H||J instanceof S||J instanceof q)throw J;throw NO.error("[TaskRoutes] Failed to load task diff:",J),new r("Failed to load task diff")}}),$.post("/:sessionId/delivery",async(x)=>{let J;try{J=await x.req.json()}catch{throw new H("Invalid request body")}let Q=P(b4,J);if(!Q.success)throw new H("Invalid task delivery request");try{let z=await O.deliverTask(x.req.param("sessionId"),Q.data.action,x.req.query("projectPath"));return x.json(j$.parse(z))}catch(z){if(z instanceof H||z instanceof S||z instanceof q)throw z;throw NO.error("[TaskRoutes] Failed to deliver task:",z),new r("Failed to deliver task")}}),$};import{Hono as B5}from"hono";var v0=a("Service"),KO=new Map,E4=2097152,q4=65536;function k4(){return typeof globalThis.Bun<"u"}async function L5(O,$,x){if(k4()){let{spawn:z}=await import("bun-pty"),Y=z(O,$,{name:"xterm-256color",cwd:x.cwd,env:x.env});return{pid:Y.pid,write:(F)=>Y.write(F),resize:(F,T)=>Y.resize(F,T),kill:()=>Y.kill(),onData:(F)=>Y.onData(F),onExit:(F)=>Y.onExit(F)}}let Q=(await import("node-pty")).spawn(O,$,{name:"xterm-256color",cwd:x.cwd,env:x.env,cols:80,rows:24});return{pid:Q.pid,write:(z)=>Q.write(z),resize:(z,Y)=>Q.resize(z,Y),kill:()=>Q.kill(),onData:(z)=>{Q.onData(z)},onExit:(z)=>{Q.onExit(z)}}}var R$=void 0,b$;if(k4())try{let{createBunWebSocket:O}=await import("hono/bun"),$=O();b$=$.upgradeWebSocket,R$=$.websocket}catch(O){v0.warn("[Terminal] Failed to initialize Bun WebSocket support:",O)}async function I4(O,$){let x=`term-${Date.now()}`;v0.info(`[Terminal] New connection: ${x}, cwd: ${O}`);let J=process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/zsh",Q=J.endsWith("sh")?["-l"]:[],z=await L5(J,Q,{cwd:O,env:{...process.env,TERM:"xterm-256color",COLORTERM:"truecolor"}}),Y={id:x,process:z,cwd:O,buffer:"",subscribers:new Set};if(KO.set(x,Y),Y.subscribers.add($),z.onData((F)=>{let T=!1;for(let B of Y.subscribers)try{B.send(F),T=!0}catch{Y.subscribers.delete(B)}if(T)return;if(Y.buffer+=F,Y.buffer.length>E4)Y.buffer=Y.buffer.slice(-E4)}),z.onExit(({exitCode:F})=>{v0.info(`[Terminal] Process exited: ${x}, code: ${F}`);for(let T of Y.subscribers)try{T.close()}catch{}KO.delete(x)}),Y.buffer){let F=Y.buffer;Y.buffer="";for(let T=0;T<F.length;T+=q4)$.send(F.slice(T,T+q4))}return{session:Y,cleanup:()=>{if(v0.info(`[Terminal] Connection closed: ${x}`),Y.subscribers.delete($),Y.subscribers.size===0){try{Y.process.kill()}catch{}KO.delete(x)}}}}function S4(O,$){O.on("connection",async(x,J)=>{let Q=new URL(J.url||"/",`http://${J.headers.host}`);if(!Q.pathname.endsWith("/terminal/ws")){x.close();return}let z=Q.searchParams.get("cwd")||$()||c();try{let{session:Y,cleanup:F}=await I4(z,{send:(T)=>x.send(T),close:()=>x.close()});x.on("message",(T)=>{try{Y.process.write(String(T))}catch(B){v0.error("[Terminal] Failed to write to PTY:",B)}}),x.on("close",F),x.on("error",F)}catch(Y){v0.error("[Terminal] Failed to spawn PTY:",Y),x.close()}})}var P4=()=>{let O=new B5;if(O.get("/status",($)=>{let x=Array.from(KO.values()).map((J)=>({id:J.id,cwd:J.cwd}));return $.json({active:x.length,terminals:x})}),O.post("/kill/:terminalId",($)=>{let x=$.req.param("terminalId"),J=KO.get(x);if(J){try{J.process.kill()}catch{}for(let Q of J.subscribers)Q.close();return KO.delete(x),$.json({success:!0})}return $.json({success:!1,error:"Terminal not found"},404)}),b$)O.get("/ws",b$(($)=>{let x=$.req.query("cwd")||$.get("directory")||c(),J;return{async onOpen(Q,z){try{J=await I4(x,{send:(Y)=>z.send(Y),close:()=>z.close()})}catch(Y){v0.error("[Terminal] Failed to spawn PTY:",Y),z.close()}},onMessage(Q){if(!J)return;try{J.session.process.write(String(Q.data))}catch(z){v0.error("[Terminal] Failed to write to PTY:",z)}},onClose(){J?.cleanup()}}}));else O.get("/ws",($)=>{return $.json({message:"WebSocket endpoint - connect via ws:// protocol",hint:"Use WebSocket client to connect to this endpoint"})});return O};import w5 from"node:path";import{Hono as M5}from"hono";var A5=U.Object({projectPath:U.String({minLength:1}),action:F0(["trust","revoke"])});function f4(O){if(!w5.isAbsolute(O))throw new H("projectPath must be absolute")}var m4=()=>{let O=new M5;return O.get("/",async($)=>{let x=$.req.query("projectPath");if(!x)throw new H("projectPath query parameter is required");return f4(x),$.json(await E$.getInstance().getStatus(x))}),O.post("/",async($)=>{let x=P(A5,await $.req.json());if(!x.success)throw new H("Invalid workspace trust request");let{projectPath:J,action:Q}=x.data;f4(J);let z=E$.getInstance(),Y=Q==="trust"?await z.trust(J):await z.revoke(J);return await y4(),$.json({...Y,reloadRequired:Y.sensitiveSources>0})}),O};var W0=a("Service"),I$=[],rO,WO,FO,fO,h4=new Map,g4=new Map,f5=new Set([".css",".html",".js",".json",".svg"]),y5=1024,m5=3600000;function h5(O,$){if(!O)return 0;let x=O.split(",").map((J)=>{let[Q,...z]=J.trim().toLowerCase().split(";"),Y=z.find((T)=>T.trim().startsWith("q=")),F=Y?Number(Y.trim().slice(2)):1;return{name:Q,quality:Number.isFinite(F)?Math.max(0,Math.min(1,F)):0}});return x.find((J)=>J.name===$)?.quality??x.find((J)=>J.name==="*")?.quality??0}function v4(){if(FO)return;let O=()=>{E.collectStaleEmptySessions().then(($)=>{if($>0)W0.info(`[SessionGC] removed ${$} stale empty session(s)`)}).catch(($)=>{W0.warn("[SessionGC] failed to collect stale empty sessions:",$)})};O(),FO=setInterval(O,m5),FO.unref?.()}function g5(){if(!FO)return;clearInterval(FO),FO=void 0}function v5(O){return["br","gzip"].map((x)=>({encoding:x,quality:h5(O,x)})).filter((x)=>x.quality>0).sort((x,J)=>J.quality-x.quality||(x.encoding==="br"?-1:1))[0]?.encoding}function u5(O){let $=h4.get(O);if($)return $;let x=yO(O);return h4.set(O,x),x}function p5(O,$,x){let J=`${x}:${O}`,Q=g4.get(J);if(Q)return Q;let z=x==="br"?E5($,{params:{[k5.BROTLI_PARAM_QUALITY]:5}}):q5($,{level:6});return g4.set(J,z),z}function d5(){let O=C5(R5(import.meta.url)),$=[u0(O,"web"),u0(c(),"dist/web"),u0(c(),"packages/cli/dist/web")];for(let x of $){let J=u0(x,"index.html");if(k$(J)){if(yO(J,"utf-8").includes("/assets/"))return W0.debug(`[Server] Found web dist at: ${x}`),x}}return null}function l5(){let O=new I5;O.onError((J,Q)=>{if(W0.error("[Server] Request error:",J),J instanceof d4){let Y=new k0(J.message,{resource:"workspace_agent_resources",limit:J.capacity});return Q.json(Y.toObject(),429)}if(J instanceof Z0)return Q.json(J.toObject(),J.statusCode);let z=J instanceof Error?J.message:String(J);return Q.json({error:{code:"INTERNAL_ERROR",message:z}},500)}),O.use(async(J,Q)=>{let z=process.env.BLADE_SERVER_PASSWORD;if(!z)return Q();let Y=J.req.path;if(Y==="/"||Y==="/favicon.svg"||Y.startsWith("/assets/")||Y.endsWith(".html")||Y.endsWith(".js")||Y.endsWith(".css"))return Q();let F=J.req.header("Authorization");if(!F?.startsWith("Basic "))return J.header("WWW-Authenticate",'Basic realm="Blade Server"'),J.json({error:{code:"UNAUTHORIZED",message:"Authentication required"}},401);let T=Buffer.from(F.slice(6),"base64").toString(),[B,C]=T.split(":"),w=process.env.BLADE_SERVER_USERNAME??"blade";if(B!==w||C!==z)return J.json({error:{code:"UNAUTHORIZED",message:"Invalid credentials"}},401);return Q()}),O.use(async(J,Q)=>{let z=J.req.path==="/health"||J.req.path==="/global/health"||J.req.path.startsWith("/assets/");if(!z)W0.debug(`[Server] ${J.req.method} ${J.req.path}`);let Y=Date.now();if(await Q(),!z){let F=Date.now()-Y;W0.debug(`[Server] ${J.req.method} ${J.req.path} - ${J.res.status} (${F}ms)`)}}),O.use(S5({origin(J){if(!J)return;if(J.startsWith("http://localhost:"))return J;if(J.startsWith("http://127.0.0.1:"))return J;if(J==="tauri://localhost"||J==="http://tauri.localhost")return J;if(I$.includes(J))return J;return}})),O.use(async(J,Q)=>{let z=J.req.query("directory")||J.req.header("x-blade-directory")||c();try{z=decodeURIComponent(z)}catch{}return J.set("directory",z),Q()});let $=u1();fO=$,rO=$.recoverQueuedTasks,WO=new J$({dispatch:(J)=>$.dispatchTask(J),store:q$}),O.route("/global",t$()),O.route("/events",o$()),O.route("/sessions",$.app),O.route("/tasks",R4($)),O.route("/schedules",U4(q$,WO)),O.route("/configs",p$()),O.route("/permissions",d1()),O.route("/plugins",J4()),O.route("/hooks",x1()),O.route("/workspace-trust",m4()),O.route("/providers",N4()),O.route("/models",N1()),O.route("/projects",Y4()),O.route("/suggestions",A4()),O.route("/terminal",P4()),O.route("/mcp",Z1()),O.route("/skills",L4()),O.get("/health",(J)=>{return J.json({healthy:!0,version:xO()})});let x=d5();if(x)W0.info(`[Server] Serving static files from ${x}`),O.get("/favicon.svg",()=>{let J=u0(x,"favicon.svg");if(!k$(J))return new Response(null,{status:404});return new Response(yO(J),{headers:{"Content-Type":"image/svg+xml","Cache-Control":"public, max-age=86400"}})}),O.get("/assets/*",(J)=>{let Q=u0(x,J.req.path);if(!k$(Q))return J.json({error:{code:"NOT_FOUND",message:`File not found: ${J.req.path}`}},404);let z=u5(Q),Y=b5(Q).toLowerCase(),T={".js":"application/javascript",".css":"text/css",".html":"text/html",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".eot":"application/vnd.ms-fontobject"}[Y]||"application/octet-stream",B=f5.has(Y)&&z.byteLength>=y5?v5(J.req.header("Accept-Encoding")):void 0,C=B?p5(Q,z,B):z;return new Response(new Uint8Array(C),{headers:{"Content-Type":T,"Content-Length":String(C.byteLength),"Cache-Control":"public, max-age=31536000, immutable",Vary:"Accept-Encoding",...B?{"Content-Encoding":B}:{}}})}),O.get("/",(J)=>{let Q=u0(x,"index.html"),z=yO(Q,"utf-8");return J.html(z,200,{"Cache-Control":"no-cache"})}),O.get("*",(J)=>{let Q=J.req.path;if(Q.includes("."))return J.json({error:{code:"NOT_FOUND",message:`File not found: ${Q}`}},404);let z=u0(x,"index.html"),Y=yO(z,"utf-8");return J.html(Y,200,{"Cache-Control":"no-cache"})});else W0.warn('[Server] Web UI not found. Run "cd packages/cli/web && bun run build" to enable web interface.'),O.get("/",(J)=>{return J.json({message:"Blade API Server",version:xO(),webUI:!1,hint:'Web UI not built. Run "cd packages/cli/web && bun run build" to enable.',endpoints:{health:"/health",sessions:"/sessions",configs:"/configs",permissions:"/permissions",providers:"/providers"}})}),O.all("*",(J)=>{return J.json({error:{code:"NOT_FOUND",message:`Route not found: ${J.req.path}`}},404)});return O}function c5(){let O=T5(),$=[];for(let x of Object.keys(O)){let J=O[x];if(!J)continue;for(let Q of J){if(Q.internal||Q.family!=="IPv4")continue;if(Q.address.startsWith("172."))continue;$.push(Q.address)}}return $}function u4(){return typeof globalThis.Bun<"u"}function p4(O,$){let x=globalThis.Bun,J=(z)=>{try{return x.serve({hostname:$.hostname,port:z,fetch:O.fetch,idleTimeout:0,websocket:R$})}catch(Y){W0.error("Failed to start Bun server:",Y);return}},Q=$.port===0?J(4096)??J(0):J($.port);if(!Q)throw Error(`Failed to start Bun server on port ${$.port}`);return{url:Q.url,port:Q.port,hostname:Q.hostname,stop:async()=>{Q.stop(!0)}}}function i5(O,$){return new Promise((x,J)=>{let Q=j5(async(B,C)=>{let w=new URL(B.url||"/",`http://${B.headers.host}`),W=new Headers;for(let[p,b]of Object.entries(B.headers))if(b)if(Array.isArray(b))for(let e of b)W.append(p,e);else W.set(p,b);let I;if(B.method!=="GET"&&B.method!=="HEAD")I=(await new Promise((b)=>{let e=[];B.on("data",(v)=>e.push(v)),B.on("end",()=>b(Buffer.concat(e)))})).toString();let Q0=new Request(w.toString(),{method:B.method,headers:W,body:I});try{let p=await O.fetch(Q0);if(C.statusCode=p.status,p.headers.forEach((b,e)=>{C.setHeader(e,b)}),p.body){let b=p.body.getReader(),e=async()=>{let{done:v,value:Y0}=await b.read();if(v){C.end();return}return C.write(Y0),e()};await e()}else{let b=await p.text();C.end(b)}}catch(p){W0.error("[Server] Node request error:",p),C.statusCode=500,C.end(JSON.stringify({error:{code:"INTERNAL_ERROR",message:"Internal server error"}}))}}),z=new P5({noServer:!0}),Y=c();S4(z,()=>Y),Q.on("upgrade",(B,C,w)=>{if(new URL(B.url||"/",`http://${B.headers.host}`).pathname==="/terminal/ws")z.handleUpgrade(B,C,w,(I)=>{z.emit("connection",I,B)});else C.destroy()});let F=(B)=>{return new Promise((C,w)=>{Q.once("error",(W)=>{if(W.code==="EADDRINUSE")w(W);else w(W)}),Q.listen(B,$.hostname,()=>{let W=Q.address();if(W&&typeof W==="object")C(W.port);else C(B)})})};(async()=>{let B;if($.port===0)try{B=await F(4096)}catch{B=await F(0)}else B=await F($.port);let C=new URL(`http://${$.hostname==="0.0.0.0"?"localhost":$.hostname}:${B}`);x({url:C,port:B,hostname:$.hostname,stop:async()=>{return new Promise((w)=>{z.close(()=>{Q.close(()=>w())})})}})})().catch(J)})}var c4;((V6)=>{let O,$,x,J=(B,C)=>{if(O!==B)return Promise.resolve();if(x)return x;let w=C?.shutdown("server-shutdown");return WO?.stop(),g5(),x=(async()=>{let W,I=async(Q0)=>{if(!Q0)return;try{await Q0()}catch(p){W??=p}};if(await I(()=>B.stop()),await I(w?()=>w:void 0),l4(),O===B)O=void 0,$=void 0,fO=void 0,rO=void 0,WO=void 0;if(W0.info("[Server] Blade server stopped"),W!==void 0)throw W})(),x};function Q(){if(!$)$=l5();return $}V6.getApp=Q;function z(B){I$=B.cors??[];let C=Q();if(u4())O=p4(C,B),x=void 0,W0.info(`[Server] Blade server listening on ${O.url} (Bun runtime)`);else throw Error("Blade web server requires Bun runtime. Please run with Bun: `bun run blade web` or install Bun from https://bun.sh");let w=O,W=fO;return rO?.().catch((I)=>{W0.warn("[Server] Failed to recover queued tasks:",I)}),WO?.start(),v4(),{url:w.url,port:w.port,hostname:w.hostname,stop:()=>J(w,W)}}V6.listen=z;async function Y(B){I$=B.cors??[];let C=Q();if(u4())O=p4(C,B),W0.info(`[Server] Blade server listening on ${O.url} (Bun runtime)`);else O=await i5(C,B),W0.info(`[Server] Blade server listening on ${O.url} (Node.js runtime)`);x=void 0;let w=O,W=fO;try{await rO?.()}catch(I){W0.warn("[Server] Failed to recover queued tasks:",I)}return WO?.start(),v4(),{url:w.url,port:w.port,hostname:w.hostname,stop:()=>J(w,W)}}V6.listenAsync=Y;function F(){return O!==void 0}V6.isRunning=F;function T(){return fO?.getCoordinationStats()}V6.getSessionCoordinationStatsForTests=T})(c4||={});export{a5 as f,o5 as g,c5 as h,c4 as i};
|
package/dist/chunk-w67k19a1.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{fe as a,ge as b,he as c}from"./chunk-efemjy9y.js";import"./chunk-yn51162x.js";import"./chunk-ypqp368c.js";import"./chunk-t8xmh4w2.js";import"./chunk-ppsvzgs5.js";import"./chunk-hcv17986.js";export{b as resolveModelConfig,c as getModelDisplayName,a as getModelApiKeyEnvironmentVariable};
|