blade-code 0.10.150 → 0.10.152
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-cz77x04v.js → chunk-069ffeb6.js} +1 -1
- package/dist/{chunk-j8hbddjp.js → chunk-0b67y4j1.js} +2 -2
- package/dist/{chunk-8gg7zddg.js → chunk-0y8bxjwj.js} +1 -1
- package/dist/{chunk-3y2x6fb6.js → chunk-28tzj187.js} +1 -1
- package/dist/chunk-514va7ce.js +2 -0
- package/dist/{chunk-wcps5gjm.js → chunk-53vh6vpt.js} +1 -1
- package/dist/{chunk-mmcjckwx.js → chunk-5jabe6fh.js} +1 -1
- package/dist/{chunk-2mk914vk.js → chunk-5q4z0sfr.js} +2 -2
- package/dist/{chunk-mpexy01a.js → chunk-68y9kcyz.js} +1 -1
- package/dist/{chunk-qf6vf457.js → chunk-7mexgpjc.js} +1 -1
- package/dist/{chunk-4wx5sya5.js → chunk-7xtxvrh8.js} +1 -1
- package/dist/chunk-8g3dph9d.js +14 -0
- package/dist/{chunk-wkjdgbnx.js → chunk-9daqcc7x.js} +1 -1
- package/dist/{chunk-4cdk4mds.js → chunk-9kj19a8t.js} +1 -1
- package/dist/{chunk-jq5bhnrd.js → chunk-9tk6wq70.js} +1 -1
- package/dist/{chunk-3rv3fnwr.js → chunk-ae8966n2.js} +1 -1
- package/dist/{chunk-dxtbv0v7.js → chunk-azc480af.js} +1 -1
- package/dist/chunk-c0n0fxkt.js +1 -0
- package/dist/{chunk-3tvkp2yd.js → chunk-ce7e73tx.js} +1 -1
- package/dist/{chunk-87xebr2g.js → chunk-cv4h5c96.js} +1 -1
- package/dist/chunk-cvazye0h.js +733 -0
- package/dist/{chunk-d1navt68.js → chunk-d0q5n5ea.js} +3 -3
- package/dist/{chunk-cxenrejk.js → chunk-d5wbm0qg.js} +1 -1
- package/dist/chunk-dzeh2tx3.js +1 -0
- package/dist/{chunk-s1cs5ga0.js → chunk-e1j1gsr5.js} +2 -2
- package/dist/{chunk-3hgb942q.js → chunk-e8gmfajx.js} +1 -1
- package/dist/chunk-enf0egke.js +1 -0
- package/dist/{chunk-06hkf59s.js → chunk-erhaedch.js} +1 -1
- package/dist/{chunk-3kszepm6.js → chunk-ewwrss2w.js} +1 -1
- package/dist/{chunk-w6qfbea8.js → chunk-f2y0gxyq.js} +1 -1
- package/dist/chunk-fswy6tg3.js +1 -0
- package/dist/{chunk-mh9nqbwa.js → chunk-fx9vm1n5.js} +1 -1
- package/dist/{chunk-vj50xf5c.js → chunk-fxhjbst1.js} +1 -1
- package/dist/chunk-g3h54s6h.js +1 -0
- package/dist/chunk-genqngnt.js +10 -0
- package/dist/{chunk-rvs364rz.js → chunk-gm2yfq3r.js} +2 -2
- package/dist/chunk-gtajytct.js +1 -0
- package/dist/{chunk-6hb0pjmk.js → chunk-h1pw492p.js} +1 -1
- package/dist/{chunk-e12xrg41.js → chunk-ht8epjz2.js} +1 -1
- package/dist/{chunk-vbjgcn49.js → chunk-hv8nt7wj.js} +1 -1
- package/dist/chunk-j7784bxm.js +1 -0
- package/dist/{chunk-xmymx75h.js → chunk-jbpasjg9.js} +1 -1
- package/dist/{chunk-wv8dy886.js → chunk-jgqk2tmr.js} +3 -3
- package/dist/{chunk-2f8d0km4.js → chunk-jsv3e4k6.js} +1 -1
- package/dist/{chunk-z2k08r1h.js → chunk-k1tfry97.js} +1 -1
- package/dist/{chunk-shb7g2vr.js → chunk-k3ne93k8.js} +1 -1
- package/dist/{chunk-6vcqajdc.js → chunk-mt26v0vg.js} +1 -1
- package/dist/{chunk-ddvdc2p0.js → chunk-n34qsnks.js} +1 -1
- package/dist/{chunk-vw9paban.js → chunk-n9819k4p.js} +1 -1
- package/dist/chunk-nv1e4f05.js +1 -0
- package/dist/chunk-p9vtz642.js +1 -0
- package/dist/{chunk-zj1g4nbq.js → chunk-pv6cgfv1.js} +1 -1
- package/dist/{chunk-3a217980.js → chunk-q1rnvn85.js} +1 -1
- package/dist/{chunk-f71j03pq.js → chunk-qmveehgt.js} +1 -1
- package/dist/chunk-qv6s1q20.js +1 -0
- package/dist/{chunk-kv458q06.js → chunk-sd9bze9x.js} +1 -1
- package/dist/{chunk-eg3ms291.js → chunk-sdapqhj0.js} +1 -1
- package/dist/chunk-sgy87nrv.js +1 -0
- package/dist/{chunk-zyxfdewk.js → chunk-sj578593.js} +2 -2
- package/dist/chunk-sja01scc.js +1 -0
- package/dist/{chunk-2zzsyaf4.js → chunk-sncepfa3.js} +1 -1
- package/dist/{chunk-q5gcqckt.js → chunk-tq99wv62.js} +1 -1
- package/dist/{chunk-0tzecdv3.js → chunk-tya95jej.js} +1 -1
- package/dist/{chunk-wzqcea6x.js → chunk-v1mamd1x.js} +1 -1
- package/dist/{chunk-6a16zba3.js → chunk-v67st2xb.js} +1 -1
- package/dist/{chunk-ghqvews8.js → chunk-w1e6gagm.js} +1 -1
- package/dist/{chunk-9a0cy4z7.js → chunk-wfynmt9r.js} +2 -2
- package/dist/{chunk-mhb3gg9s.js → chunk-wpa74vxq.js} +2 -2
- package/dist/{chunk-01framym.js → chunk-y5dbpqzw.js} +1 -1
- package/dist/{chunk-sxvhv62s.js → chunk-yvccs002.js} +1 -1
- package/dist/chunk-zqjm9yd8.js +1 -0
- package/dist/{chunk-qm0j4szw.js → chunk-zrgfvc4k.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-0ktd3vpk.js +0 -10
- package/dist/chunk-25zrctsh.js +0 -1
- package/dist/chunk-5v0jcyea.js +0 -2
- package/dist/chunk-5y4btx3c.js +0 -1
- package/dist/chunk-66wk3exc.js +0 -1
- package/dist/chunk-8s93p05b.js +0 -1
- package/dist/chunk-ahz3sskk.js +0 -1
- package/dist/chunk-d9q5dn00.js +0 -1
- package/dist/chunk-ddxpgrcv.js +0 -14
- package/dist/chunk-fkbnsn0a.js +0 -1
- package/dist/chunk-h8s11k0r.js +0 -733
- package/dist/chunk-k5m9yj9n.js +0 -1
- package/dist/chunk-n14kcb52.js +0 -1
- package/dist/chunk-q8erftv7.js +0 -1
- package/dist/chunk-qypjj8rk.js +0 -1
- package/dist/chunk-rxc6mazk.js +0 -1
- package/dist/chunk-xtbcwn9q.js +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{vg as B}from"./chunk-7wcxjbyg.js";import{
|
|
1
|
+
import{vg as B}from"./chunk-7wcxjbyg.js";import{Oj as Y}from"./chunk-0b67y4j1.js";import{Rj as Z,Uj as $}from"./chunk-9kj19a8t.js";import{createHash as H}from"node:crypto";var N="fast-mode-2026-02-01";function R(q,x,z){if(x.api!=="anthropic-messages"||z.providerValue!=="fast")return q;let J={...q},w=Object.keys(J).find((G)=>G.toLowerCase()==="anthropic-beta")??"anthropic-beta",Q=new Set((J[w]??"").split(",").map((G)=>G.trim()).filter(Boolean));return Q.add(N),J[w]=[...Q].join(","),J}function D(q){return`BLADE_MODEL_API_KEY_${H("sha256").update(q).digest("hex").slice(0,32).toUpperCase()}`}function F(q,x){if(!q.fallbackModels?.length)return;return q.fallbackModels.map((z)=>{let J=(x.models??[]).filter((G)=>G.provider===z.provider&&G.model===z.model),w=z.configId?(x.models??[]).find((G)=>G.id===z.configId):J.length===1?J[0]:void 0;if(z.configId&&!w)throw Error(`Unknown fallback model config ID: ${z.configId}`);if(w&&(w.provider!==z.provider||w.model!==z.model))throw Error(`Fallback model config ${w.id} does not match ${z.provider}/${z.model}`);if(!z.configId&&J.length>1)throw Error(`Fallback model ${z.provider}/${z.model} is ambiguous; set configId`);if(!w)return z;let Q=w.provider===q.provider;return{...z,configId:w.id,channel:{apiKey:process.env[D(w.id)]??(Q?process.env.BLADE_API_KEY:void 0),baseUrl:w.overrides?.baseUrl??(Q?process.env.BLADE_BASE_URL:void 0),temperature:w.overrides?.temperature??x.temperature,maxOutputTokens:w.overrides?.maxOutputTokens,timeout:w.overrides?.timeout??x.timeout,streamIdleTimeout:w.overrides?.streamIdleTimeout,apiVersion:w.overrides?.apiVersion,customHeaders:w.overrides?.customHeaders,enablePromptCaching:w.overrides?.enablePromptCaching}}})}function h(q,x,z,J=Y(),w="auto",Q="auto"){let G=J.resolveConfig(q),U=B(G,z),W=$(G,w),X=Z(G,Q),L=q.overrides;return{config:q,model:G,displayName:q.displayName??G.name,chat:{provider:q.provider,model:q.model,apiKey:process.env[D(q.id)]??process.env.BLADE_API_KEY,baseUrl:process.env.BLADE_BASE_URL??L?.baseUrl,temperature:L?.temperature??x.temperature,maxContextTokens:G.contextWindow,maxOutputTokens:L?.maxOutputTokens,timeout:L?.timeout??x.timeout,streamIdleTimeout:L?.streamIdleTimeout,reasoningEnabled:U.effective!=="off",...U.effective==="off"?{}:{reasoningEffort:U.effective},...W.providerValue?{serviceTier:W.providerValue}:{},...X.providerValue?{responseVerbosity:X.providerValue}:{},fallbackModels:F(q,x),enablePromptCaching:L?.enablePromptCaching,customHeaders:R(L?.customHeaders,G,W),apiVersion:L?.apiVersion,maxRetries:L?.maxRetries,providerCircuitBreakerOpenMs:x.providerCircuitBreakerOpenMs,providerRequestConcurrency:x.providerRequestConcurrency,providerGlobalConcurrency:x.providerGlobalConcurrency,providerOwnerConcurrency:x.providerOwnerConcurrency,providerRequestAdmissionMs:x.providerRequestAdmissionMs,providerRequestPendingBytes:x.providerRequestPendingBytes,modelCatalog:J},reasoning:U,serviceTier:W,responseVerbosity:X}}function j(q,x=Y()){try{return q.displayName??x.getModel(q.provider,q.model).name}catch{return q.displayName??q.model}}
|
|
2
2
|
export{D as rg,h as sg,j as tg};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ab as V,cb as W,db as O,vb as J}from"./chunk-
|
|
1
|
+
import{ab as V,cb as W,db as O,vb as J}from"./chunk-ht8epjz2.js";import"./chunk-fx9vm1n5.js";import"./chunk-f2y0gxyq.js";import"./chunk-53vh6vpt.js";import"./chunk-514va7ce.js";import{aj as Q}from"./chunk-jsv3e4k6.js";import"./chunk-5q4z0sfr.js";import"./chunk-7xtxvrh8.js";import"./chunk-sdapqhj0.js";import F from"chalk";var K=(f)=>typeof f==="string"&&f.length>0?f:void 0;function X(f){let z=K(f.cron),G=K(f.every),H=K(f.at);if([z,G,H].filter(Boolean).length!==1)throw Error("Provide exactly one of --cron, --every, or --at");if(z)return{kind:"cron",cron:z};if(G){let P=V(G);if(!P)throw Error(`Invalid --every value "${G}" (use e.g. 30m, 2h, 1d)`);return{kind:"interval",intervalMs:P}}let N=new Date(H);if(Number.isNaN(N.getTime()))throw Error(`Invalid --at value "${H}" (use an ISO timestamp)`);return{kind:"once",runAt:N.toISOString()}}var Y={command:"create <prompt>",describe:"创建定时任务",builder:(f)=>f.positional("prompt",{type:"string",describe:"定时任务运行时发送给 Agent 的提示词",demandOption:!0}).option("cron",{type:"string",describe:"5 段 cron 表达式(本地时区)"}).option("every",{type:"string",describe:"间隔(如 30m、2h、1d)"}).option("at",{type:"string",describe:"一次性运行的 ISO 时间点"}).option("project-path",{alias:["projectPath","project"],type:"string",describe:"目标项目路径(默认当前目录)"}).option("title",{type:"string",describe:"定时任务标题"}).option("model",{alias:"m",type:"string",describe:"模型 ID"}).option("permission-mode",{type:"string",choices:["default","autoEdit","yolo","plan"],default:"default",describe:"权限模式"}).option("isolation",{type:"string",choices:["local","worktree"],default:"worktree",describe:"执行隔离方式"}).example([['$0 schedule create "跑测试并汇报失败" --every 1h',"每小时运行一次"],['$0 schedule create "生成每日站会摘要" --cron "0 9 * * 1-5"',"工作日 9 点运行"]]),handler:async(f)=>{try{let z=X(f),G=W(z);if(G)throw Error(G);let H={prompt:f.prompt,projectPath:K(f.projectPath)??Q(),title:K(f.title),trigger:z,modelId:K(f.model),isolation:K(f.isolation)??"worktree",permissionMode:K(f.permissionMode)??"default",enabled:!0},B=await J.create(H);console.log(F.green(`✓ 已创建定时任务 ${B.id}`)),console.log(` ${O(B.trigger)}`),console.log(` 项目: ${B.projectPath}`),console.log(` 下次运行: ${B.nextRunAt?new Date(B.nextRunAt).toLocaleString():"(无)"}`),process.exit(0)}catch(z){console.error(F.red(`创建定时任务失败: ${z instanceof Error?z.message:z}`)),process.exit(1)}}},Z={command:"list",aliases:["ls"],describe:"列出所有定时任务",handler:async()=>{let f=await J.list();if(f.length===0)console.log(F.dim("尚无定时任务。使用 `blade schedule create` 创建。")),process.exit(0);for(let z of f){let G=z.enabled?F.green("启用"):F.dim("停用"),H=z.nextRunAt?new Date(z.nextRunAt).toLocaleString():"—",B=z.lastRunAt?`${new Date(z.lastRunAt).toLocaleString()} (${z.lastStatus??"?"})`:"从未";console.log(`${F.cyan(z.id)} [${G}] ${z.title??z.prompt.slice(0,40)}`),console.log(` ${O(z.trigger)} · 下次: ${H} · 上次: ${B} · 运行 ${z.runCount} 次`),console.log(F.dim(` 项目: ${z.projectPath}`))}process.exit(0)}},_={command:"show <id>",describe:"查看定时任务详情",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{let z=await J.get(f.id);if(!z)console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(JSON.stringify(z,null,2)),process.exit(0)}},$={command:"remove <id>",aliases:["rm"],describe:"删除定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.remove(f.id))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已删除定时任务 ${f.id}`)),process.exit(0)}},q={command:"enable <id>",describe:"启用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!0))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已启用定时任务 ${f.id}`)),process.exit(0)}},x={command:"disable <id>",describe:"停用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!1))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已停用定时任务 ${f.id}`)),process.exit(0)}},D={command:"run <id>",describe:"立即运行定时任务(需要 blade serve)",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}).option("server",{type:"string",default:process.env.BLADE_SERVER_URL??"http://127.0.0.1:4097",describe:"Blade server 地址"}),handler:async(f)=>{let z=f.id,G=(K(f.server)??"http://127.0.0.1:4097").replace(/\/$/,""),H={};if(process.env.BLADE_SERVER_PASSWORD){let B=process.env.BLADE_SERVER_USERNAME??"blade";H.Authorization=`Basic ${Buffer.from(`${B}:${process.env.BLADE_SERVER_PASSWORD}`).toString("base64")}`}try{let B=await fetch(`${G}/schedules/${encodeURIComponent(z)}/run`,{method:"POST",headers:H});if(!B.ok){let N=await B.json().catch(()=>{return});throw Error(N?.error?.message??`Schedule run failed (${B.status})`)}console.log(F.green(`✓ 已触发定时任务 ${z}`)),process.exit(0)}catch(B){console.error(F.red(`运行定时任务失败: ${B instanceof Error?B.message:B}`)),process.exit(1)}}},R={command:"schedule",describe:"管理定时任务",builder:(f)=>f.command(Y).command(Z).command(_).command($).command(q).command(x).command(D).demandCommand(1,"请提供子命令:create | list | show | remove | enable | disable | run"),handler:()=>{}};export{R as scheduleCommands};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var I=600000,r=30000,t=3600000,o=12,O=15000,P=60000;function R(_){return _===0||typeof _==="number"&&Number.isSafeInteger(_)&&_>=30000&&_<=3600000}var C=1e4,M=1000,p=300000;function E(_){return _===0||typeof _==="number"&&Number.isSafeInteger(_)&&_>=1000&&_<=300000}var T=1,s=16,n=Number.MAX_SAFE_INTEGER,D=180000,m=1000,x=600000,S=134217728,U=65536,V=134217728;function A(_){return typeof _==="number"&&Number.isSafeInteger(_)&&_>=1&&_<=16}function w(_){return typeof _==="number"&&Number.isSafeInteger(_)&&_>=1&&_<=n}function z(_){return _===0||typeof _==="number"&&Number.isSafeInteger(_)&&_>=1000&&_<=600000}function F(_){return typeof _==="number"&&Number.isSafeInteger(_)&&_>=65536&&_<=134217728}
|
|
2
|
-
export{I as
|
|
2
|
+
export{I as bj,r as cj,t as dj,o as ej,O as fj,P as gj,R as hj,C as ij,M as jj,p as kj,E as lj,T as mj,s as nj,n as oj,D as pj,m as qj,x as rj,S as sj,U as tj,V as uj,A as vj,w as wj,z as xj,F as yj};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{promises as B}from"node:fs";import q from"node:path";import{LRUCache as H}from"lru-cache";var K=512,Z=new H({max:K});async function L(x){let b=x;while(!0){try{return await B.lstat(q.join(b,".git")),b}catch(V){if(V.code!=="ENOENT")return}let F=q.dirname(b);if(F===b)return;b=F}}async function M(x){let b=q.join(x,".git"),F=await B.lstat(b);if(F.isDirectory())return x;if(!F.isFile())return;let V=await B.readFile(b,"utf8"),J=/^gitdir:\s*(.+)\s*$/im.exec(V);if(!J)return;let Q=await B.realpath(q.isAbsolute(J[1])?J[1]:q.resolve(x,J[1])),Y=Q;try{let z=(await B.readFile(q.join(Q,"commondir"),"utf8")).trim();if(z)Y=await B.realpath(q.resolve(Q,z))}catch(z){if(z.code!=="ENOENT")throw z}return q.basename(Y)===".git"?B.realpath(q.dirname(Y)):void 0}async function N(x){if(!q.isAbsolute(x))throw Error("Workspace path must be absolute");let b=await B.realpath(x),F=Z.get(b);if(F)return F;let V=b;try{let Q=await L(b);if(Q){let Y=await M(Q),z=q.relative(Q,b);if(Y&&(z===""||!z.startsWith(`..${q.sep}`)&&z!==".."&&!q.isAbsolute(z))){let $=q.resolve(Y,z);V=await B.realpath($).catch(()=>$)}}}catch{}let J={projectPath:b,trustRoot:V};return Z.set(b,J),J}async function S(x){if(!q.isAbsolute(x))throw Error("Workspace path must be absolute");let b=await B.realpath(x);Z.delete(b)}
|
|
2
|
-
export{N as
|
|
2
|
+
export{N as ck,S as dk};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{qf as a,rf as b}from"./chunk-5jabe6fh.js";import"./chunk-e1j1gsr5.js";import"./chunk-sdapqhj0.js";export{a as globalOptions,b as cliConfig};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{wg as a,xg as b,yg as c,zg as d}from"./chunk-y5dbpqzw.js";import"./chunk-wfynmt9r.js";import"./chunk-sd9bze9x.js";import"./chunk-514va7ce.js";import"./chunk-jsv3e4k6.js";import"./chunk-n34qsnks.js";import"./chunk-5q4z0sfr.js";import"./chunk-0b67y4j1.js";import"./chunk-9kj19a8t.js";import"./chunk-e1j1gsr5.js";import"./chunk-gm2yfq3r.js";import"./chunk-n9819k4p.js";import"./chunk-7xtxvrh8.js";import"./chunk-sdapqhj0.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,d as createProcessModelResources,a as cloneWorkspaceModelConfig};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Ik as $,ek as F}from"./chunk-7xtxvrh8.js";import{promises as J}from"node:fs";import Q from"node:path";import{Mutex as U}from"async-mutex";import w from"write-file-atomic";var X=1;function D(k){if(!k||typeof k!=="object"||Array.isArray(k))return!1;let q=k;return typeof q.path==="string"&&Q.isAbsolute(q.path)&&typeof q.boundAt==="string"}async function Z(k){if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k);if(!(await J.stat(q)).isDirectory())throw Error("Project path must be a directory");return q}class K{filePath;mutex=new U;constructor(k=Q.join(F(),"bound-projects.json")){this.filePath=k}async list(k){let q=await this.read(),z=await Z(k),H=new Map;for(let C of q.projects)H.set(C.path,C);if(!H.has(z))H.set(z,{path:z,boundAt:new Date(0).toISOString()});return(await Promise.all([...H.values()].map(async(C)=>{let L=!1;try{L=(await J.stat(C.path)).isDirectory()}catch{}return{path:C.path,name:Q.basename(C.path)||C.path,...L?{gitBranch:$(C.path)}:{},available:L,isCurrent:C.path===z,boundAt:C.boundAt}}))).sort((C,L)=>{if(C.isCurrent!==L.isCurrent)return C.isCurrent?-1:1;return C.name.localeCompare(L.name)})}async bind(k,q){return this.mutex.runExclusive(async()=>{let z=await Z(k),H=await this.read(),W=H.projects.find((M)=>M.path===z),C=W??{path:z,boundAt:new Date().toISOString()};if(!W)H.projects.push(C),await this.write(H);let L=await Z(q),A=$(z);return{path:z,name:Q.basename(z)||z,...A?{gitBranch:A}:{},available:!0,isCurrent:z===L,boundAt:C.boundAt}})}async unbind(k){return this.mutex.runExclusive(async()=>{if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k).catch(()=>Q.resolve(k)),z=await this.read(),H=z.projects.filter((W)=>W.path!==q);if(H.length===z.projects.length)return!1;return z.projects=H,await this.write(z),!0})}async read(){try{let k=await J.readFile(this.filePath,"utf8"),q=JSON.parse(k);if(q.version!==X||!Array.isArray(q.projects))return{version:X,projects:[]};return{version:X,projects:q.projects.filter(D)}}catch(k){if(k.code==="ENOENT"||k instanceof SyntaxError)return{version:X,projects:[]};throw k}}async write(k){let q=Q.dirname(this.filePath);await J.mkdir(q,{recursive:!0,mode:448}),await J.chmod(q,448),await w(this.filePath,`${JSON.stringify(k,null,2)}
|
|
2
2
|
`,{mode:384}),await J.chmod(this.filePath,384)}}var _=new K;
|
|
3
3
|
export{_ as j};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{gf as h0,hf as mT}from"./chunk-
|
|
1
|
+
import{gf as h0,hf as mT}from"./chunk-fx9vm1n5.js";import{Ch as LT}from"./chunk-28tzj187.js";import{Cj as PT}from"./chunk-5q4z0sfr.js";import{Bk as y0,Ck as r,Kk as hT,ek as V0,mk as D,ok as S,pk as d,rk as s,sk as q0,tk as RT,uk as bT,vk as yT,zk as A}from"./chunk-7xtxvrh8.js";import{Lk as g0}from"./chunk-sdapqhj0.js";import{createHash as I_}from"node:crypto";import{readdir as D0,stat as w0}from"node:fs/promises";import U0 from"node:path";import{createHash as T$,randomBytes as n0}from"node:crypto";import{chmod as i0,link as $$,lstat as n,mkdir as _$,open as i,readdir as c0,realpath as l0,unlink as C0}from"node:fs/promises";import W from"node:path";function tT(){return typeof globalThis.Bun<"u"}function oT(T){return{exec:($)=>T.exec($),prepare:($)=>{let _=T.prepare($);return{run:(...G)=>{_.run(...G)},get:(...G)=>_.get(...G),all:(...G)=>_.all(...G)}},transaction:($)=>T.transaction($)(),pragma:($)=>T.pragma($,{simple:!0}),close:()=>T.close()}}function rT(T){return{exec:($)=>T.exec($),prepare:($)=>{let _=T.query($);return{run:(...G)=>{_.run(...G)},get:(...G)=>_.get(...G),all:(...G)=>_.all(...G)}},transaction:($)=>T.transaction($)(),pragma:($)=>{let _=T.query(`PRAGMA ${$}`).get();if(!_)return;let G=Object.values(_);return G.length===1?G[0]:_},close:()=>T.close()}}function eT(T){return[`PRAGMA busy_timeout=${T};`,"PRAGMA journal_mode=WAL;","PRAGMA synchronous=NORMAL;","PRAGMA foreign_keys=ON;"].join(`
|
|
2
2
|
`)}async function T0(T,$={}){let _=$.busyTimeoutMs??5000;if(!Number.isSafeInteger(_)||_<0)return null;let G=null;try{if(tT()){let{Database:Y}=await import("bun:sqlite");G=rT(new Y(T))}else{let Q=(await import("better-sqlite3")).default;G=oT(new Q(T))}return G.exec(eT(_)),G}catch{try{G?.close()}catch{}return null}}var G$="surface-workspaces-v1",d0=/^[a-f0-9]{64}$/,X$=/^acp-remote-workspace:[A-Za-z0-9_-]{43}$/,Y$=1024,Q$=".surface-workspaces-v1.capacity.sqlite",s0=/^\.tmp-acp-remote-workspace-([1-9][0-9]*)-[a-f0-9]{32}\.pending$/;class H extends Error{name="AcpRemoteWorkspaceReferenceError";code;retryable;constructor(T){let $=T==="session_surface_not_found"?{message:"Session surface was not found",retryable:!1}:T==="session_surface_capacity"?{message:"Session surface capacity is exhausted",retryable:!0}:{message:"Session surface state is invalid",retryable:!1};super($.message);this.code=T,this.retryable=$.retryable,Object.setPrototypeOf(this,new.target.prototype)}}var v,$0=new Map;function a0(T){return W.join(String(T),G$)}async function t0(T,$){let _=S($);if(d(_.collisionIdentity)!==String(T))throw new H("session_surface_state_invalid");let G=r0(_.exactIdentity),X=a0(T);return await U$(T,X),Z$(X,()=>V$(X,async()=>{await H$(X);let Y=await o0(T,X,!0),Q=Y.recordsByDigest.get(G);if(Q)return Q.workspaceRef;if(Y.recordsByDigest.size>=Y$)throw new H("session_surface_capacity");let Z=W.join(X,`${G}.json`),U=new Set(Y.workspaceRefToDigest.keys());for(let V=0;V<32;V+=1){let g=L$();if(U.has(g))continue;return z$(T,X,Z,_,{version:1,exactIdentityDigest:G,workspaceRef:g})}throw new H("session_surface_state_invalid")}))}async function Z$(T,$){let _=$0.get(T)??Promise.resolve(),G=()=>{return},X=new Promise((Q)=>{G=Q}),Y=_.catch(()=>{return}).then(()=>X);$0.set(T,Y),await _.catch(()=>{return});try{return await $()}finally{if(G(),$0.get(T)===Y)$0.delete(T)}}async function U$(T,$){try{await H0($,String(T))}catch(_){if(q(_)!=="ENOENT"){if(_ instanceof H)throw _;throw new H("session_surface_state_invalid")}try{await _$($,{recursive:!1,mode:448})}catch(G){if(q(G)!=="EEXIST")throw new H("session_surface_state_invalid")}await H0($,String(T)),await m(String(T))}}async function V$(T,$){await v?.beforeCapacityLockAttempt?.();let _=await B$(T),G=!1,X,Y,Q;try{_.database.exec("BEGIN IMMEDIATE;"),G=!0,await v?.afterCapacityLockAcquired?.(),Q={value:await $()}}catch(Z){X=Z}if(G)try{await g$(_),_.database.exec("ROLLBACK;")}catch(Z){Y=Z}try{_.database.close()}catch(Z){if(!G)Y=Z}if(await _.identityHandle.close().catch(()=>{return}),Y!==void 0)throw new H("session_surface_state_invalid");if(X instanceof H)throw X;if(X!==void 0||!Q)throw new H("session_surface_state_invalid");return Q.value}async function B$(T){let $=W.join(T,Q$),_=null,G;try{let X=!1;try{let Q=await i($,"wx",384);X=!0,await Q.sync(),await Q.close()}catch(Q){if(q(Q)!=="EEXIST")throw Q}if(await u($,T),X)await m(T);G=await i($,"r"),await c(G,$,T);let Y=await G.stat({bigint:!0});if(_=await T0($,{busyTimeoutMs:30000}),!_)throw new H("session_surface_state_invalid");if(_.exec("PRAGMA locking_mode=NORMAL;"),_.exec("PRAGMA synchronous=FULL;"),_.exec("PRAGMA busy_timeout=30000;"),process.platform!=="win32")await i0($,384);return await c(G,$,T),await C$($,T),{database:_,identity:Y,identityHandle:G,path:$}}catch(X){await G?.close().catch(()=>{return});try{_?.close()}catch{}if(X instanceof H)throw X;throw new H("session_surface_state_invalid")}}async function g$(T){await c(T.identityHandle,T.path,W.dirname(T.path));let $=await T.identityHandle.stat({bigint:!0});if(!O0(T.identity,$))throw new H("session_surface_state_invalid")}async function C$(T,$){for(let _ of["-journal","-shm","-wal"]){let G=`${T}${_}`;try{if(process.platform!=="win32")await i0(G,384);await u(G,$)}catch(X){if(q(X)!=="ENOENT"){if(X instanceof H)throw X;throw new H("session_surface_state_invalid")}}}}async function H$(T){let $=await c0(T,{withFileTypes:!0}),_=!1;for(let G of $){if(!s0.test(G.name))continue;let X=W.join(T,G.name);await u(X,T),await C0(X),_=!0}if(_)await m(T)}async function o0(T,$,_){try{await H0($,String(T))}catch(Q){if(!_&&q(Q)==="ENOENT")return{recordsByDigest:new Map,workspaceRefToDigest:new Map};if(Q instanceof H)throw Q;throw new H("session_surface_state_invalid")}let G;try{G=await c0($,{withFileTypes:!0})}catch(Q){if(!_&&q(Q)==="ENOENT")return{recordsByDigest:new Map,workspaceRefToDigest:new Map};throw new H("session_surface_state_invalid")}let X=new Map,Y=new Map;for(let Q of G){if(s0.test(Q.name)){await u(W.join($,Q.name),$);continue}if(!Q.name.endsWith(".json"))continue;let Z=W.basename(Q.name,".json");if(!d0.test(Z))throw new H("session_surface_state_invalid");let U=W.join($,Q.name),V=await O$(U,$);if(V.exactIdentityDigest!==Z)throw new H("session_surface_state_invalid");if(X.has(Z))throw new H("session_surface_state_invalid");let g=Y.get(V.workspaceRef);if(g&&g!==Z)throw new H("session_surface_state_invalid");X.set(Z,V),Y.set(V.workspaceRef,Z)}return{recordsByDigest:X,workspaceRefToDigest:Y}}async function O$(T,$){let _;try{await u(T,$),_=await i(T,"r"),await c(_,T,$);let G=await _.readFile({encoding:"utf8"});return M$(G)}catch(G){if(G instanceof H&&G.code==="session_surface_not_found")throw G;if(q(G)==="ENOENT")throw new H("session_surface_not_found");throw new H("session_surface_state_invalid")}finally{await _?.close()}}function M$(T){let $;try{$=JSON.parse(T)}catch{throw new H("session_surface_state_invalid")}if(!F$($))throw new H("session_surface_state_invalid");return $}function F$(T){if(!T||typeof T!=="object"||Array.isArray(T))return!1;let $=T,_=Object.keys($).sort();if(_.length!==3||_[0]!=="exactIdentityDigest"||_[1]!=="version"||_[2]!=="workspaceRef")return!1;return $.version===1&&typeof $.exactIdentityDigest==="string"&&d0.test($.exactIdentityDigest)&&typeof $.workspaceRef==="string"&&X$.test($.workspaceRef)}function r0(T){return T$("sha256").update(`acp-remote-workspace-exact-identity\x00${T}`).digest("hex")}function L$(){return`acp-remote-workspace:${n0(32).toString("base64url")}`}function J$(){return`.tmp-acp-remote-workspace-${process.pid}-${n0(16).toString("hex")}.pending`}async function H0(T,$){if(W.dirname(T)!==$)throw new H("session_surface_state_invalid");let _=await n(T);if(_.isSymbolicLink()||!_.isDirectory())throw new H("session_surface_state_invalid");if(typeof process.getuid==="function"&&_.uid!==process.getuid())throw new H("session_surface_state_invalid");let G=e0(_.mode);if(process.platform!=="win32"&&G!==448)throw new H("session_surface_state_invalid");await M0(T,$,W.basename(T))}async function u(T,$){if(W.dirname(T)!==$)throw new H("session_surface_state_invalid");let _=await n(T);if(_.isSymbolicLink()||!_.isFile())throw new H("session_surface_state_invalid");if(typeof process.getuid==="function"&&_.uid!==process.getuid())throw new H("session_surface_state_invalid");let G=e0(_.mode);if(process.platform!=="win32"&&G!==384)throw new H("session_surface_state_invalid");await M0(T,$,W.basename(T))}async function c(T,$,_){let[G,X]=await Promise.all([T.stat({bigint:!0}),n($,{bigint:!0})]);if(W.dirname($)!==_||X.isSymbolicLink()||!X.isFile()||!G.isFile()||X.dev!==G.dev||X.ino!==G.ino)throw new H("session_surface_state_invalid");if(typeof process.getuid==="function"&&(Number(X.uid)!==process.getuid()||Number(G.uid)!==process.getuid()))throw new H("session_surface_state_invalid");let Y=Number(X.mode&BigInt(511)),Q=Number(G.mode&BigInt(511));if(process.platform!=="win32"&&(Y!==384||Q!==384))throw new H("session_surface_state_invalid");await M0($,_,W.basename($))}async function M0(T,$,_){let G=await l0(T),X=await l0($);if(G!==W.join(X,_))throw new H("session_surface_state_invalid")}async function m(T){if(!I$(process.platform))return;try{if(v?.syncDirectory){await v.syncDirectory(T);return}await N$(T)}catch{throw new H("session_surface_state_invalid")}}function I$(T){return T!=="win32"}async function N$(T){let $=await i(T,"r");try{await $.sync()}finally{await $.close()}}async function z$(T,$,_,G,X){let Y=W.join($,J$()),Q,Z,U=!1,V=!1,g,O;try{Q=await i(Y,"wx",384),await Q.writeFile(JSON.stringify(X),"utf8"),await Q.sync(),await c(Q,Y,$),Z=await Q.stat({bigint:!0}),await Q.close(),Q=void 0,await v?.beforePublish?.({finalPath:_,referenceDirectoryPath:$,tempPath:Y});try{await $$(Y,_),U=!0}catch(M){if(q(M)!=="EEXIST")throw M;g=await j$(T,G)}if(U){let M=await n(_,{bigint:!0});if(!Z||!O0(Z,M))throw new H("session_surface_state_invalid");await u(_,$),await m($),V=!0,g=X.workspaceRef;try{await v?.afterPublish?.({finalPath:_,referenceDirectoryPath:$,tempPath:Y})}catch{}}}catch(M){O=M}finally{await Q?.close().catch(()=>{return})}if(O!==void 0&&U&&!V&&Z)try{let M=await n(_,{bigint:!0});if(O0(Z,M))await C0(_),await m($)}catch{}try{if(await C0(Y),!V)await m($)}catch(M){if(q(M)!=="ENOENT"&&O===void 0&&!V)O=M}if(O instanceof H)throw O;if(O!==void 0||g===void 0)throw new H("session_surface_state_invalid");return g}async function j$(T,$){let _=a0(T),G=await o0(T,_,!0),X=r0(S($).exactIdentity),Y=G.recordsByDigest.get(X);if(!Y)throw new H("session_surface_state_invalid");return Y.workspaceRef}function O0(T,$){return BigInt(T.dev)===BigInt($.dev)&&BigInt(T.ino)===BigInt($.ino)}function q(T){return T!==null&&typeof T==="object"&&"code"in T&&typeof T.code==="string"?T.code:void 0}function e0(T){return typeof T==="bigint"?Number(T&BigInt(511)):T&511}import*as b from"node:path";var XT=50,YT=100,W$=new Set(["queued","running","completed","failed","cancelled","interrupted"]),K$=new Set(["high","medium","low"]),QT=/^[A-Za-z0-9_-]+$/,k$=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/,A$=/^acp-remote-exact-path:[a-f0-9]{64}$/;function ZT(T){return typeof T==="string"&&k$.test(T)&&Number.isFinite(Date.parse(T))}function TT(T){return typeof T==="string"&&b.isAbsolute(T)}function $T(T){return typeof T==="string"&&A$.test(T)}function x$(T){return Buffer.from(JSON.stringify(T),"utf8").toString("base64url")}function E$(T){return Buffer.from(JSON.stringify(T),"utf8").toString("base64url")}function q$(T){try{if(!QT.test(T))throw Error("invalid");let $=Buffer.from(T,"base64url").toString("utf8");if(Buffer.from($,"utf8").toString("base64url")!==T)throw Error("invalid");let _=JSON.parse($);if(_.version!==1||_.kind!==void 0&&_.kind!=="local"||typeof _.includeSubagents!=="boolean"||_.archived!==void 0&&typeof _.archived!=="boolean"||!(_.cwd===null||TT(_.cwd))||!ZT(_.lastMessageTime)||!TT(_.projectPath)||!A(_.sessionId))throw Error("invalid");return{version:1,kind:"local",cwd:_.cwd===null?null:b.resolve(_.cwd),includeSubagents:_.includeSubagents,archived:_.archived??!1,lastMessageTime:_.lastMessageTime,projectPath:b.resolve(_.projectPath),sessionId:_.sessionId}}catch{throw Error("Invalid session cursor")}}function D$(T){try{if(!QT.test(T))throw Error("invalid");let $=Buffer.from(T,"base64url").toString("utf8");if(Buffer.from($,"utf8").toString("base64url")!==T)throw Error("invalid");let _=JSON.parse($),G=Object.keys(_),X=new Set(["version","kind","exactIdentity","includeSubagents","archived","lastMessageTime","workspaceIdentity","sessionId"]);if(G.some((Y)=>!X.has(Y))||_.version!==1||_.kind!=="remote"||typeof _.includeSubagents!=="boolean"||typeof _.archived!=="boolean"||!(_.exactIdentity===null||$T(_.exactIdentity))||!ZT(_.lastMessageTime)||!$T(_.workspaceIdentity)||!A(_.sessionId))throw Error("invalid");return{version:1,kind:"remote",exactIdentity:_.exactIdentity??null,includeSubagents:_.includeSubagents,archived:_.archived,lastMessageTime:_.lastMessageTime,workspaceIdentity:_.workspaceIdentity,sessionId:_.sessionId}}catch{throw Error("Invalid remote session cursor")}}function p(T){let $="";for(let _=0;_<T.length;_+=1)$+=T.charCodeAt(_).toString(16).padStart(4,"0");return $}function w$(T){if(!T.cursor)return;let $=q$(T.cursor);if($.cwd!==T.cwd||$.includeSubagents!==T.includeSubagents||($.archived??!1)!==T.archived)throw Error("Session cursor scope does not match this query");return $}function S$(T){if(!T.cursor)return;let $=D$(T.cursor);if($.exactIdentity!==T.exactIdentity||T.exactIdentity!==null&&$.workspaceIdentity!==T.exactIdentity||$.includeSubagents!==T.includeSubagents||($.archived??!1)!==T.archived)throw Error("Remote session cursor scope does not match this query");return $}function i_(T={}){let{cwd:$,cursor:_,limit:G,includeSubagents:X=!1,archived:Y=!1}=T;if($!==void 0&&!b.isAbsolute($))throw Error("Session catalog cwd must be absolute");let Q=G===void 0?XT:G;if(!Number.isInteger(Q)||Q<1||Q>YT)throw Error("Session catalog limit must be an integer from 1 to 100");return{cwd:$===void 0?null:b.resolve($),cursor:_??void 0,limit:Q,includeSubagents:X,archived:Y}}function c_(T={}){let{descriptor:$,cursor:_,limit:G,includeSubagents:X=!1,archived:Y=!1}=T,Q=G===void 0?XT:G;if(!Number.isInteger(Q)||Q<1||Q>YT)throw Error("Session catalog limit must be an integer from 1 to 100");return{descriptor:$,exactIdentity:$?.exactIdentity??null,cursor:_??void 0,limit:Q,includeSubagents:X,archived:Y}}function d_(T={}){let $=_T(T.taskStatus,W$,"task status"),_=_T(T.taskPriority,K$,"task priority"),G=GT(T.taskDueAfter,"taskDueAfter"),X=GT(T.taskDueBefore,"taskDueBefore");return f$(G,X),{...$?{taskStatuses:$}:{},..._?{taskPriorities:_}:{},...G?{taskDueAfter:G}:{},...X?{taskDueBefore:X}:{}}}function _T(T,$,_){if(T===void 0)return;let G=Array.isArray(T)?T:[T];if(G.length===0)return;let X=new Set;for(let Y of G){if(typeof Y!=="string"||!$.has(Y))throw Error(`Invalid session ${_} filter`);X.add(Y)}return[...X].sort()}function GT(T,$){if(T===void 0)return;if(typeof T!=="string"||!Number.isFinite(Date.parse(T)))throw Error(`Invalid session ${$} filter`);return new Date(T).toISOString()}function f$(T,$){if(T!==void 0&&$!==void 0&&T>$)throw Error("Session task due range is inverted")}function R$(T,$){if(T.lastMessageTime>$.lastMessageTime)return-1;if(T.lastMessageTime<$.lastMessageTime)return 1;if(T.projectPath<$.projectPath)return-1;if(T.projectPath>$.projectPath)return 1;if(T.sessionId<$.sessionId)return-1;if(T.sessionId>$.sessionId)return 1;return 0}function b$(T,$){if(T.lastMessageTime>$.lastMessageTime)return-1;if(T.lastMessageTime<$.lastMessageTime)return 1;if(T.workspaceIdentity<$.workspaceIdentity)return-1;if(T.workspaceIdentity>$.workspaceIdentity)return 1;if(T.sessionId<$.sessionId)return-1;if(T.sessionId>$.sessionId)return 1;return 0}function s_(T,$){let _=[...T],G=w$($);if(G)_=_.filter((Q)=>R$(Q,{sessionId:G.sessionId,projectPath:G.projectPath,lastMessageTime:G.lastMessageTime})>0);let X=_.slice(0,$.limit);if(X.length===0||_.length<=X.length)return{sessions:X};let Y=X[X.length-1];return{sessions:X,nextCursor:x$({version:1,kind:"local",cwd:$.cwd,includeSubagents:$.includeSubagents,archived:$.archived,lastMessageTime:Y.lastMessageTime,projectPath:Y.projectPath,sessionId:Y.sessionId})}}function a_(T,$){let _=[...T],G=S$($);if(G)_=_.filter((Q)=>b$(Q,{sessionId:G.sessionId,projectPath:Q.projectPath,lastMessageTime:G.lastMessageTime,workspaceIdentity:G.workspaceIdentity})>0);let X=_.slice(0,$.limit);if(X.length===0||_.length<=X.length)return{sessions:X};let Y=X[X.length-1];return{sessions:X,nextCursor:E$({version:1,kind:"remote",exactIdentity:$.exactIdentity,includeSubagents:$.includeSubagents,archived:$.archived,lastMessageTime:Y.lastMessageTime,workspaceIdentity:Y.workspaceIdentity,sessionId:Y.sessionId})}}function y$(T){return T.type==="message_created"||T.type==="token_budget_handoff_recorded"||T.type==="part_created"||T.type==="part_updated"||T.type==="turn_started"||T.type==="turn_completed"||T.type==="turn_aborted"||T.type==="turn_recovery_acknowledged"||T.type==="interaction_requested"||T.type==="interaction_responded"||T.type==="interaction_recovered"||T.type==="review_started"||T.type==="review_completed"}function F0(T){return T.type==="message_created"&&T.data.role==="user"&&(T.data.inboxMessageId!==void 0||T.data.parentMessageId===void 0)}function L0(T,$){let _=T.find((G)=>F0(G)&&G.data.messageId===$);if(!_)throw Error(`Rewind checkpoint not found: ${$}`);return{messageId:$,preview:UT(T,$),createdAt:_.data.createdAt}}function UT(T,$){let _=T.flatMap((G)=>{if(G.type!=="part_created"||G.data.messageId!==$)return[];if(G.data.partType==="text"){let X=G.data.payload;return typeof X.text==="string"?[X.text]:[]}if(G.data.partType==="image")return["[Image]"];return[]}).join("").trim();if(_.length<=160)return _;return`${_.slice(0,160)}...`}function VT(T,$){L0(T,$);let _=T.findIndex((Q)=>Q.type==="message_created"&&Q.data.messageId===$),G=T[_],X=G?.type==="message_created"?G.data.inboxMessageId:void 0,Y=new Set(T.flatMap((Q)=>Q.type==="turn_started"&&X&&Q.data.inputMessageIds?.includes(X)?[Q.data.turnId]:[]));return T.filter((Q,Z)=>{if((Q.type==="turn_started"||Q.type==="turn_completed"||Q.type==="turn_aborted"||Q.type==="turn_recovery_acknowledged")&&Y.has(Q.data.turnId))return!1;return Z<_||!y$(Q)})}function l(T){let $=[];for(let _ of T){if(_.type!=="session_rewound"){$.push(_);continue}if(L0($,_.data.targetMessageId),_.data.mode!=="code")$=VT($,_.data.targetMessageId)}return $}function o_(T){let $=l(T);return $.filter(F0).map((_)=>({messageId:_.data.messageId,preview:UT($,_.data.messageId),createdAt:_.data.createdAt})).reverse()}function r_(T,$){let _=l(T),G=L0(_,$),X=_.findIndex((Q)=>Q.type==="message_created"&&Q.data.messageId===$),Y=_.slice(X);return{checkpoint:G,projectedEntries:VT(_,$),removedTurns:Y.filter(F0).length,snapshotMessageIds:Y.flatMap((Q)=>Q.type==="part_created"&&Q.data.partType==="tool_call"?[Q.data.partId]:[])}}import{createHash as s$}from"node:crypto";var T1={clientVisible:!1};function BT(T){if(T.metadata&&typeof T.metadata==="object"&&!Array.isArray(T.metadata)&&T.metadata.clientVisible===!1)return!1;return!(T.role==="user"&&typeof T.content==="string"&&T.content.startsWith("This turn made a non-trivial implementation. Before finishing, call Task ")&&T.content.endsWith("Only a fresh structured PASS verdict allows completion."))}import{StringDecoder as m$}from"node:string_decoder";var _1=1048576;function J0(T,$){let _=$;while(_<T.length&&(T[_]&192)===128)_+=1;return _}class I0{maxBytes;chunks=[];retainedBytes=0;omittedBytes=0;totalBytes=0;constructor(T=1048576){this.maxBytes=T;if(!Number.isSafeInteger(T)||T<=0)throw Error("maxBytes must be a positive safe integer")}append(T){let $=Buffer.isBuffer(T)?T:Buffer.from(T);if($.length===0)return;if(this.totalBytes+=$.length,$.length>this.maxBytes){this.retainOversizedChunkTail($);return}this.chunks.push($),this.retainedBytes+=$.length,this.trimToLimit(),this.compactChunks()}peek(){return{content:Buffer.concat(this.chunks,this.retainedBytes).toString("utf8"),retainedBytes:this.retainedBytes,omittedBytes:this.omittedBytes,totalBytes:this.totalBytes}}consume(){let T=this.peek();return this.chunks.length=0,this.retainedBytes=0,this.omittedBytes=0,T}retainedChunkCountForTests(){return this.chunks.length}retainOversizedChunkTail(T){this.omittedBytes+=this.retainedBytes,this.chunks.length=0,this.retainedBytes=0;let $=J0(T,T.length-this.maxBytes);if(this.omittedBytes+=$,$===T.length)return;let _=Buffer.from(T.subarray($));this.chunks.push(_),this.retainedBytes=_.length}trimToLimit(){let T=!1;while(this.retainedBytes>this.maxBytes){let $=this.chunks[0];if(!$)return;let _=this.retainedBytes-this.maxBytes;if($.length<=_){this.chunks.shift(),this.retainedBytes-=$.length,this.omittedBytes+=$.length,T=!0;continue}let G=J0($,_);this.chunks[0]=$.subarray(G),this.retainedBytes-=G,this.omittedBytes+=G,T=!0}if(T)this.realignRetainedStart()}realignRetainedStart(){while(this.chunks.length>0){let T=this.chunks[0];if(T.length===0){this.chunks.shift();continue}let $=J0(T,0);if($===0)return;if(this.retainedBytes-=$,this.omittedBytes+=$,$===T.length)this.chunks.shift();else{this.chunks[0]=T.subarray($);return}}}compactChunks(){if(this.chunks.length<=32)return;let T=Buffer.concat(this.chunks,this.retainedBytes);if(this.chunks.length=0,T.length>0)this.chunks.push(T)}}var _0={maxLines:30,maxChars:3000,keepHead:10,keepTail:10,summarize:!0},y={maxLines:100,maxChars:1e4,keepHead:40,keepTail:40,summarize:!0},gT={maxLines:200,maxChars:20000,keepHead:80,keepTail:80,summarize:!1},h$={maxLines:150,maxChars:15000,keepHead:50,keepTail:50,summarize:!0},P$=[{pattern:/^git\s+(rm|add)\s+(-r|--cached|-rf|-f)?\s*/i,config:_0,summaryTemplate:(T)=>`Successfully processed ${T} files`},{pattern:/^(npm|pnpm|yarn|bun)\s+(install|i|add|remove|uninstall)/i,config:_0,summaryTemplate:(T)=>`Package operation completed (${T} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(build|compile|bundle)/i,config:y,summaryTemplate:(T)=>`Build completed (${T} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(test|lint|check)/i,config:gT},{pattern:/^git\s+(status|branch|remote)/i,config:y},{pattern:/^git\s+(log|diff|show)/i,config:gT},{pattern:/^(ls|dir|tree)\s+/i,config:y,summaryTemplate:(T)=>`Listed ${T} items`},{pattern:/^find\s+/i,config:y,summaryTemplate:(T)=>`Found ${T} matches`},{pattern:/^(grep|rg|ag)\s+/i,config:y,summaryTemplate:(T)=>`Found ${T} matching lines`},{pattern:/^(docker|podman)\s+(build|pull|push)/i,config:_0,summaryTemplate:(T)=>`Docker operation completed (${T} lines)`},{pattern:/^(pip|pip3|poetry|pipenv)\s+(install|uninstall)/i,config:_0,summaryTemplate:(T)=>`Python package operation completed (${T} lines)`},{pattern:/^(cargo|rustup)\s+(build|install|update)/i,config:y,summaryTemplate:(T)=>`Rust operation completed (${T} lines)`},{pattern:/^(go)\s+(build|get|mod)/i,config:y,summaryTemplate:(T)=>`Go operation completed (${T} lines)`}];function CT(T,$,_){let G=$,X=_??T.length;if(G>0){let Y=T.charCodeAt(G);if(Y>=56320&&Y<=57343)G+=1}if(X<T.length){let Y=T.charCodeAt(X-1);if(Y>=55296&&Y<=56319)X-=1}return T.slice(G,X)}class N0{static getConfigForCommand(T){for(let{pattern:$,config:_,summaryTemplate:G}of P$)if($.test(T))return{config:_,summaryTemplate:G};return{config:h$}}static truncate(T,$){let{config:_,summaryTemplate:G}=this.getConfigForCommand($);return this.truncateWithConfig(T,_,G)}static truncateWithConfig(T,$,_){let G=T.length,X=T.split(`
|
|
3
3
|
`),Y=X.length;if(Y<=$.maxLines&&G<=$.maxChars)return{content:T,truncated:!1,originalLines:Y,originalChars:G};let Q=X.slice(0,$.keepHead),Z=X.slice(-$.keepTail),U=Y-$.keepHead-$.keepTail,V=Q.join(`
|
|
4
4
|
`);if(V+=`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Ae as A0,Be as B1,Ce as H1,Ee as d2,Le as i2,Me as C0,Te as p_,Ve as N1,Xe as r2,Ye as o2,Ze as q1,_e as a2,ne as u2,oe as e,pe as h2,qe as Z1,re as l2,se as m,te as G1,ue as c2,ve as p2,we as V1,xe as L1,ye as n2,ze as U1}from"./chunk-
|
|
1
|
+
import{Ae as A0,Be as B1,Ce as H1,Ee as d2,Le as i2,Me as C0,Te as p_,Ve as N1,Xe as r2,Ye as o2,Ze as q1,_e as a2,ne as u2,oe as e,pe as h2,qe as Z1,re as l2,se as m,te as G1,ue as c2,ve as p2,we as V1,xe as L1,ye as n2,ze as U1}from"./chunk-q1rnvn85.js";import{ug as o_}from"./chunk-7wcxjbyg.js";import{qh as a_}from"./chunk-hv8nt7wj.js";import{Ui as v2,Vi as P2,Wi as x_,Xi as Q0,Yi as w_}from"./chunk-514va7ce.js";import{aj as f1}from"./chunk-jsv3e4k6.js";import{Cj as H0}from"./chunk-5q4z0sfr.js";import{Pj as i_,Sj as r_}from"./chunk-9kj19a8t.js";import{Wj as __}from"./chunk-e1j1gsr5.js";import{Ak as A,Bk as P,Ck as S,Dk as E1,Ek as F1,Fk as M_,Gk as z1,Hk as b1,Ik as q_,ek as h,ok as o,pk as p,qk as S2,rk as n,sk as d,tk as I2,uk as K0,vk as Y1,wk as m2,xk as K_,yk as M0,zk as c_}from"./chunk-7xtxvrh8.js";import{readdir as b_,readFile as V_,rm as f_,stat as E0}from"node:fs/promises";import*as N from"node:path";import{nanoid as I}from"nanoid";import{createHash as F4,randomUUID as z4}from"node:crypto";import*as W_ from"node:fs/promises";import*as W0 from"node:path";import D4 from"proper-lockfile";function cX(_){return Object.freeze({kind:"local",root:_})}function pX(_,X){let $=o(X);if(p($.collisionIdentity)!==_)throw Error("ACP remote workspace durable state is invalid");return Object.freeze({kind:"acp-remote",root:_,descriptor:$})}function nX(_,X){return _.kind==="acp-remote"?`${_.kind}\x00${_.root}\x00${_.descriptor.exactIdentity}\x00${X}`:`${_.kind}\x00${_.root}\x00${X}`}async function H_(_,X){if(_.kind==="local")return X(K_(_.root));return n(_.root,($)=>X(String($),$))}async function dX(_,X,$){return H_(_,(W,J)=>$(J?{storageRoot:W,transcriptPath:S(J,X),inboxPath:F1(J,X),goalPath:z1(J,X),remoteScope:J}:{storageRoot:W,transcriptPath:P(_.root,X),inboxPath:E1(_.root,X),goalPath:M_(_.root,X)}))}import{execFileSync as T4}from"node:child_process";import{createHash as C4}from"node:crypto";import{readFileSync as K4}from"node:fs";var M4=/^[a-f0-9]{64}$/;function D1(_){if(!_||typeof _!=="object")return!1;let X=_;return(X.platform==="linux"||X.platform==="darwin"||X.platform==="win32")&&typeof X.fingerprint==="string"&&M4.test(X.fingerprint)}var R1={readFile:(_)=>K4(_,"utf8"),execFile:(_,X)=>T4(_,X,{encoding:"utf8",timeout:_==="powershell.exe"?3000:2000,windowsHide:!0})},A4=(_)=>{try{return process.kill(_,0),!0}catch(X){return X instanceof Error&&"code"in X&&X.code==="EPERM"}};function x0(_,X){return{platform:_,fingerprint:C4("sha256").update(`${_}\x00${X}`).digest("hex")}}function E4(_,X){let $=X.readFile(`/proc/${_}/stat`).trim(),W=$.lastIndexOf(")");if(W<0)throw Error("Invalid /proc process stat");let O=$.slice(W+2).split(/\s+/)[19];if(!O||!/^\d+$/.test(O))throw Error("Missing process start ticks");return O}function m_(_,X=process.platform,$=R1){if(!Number.isInteger(_)||_<=1)return;try{if(X==="linux")return x0(X,E4(_,$));if(X==="darwin"){let W=$.execFile("ps",["-o","lstart=","-p",String(_)]).trim();return W?x0(X,W):void 0}if(X==="win32"){let W=`(Get-CimInstance Win32_Process -Filter "ProcessId = ${_}").CreationDate.ToUniversalTime().ToString('O')`,J=$.execFile("powershell.exe",["-NoProfile","-NonInteractive","-Command",W]).trim();return J?x0(X,J):void 0}}catch{return}return}function tX(_,X){return m_(_,X.platform)?.fingerprint===X.fingerprint}function sX(_,X,$=R1,W=A4){if(!Number.isInteger(_)||_<=1)return!1;let J=m_(_,X.platform,$);if(J)return J.fingerprint===X.fingerprint;return!W(_)}var j1=1;function R4(_,X){let $=F4("sha256").update(X).digest("hex");return W0.join(K_(_),".locks",`${$}.lock`)}function R_(_,X){return _ instanceof Error&&"code"in _&&_.code===X}async function k0(_){try{let X=JSON.parse(await W_.readFile(_,"utf8"));if(X.version!==j1||typeof X.sessionId!=="string"||typeof X.ownerId!=="string"||!Number.isInteger(X.pid)||(X.pid??0)<=0||X.processIdentity!==void 0&&!D1(X.processIdentity)||typeof X.acquiredAt!=="string")return;return X}catch(X){if(R_(X,"ENOENT")||X instanceof SyntaxError)return;throw X}}async function w1(_){let X=await k0(_);if(X)return X;return await new Promise(($)=>setTimeout($,10)),k0(_)}function w4(_){try{return process.kill(_,0),!0}catch(X){return!R_(X,"ESRCH")}}async function x1(_,X){let $;try{return $=await W_.open(_,"wx",384),await $.writeFile(`${JSON.stringify(X)}
|
|
2
2
|
`,"utf8"),!0}catch(W){if(R_(W,"EEXIST"))return!1;if($)await W_.unlink(_).catch(()=>{return});throw W}finally{await $?.close().catch(()=>{return})}}class $_ extends Error{code="BLADE_SESSION_IN_USE";constructor(_){super(_?`Session is already active in another Blade process (PID ${_}). Stop that process or choose a different session.`:"Session is already active in another Blade process. Stop that process or choose a different session.");this.name="SessionInUseError"}}async function k1(_,X,$=!1){let W,J;try{J=await D4.lock(_,{realpath:!1,retries:$?{retries:50,minTimeout:10,maxTimeout:100,factor:1.2}:0,onCompromised:(Q)=>{W=Q}})}catch(Q){if(R_(Q,"ELOCKED"))throw new $_;throw Q}let O=()=>{if(W)throw W};try{O();let Q=await X(O);return O(),Q}finally{await J()}}class u{filePath;record;stateStorage;released=!1;constructor(_,X,$){this.filePath=_;this.record=X;this.stateStorage=$}static async acquireForStorage(_,X){if(X.kind==="local")return u.acquire(_,X.root);return H_(X,($,W)=>{if(!W||$!==X.root)throw Error("ACP remote session lease scope is invalid");return u.acquireRemote(_,W,X)})}static async acquire(_,X=f1()){return u.acquireAtPath(_,R4(X,_))}static async acquireRemote(_,X,$){let W=b1(X,_);try{await d(X,W)}catch(O){if(O.code!=="ENOENT")throw O}let J=await u.acquireAtPath(_,W);try{return await d(X,W),new u(W,J.record,$)}catch(O){throw await J.release(),O}}static async acquireAtPath(_,X){return await W_.mkdir(W0.dirname(X),{recursive:!0,mode:448}),k1(X,async($)=>{let W={version:j1,sessionId:_,ownerId:z4(),pid:process.pid,processIdentity:m_(process.pid),acquiredAt:new Date().toISOString()};if($(),await x1(X,W))return new u(X,W);let J=await w1(X);if(!J||J.sessionId!==_)throw new $_;if(w4(J.pid)){let O=J.processIdentity?m_(J.pid,J.processIdentity.platform):void 0;if(!O||O.fingerprint===J.processIdentity?.fingerprint)throw new $_(J.pid)}if($(),await W_.unlink(X).catch((O)=>{if(!R_(O,"ENOENT"))throw O}),$(),await x1(X,W))return new u(X,W);throw new $_((await w1(X))?.pid)})}async release(){if(this.released)return;let _=()=>k1(this.filePath,async(X)=>{if((await k0(this.filePath))?.ownerId!==this.record.ownerId)return;X(),await W_.unlink(this.filePath).catch((W)=>{if(!R_(W,"ENOENT"))throw W})},!0);if(this.stateStorage?.kind==="acp-remote")await H_(this.stateStorage,_);else await _();this.released=!0}}import{createHash as O0}from"node:crypto";import{constants as A_,promises as O_}from"node:fs";import G_ from"node:path";import{Mutex as x4}from"async-mutex";var y1=128,g1=67108864,k4=24576,S1=65536,f0=1,h1=/^[a-f0-9]{64}$/,b4=/^[a-f0-9]{64}\.txt$/,l1=64,f4=new Set(["EBUSY","EAGAIN","EMFILE","ENFILE"]),Y0=`
|
|
3
3
|
|
|
4
4
|
...[middle omitted; read the private prompt artifact for the complete request]...
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{ae as a,be as b,ce as c,de as d,ee as e,fe as f,ge as g}from"./chunk-qmveehgt.js";import"./chunk-9xbwtjac.js";import"./chunk-q1rnvn85.js";import"./chunk-fx9vm1n5.js";import"./chunk-7wcxjbyg.js";import"./chunk-hv8nt7wj.js";import"./chunk-28tzj187.js";import"./chunk-514va7ce.js";import"./chunk-jsv3e4k6.js";import"./chunk-5q4z0sfr.js";import"./chunk-9kj19a8t.js";import"./chunk-e1j1gsr5.js";import"./chunk-7xtxvrh8.js";import"./chunk-sdapqhj0.js";export{b as __setSessionSnapshotIOForTesting,c as __resetSessionSnapshotIOForTesting,g as SessionService,d as SessionMissingCreationError,e as SessionArchivedError,f as SessionArchiveConflictError,a as STALE_EMPTY_SESSION_AGE_MS};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var F;((D)=>{D.DEFAULT="default";D.AUTO_EDIT="autoEdit";D.YOLO="yolo";D.PLAN="plan"})(F||={});import{Mutex as G}from"async-mutex";class H{entries=new Map;async runExclusive(C,E){let B=this.entries.get(C);if(!B)B={mutex:new G,operations:0},this.entries.set(C,B);B.operations++;try{return await B.mutex.runExclusive(E)}finally{if(B.operations--,B.operations===0&&this.entries.get(C)===B)this.entries.delete(C)}}getStats(){let C=0;for(let E of this.entries.values())C+=E.operations;return{keys:this.entries.size,operations:C}}}
|
|
2
|
-
export{F as
|
|
2
|
+
export{F as Si,H as Ti};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{createRequire as a}from"node:module";var c=a(import.meta.url);
|
|
2
|
-
export{c as
|
|
2
|
+
export{c as Lk};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b as i,c as l,d as m}from"./chunk-8g3dph9d.js";import"./chunk-tq99wv62.js";import"./chunk-pv6cgfv1.js";import"./chunk-sncepfa3.js";import"./chunk-7mexgpjc.js";import"./chunk-w1e6gagm.js";import"./chunk-d0q5n5ea.js";import"./chunk-zrgfvc4k.js";import"./chunk-h1pw492p.js";import"./chunk-ht8epjz2.js";import"./chunk-wpa74vxq.js";import"./chunk-wm896gnx.js";import"./chunk-qmveehgt.js";import"./chunk-9xbwtjac.js";import"./chunk-q1rnvn85.js";import"./chunk-fx9vm1n5.js";import{xf as n}from"./chunk-ae8966n2.js";import"./chunk-v1mamd1x.js";import{Tf as s}from"./chunk-68y9kcyz.js";import"./chunk-v508x7cg.js";import"./chunk-7xhw74hk.js";import"./chunk-k1tfry97.js";import"./chunk-f2y0gxyq.js";import"./chunk-k3ne93k8.js";import"./chunk-7wcxjbyg.js";import"./chunk-y5dbpqzw.js";import"./chunk-cvazye0h.js";import"./chunk-ewwrss2w.js";import"./chunk-53vh6vpt.js";import"./chunk-hv8nt7wj.js";import"./chunk-erhaedch.js";import"./chunk-jgqk2tmr.js";import"./chunk-28tzj187.js";import"./chunk-wfynmt9r.js";import"./chunk-sd9bze9x.js";import"./chunk-514va7ce.js";import"./chunk-jsv3e4k6.js";import"./chunk-n34qsnks.js";import"./chunk-5q4z0sfr.js";import"./chunk-0b67y4j1.js";import"./chunk-9kj19a8t.js";import"./chunk-e1j1gsr5.js";import"./chunk-gm2yfq3r.js";import"./chunk-n9819k4p.js";import"./chunk-7xtxvrh8.js";import"./chunk-sdapqhj0.js";import v from"chalk";var C={command:"serve",describe:"Start a headless Blade server (no browser)",builder:a,handler:async(p)=>{let r=i(p);if(await s(),!process.env.BLADE_SERVER_PASSWORD)console.log(v.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let e=await m.listenAsync(r);if(console.log(`Blade server listening on http://${e.hostname}:${e.port}`),r.hostname==="0.0.0.0"){let o=l();for(let g of o)console.log(` Network: http://${g}:${e.port}`)}let t,c=new Promise((o)=>{t=o}),d=n(async()=>{await e.stop(),t()});try{await c}finally{d(),await e.stop()}}};export{C as serveCommand};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import"./chunk-v508x7cg.js";import{
|
|
2
|
-
`);try{let{rebuildProjectionIndex:z}=await import("./chunk-
|
|
1
|
+
import"./chunk-v508x7cg.js";import{Qi as Q}from"./chunk-wfynmt9r.js";import"./chunk-sd9bze9x.js";import"./chunk-514va7ce.js";import{aj as L}from"./chunk-jsv3e4k6.js";import"./chunk-n34qsnks.js";import"./chunk-5q4z0sfr.js";import"./chunk-0b67y4j1.js";import"./chunk-9kj19a8t.js";import"./chunk-e1j1gsr5.js";import"./chunk-gm2yfq3r.js";import"./chunk-n9819k4p.js";import"./chunk-7xtxvrh8.js";import{Lk as F}from"./chunk-sdapqhj0.js";var K=[22,19,0];function T(G){let A=/^v?(\d+)\.(\d+)\.(\d+)/.exec(G);if(!A)return!1;let H=A.slice(1).map(Number);for(let z=0;z<K.length;z++){let B=H[z]??0,J=K[z];if(B!==J)return B>J}return!0}var X={command:"doctor",describe:"Check the health of your Blade installation",builder:(G)=>G.option("rebuild-index",{type:"boolean",default:!1,describe:"Rebuild the SQLite session index from JSONL transcripts"}),handler:async(G)=>{if(G.rebuildIndex){console.log(`Rebuilding session index from JSONL transcripts...
|
|
2
|
+
`);try{let{rebuildProjectionIndex:z}=await import("./chunk-cv4h5c96.js"),{SessionService:B}=await import("./chunk-qv6s1q20.js"),J=await z(B.projectionDeriverForSearch());if(J===null)console.log("[WARN] Session index unavailable (SQLite driver missing); reads fall back to JSONL scan.");else console.log(`[OK] Session index rebuilt: ${J} session(s) indexed.`)}catch(z){console.log("[FAIL] Session index rebuild failed"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),process.exit(1)}return}console.log(`Running Blade health check...
|
|
3
3
|
`);let A=0;try{await Q.getInstance().initialize(),console.log("[OK] Configuration: OK")}catch(z){console.log("[FAIL] Configuration: FAILED"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),A++}let H=process.version;if(T(H))console.log(`[OK] Node.js version: ${H}`);else console.log(`[WARN] Node.js version: ${H} (required: >=22.19.0)`),A++;try{let z=await import("fs/promises"),B=L();await z.access(B,(await import("fs")).constants.R_OK|(await import("fs")).constants.W_OK),console.log("[OK] File system permissions: OK")}catch(z){console.log("[FAIL] File system permissions: FAILED"),console.log(" Error: Cannot read/write in current directory"),A++}try{await import("ink"),console.log("[OK] Dependencies: OK")}catch(z){console.log("[FAIL] Dependencies: FAILED"),console.log(" Error: Missing required dependencies"),A++}if(console.log(`
|
|
4
4
|
Health Check Summary:`),A===0)console.log("All checks passed! Blade is ready to use.");else console.log(`Warning: Found ${A} issue(s). Please resolve them for optimal performance.`),process.exit(1)}};export{T as isSupportedNodeVersion,X as doctorCommands};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{$g as k,Rg as a,Sg as b,Tg as c,Ug as d,Vg as e,Wg as f,Xg as g,Yg as h,Zg as i,_g as j}from"./chunk-cvazye0h.js";import"./chunk-ewwrss2w.js";import"./chunk-53vh6vpt.js";import"./chunk-hv8nt7wj.js";import"./chunk-erhaedch.js";import"./chunk-jgqk2tmr.js";import"./chunk-28tzj187.js";import"./chunk-wfynmt9r.js";import"./chunk-sd9bze9x.js";import"./chunk-514va7ce.js";import"./chunk-jsv3e4k6.js";import"./chunk-n34qsnks.js";import"./chunk-5q4z0sfr.js";import"./chunk-0b67y4j1.js";import"./chunk-9kj19a8t.js";import"./chunk-e1j1gsr5.js";import"./chunk-gm2yfq3r.js";import"./chunk-n9819k4p.js";import"./chunk-7xtxvrh8.js";import"./chunk-sdapqhj0.js";export{g as withWorkspaceAgentResources,i as snapshotWorkspaceAgentResources,f as resolveWorkspaceAgentResources,k as resetWorkspaceAgentResources,d as refreshWorkspaceCommunicationStyles,h as getWorkspaceAgentResourceCacheStats,j as createEmptySessionAgentResources,e as configureInvocationPluginDirs,c as WorkspaceAgentResourceCapacityError,a as MAX_RESIDENT_WORKSPACE_AGENT_RESOURCES,b as MAX_ACTIVE_WORKSPACE_AGENT_RESOURCES};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Ai as
|
|
1
|
+
import{Ai as I,zi as H}from"./chunk-wfynmt9r.js";import{Mutex as J}from"async-mutex";class B extends Error{limit;resource="resident_runtimes";retryable=!0;constructor(b){super("Session runtime capacity is full");this.limit=b;this.name="SessionRuntimeCapacityError"}}class D extends Error{constructor(){super("Session runtime residency is closed");this.name="SessionRuntimeResidencyClosedError"}}class A extends Error{constructor(b){super(`Session runtime residency already owns key: ${b}`);this.name="SessionRuntimeResidencyConflictError"}}class K{maxResident;idleMs;now;residents=new Map;reservations=new Map;operations=new J;nextGeneration=1;closed=!1;constructor(b){if(!H(b.maxResident))throw Error("Invalid max resident Session Runtime limit");if(!I(b.idleMs))throw Error("Invalid Session Runtime idle timeout");this.maxResident=b.maxResident,this.idleMs=b.idleMs,this.now=b.now??Date.now}acquire(b){let j=this.residents.get(b);if(!j||j.poisoned)return;return j.pins++,j.lastUsedAt=this.now(),this.createLease(j)}owns(b,j){let q=this.residents.get(b);return Boolean(q&&(j===void 0||q.value===j))}async reserve(b,j){if(!b.trim())throw Error("Session runtime residency key must not be blank");return this.operations.runExclusive(async()=>{if(this.closed)throw new D;if(this.residents.has(b)||this.reservations.has(b))throw new A(b);while(this.retainedCount()>=this.maxResident){if(!j.allowEviction)throw new B(this.maxResident);let z=this.oldestEvictableWebResident();if(!z)throw new B(this.maxResident);await this.disposeResident(z,!0)}let q={generation:this.allocateGeneration(),surface:j.surface};return this.reservations.set(b,q),this.createReservation(b,q)})}async remove(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j)return!1;if(q.pins>0)return!1;return await this.disposeResident(q,!0),!0})}async forget(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j||q.pins>0)return!1;return this.residents.delete(b),!0})}async sweepIdle(){return this.operations.runExclusive(async()=>{if(this.closed)return 0;let b=0;while(!0){let j=this.oldestIdleWebResident();if(!j)return b;await this.disposeResident(j,!0),b++}})}async disposeAll(){await this.operations.runExclusive(async()=>{this.closed=!0,this.reservations.clear();let b;for(let j of[...this.residents.values()])try{await this.disposeResident(j,!1)}catch(q){b??=q}if(this.residents.clear(),b!==void 0)throw b})}getStats(){let b=0;for(let j of this.residents.values())if(j.pins>0)b++;return{resident:this.residents.size,reserved:this.reservations.size,pinned:b,maxResident:this.maxResident}}retainedCount(){return this.residents.size+this.reservations.size}allocateGeneration(){let b=this.nextGeneration;return this.nextGeneration=this.nextGeneration===Number.MAX_SAFE_INTEGER?1:this.nextGeneration+1,b}createReservation(b,j){let q=!1;return{commit:(z)=>{if(q)throw new A(b);if(z.key!==b||z.surface!==j.surface||this.reservations.get(b)!==j||this.closed)throw this.reservations.delete(b),q=!0,this.closed?new D:new A(b);this.reservations.delete(b);let G={...z,generation:j.generation,pins:1,lastUsedAt:this.now(),poisoned:!1};return this.residents.set(b,G),q=!0,this.createLease(G)},cancel:()=>{if(q)return;if(this.reservations.get(b)===j)this.reservations.delete(b);q=!0}}}createLease(b){let j=!1;return{value:b.value,release:()=>{if(j)return;j=!0;let q=this.residents.get(b.key);if(q!==b||q.generation!==b.generation)return;q.pins=Math.max(0,q.pins-1),q.lastUsedAt=this.now()}}}oldestEvictableWebResident(){return this.sortedWebResidents().find((b)=>this.canEvict(b))}oldestIdleWebResident(){let b=this.now();return this.sortedWebResidents().find((j)=>b-j.lastUsedAt>=this.idleMs&&this.canEvict(j))}sortedWebResidents(){return[...this.residents.values()].filter((b)=>b.surface==="web").sort((b,j)=>b.lastUsedAt-j.lastUsedAt||b.generation-j.generation)}canEvict(b){if(b.pins>0||b.poisoned)return!1;try{return b.canEvict()}catch{return!1}}async disposeResident(b,j){if(this.residents.get(b.key)!==b)return;this.residents.delete(b.key);try{await b.dispose()}catch(q){if(j&&!this.closed&&!this.residents.has(b.key))b.lastUsedAt=this.now(),b.poisoned=!0,this.residents.set(b.key,b);throw q}}}
|
|
2
2
|
export{B as v,K as w};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{N as GP}from"./chunk-d1navt68.js";import{ge as N}from"./chunk-f71j03pq.js";import{Ne as r,Oe as e,Re as L,Te as PP,We as d,Ye as l,_e as JP,af as QP,bf as ZP,cf as $P,df as w}from"./chunk-3a217980.js";import{ff as t,gf as a,if as R,kf as y,lf as A,nf as p}from"./chunk-mh9nqbwa.js";import{Pj as q}from"./chunk-j8hbddjp.js";import{Ak as n,fk as o,zk as s}from"./chunk-4wx5sya5.js";async function qP(){return q().listProviders()}async function EP(P){return q().listModels(P)}import{randomBytes as XP}from"node:crypto";var NP=600000,OP=2048,jP=64,MP=32,HP=67108864,WP=4,D={catalog:"session-surface-catalog:",history:"session-surface-history:",snapshot:"session-surface-snapshot:"},c={session_surface_cursor_invalid:{message:"session surface cursor is invalid",retryable:!1},session_surface_snapshot_changed:{message:"session surface snapshot changed",retryable:!1},session_surface_capacity:{message:"session surface cursor capacity exceeded",retryable:!0},session_surface_unavailable:{message:"session surface cursor registry is unavailable",retryable:!0}};class U extends Error{code;retryable;constructor(P){super(c[P].message);this.code=P;this.name="SessionSurfaceCursorRegistryError",this.retryable=c[P].retryable}}class g{now;tokenSource;tokenCollisionRetries;limitsValue;entries=new Map;chains=new Map;closed=!1;closePromise;totalIssues=0;activeLoads=0;frozenSnapshotBytes=0;retainedPayloadBytes=0;constructor(P={}){if(this.now=P.now??(()=>Date.now()),this.tokenSource=P.tokenSource??(()=>XP(32).toString("base64url")),this.tokenCollisionRetries=P.tokenCollisionRetries??WP,this.limitsValue=_P(P.limits??{}),!Number.isSafeInteger(this.tokenCollisionRetries)||this.tokenCollisionRetries<0)throw Error("tokenCollisionRetries must be a non-negative safe integer")}issueCatalogCursor(P){this.assertAvailable(),this.cleanup();let J=m(P.boundary);if(J.value===void 0)throw new U("session_surface_cursor_invalid");let Q=T(P.request);this.ensureCapacity({requestedEntries:1,requestedRetainedBytes:J.bytes,chainId:P.chainId});let Z=this.createToken("catalog"),$=this.now(),G=this.ensureChain(P.chainId,$),Y={token:Z,chainId:P.chainId,kind:"catalog",expiresAt:$+this.limitsValue.idleTtlMs,lastAccessAt:$,scopeKey:P.scopeKey,epoch:P.epoch,revision:P.revision,boundary:J.value,boundaryBytes:J.bytes,requestHash:Q,cachedResultBytes:0};return this.storeEntry(G,Y),this.retainedPayloadBytes+=J.bytes,G.retainedPayloadBytes+=J.bytes,Z}issueHistoryCursor(P){this.assertAvailable(),this.cleanup();let J=T(P.request),Q=this.assertSnapshotIssuableForHistory(P);this.ensureCapacity({requestedEntries:1,requestedRetainedBytes:0,chainId:P.chainId});let Z=this.createToken("history"),$=this.now(),G=this.ensureChain(P.chainId,$);this.touch(Q);let Y={token:Z,chainId:P.chainId,kind:"history",expiresAt:$+this.limitsValue.idleTtlMs,lastAccessAt:$,locatorDigest:P.locatorDigest,transcriptFingerprint:P.transcriptFingerprint,nextSequence:P.nextSequence,snapshotToken:P.snapshotToken,requestHash:J,cachedResultBytes:0};return this.storeEntry(G,Y),Z}issueSnapshotToken(P){this.assertAvailable(),this.cleanup();let J=P.frozenSnapshot===void 0?{value:void 0,bytes:0}:m(P.frozenSnapshot);this.ensureCapacity({requestedEntries:1,requestedRetainedBytes:J.bytes,chainId:P.chainId});let Q=this.createToken("snapshot"),Z=this.now(),$=this.ensureChain(P.chainId,Z),G={token:Q,chainId:P.chainId,kind:"snapshot",expiresAt:Z+this.limitsValue.idleTtlMs,lastAccessAt:Z,locatorDigest:P.locatorDigest,transcriptFingerprint:P.transcriptFingerprint,frozenBytes:J.bytes,frozenSnapshot:J.value};return this.storeEntry($,G),this.frozenSnapshotBytes+=J.bytes,this.retainedPayloadBytes+=J.bytes,$.frozenSnapshotBytes+=J.bytes,$.retainedPayloadBytes+=J.bytes,Q}async redeemCatalogCursor(P){this.assertAvailable(),this.cleanup();let J=this.getEntry(P.token,"catalog");if(J.scopeKey!==P.scopeKey)throw new U("session_surface_cursor_invalid");if(J.epoch!==P.epoch||J.revision!==P.revision)throw new U("session_surface_snapshot_changed");if(J.requestHash!==T(P.request))throw new U("session_surface_cursor_invalid");if(this.touch(J),J.cachedResult!==void 0)return W(J.cachedResult);if(J.activeLoad)return this.cloneActiveLoadResult(J.activeLoad);return this.startCatalogLoad(J,P.loader)}async redeemHistoryCursor(P){this.assertAvailable(),this.cleanup();let J=this.getEntry(P.token,"history");if(J.locatorDigest!==P.locatorDigest)throw new U("session_surface_snapshot_changed");if(J.transcriptFingerprint!==P.transcriptFingerprint)throw new U("session_surface_snapshot_changed");if(J.requestHash!==T(P.request))throw new U("session_surface_cursor_invalid");let Q=this.resolveHistorySnapshot(J);if(this.touch(J),this.touch(Q),J.cachedResult!==void 0)return W(J.cachedResult);if(J.activeLoad)return this.cloneActiveLoadResult(J.activeLoad);return this.startHistoryLoad(J,Q,P.loader)}async assertSnapshotToken(P){this.assertAvailable(),this.cleanup();let J=this.getEntry(P.token,"snapshot");if(J.locatorDigest!==P.locatorDigest)throw new U("session_surface_cursor_invalid");if(J.transcriptFingerprint!==P.transcriptFingerprint)throw new U("session_surface_snapshot_changed");return this.touch(J),{chainId:J.chainId,locatorDigest:J.locatorDigest,transcriptFingerprint:J.transcriptFingerprint,frozenBytes:J.frozenBytes,frozenSnapshot:J.frozenSnapshot===void 0?void 0:W(J.frozenSnapshot)}}completeChain(P){this.cleanup();let J=this.chains.get(P);if(!J)return;J.completed=!0,J.lastAccessAt=this.now()}stats(){this.cleanup();let P=0;for(let J of this.chains.values())if(J.completed)P+=1;return{closed:this.closed,chainCount:this.chains.size,activeChains:this.chains.size-P,completedChains:P,entryCount:this.entries.size,activeLoads:this.activeLoads,frozenSnapshotBytes:this.frozenSnapshotBytes,retainedPayloadBytes:this.retainedPayloadBytes,totalIssues:this.totalIssues,limits:{...this.limitsValue}}}async close(P){if(this.closePromise)return this.closePromise;this.closed=!0;let J=[];for(let Q of this.entries.values())if((Q.kind==="catalog"||Q.kind==="history")&&Q.activeLoad)J.push(Q.activeLoad.promise),Q.activeLoad.controller.abort(_());return this.closePromise=Promise.allSettled(J).then(()=>{this.entries.clear(),this.chains.clear(),this.activeLoads=0,this.frozenSnapshotBytes=0,this.retainedPayloadBytes=0}),this.closePromise}startCatalogLoad(P,J){let Q=this.requireChain(P.chainId),Z=new AbortController;this.activeLoads+=1,Q.activeLoads+=1;let $=Promise.resolve().then(()=>J({boundary:W(P.boundary)},Z.signal)).then((G)=>{return this.assertLoadAvailable(Z.signal),this.admitCachedResult(P,G)}).catch((G)=>{if(this.closed||Z.signal.aborted)throw _();throw G}).finally(()=>{P.activeLoad=void 0,this.activeLoads-=1,Q.activeLoads-=1});return P.activeLoad={controller:Z,promise:$},this.cloneActiveLoadResult(P.activeLoad)}startHistoryLoad(P,J,Q){let Z=this.requireChain(P.chainId),$=new AbortController;this.activeLoads+=1,Z.activeLoads+=1;let G=Promise.resolve().then(()=>Q({nextSequence:P.nextSequence,frozenSnapshot:J.frozenSnapshot===void 0?void 0:W(J.frozenSnapshot)},$.signal)).then((Y)=>{return this.assertLoadAvailable($.signal),this.admitCachedResult(P,Y)}).catch((Y)=>{if(this.closed||$.signal.aborted)throw _();throw Y}).finally(()=>{P.activeLoad=void 0,this.activeLoads-=1,Z.activeLoads-=1});return P.activeLoad={controller:$,promise:G},this.cloneActiveLoadResult(P.activeLoad)}resolveHistorySnapshot(P){let J=P.snapshotToken;if(E(J)!=="snapshot")throw new U("session_surface_snapshot_changed");let Q=this.entries.get(J);if(!Q||Q.kind!=="snapshot")throw new U("session_surface_snapshot_changed");if(Q.expiresAt<=this.now())throw this.removeEntry(Q),new U("session_surface_snapshot_changed");if(Q.locatorDigest!==P.locatorDigest||Q.transcriptFingerprint!==P.transcriptFingerprint)throw new U("session_surface_snapshot_changed");return Q}assertSnapshotIssuableForHistory(P){let J=P.snapshotToken;if(E(J)!=="snapshot")throw new U("session_surface_snapshot_changed");let Q=this.entries.get(J);if(!Q||Q.kind!=="snapshot")throw new U("session_surface_snapshot_changed");if(Q.expiresAt<=this.now())throw this.removeEntry(Q),new U("session_surface_snapshot_changed");if(Q.chainId!==P.chainId||Q.locatorDigest!==P.locatorDigest||Q.transcriptFingerprint!==P.transcriptFingerprint)throw new U("session_surface_snapshot_changed");return Q}requireChain(P){let J=this.chains.get(P);if(!J)throw new U("session_surface_cursor_invalid");return J}assertLoadAvailable(P){if(this.closed||P.aborted)throw _()}getEntry(P,J){if(E(P)!==J)throw new U("session_surface_cursor_invalid");let Z=this.entries.get(P);if(!Z)throw new U("session_surface_cursor_invalid");if(Z.kind!==J)throw new U("session_surface_cursor_invalid");if(Z.expiresAt<=this.now()&&!f(Z))throw this.removeEntry(Z),new U("session_surface_cursor_invalid");return Z}touch(P){let J=this.now();P.lastAccessAt=J,P.expiresAt=J+this.limitsValue.idleTtlMs;let Q=this.chains.get(P.chainId);if(Q)Q.lastAccessAt=J}storeEntry(P,J){if(P.tokens.size>=this.limitsValue.maxEntriesPerChain)throw new U("session_surface_capacity");this.entries.set(J.token,J),P.tokens.add(J.token),P.completed=!1,P.lastAccessAt=J.lastAccessAt,P.issueCount+=1,this.totalIssues+=1}ensureChain(P,J){let Q=this.chains.get(P);if(Q)return Q.lastAccessAt=J,Q;let Z={chainId:P,tokens:new Set,completed:!1,lastAccessAt:J,issueCount:0,activeLoads:0,frozenSnapshotBytes:0,retainedPayloadBytes:0};return this.chains.set(P,Z),Z}cloneActiveLoadResult(P){return P.promise.then((J)=>W(J))}admitCachedResult(P,J){let Q=m(J),Z=this.requireChain(P.chainId),$=Q.bytes-P.cachedResultBytes;if(this.ensureCapacity({requestedEntries:0,requestedRetainedBytes:Math.max(0,$),chainId:P.chainId}),this.releaseCachedResult(P,Z),Q.value===void 0)throw new U("session_surface_cursor_invalid");return P.cachedResult=Q.value,P.cachedResultBytes=Q.bytes,this.retainedPayloadBytes+=Q.bytes,Z.retainedPayloadBytes+=Q.bytes,P.cachedResult}createToken(P){let J=D[P];for(let Q=0;Q<=this.tokenCollisionRetries;Q+=1){this.assertAvailable();let Z=`${J}${this.tokenSource()}`;if(!this.entries.has(Z))return Z}throw new U("session_surface_capacity")}ensureCapacity(P){this.reclaimCompletedChains(P);let J=this.entries.size+P.requestedEntries,Q=this.chains.size+(this.chains.has(P.chainId)?0:1),Z=this.retainedPayloadBytes+P.requestedRetainedBytes,$=(this.chains.get(P.chainId)?.tokens.size??0)+P.requestedEntries;if(J>this.limitsValue.maxEntries||Q>this.limitsValue.maxChains||$>this.limitsValue.maxEntriesPerChain||Z>this.limitsValue.maxFrozenSnapshotBytes)throw new U("session_surface_capacity")}reclaimCompletedChains(P){let J=[...this.chains.values()].filter((Q)=>Q.completed&&Q.activeLoads===0).sort((Q,Z)=>Q.lastAccessAt-Z.lastAccessAt);for(let Q of J){if(!(this.entries.size+P.requestedEntries>this.limitsValue.maxEntries||this.chains.size+(P.chainId!==""&&this.chains.has(P.chainId)?0:1)>this.limitsValue.maxChains||this.retainedPayloadBytes+P.requestedRetainedBytes>this.limitsValue.maxFrozenSnapshotBytes))break;this.removeChain(Q.chainId)}}cleanup(){let P=this.now();for(let J of[...this.entries.values()]){if(J.expiresAt>P||f(J))continue;this.removeEntry(J)}for(let J of[...this.chains.values()])if(J.tokens.size===0&&J.activeLoads===0)this.chains.delete(J.chainId)}removeEntry(P){this.entries.delete(P.token);let J=this.chains.get(P.chainId);if(J){if(J.tokens.delete(P.token),this.releaseEntryRetainedPayload(P,J),J.tokens.size===0&&J.activeLoads===0)this.chains.delete(J.chainId)}else this.releaseEntryRetainedPayload(P)}removeChain(P){let J=this.chains.get(P);if(!J)return;for(let Q of J.tokens){let Z=this.entries.get(Q);if(!Z||f(Z))continue;this.entries.delete(Q),this.releaseEntryRetainedPayload(Z,J)}this.chains.delete(P)}releaseEntryRetainedPayload(P,J){if(P.kind==="snapshot"){if(this.frozenSnapshotBytes-=P.frozenBytes,this.retainedPayloadBytes-=P.frozenBytes,J)J.frozenSnapshotBytes-=P.frozenBytes,J.retainedPayloadBytes-=P.frozenBytes;return}if(P.kind==="catalog"){if(this.retainedPayloadBytes-=P.boundaryBytes,J)J.retainedPayloadBytes-=P.boundaryBytes}this.releaseCachedResult(P,J)}releaseCachedResult(P,J){if(P.cachedResultBytes===0){P.cachedResult=void 0;return}if(this.retainedPayloadBytes-=P.cachedResultBytes,J)J.retainedPayloadBytes-=P.cachedResultBytes;P.cachedResult=void 0,P.cachedResultBytes=0}assertAvailable(){if(this.closed)throw _()}}function E(P){if(P.startsWith(D.catalog))return"catalog";if(P.startsWith(D.history))return"history";if(P.startsWith(D.snapshot))return"snapshot";return}function f(P){return P.kind!=="snapshot"&&P.activeLoad!==void 0}function _P(P){let J={idleTtlMs:P.idleTtlMs??NP,maxEntries:P.maxEntries??OP,maxChains:P.maxChains??jP,maxEntriesPerChain:P.maxEntriesPerChain??MP,maxFrozenSnapshotBytes:P.maxFrozenSnapshotBytes??HP};for(let Q of Object.values(J))if(!Number.isSafeInteger(Q)||Q<=0)throw Error("session surface cursor registry limits must be positive safe integers");return J}function _(){return new U("session_surface_unavailable")}function T(P){return B(W(P))}function W(P){try{return S(P,new Set)}catch{throw new U("session_surface_cursor_invalid")}}function S(P,J){if(P===null)return null;if(typeof P==="string"||typeof P==="boolean")return P;if(typeof P==="number"){if(!Number.isFinite(P))throw Error("invalid number");return P}if(typeof P>"u"||typeof P==="function"||typeof P==="symbol"||typeof P==="bigint")throw Error("invalid JSON type");if(!P||typeof P!=="object")throw Error("invalid JSON value");if(J.has(P))throw Error("cycle");J.add(P);try{if(Array.isArray(P)){let $=[];for(let G=0;G<P.length;G+=1){if(!(G in P))throw Error("sparse array");$.push(S(P[G],J))}return $}if(Object.getOwnPropertySymbols(P).length>0)throw Error("symbol keys");let Q=Object.getPrototypeOf(P);if(Q!==Object.prototype&&Q!==null)throw Error("non-plain object");let Z={};for(let $ of Object.keys(P)){let G=Reflect.get(P,$);if(G===void 0)throw Error("undefined object value");Z[$]=S(G,J)}return Z}finally{J.delete(P)}}function B(P){if(P===null)return"null";if(typeof P==="string"||typeof P==="number")return JSON.stringify(P);if(typeof P==="boolean")return P?"true":"false";if(Array.isArray(P))return`[${P.map((Q)=>B(Q)).join(",")}]`;return`{${Object.keys(P).sort().map((Q)=>`${JSON.stringify(Q)}:${B(P[Q])}`).join(",")}}`}function m(P,J={}){if(P===void 0){if(J.allowUndefined)return{value:void 0,bytes:0};throw new U("session_surface_cursor_invalid")}let Q=W(P);return{value:Q,bytes:Buffer.byteLength(B(Q),"utf8")}}import{createHash as C,randomBytes as F}from"node:crypto";import FP from"node:path";var YP=50,zP=100,AP=16,TP=1e4,DP=16777216;class z extends Error{code;retryable;constructor(P){let J=CP(P);super(J.message);this.code=P;this.name="SessionSurfaceServiceError",this.retryable=J.retryable}}class BP{database;registry;epoch;maxConcurrentOperations;activeControllers=new Set;activeOperations=new Set;closed=!1;closePromise;concurrentOperations=0;constructor(P={}){if(this.database=P.database,this.registry=P.cursorRegistry??new g(P.cursorRegistryOptions),this.epoch=P.epochSource?.()??`session-surface-epoch:${F(32).toString("base64url")}`,this.maxConcurrentOperations=P.maxConcurrentOperations??AP,!Number.isSafeInteger(this.maxConcurrentOperations)||this.maxConcurrentOperations<1||this.maxConcurrentOperations>256)throw Error("maxConcurrentOperations must be an integer from 1 to 256")}async listPage(P={}){return this.runOperation(async(J)=>{let Q=K(P.limit),Z=P.archived??!1,$={archived:Z,limit:Q,workspaceKind:P.workspaceKind??null},G=JSON.stringify([Z,P.workspaceKind??null]),Y=await this.requireDatabase();if(J.throwIfAborted(),!Y)return this.listFallbackPage($,G,J,P.cursor);if(await this.syncAllSurfaces(Y,J),P.cursor){let V=String(ZP(Y));return this.registry.redeemCatalogCursor({token:P.cursor,scopeKey:G,epoch:this.epoch,revision:V,request:$,loader:async({boundary:X})=>{let O=KP(X);return this.loadCatalogPage(Y,$,G,V,O,O.chainId,J)}})}return this.loadCatalogPage(Y,$,G,void 0,void 0,void 0,J)})}async open(P,J={}){return this.runOperation((Q)=>this.openInternal(P,J,Q))}async historyPage(P,J){return this.runOperation(async(Q)=>{let Z=I(P),$=K(J.limit);if(!J.cursor||!J.expectedSnapshot)throw new z("invalid_session_surface_request");let G=await this.requireDatabase();if(!G)return this.readFallbackHistoryPage(Z,J,Q);await this.syncForLocator(G,Z,Q);let Y=await this.resolveFromProjection(G,Z,Q),V=w(G,{sourceKind:Y.candidate.sourceKind,projectPath:Y.candidate.projectPath,sessionId:Y.candidate.sessionId,limit:1}),X=x(Z);await this.registry.assertSnapshotToken({token:J.expectedSnapshot,locatorDigest:X,transcriptFingerprint:V.transcriptFingerprint});let O={expectedSnapshot:J.expectedSnapshot,limit:$},j=await this.registry.redeemHistoryCursor({token:J.cursor,locatorDigest:X,transcriptFingerprint:V.transcriptFingerprint,request:O,loader:async({nextSequence:M})=>{let H=w(G,{sourceKind:Y.candidate.sourceKind,projectPath:Y.candidate.projectPath,sessionId:Y.candidate.sessionId,beforeSequence:M,limit:$});return this.publicHistoryPage({history:H,snapshot:J.expectedSnapshot,chainId:(await this.registry.assertSnapshotToken({token:J.expectedSnapshot,locatorDigest:X,transcriptFingerprint:V.transcriptFingerprint})).chainId,locatorDigest:X,limit:$})}});return A.parse(j)})}async fork(P){return this.runOperation(async(J)=>{let Q=I(P),Z=await this.requireDatabase(),$=Z?await this.resolveFromProjectionAfterSync(Z,Q,J):await this.resolveFallback(Q,J);if($.candidate.summary.archivedAt)throw new z("session_surface_read_only");J.throwIfAborted();let G=await N.forkSession(Q.sessionId,{sourceProjectPath:$.candidate.projectPath,targetProjectPath:$.candidate.projectPath,...$.remoteCandidate?{remote:{expectedDescriptor:$.remoteCandidate.descriptor}}:{}}),Y=$.remoteCandidate?{version:2,sessionId:G.sessionId,workspace:{kind:"acp-remote",workspaceRef:$.candidate.publicWorkspaceRef}}:{version:2,sessionId:G.sessionId,workspace:{kind:"local",projectPath:$.candidate.projectPath}};return Z?this.openInternal(Y,{},J):this.openFallback(Y,YP,J)})}async resolveFromProjectionAfterSync(P,J,Q){return await this.syncForLocator(P,J,Q),this.resolveFromProjection(P,J,Q)}async close(P){if(this.closePromise)return this.closePromise;this.closed=!0;for(let J of this.activeControllers)J.abort(new z("session_surface_unavailable"));return this.closePromise=Promise.allSettled([...this.activeOperations,this.registry.close()]).then(()=>{return}),this.closePromise}async openInternal(P,J={},Q){let Z=I(P),$=K(J.limit);if(J.cursor!==void 0||J.expectedSnapshot!==void 0)throw new z("invalid_session_surface_request");let G=await this.requireDatabase();if(!G)return this.openFallback(Z,$,Q);await this.syncForLocator(G,Z,Q);let Y=await this.resolveFromProjection(G,Z,Q),V=w(G,{sourceKind:Y.candidate.sourceKind,projectPath:Y.candidate.projectPath,sessionId:Y.candidate.sessionId,limit:$}),X=`history-chain:${F(16).toString("base64url")}`,O=x(Z),j=this.registry.issueSnapshotToken({chainId:X,locatorDigest:O,transcriptFingerprint:V.transcriptFingerprint}),M={session:this.toSummary(Y),history:this.publicHistoryPage({history:V,snapshot:j,chainId:X,locatorDigest:O,limit:$})};return p.parse(M)}runOperation(P){if(this.assertAvailable(),this.concurrentOperations>=this.maxConcurrentOperations)throw new z("session_surface_capacity");let J=new AbortController;this.activeControllers.add(J),this.concurrentOperations+=1;let Q;return Q=Promise.resolve().then(()=>P(J.signal)).then((Z)=>{if(J.signal.aborted||this.closed)throw new z("session_surface_unavailable");return Z}).catch((Z)=>{if(J.signal.aborted||this.closed)throw new z("session_surface_unavailable");throw kP(Z)}).finally(()=>{this.activeControllers.delete(J),this.activeOperations.delete(Q),this.concurrentOperations-=1}),this.activeOperations.add(Q),Q}async loadCatalogPage(P,J,Q,Z,$,G,Y){let V=$P(P,{archived:J.archived,limit:J.limit,...J.workspaceKind?{workspaceKind:J.workspaceKind}:{},...$?{boundary:$}:{}}),X=String(V.revision);if(Z!==void 0&&Z!==X)throw new z("session_surface_snapshot_changed");let O=G??`catalog-chain:${F(16).toString("base64url")}`,j={sessions:await Promise.all(V.sessions.map(async(M)=>this.toSummary(await this.resolveCandidate(M,Y)))),...V.nextBoundary?{nextCursor:this.registry.issueCatalogCursor({chainId:O,scopeKey:Q,epoch:this.epoch,revision:X,boundary:{...V.nextBoundary,chainId:O},request:J})}:{}};if(!V.nextBoundary)this.registry.completeChain(O);return y.parse(j)}publicHistoryPage(P){let J=h(P.history.messages,L()),Q={messages:J.messages,snapshot:P.snapshot,truncated:P.history.hasOlder||J.truncated||J.messages.some((Z)=>Z.truncated===!0),...P.history.hasOlder&&P.history.nextSequence!==void 0?{olderCursor:this.registry.issueHistoryCursor({chainId:P.chainId,locatorDigest:P.locatorDigest,transcriptFingerprint:P.history.transcriptFingerprint,nextSequence:P.history.nextSequence,snapshotToken:P.snapshot,request:{expectedSnapshot:P.snapshot,limit:P.limit}})}:{}};if(!P.history.hasOlder)this.registry.completeChain(P.chainId);return A.parse(Q)}async syncForLocator(P,J,Q){if(Q?.throwIfAborted(),J.workspace.kind==="local"){await N.findSessionMetadata(J.sessionId,J.workspace.projectPath),Q?.throwIfAborted(),await d(P,J.sessionId,J.workspace.projectPath,N.projectionDeriverForSearch(),void 0,"local",Q);return}await N.listValidatedRemoteSurfaceCandidates(Q),await l(P,N.projectionDeriverForSearch(),Q)}async syncAllSurfaces(P,J){let Q=N.projectionDeriverForSearch(),Z=await N.listValidatedLocalSurfaceCandidates(J),$=new Set(Z.map((Y)=>`${Y.projectPath}\x00${Y.sessionId}`)),G=P.prepare("SELECT project_path, session_id FROM sessions WHERE source_kind='local'").all();for(let Y of G)if(!$.has(`${Y.project_path}\x00${Y.session_id}`))JP(P,Y.session_id,Y.project_path,"local");for(let Y of Z)J?.throwIfAborted(),await d(P,Y.sessionId,Y.projectPath,Q,void 0,"local",J);await N.listValidatedRemoteSurfaceCandidates(J),await l(P,Q,J)}async listFallbackPage(P,J,Q,Z){if(Z)return this.registry.redeemCatalogCursor({token:Z,scopeKey:J,epoch:this.epoch,revision:"fallback",request:P,loader:async({boundary:G})=>{let Y=LP(G);return this.pageFallbackCatalog(Y.entries,P,J,Y.chainId)}});let $=await this.loadFallbackCatalog(P,Q);return this.pageFallbackCatalog($,P,J,`catalog-fallback:${F(16).toString("base64url")}`)}async loadFallbackCatalog(P,J){let Q=[];if(P.workspaceKind!=="acp-remote")for(let $ of await N.listValidatedLocalSurfaceCandidates(J)){J?.throwIfAborted();let Y=(await N.readValidatedLocalSurfaceSnapshot($.sessionId,$.projectPath,J)).summary;if(Boolean(Y.archivedAt)!==P.archived)continue;Q.push({locator:{version:2,sessionId:$.sessionId,workspace:{kind:"local",projectPath:$.projectPath}},summary:Y})}if(P.workspaceKind!=="local")for(let $ of await N.listValidatedRemoteSurfaceCandidates(J)){J?.throwIfAborted();let Y=(await N.readValidatedRemoteSurfaceSnapshot($,J)).summary;if(Boolean(Y.archivedAt)!==P.archived)continue;Q.push({locator:{version:2,sessionId:$.sessionId,workspace:{kind:"acp-remote",workspaceRef:$.workspaceRef}},summary:Y})}Q.sort(IP);let Z=Buffer.byteLength(JSON.stringify(Q));if(Q.length>TP||Z>DP)throw new z("session_surface_capacity");return Q}async pageFallbackCatalog(P,J,Q,Z){let $=P.slice(0,J.limit),G=P.slice($.length),V={sessions:$.map((X)=>R.parse({locator:X.locator,...X.summary,capabilities:X.locator.workspace.kind==="local"?UP(Boolean(X.summary.archivedAt)):RP(Boolean(X.summary.archivedAt))})),...G.length>0?{nextCursor:this.registry.issueCatalogCursor({chainId:Z,scopeKey:Q,epoch:this.epoch,revision:"fallback",boundary:{chainId:Z,entries:G},request:J})}:{}};if(G.length===0)this.registry.completeChain(Z);return y.parse(V)}async openFallback(P,J,Q){let Z=await this.resolveFallback(P,Q),$=Z.remoteCandidate?await N.readValidatedRemoteSurfaceSnapshot(Z.remoteCandidate,Q):await N.readValidatedLocalSurfaceSnapshot(Z.candidate.sessionId,Z.candidate.projectPath,Q),G=e($.entries,{...Z.remoteCandidate?r(Z.remoteCandidate.hostStateRoot,Z.remoteCandidate.descriptor):{privateRoots:[]},bladeStorageRoots:[o()]}),Y=h(G.slice(-J),L()),V=`history-fallback:${F(16).toString("base64url")}`,X=x(P),O=C("sha256").update(JSON.stringify($.entries)).digest("hex"),j=this.registry.issueSnapshotToken({chainId:V,locatorDigest:X,transcriptFingerprint:O,frozenSnapshot:G}),M={session:this.toSummary(Z),history:A.parse({messages:Y.messages,snapshot:j,truncated:Y.messages.length<G.length||Y.truncated||Y.messages.some((H)=>H.truncated===!0),...G.length>Y.messages.length&&Y.messages[0]?{olderCursor:this.registry.issueHistoryCursor({chainId:V,locatorDigest:X,transcriptFingerprint:O,nextSequence:v(Y.messages[0].id),snapshotToken:j,request:{expectedSnapshot:j,limit:J}})}:{}})};if(G.length<=Y.messages.length)this.registry.completeChain(V);return p.parse(M)}async readFallbackHistoryPage(P,J,Q){let Z=K(J.limit);if(!J.cursor||!J.expectedSnapshot)throw new z("invalid_session_surface_request");let $=x(P),G=await this.resolveFallback(P,Q),Y=G.remoteCandidate?await N.readValidatedRemoteSurfaceSnapshot(G.remoteCandidate,Q):await N.readValidatedLocalSurfaceSnapshot(G.candidate.sessionId,G.candidate.projectPath,Q),V=C("sha256").update(JSON.stringify(Y.entries)).digest("hex");await this.registry.assertSnapshotToken({token:J.expectedSnapshot,locatorDigest:$,transcriptFingerprint:V});let X={expectedSnapshot:J.expectedSnapshot,limit:Z};return this.registry.redeemHistoryCursor({token:J.cursor,locatorDigest:$,transcriptFingerprint:V,request:X,loader:async({nextSequence:O,frozenSnapshot:j})=>{let M=xP(j).filter((b)=>v(b.id)<O),H=h(M.slice(-Z),L()),u=await this.registry.assertSnapshotToken({token:J.expectedSnapshot,locatorDigest:$,transcriptFingerprint:V}),k=H.messages.length<M.length,VP={messages:H.messages,snapshot:J.expectedSnapshot,truncated:k||H.truncated||H.messages.some((b)=>b.truncated===!0),...k&&H.messages[0]?{olderCursor:this.registry.issueHistoryCursor({chainId:u.chainId,locatorDigest:$,transcriptFingerprint:V,nextSequence:v(H.messages[0].id),snapshotToken:J.expectedSnapshot,request:X})}:{}};if(!k)this.registry.completeChain(u.chainId);return A.parse(VP)}})}async resolveFallback(P,J){let Q=[];for(let G of[!1,!0]){let Y={archived:G,limit:zP,workspaceKind:P.workspace.kind};Q.push(...(await this.loadFallbackCatalog(Y,J)).filter((V)=>JSON.stringify(V.locator)===JSON.stringify(P)))}if(Q.length!==1)throw new z("session_surface_not_found");let Z=Q[0],$;if(P.workspace.kind==="acp-remote"){let G=P.workspace.workspaceRef;if($=(await N.listValidatedRemoteSurfaceCandidates(J)).find((Y)=>Y.sessionId===P.sessionId&&Y.workspaceRef===G),!$)throw new z("workspace_binding_mismatch")}return{candidate:{sourceKind:P.workspace.kind,projectPath:P.workspace.kind==="local"?P.workspace.projectPath:$.hostStateRoot,sessionId:P.sessionId,...P.workspace.kind==="acp-remote"?{publicWorkspaceRef:P.workspace.workspaceRef}:{},publicWorkspaceSortKey:"",surfaceDigest:i(Z),transcriptFingerprint:i(Z),lastMessageTime:Z.summary.lastMessageTime,sessionSortKey:"",summary:Z.summary},...$?{remoteCandidate:$}:{}}}async resolveFromProjection(P,J,Q){let Z=QP(P,J.sessionId).filter((G)=>J.workspace.kind==="local"?G.sourceKind==="local"&&G.projectPath===FP.resolve(J.workspace.projectPath):G.sourceKind==="acp-remote"&&G.publicWorkspaceRef===J.workspace.workspaceRef);if(Z.length!==1)throw new z(Z.length===0?"session_surface_not_found":"workspace_binding_mismatch");let $;if(J.workspace.kind==="acp-remote"){let G=J.workspace.workspaceRef;if($=(await N.listValidatedRemoteSurfaceCandidates(Q)).filter((Y)=>Y.sessionId===J.sessionId&&Y.workspaceRef===G),$.length===0)throw new z("workspace_binding_mismatch");if($.length>1)throw new z("session_surface_state_invalid")}return $?{candidate:Z[0],remoteCandidate:$[0]}:{candidate:Z[0]}}async resolveCandidate(P,J){if(P.sourceKind==="local")return{candidate:P};let Q=(await N.listValidatedRemoteSurfaceCandidates(J)).filter((Z)=>Z.sessionId===P.sessionId&&Z.workspaceRef===P.publicWorkspaceRef);if(Q.length!==1)throw new z(Q.length===0?"workspace_binding_mismatch":"session_surface_state_invalid");return{candidate:P,remoteCandidate:Q[0]}}toSummary(P){let J=P.candidate,Q=J.sourceKind==="local"?{version:2,sessionId:J.sessionId,workspace:{kind:"local",projectPath:J.projectPath}}:{version:2,sessionId:J.sessionId,workspace:{kind:"acp-remote",workspaceRef:J.publicWorkspaceRef}};return R.parse({locator:Q,...J.summary,capabilities:this.capabilitiesFor(P)})}capabilitiesFor(P){let J=P.candidate.summary.archivedAt!==void 0;if(!P.remoteCandidate)return{connection:"local",history:{read:!0,fork:!J},turn:J?{start:!1,reason:"archived"}:{start:!0},files:J?{readText:!1,writeText:!1,browse:"none",reason:"archived"}:{readText:!0,writeText:!0,browse:"tree"},terminal:J?{mode:"none",owner:"none",reason:"archived"}:{mode:"interactive",owner:"local"}};return{connection:GP.getRemoteSurfaceOwnerSnapshot(P.candidate.sessionId,P.remoteCandidate.descriptor).connection,history:{read:!0,fork:!J},turn:{start:!1,reason:J?"archived":"history-only"},files:{readText:!1,writeText:!1,browse:"none",reason:J?"archived":"history-only"},terminal:{mode:"none",owner:"none",reason:J?"archived":"history-only"}}}async requireDatabase(){if(this.database===null)return null;return this.database??await PP()}assertAvailable(){if(this.closed)throw new z("session_surface_unavailable")}}function K(P){let J=P??YP;if(!Number.isSafeInteger(J)||J<1||J>zP)throw new z("invalid_session_surface_request");return J}function I(P){try{let J=t.parse(P);if(!n(J.sessionId))throw Error("invalid");if(J.workspace.kind==="local"){if(s(J.workspace.projectPath)!==J.workspace.projectPath)throw Error("invalid")}return J}catch{throw new z("invalid_session_locator")}}function x(P){return C("sha256").update("session-surface-locator-v2\x00").update(JSON.stringify(P)).digest("hex")}function KP(P){if(!P||typeof P!=="object"||Array.isArray(P))throw new z("session_surface_cursor_invalid");let J=P;if(typeof J.lastMessageTime!=="string"||J.sourceKind!=="local"&&J.sourceKind!=="acp-remote"||typeof J.publicWorkspaceSortKey!=="string"||typeof J.sessionSortKey!=="string"||typeof J.chainId!=="string"||!J.chainId)throw new z("session_surface_cursor_invalid");return{lastMessageTime:J.lastMessageTime,sourceKind:J.sourceKind,publicWorkspaceSortKey:J.publicWorkspaceSortKey,sessionSortKey:J.sessionSortKey,chainId:J.chainId}}function h(P,J){let Q=[];for(let Z=P.length-1;Z>=0;Z-=1){let $=P[Z];if(!$)continue;let G=[$,...Q];if(Q.length>0&&Buffer.byteLength(JSON.stringify(G))>J)break;Q.unshift($)}return{messages:Q,truncated:Q.length<P.length}}function v(P){let J=/^surface-message:([0-9]+):/.exec(P),Q=J?Number(J[1]):Number.NaN;if(!Number.isSafeInteger(Q)||Q<=0)throw new z("session_surface_state_invalid");return Q}function xP(P){if(!Array.isArray(P))throw new z("session_surface_snapshot_changed");return P.map((J)=>{try{return a.parse(J)}catch{throw new z("session_surface_snapshot_changed")}})}function LP(P){if(!P||typeof P!=="object"||Array.isArray(P))throw new z("session_surface_cursor_invalid");let J=P;if(typeof J.chainId!=="string"||J.chainId.length===0||!Array.isArray(J.entries))throw new z("session_surface_cursor_invalid");let Q=J.entries.map((Z)=>{if(!Z||typeof Z!=="object"||Array.isArray(Z))throw new z("session_surface_cursor_invalid");let $=Z;return{locator:I($.locator),summary:wP($.summary)}});return{chainId:J.chainId,entries:Q}}function wP(P){let J={version:2,sessionId:"placeholder",workspace:{kind:"local",projectPath:"/"}},Q=R.parse({...P&&typeof P==="object"&&!Array.isArray(P)?P:{},locator:J,capabilities:UP(!1)}),{locator:Z,capabilities:$,...G}=Q;return G}function IP(P,J){if(P.summary.lastMessageTime>J.summary.lastMessageTime)return-1;if(P.summary.lastMessageTime<J.summary.lastMessageTime)return 1;if(P.locator.workspace.kind!==J.locator.workspace.kind)return P.locator.workspace.kind==="local"?-1:1;let Q=P.locator.workspace.kind==="local"?P.locator.workspace.projectPath:P.locator.workspace.workspaceRef,Z=J.locator.workspace.kind==="local"?J.locator.workspace.projectPath:J.locator.workspace.workspaceRef;if(Q<Z)return-1;if(Q>Z)return 1;return P.locator.sessionId<J.locator.sessionId?-1:P.locator.sessionId>J.locator.sessionId?1:0}function i(P){return C("sha256").update("session-surface-fallback-entry\x00").update(JSON.stringify(P)).digest("hex")}function UP(P){return{connection:"local",history:{read:!0,fork:!P},turn:P?{start:!1,reason:"archived"}:{start:!0},files:P?{readText:!1,writeText:!1,browse:"none",reason:"archived"}:{readText:!0,writeText:!0,browse:"tree"},terminal:P?{mode:"none",owner:"none",reason:"archived"}:{mode:"interactive",owner:"local"}}}function RP(P){return{connection:"offline",history:{read:!0,fork:!P},turn:{start:!1,reason:P?"archived":"history-only"},files:{readText:!1,writeText:!1,browse:"none",reason:P?"archived":"history-only"},terminal:{mode:"none",owner:"none",reason:P?"archived":"history-only"}}}function CP(P){if(P==="session_surface_cursor_invalid")return{message:"Session surface cursor is invalid",retryable:!1};if(P==="session_surface_snapshot_changed")return{message:"Session surface snapshot changed",retryable:!1};if(P==="session_surface_state_invalid")return{message:"Session surface state is invalid",retryable:!1};if(P==="session_surface_capability_unavailable")return{message:"Session surface capability is unavailable",retryable:!1};if(P==="session_surface_unavailable")return{message:"Session surface is unavailable",retryable:!0};if(P==="session_surface_not_found")return{message:"Session surface was not found",retryable:!1};if(P==="workspace_binding_mismatch")return{message:"Session workspace binding changed",retryable:!1};if(P==="session_surface_read_only")return{message:"Session surface is read only",retryable:!1};if(P==="session_surface_capacity")return{message:"Session surface capacity is exhausted",retryable:!0};if(P==="invalid_session_locator")return{message:"Session locator is invalid",retryable:!1};return{message:"Session surface request is invalid",retryable:!1}}function kP(P){if(P instanceof z)return P;if(P&&typeof P==="object"&&"code"in P&&typeof P.code==="string"){let J=P.code;if(J==="session_surface_cursor_invalid"||J==="session_surface_snapshot_changed"||J==="session_surface_capacity"||J==="session_surface_unavailable"||J==="session_surface_state_invalid")return new z(J);if(J==="acp_remote_workspace_state_invalid")return new z("session_surface_state_invalid")}return P instanceof Error?P:new z("session_surface_state_invalid")}
|
|
1
|
+
import{N as GP}from"./chunk-d0q5n5ea.js";import{ge as N}from"./chunk-qmveehgt.js";import{Ne as r,Oe as e,Re as L,Te as PP,We as d,Ye as l,_e as JP,af as QP,bf as ZP,cf as $P,df as w}from"./chunk-q1rnvn85.js";import{ff as t,gf as a,if as R,kf as y,lf as A,nf as p}from"./chunk-fx9vm1n5.js";import{Oj as q}from"./chunk-0b67y4j1.js";import{ek as o,yk as s,zk as n}from"./chunk-7xtxvrh8.js";async function qP(){return q().listProviders()}async function EP(P){return q().listModels(P)}import{randomBytes as XP}from"node:crypto";var NP=600000,OP=2048,jP=64,MP=32,HP=67108864,WP=4,D={catalog:"session-surface-catalog:",history:"session-surface-history:",snapshot:"session-surface-snapshot:"},c={session_surface_cursor_invalid:{message:"session surface cursor is invalid",retryable:!1},session_surface_snapshot_changed:{message:"session surface snapshot changed",retryable:!1},session_surface_capacity:{message:"session surface cursor capacity exceeded",retryable:!0},session_surface_unavailable:{message:"session surface cursor registry is unavailable",retryable:!0}};class U extends Error{code;retryable;constructor(P){super(c[P].message);this.code=P;this.name="SessionSurfaceCursorRegistryError",this.retryable=c[P].retryable}}class g{now;tokenSource;tokenCollisionRetries;limitsValue;entries=new Map;chains=new Map;closed=!1;closePromise;totalIssues=0;activeLoads=0;frozenSnapshotBytes=0;retainedPayloadBytes=0;constructor(P={}){if(this.now=P.now??(()=>Date.now()),this.tokenSource=P.tokenSource??(()=>XP(32).toString("base64url")),this.tokenCollisionRetries=P.tokenCollisionRetries??WP,this.limitsValue=_P(P.limits??{}),!Number.isSafeInteger(this.tokenCollisionRetries)||this.tokenCollisionRetries<0)throw Error("tokenCollisionRetries must be a non-negative safe integer")}issueCatalogCursor(P){this.assertAvailable(),this.cleanup();let J=m(P.boundary);if(J.value===void 0)throw new U("session_surface_cursor_invalid");let Q=T(P.request);this.ensureCapacity({requestedEntries:1,requestedRetainedBytes:J.bytes,chainId:P.chainId});let Z=this.createToken("catalog"),$=this.now(),G=this.ensureChain(P.chainId,$),Y={token:Z,chainId:P.chainId,kind:"catalog",expiresAt:$+this.limitsValue.idleTtlMs,lastAccessAt:$,scopeKey:P.scopeKey,epoch:P.epoch,revision:P.revision,boundary:J.value,boundaryBytes:J.bytes,requestHash:Q,cachedResultBytes:0};return this.storeEntry(G,Y),this.retainedPayloadBytes+=J.bytes,G.retainedPayloadBytes+=J.bytes,Z}issueHistoryCursor(P){this.assertAvailable(),this.cleanup();let J=T(P.request),Q=this.assertSnapshotIssuableForHistory(P);this.ensureCapacity({requestedEntries:1,requestedRetainedBytes:0,chainId:P.chainId});let Z=this.createToken("history"),$=this.now(),G=this.ensureChain(P.chainId,$);this.touch(Q);let Y={token:Z,chainId:P.chainId,kind:"history",expiresAt:$+this.limitsValue.idleTtlMs,lastAccessAt:$,locatorDigest:P.locatorDigest,transcriptFingerprint:P.transcriptFingerprint,nextSequence:P.nextSequence,snapshotToken:P.snapshotToken,requestHash:J,cachedResultBytes:0};return this.storeEntry(G,Y),Z}issueSnapshotToken(P){this.assertAvailable(),this.cleanup();let J=P.frozenSnapshot===void 0?{value:void 0,bytes:0}:m(P.frozenSnapshot);this.ensureCapacity({requestedEntries:1,requestedRetainedBytes:J.bytes,chainId:P.chainId});let Q=this.createToken("snapshot"),Z=this.now(),$=this.ensureChain(P.chainId,Z),G={token:Q,chainId:P.chainId,kind:"snapshot",expiresAt:Z+this.limitsValue.idleTtlMs,lastAccessAt:Z,locatorDigest:P.locatorDigest,transcriptFingerprint:P.transcriptFingerprint,frozenBytes:J.bytes,frozenSnapshot:J.value};return this.storeEntry($,G),this.frozenSnapshotBytes+=J.bytes,this.retainedPayloadBytes+=J.bytes,$.frozenSnapshotBytes+=J.bytes,$.retainedPayloadBytes+=J.bytes,Q}async redeemCatalogCursor(P){this.assertAvailable(),this.cleanup();let J=this.getEntry(P.token,"catalog");if(J.scopeKey!==P.scopeKey)throw new U("session_surface_cursor_invalid");if(J.epoch!==P.epoch||J.revision!==P.revision)throw new U("session_surface_snapshot_changed");if(J.requestHash!==T(P.request))throw new U("session_surface_cursor_invalid");if(this.touch(J),J.cachedResult!==void 0)return W(J.cachedResult);if(J.activeLoad)return this.cloneActiveLoadResult(J.activeLoad);return this.startCatalogLoad(J,P.loader)}async redeemHistoryCursor(P){this.assertAvailable(),this.cleanup();let J=this.getEntry(P.token,"history");if(J.locatorDigest!==P.locatorDigest)throw new U("session_surface_snapshot_changed");if(J.transcriptFingerprint!==P.transcriptFingerprint)throw new U("session_surface_snapshot_changed");if(J.requestHash!==T(P.request))throw new U("session_surface_cursor_invalid");let Q=this.resolveHistorySnapshot(J);if(this.touch(J),this.touch(Q),J.cachedResult!==void 0)return W(J.cachedResult);if(J.activeLoad)return this.cloneActiveLoadResult(J.activeLoad);return this.startHistoryLoad(J,Q,P.loader)}async assertSnapshotToken(P){this.assertAvailable(),this.cleanup();let J=this.getEntry(P.token,"snapshot");if(J.locatorDigest!==P.locatorDigest)throw new U("session_surface_cursor_invalid");if(J.transcriptFingerprint!==P.transcriptFingerprint)throw new U("session_surface_snapshot_changed");return this.touch(J),{chainId:J.chainId,locatorDigest:J.locatorDigest,transcriptFingerprint:J.transcriptFingerprint,frozenBytes:J.frozenBytes,frozenSnapshot:J.frozenSnapshot===void 0?void 0:W(J.frozenSnapshot)}}completeChain(P){this.cleanup();let J=this.chains.get(P);if(!J)return;J.completed=!0,J.lastAccessAt=this.now()}stats(){this.cleanup();let P=0;for(let J of this.chains.values())if(J.completed)P+=1;return{closed:this.closed,chainCount:this.chains.size,activeChains:this.chains.size-P,completedChains:P,entryCount:this.entries.size,activeLoads:this.activeLoads,frozenSnapshotBytes:this.frozenSnapshotBytes,retainedPayloadBytes:this.retainedPayloadBytes,totalIssues:this.totalIssues,limits:{...this.limitsValue}}}async close(P){if(this.closePromise)return this.closePromise;this.closed=!0;let J=[];for(let Q of this.entries.values())if((Q.kind==="catalog"||Q.kind==="history")&&Q.activeLoad)J.push(Q.activeLoad.promise),Q.activeLoad.controller.abort(_());return this.closePromise=Promise.allSettled(J).then(()=>{this.entries.clear(),this.chains.clear(),this.activeLoads=0,this.frozenSnapshotBytes=0,this.retainedPayloadBytes=0}),this.closePromise}startCatalogLoad(P,J){let Q=this.requireChain(P.chainId),Z=new AbortController;this.activeLoads+=1,Q.activeLoads+=1;let $=Promise.resolve().then(()=>J({boundary:W(P.boundary)},Z.signal)).then((G)=>{return this.assertLoadAvailable(Z.signal),this.admitCachedResult(P,G)}).catch((G)=>{if(this.closed||Z.signal.aborted)throw _();throw G}).finally(()=>{P.activeLoad=void 0,this.activeLoads-=1,Q.activeLoads-=1});return P.activeLoad={controller:Z,promise:$},this.cloneActiveLoadResult(P.activeLoad)}startHistoryLoad(P,J,Q){let Z=this.requireChain(P.chainId),$=new AbortController;this.activeLoads+=1,Z.activeLoads+=1;let G=Promise.resolve().then(()=>Q({nextSequence:P.nextSequence,frozenSnapshot:J.frozenSnapshot===void 0?void 0:W(J.frozenSnapshot)},$.signal)).then((Y)=>{return this.assertLoadAvailable($.signal),this.admitCachedResult(P,Y)}).catch((Y)=>{if(this.closed||$.signal.aborted)throw _();throw Y}).finally(()=>{P.activeLoad=void 0,this.activeLoads-=1,Z.activeLoads-=1});return P.activeLoad={controller:$,promise:G},this.cloneActiveLoadResult(P.activeLoad)}resolveHistorySnapshot(P){let J=P.snapshotToken;if(E(J)!=="snapshot")throw new U("session_surface_snapshot_changed");let Q=this.entries.get(J);if(!Q||Q.kind!=="snapshot")throw new U("session_surface_snapshot_changed");if(Q.expiresAt<=this.now())throw this.removeEntry(Q),new U("session_surface_snapshot_changed");if(Q.locatorDigest!==P.locatorDigest||Q.transcriptFingerprint!==P.transcriptFingerprint)throw new U("session_surface_snapshot_changed");return Q}assertSnapshotIssuableForHistory(P){let J=P.snapshotToken;if(E(J)!=="snapshot")throw new U("session_surface_snapshot_changed");let Q=this.entries.get(J);if(!Q||Q.kind!=="snapshot")throw new U("session_surface_snapshot_changed");if(Q.expiresAt<=this.now())throw this.removeEntry(Q),new U("session_surface_snapshot_changed");if(Q.chainId!==P.chainId||Q.locatorDigest!==P.locatorDigest||Q.transcriptFingerprint!==P.transcriptFingerprint)throw new U("session_surface_snapshot_changed");return Q}requireChain(P){let J=this.chains.get(P);if(!J)throw new U("session_surface_cursor_invalid");return J}assertLoadAvailable(P){if(this.closed||P.aborted)throw _()}getEntry(P,J){if(E(P)!==J)throw new U("session_surface_cursor_invalid");let Z=this.entries.get(P);if(!Z)throw new U("session_surface_cursor_invalid");if(Z.kind!==J)throw new U("session_surface_cursor_invalid");if(Z.expiresAt<=this.now()&&!f(Z))throw this.removeEntry(Z),new U("session_surface_cursor_invalid");return Z}touch(P){let J=this.now();P.lastAccessAt=J,P.expiresAt=J+this.limitsValue.idleTtlMs;let Q=this.chains.get(P.chainId);if(Q)Q.lastAccessAt=J}storeEntry(P,J){if(P.tokens.size>=this.limitsValue.maxEntriesPerChain)throw new U("session_surface_capacity");this.entries.set(J.token,J),P.tokens.add(J.token),P.completed=!1,P.lastAccessAt=J.lastAccessAt,P.issueCount+=1,this.totalIssues+=1}ensureChain(P,J){let Q=this.chains.get(P);if(Q)return Q.lastAccessAt=J,Q;let Z={chainId:P,tokens:new Set,completed:!1,lastAccessAt:J,issueCount:0,activeLoads:0,frozenSnapshotBytes:0,retainedPayloadBytes:0};return this.chains.set(P,Z),Z}cloneActiveLoadResult(P){return P.promise.then((J)=>W(J))}admitCachedResult(P,J){let Q=m(J),Z=this.requireChain(P.chainId),$=Q.bytes-P.cachedResultBytes;if(this.ensureCapacity({requestedEntries:0,requestedRetainedBytes:Math.max(0,$),chainId:P.chainId}),this.releaseCachedResult(P,Z),Q.value===void 0)throw new U("session_surface_cursor_invalid");return P.cachedResult=Q.value,P.cachedResultBytes=Q.bytes,this.retainedPayloadBytes+=Q.bytes,Z.retainedPayloadBytes+=Q.bytes,P.cachedResult}createToken(P){let J=D[P];for(let Q=0;Q<=this.tokenCollisionRetries;Q+=1){this.assertAvailable();let Z=`${J}${this.tokenSource()}`;if(!this.entries.has(Z))return Z}throw new U("session_surface_capacity")}ensureCapacity(P){this.reclaimCompletedChains(P);let J=this.entries.size+P.requestedEntries,Q=this.chains.size+(this.chains.has(P.chainId)?0:1),Z=this.retainedPayloadBytes+P.requestedRetainedBytes,$=(this.chains.get(P.chainId)?.tokens.size??0)+P.requestedEntries;if(J>this.limitsValue.maxEntries||Q>this.limitsValue.maxChains||$>this.limitsValue.maxEntriesPerChain||Z>this.limitsValue.maxFrozenSnapshotBytes)throw new U("session_surface_capacity")}reclaimCompletedChains(P){let J=[...this.chains.values()].filter((Q)=>Q.completed&&Q.activeLoads===0).sort((Q,Z)=>Q.lastAccessAt-Z.lastAccessAt);for(let Q of J){if(!(this.entries.size+P.requestedEntries>this.limitsValue.maxEntries||this.chains.size+(P.chainId!==""&&this.chains.has(P.chainId)?0:1)>this.limitsValue.maxChains||this.retainedPayloadBytes+P.requestedRetainedBytes>this.limitsValue.maxFrozenSnapshotBytes))break;this.removeChain(Q.chainId)}}cleanup(){let P=this.now();for(let J of[...this.entries.values()]){if(J.expiresAt>P||f(J))continue;this.removeEntry(J)}for(let J of[...this.chains.values()])if(J.tokens.size===0&&J.activeLoads===0)this.chains.delete(J.chainId)}removeEntry(P){this.entries.delete(P.token);let J=this.chains.get(P.chainId);if(J){if(J.tokens.delete(P.token),this.releaseEntryRetainedPayload(P,J),J.tokens.size===0&&J.activeLoads===0)this.chains.delete(J.chainId)}else this.releaseEntryRetainedPayload(P)}removeChain(P){let J=this.chains.get(P);if(!J)return;for(let Q of J.tokens){let Z=this.entries.get(Q);if(!Z||f(Z))continue;this.entries.delete(Q),this.releaseEntryRetainedPayload(Z,J)}this.chains.delete(P)}releaseEntryRetainedPayload(P,J){if(P.kind==="snapshot"){if(this.frozenSnapshotBytes-=P.frozenBytes,this.retainedPayloadBytes-=P.frozenBytes,J)J.frozenSnapshotBytes-=P.frozenBytes,J.retainedPayloadBytes-=P.frozenBytes;return}if(P.kind==="catalog"){if(this.retainedPayloadBytes-=P.boundaryBytes,J)J.retainedPayloadBytes-=P.boundaryBytes}this.releaseCachedResult(P,J)}releaseCachedResult(P,J){if(P.cachedResultBytes===0){P.cachedResult=void 0;return}if(this.retainedPayloadBytes-=P.cachedResultBytes,J)J.retainedPayloadBytes-=P.cachedResultBytes;P.cachedResult=void 0,P.cachedResultBytes=0}assertAvailable(){if(this.closed)throw _()}}function E(P){if(P.startsWith(D.catalog))return"catalog";if(P.startsWith(D.history))return"history";if(P.startsWith(D.snapshot))return"snapshot";return}function f(P){return P.kind!=="snapshot"&&P.activeLoad!==void 0}function _P(P){let J={idleTtlMs:P.idleTtlMs??NP,maxEntries:P.maxEntries??OP,maxChains:P.maxChains??jP,maxEntriesPerChain:P.maxEntriesPerChain??MP,maxFrozenSnapshotBytes:P.maxFrozenSnapshotBytes??HP};for(let Q of Object.values(J))if(!Number.isSafeInteger(Q)||Q<=0)throw Error("session surface cursor registry limits must be positive safe integers");return J}function _(){return new U("session_surface_unavailable")}function T(P){return B(W(P))}function W(P){try{return S(P,new Set)}catch{throw new U("session_surface_cursor_invalid")}}function S(P,J){if(P===null)return null;if(typeof P==="string"||typeof P==="boolean")return P;if(typeof P==="number"){if(!Number.isFinite(P))throw Error("invalid number");return P}if(typeof P>"u"||typeof P==="function"||typeof P==="symbol"||typeof P==="bigint")throw Error("invalid JSON type");if(!P||typeof P!=="object")throw Error("invalid JSON value");if(J.has(P))throw Error("cycle");J.add(P);try{if(Array.isArray(P)){let $=[];for(let G=0;G<P.length;G+=1){if(!(G in P))throw Error("sparse array");$.push(S(P[G],J))}return $}if(Object.getOwnPropertySymbols(P).length>0)throw Error("symbol keys");let Q=Object.getPrototypeOf(P);if(Q!==Object.prototype&&Q!==null)throw Error("non-plain object");let Z={};for(let $ of Object.keys(P)){let G=Reflect.get(P,$);if(G===void 0)throw Error("undefined object value");Z[$]=S(G,J)}return Z}finally{J.delete(P)}}function B(P){if(P===null)return"null";if(typeof P==="string"||typeof P==="number")return JSON.stringify(P);if(typeof P==="boolean")return P?"true":"false";if(Array.isArray(P))return`[${P.map((Q)=>B(Q)).join(",")}]`;return`{${Object.keys(P).sort().map((Q)=>`${JSON.stringify(Q)}:${B(P[Q])}`).join(",")}}`}function m(P,J={}){if(P===void 0){if(J.allowUndefined)return{value:void 0,bytes:0};throw new U("session_surface_cursor_invalid")}let Q=W(P);return{value:Q,bytes:Buffer.byteLength(B(Q),"utf8")}}import{createHash as C,randomBytes as F}from"node:crypto";import FP from"node:path";var YP=50,zP=100,AP=16,TP=1e4,DP=16777216;class z extends Error{code;retryable;constructor(P){let J=CP(P);super(J.message);this.code=P;this.name="SessionSurfaceServiceError",this.retryable=J.retryable}}class BP{database;registry;epoch;maxConcurrentOperations;activeControllers=new Set;activeOperations=new Set;closed=!1;closePromise;concurrentOperations=0;constructor(P={}){if(this.database=P.database,this.registry=P.cursorRegistry??new g(P.cursorRegistryOptions),this.epoch=P.epochSource?.()??`session-surface-epoch:${F(32).toString("base64url")}`,this.maxConcurrentOperations=P.maxConcurrentOperations??AP,!Number.isSafeInteger(this.maxConcurrentOperations)||this.maxConcurrentOperations<1||this.maxConcurrentOperations>256)throw Error("maxConcurrentOperations must be an integer from 1 to 256")}async listPage(P={}){return this.runOperation(async(J)=>{let Q=K(P.limit),Z=P.archived??!1,$={archived:Z,limit:Q,workspaceKind:P.workspaceKind??null},G=JSON.stringify([Z,P.workspaceKind??null]),Y=await this.requireDatabase();if(J.throwIfAborted(),!Y)return this.listFallbackPage($,G,J,P.cursor);if(await this.syncAllSurfaces(Y,J),P.cursor){let V=String(ZP(Y));return this.registry.redeemCatalogCursor({token:P.cursor,scopeKey:G,epoch:this.epoch,revision:V,request:$,loader:async({boundary:X})=>{let O=KP(X);return this.loadCatalogPage(Y,$,G,V,O,O.chainId,J)}})}return this.loadCatalogPage(Y,$,G,void 0,void 0,void 0,J)})}async open(P,J={}){return this.runOperation((Q)=>this.openInternal(P,J,Q))}async historyPage(P,J){return this.runOperation(async(Q)=>{let Z=I(P),$=K(J.limit);if(!J.cursor||!J.expectedSnapshot)throw new z("invalid_session_surface_request");let G=await this.requireDatabase();if(!G)return this.readFallbackHistoryPage(Z,J,Q);await this.syncForLocator(G,Z,Q);let Y=await this.resolveFromProjection(G,Z,Q),V=w(G,{sourceKind:Y.candidate.sourceKind,projectPath:Y.candidate.projectPath,sessionId:Y.candidate.sessionId,limit:1}),X=x(Z);await this.registry.assertSnapshotToken({token:J.expectedSnapshot,locatorDigest:X,transcriptFingerprint:V.transcriptFingerprint});let O={expectedSnapshot:J.expectedSnapshot,limit:$},j=await this.registry.redeemHistoryCursor({token:J.cursor,locatorDigest:X,transcriptFingerprint:V.transcriptFingerprint,request:O,loader:async({nextSequence:M})=>{let H=w(G,{sourceKind:Y.candidate.sourceKind,projectPath:Y.candidate.projectPath,sessionId:Y.candidate.sessionId,beforeSequence:M,limit:$});return this.publicHistoryPage({history:H,snapshot:J.expectedSnapshot,chainId:(await this.registry.assertSnapshotToken({token:J.expectedSnapshot,locatorDigest:X,transcriptFingerprint:V.transcriptFingerprint})).chainId,locatorDigest:X,limit:$})}});return A.parse(j)})}async fork(P){return this.runOperation(async(J)=>{let Q=I(P),Z=await this.requireDatabase(),$=Z?await this.resolveFromProjectionAfterSync(Z,Q,J):await this.resolveFallback(Q,J);if($.candidate.summary.archivedAt)throw new z("session_surface_read_only");J.throwIfAborted();let G=await N.forkSession(Q.sessionId,{sourceProjectPath:$.candidate.projectPath,targetProjectPath:$.candidate.projectPath,...$.remoteCandidate?{remote:{expectedDescriptor:$.remoteCandidate.descriptor}}:{}}),Y=$.remoteCandidate?{version:2,sessionId:G.sessionId,workspace:{kind:"acp-remote",workspaceRef:$.candidate.publicWorkspaceRef}}:{version:2,sessionId:G.sessionId,workspace:{kind:"local",projectPath:$.candidate.projectPath}};return Z?this.openInternal(Y,{},J):this.openFallback(Y,YP,J)})}async resolveFromProjectionAfterSync(P,J,Q){return await this.syncForLocator(P,J,Q),this.resolveFromProjection(P,J,Q)}async close(P){if(this.closePromise)return this.closePromise;this.closed=!0;for(let J of this.activeControllers)J.abort(new z("session_surface_unavailable"));return this.closePromise=Promise.allSettled([...this.activeOperations,this.registry.close()]).then(()=>{return}),this.closePromise}async openInternal(P,J={},Q){let Z=I(P),$=K(J.limit);if(J.cursor!==void 0||J.expectedSnapshot!==void 0)throw new z("invalid_session_surface_request");let G=await this.requireDatabase();if(!G)return this.openFallback(Z,$,Q);await this.syncForLocator(G,Z,Q);let Y=await this.resolveFromProjection(G,Z,Q),V=w(G,{sourceKind:Y.candidate.sourceKind,projectPath:Y.candidate.projectPath,sessionId:Y.candidate.sessionId,limit:$}),X=`history-chain:${F(16).toString("base64url")}`,O=x(Z),j=this.registry.issueSnapshotToken({chainId:X,locatorDigest:O,transcriptFingerprint:V.transcriptFingerprint}),M={session:this.toSummary(Y),history:this.publicHistoryPage({history:V,snapshot:j,chainId:X,locatorDigest:O,limit:$})};return p.parse(M)}runOperation(P){if(this.assertAvailable(),this.concurrentOperations>=this.maxConcurrentOperations)throw new z("session_surface_capacity");let J=new AbortController;this.activeControllers.add(J),this.concurrentOperations+=1;let Q;return Q=Promise.resolve().then(()=>P(J.signal)).then((Z)=>{if(J.signal.aborted||this.closed)throw new z("session_surface_unavailable");return Z}).catch((Z)=>{if(J.signal.aborted||this.closed)throw new z("session_surface_unavailable");throw kP(Z)}).finally(()=>{this.activeControllers.delete(J),this.activeOperations.delete(Q),this.concurrentOperations-=1}),this.activeOperations.add(Q),Q}async loadCatalogPage(P,J,Q,Z,$,G,Y){let V=$P(P,{archived:J.archived,limit:J.limit,...J.workspaceKind?{workspaceKind:J.workspaceKind}:{},...$?{boundary:$}:{}}),X=String(V.revision);if(Z!==void 0&&Z!==X)throw new z("session_surface_snapshot_changed");let O=G??`catalog-chain:${F(16).toString("base64url")}`,j={sessions:await Promise.all(V.sessions.map(async(M)=>this.toSummary(await this.resolveCandidate(M,Y)))),...V.nextBoundary?{nextCursor:this.registry.issueCatalogCursor({chainId:O,scopeKey:Q,epoch:this.epoch,revision:X,boundary:{...V.nextBoundary,chainId:O},request:J})}:{}};if(!V.nextBoundary)this.registry.completeChain(O);return y.parse(j)}publicHistoryPage(P){let J=h(P.history.messages,L()),Q={messages:J.messages,snapshot:P.snapshot,truncated:P.history.hasOlder||J.truncated||J.messages.some((Z)=>Z.truncated===!0),...P.history.hasOlder&&P.history.nextSequence!==void 0?{olderCursor:this.registry.issueHistoryCursor({chainId:P.chainId,locatorDigest:P.locatorDigest,transcriptFingerprint:P.history.transcriptFingerprint,nextSequence:P.history.nextSequence,snapshotToken:P.snapshot,request:{expectedSnapshot:P.snapshot,limit:P.limit}})}:{}};if(!P.history.hasOlder)this.registry.completeChain(P.chainId);return A.parse(Q)}async syncForLocator(P,J,Q){if(Q?.throwIfAborted(),J.workspace.kind==="local"){await N.findSessionMetadata(J.sessionId,J.workspace.projectPath),Q?.throwIfAborted(),await d(P,J.sessionId,J.workspace.projectPath,N.projectionDeriverForSearch(),void 0,"local",Q);return}await N.listValidatedRemoteSurfaceCandidates(Q),await l(P,N.projectionDeriverForSearch(),Q)}async syncAllSurfaces(P,J){let Q=N.projectionDeriverForSearch(),Z=await N.listValidatedLocalSurfaceCandidates(J),$=new Set(Z.map((Y)=>`${Y.projectPath}\x00${Y.sessionId}`)),G=P.prepare("SELECT project_path, session_id FROM sessions WHERE source_kind='local'").all();for(let Y of G)if(!$.has(`${Y.project_path}\x00${Y.session_id}`))JP(P,Y.session_id,Y.project_path,"local");for(let Y of Z)J?.throwIfAborted(),await d(P,Y.sessionId,Y.projectPath,Q,void 0,"local",J);await N.listValidatedRemoteSurfaceCandidates(J),await l(P,Q,J)}async listFallbackPage(P,J,Q,Z){if(Z)return this.registry.redeemCatalogCursor({token:Z,scopeKey:J,epoch:this.epoch,revision:"fallback",request:P,loader:async({boundary:G})=>{let Y=LP(G);return this.pageFallbackCatalog(Y.entries,P,J,Y.chainId)}});let $=await this.loadFallbackCatalog(P,Q);return this.pageFallbackCatalog($,P,J,`catalog-fallback:${F(16).toString("base64url")}`)}async loadFallbackCatalog(P,J){let Q=[];if(P.workspaceKind!=="acp-remote")for(let $ of await N.listValidatedLocalSurfaceCandidates(J)){J?.throwIfAborted();let Y=(await N.readValidatedLocalSurfaceSnapshot($.sessionId,$.projectPath,J)).summary;if(Boolean(Y.archivedAt)!==P.archived)continue;Q.push({locator:{version:2,sessionId:$.sessionId,workspace:{kind:"local",projectPath:$.projectPath}},summary:Y})}if(P.workspaceKind!=="local")for(let $ of await N.listValidatedRemoteSurfaceCandidates(J)){J?.throwIfAborted();let Y=(await N.readValidatedRemoteSurfaceSnapshot($,J)).summary;if(Boolean(Y.archivedAt)!==P.archived)continue;Q.push({locator:{version:2,sessionId:$.sessionId,workspace:{kind:"acp-remote",workspaceRef:$.workspaceRef}},summary:Y})}Q.sort(IP);let Z=Buffer.byteLength(JSON.stringify(Q));if(Q.length>TP||Z>DP)throw new z("session_surface_capacity");return Q}async pageFallbackCatalog(P,J,Q,Z){let $=P.slice(0,J.limit),G=P.slice($.length),V={sessions:$.map((X)=>R.parse({locator:X.locator,...X.summary,capabilities:X.locator.workspace.kind==="local"?UP(Boolean(X.summary.archivedAt)):RP(Boolean(X.summary.archivedAt))})),...G.length>0?{nextCursor:this.registry.issueCatalogCursor({chainId:Z,scopeKey:Q,epoch:this.epoch,revision:"fallback",boundary:{chainId:Z,entries:G},request:J})}:{}};if(G.length===0)this.registry.completeChain(Z);return y.parse(V)}async openFallback(P,J,Q){let Z=await this.resolveFallback(P,Q),$=Z.remoteCandidate?await N.readValidatedRemoteSurfaceSnapshot(Z.remoteCandidate,Q):await N.readValidatedLocalSurfaceSnapshot(Z.candidate.sessionId,Z.candidate.projectPath,Q),G=e($.entries,{...Z.remoteCandidate?r(Z.remoteCandidate.hostStateRoot,Z.remoteCandidate.descriptor):{privateRoots:[]},bladeStorageRoots:[o()]}),Y=h(G.slice(-J),L()),V=`history-fallback:${F(16).toString("base64url")}`,X=x(P),O=C("sha256").update(JSON.stringify($.entries)).digest("hex"),j=this.registry.issueSnapshotToken({chainId:V,locatorDigest:X,transcriptFingerprint:O,frozenSnapshot:G}),M={session:this.toSummary(Z),history:A.parse({messages:Y.messages,snapshot:j,truncated:Y.messages.length<G.length||Y.truncated||Y.messages.some((H)=>H.truncated===!0),...G.length>Y.messages.length&&Y.messages[0]?{olderCursor:this.registry.issueHistoryCursor({chainId:V,locatorDigest:X,transcriptFingerprint:O,nextSequence:v(Y.messages[0].id),snapshotToken:j,request:{expectedSnapshot:j,limit:J}})}:{}})};if(G.length<=Y.messages.length)this.registry.completeChain(V);return p.parse(M)}async readFallbackHistoryPage(P,J,Q){let Z=K(J.limit);if(!J.cursor||!J.expectedSnapshot)throw new z("invalid_session_surface_request");let $=x(P),G=await this.resolveFallback(P,Q),Y=G.remoteCandidate?await N.readValidatedRemoteSurfaceSnapshot(G.remoteCandidate,Q):await N.readValidatedLocalSurfaceSnapshot(G.candidate.sessionId,G.candidate.projectPath,Q),V=C("sha256").update(JSON.stringify(Y.entries)).digest("hex");await this.registry.assertSnapshotToken({token:J.expectedSnapshot,locatorDigest:$,transcriptFingerprint:V});let X={expectedSnapshot:J.expectedSnapshot,limit:Z};return this.registry.redeemHistoryCursor({token:J.cursor,locatorDigest:$,transcriptFingerprint:V,request:X,loader:async({nextSequence:O,frozenSnapshot:j})=>{let M=xP(j).filter((b)=>v(b.id)<O),H=h(M.slice(-Z),L()),u=await this.registry.assertSnapshotToken({token:J.expectedSnapshot,locatorDigest:$,transcriptFingerprint:V}),k=H.messages.length<M.length,VP={messages:H.messages,snapshot:J.expectedSnapshot,truncated:k||H.truncated||H.messages.some((b)=>b.truncated===!0),...k&&H.messages[0]?{olderCursor:this.registry.issueHistoryCursor({chainId:u.chainId,locatorDigest:$,transcriptFingerprint:V,nextSequence:v(H.messages[0].id),snapshotToken:J.expectedSnapshot,request:X})}:{}};if(!k)this.registry.completeChain(u.chainId);return A.parse(VP)}})}async resolveFallback(P,J){let Q=[];for(let G of[!1,!0]){let Y={archived:G,limit:zP,workspaceKind:P.workspace.kind};Q.push(...(await this.loadFallbackCatalog(Y,J)).filter((V)=>JSON.stringify(V.locator)===JSON.stringify(P)))}if(Q.length!==1)throw new z("session_surface_not_found");let Z=Q[0],$;if(P.workspace.kind==="acp-remote"){let G=P.workspace.workspaceRef;if($=(await N.listValidatedRemoteSurfaceCandidates(J)).find((Y)=>Y.sessionId===P.sessionId&&Y.workspaceRef===G),!$)throw new z("workspace_binding_mismatch")}return{candidate:{sourceKind:P.workspace.kind,projectPath:P.workspace.kind==="local"?P.workspace.projectPath:$.hostStateRoot,sessionId:P.sessionId,...P.workspace.kind==="acp-remote"?{publicWorkspaceRef:P.workspace.workspaceRef}:{},publicWorkspaceSortKey:"",surfaceDigest:i(Z),transcriptFingerprint:i(Z),lastMessageTime:Z.summary.lastMessageTime,sessionSortKey:"",summary:Z.summary},...$?{remoteCandidate:$}:{}}}async resolveFromProjection(P,J,Q){let Z=QP(P,J.sessionId).filter((G)=>J.workspace.kind==="local"?G.sourceKind==="local"&&G.projectPath===FP.resolve(J.workspace.projectPath):G.sourceKind==="acp-remote"&&G.publicWorkspaceRef===J.workspace.workspaceRef);if(Z.length!==1)throw new z(Z.length===0?"session_surface_not_found":"workspace_binding_mismatch");let $;if(J.workspace.kind==="acp-remote"){let G=J.workspace.workspaceRef;if($=(await N.listValidatedRemoteSurfaceCandidates(Q)).filter((Y)=>Y.sessionId===J.sessionId&&Y.workspaceRef===G),$.length===0)throw new z("workspace_binding_mismatch");if($.length>1)throw new z("session_surface_state_invalid")}return $?{candidate:Z[0],remoteCandidate:$[0]}:{candidate:Z[0]}}async resolveCandidate(P,J){if(P.sourceKind==="local")return{candidate:P};let Q=(await N.listValidatedRemoteSurfaceCandidates(J)).filter((Z)=>Z.sessionId===P.sessionId&&Z.workspaceRef===P.publicWorkspaceRef);if(Q.length!==1)throw new z(Q.length===0?"workspace_binding_mismatch":"session_surface_state_invalid");return{candidate:P,remoteCandidate:Q[0]}}toSummary(P){let J=P.candidate,Q=J.sourceKind==="local"?{version:2,sessionId:J.sessionId,workspace:{kind:"local",projectPath:J.projectPath}}:{version:2,sessionId:J.sessionId,workspace:{kind:"acp-remote",workspaceRef:J.publicWorkspaceRef}};return R.parse({locator:Q,...J.summary,capabilities:this.capabilitiesFor(P)})}capabilitiesFor(P){let J=P.candidate.summary.archivedAt!==void 0;if(!P.remoteCandidate)return{connection:"local",history:{read:!0,fork:!J},turn:J?{start:!1,reason:"archived"}:{start:!0},files:J?{readText:!1,writeText:!1,browse:"none",reason:"archived"}:{readText:!0,writeText:!0,browse:"tree"},terminal:J?{mode:"none",owner:"none",reason:"archived"}:{mode:"interactive",owner:"local"}};return{connection:GP.getRemoteSurfaceOwnerSnapshot(P.candidate.sessionId,P.remoteCandidate.descriptor).connection,history:{read:!0,fork:!J},turn:{start:!1,reason:J?"archived":"history-only"},files:{readText:!1,writeText:!1,browse:"none",reason:J?"archived":"history-only"},terminal:{mode:"none",owner:"none",reason:J?"archived":"history-only"}}}async requireDatabase(){if(this.database===null)return null;return this.database??await PP()}assertAvailable(){if(this.closed)throw new z("session_surface_unavailable")}}function K(P){let J=P??YP;if(!Number.isSafeInteger(J)||J<1||J>zP)throw new z("invalid_session_surface_request");return J}function I(P){try{let J=t.parse(P);if(!n(J.sessionId))throw Error("invalid");if(J.workspace.kind==="local"){if(s(J.workspace.projectPath)!==J.workspace.projectPath)throw Error("invalid")}return J}catch{throw new z("invalid_session_locator")}}function x(P){return C("sha256").update("session-surface-locator-v2\x00").update(JSON.stringify(P)).digest("hex")}function KP(P){if(!P||typeof P!=="object"||Array.isArray(P))throw new z("session_surface_cursor_invalid");let J=P;if(typeof J.lastMessageTime!=="string"||J.sourceKind!=="local"&&J.sourceKind!=="acp-remote"||typeof J.publicWorkspaceSortKey!=="string"||typeof J.sessionSortKey!=="string"||typeof J.chainId!=="string"||!J.chainId)throw new z("session_surface_cursor_invalid");return{lastMessageTime:J.lastMessageTime,sourceKind:J.sourceKind,publicWorkspaceSortKey:J.publicWorkspaceSortKey,sessionSortKey:J.sessionSortKey,chainId:J.chainId}}function h(P,J){let Q=[];for(let Z=P.length-1;Z>=0;Z-=1){let $=P[Z];if(!$)continue;let G=[$,...Q];if(Q.length>0&&Buffer.byteLength(JSON.stringify(G))>J)break;Q.unshift($)}return{messages:Q,truncated:Q.length<P.length}}function v(P){let J=/^surface-message:([0-9]+):/.exec(P),Q=J?Number(J[1]):Number.NaN;if(!Number.isSafeInteger(Q)||Q<=0)throw new z("session_surface_state_invalid");return Q}function xP(P){if(!Array.isArray(P))throw new z("session_surface_snapshot_changed");return P.map((J)=>{try{return a.parse(J)}catch{throw new z("session_surface_snapshot_changed")}})}function LP(P){if(!P||typeof P!=="object"||Array.isArray(P))throw new z("session_surface_cursor_invalid");let J=P;if(typeof J.chainId!=="string"||J.chainId.length===0||!Array.isArray(J.entries))throw new z("session_surface_cursor_invalid");let Q=J.entries.map((Z)=>{if(!Z||typeof Z!=="object"||Array.isArray(Z))throw new z("session_surface_cursor_invalid");let $=Z;return{locator:I($.locator),summary:wP($.summary)}});return{chainId:J.chainId,entries:Q}}function wP(P){let J={version:2,sessionId:"placeholder",workspace:{kind:"local",projectPath:"/"}},Q=R.parse({...P&&typeof P==="object"&&!Array.isArray(P)?P:{},locator:J,capabilities:UP(!1)}),{locator:Z,capabilities:$,...G}=Q;return G}function IP(P,J){if(P.summary.lastMessageTime>J.summary.lastMessageTime)return-1;if(P.summary.lastMessageTime<J.summary.lastMessageTime)return 1;if(P.locator.workspace.kind!==J.locator.workspace.kind)return P.locator.workspace.kind==="local"?-1:1;let Q=P.locator.workspace.kind==="local"?P.locator.workspace.projectPath:P.locator.workspace.workspaceRef,Z=J.locator.workspace.kind==="local"?J.locator.workspace.projectPath:J.locator.workspace.workspaceRef;if(Q<Z)return-1;if(Q>Z)return 1;return P.locator.sessionId<J.locator.sessionId?-1:P.locator.sessionId>J.locator.sessionId?1:0}function i(P){return C("sha256").update("session-surface-fallback-entry\x00").update(JSON.stringify(P)).digest("hex")}function UP(P){return{connection:"local",history:{read:!0,fork:!P},turn:P?{start:!1,reason:"archived"}:{start:!0},files:P?{readText:!1,writeText:!1,browse:"none",reason:"archived"}:{readText:!0,writeText:!0,browse:"tree"},terminal:P?{mode:"none",owner:"none",reason:"archived"}:{mode:"interactive",owner:"local"}}}function RP(P){return{connection:"offline",history:{read:!0,fork:!P},turn:{start:!1,reason:P?"archived":"history-only"},files:{readText:!1,writeText:!1,browse:"none",reason:P?"archived":"history-only"},terminal:{mode:"none",owner:"none",reason:P?"archived":"history-only"}}}function CP(P){if(P==="session_surface_cursor_invalid")return{message:"Session surface cursor is invalid",retryable:!1};if(P==="session_surface_snapshot_changed")return{message:"Session surface snapshot changed",retryable:!1};if(P==="session_surface_state_invalid")return{message:"Session surface state is invalid",retryable:!1};if(P==="session_surface_capability_unavailable")return{message:"Session surface capability is unavailable",retryable:!1};if(P==="session_surface_unavailable")return{message:"Session surface is unavailable",retryable:!0};if(P==="session_surface_not_found")return{message:"Session surface was not found",retryable:!1};if(P==="workspace_binding_mismatch")return{message:"Session workspace binding changed",retryable:!1};if(P==="session_surface_read_only")return{message:"Session surface is read only",retryable:!1};if(P==="session_surface_capacity")return{message:"Session surface capacity is exhausted",retryable:!0};if(P==="invalid_session_locator")return{message:"Session locator is invalid",retryable:!1};return{message:"Session surface request is invalid",retryable:!1}}function kP(P){if(P instanceof z)return P;if(P&&typeof P==="object"&&"code"in P&&typeof P.code==="string"){let J=P.code;if(J==="session_surface_cursor_invalid"||J==="session_surface_snapshot_changed"||J==="session_surface_capacity"||J==="session_surface_unavailable"||J==="session_surface_state_invalid")return new z(J);if(J==="acp_remote_workspace_state_invalid")return new z("session_surface_state_invalid")}return P instanceof Error?P:new z("session_surface_state_invalid")}
|
|
2
2
|
export{qP as e,EP as f,g,z as h,BP as i};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{j as i}from"./chunk-
|
|
1
|
+
import{j as i}from"./chunk-pv6cgfv1.js";import{aj as s}from"./chunk-jsv3e4k6.js";import"./chunk-7xtxvrh8.js";import"./chunk-sdapqhj0.js";import m from"node:path";var r={registry:i,currentWorkspace:s,inputCwd:()=>process.cwd(),write:console.log};function c(t,e){return m.resolve(e.inputCwd(),t)}function p(t){return t.map((e)=>{let o=e.isCurrent?"*":" ",n=e.gitBranch?` · ${e.gitBranch}`:"",d=e.available?"":" · unavailable";return`${o} ${e.name}${n}${d}
|
|
2
2
|
${e.path}`}).join(`
|
|
3
3
|
`)}async function l(t,e=r){let o=await e.registry.list(e.currentWorkspace());return e.write(t.json?JSON.stringify(o,null,2):p(o)),o}async function u(t,e=r){let o=await e.registry.bind(c(t.path,e),e.currentWorkspace());return e.write(t.json?JSON.stringify(o,null,2):`Bound project: ${o.path}`),o}async function j(t,e=r){let o=c(t.path,e),n=await e.registry.unbind(o);return e.write(t.json?JSON.stringify({path:o,removed:n},null,2):n?`Unbound project: ${o}`:`Project was not bound: ${o}`),n}var a={type:"boolean",default:!1,describe:"Print machine-readable JSON"},P={command:"list",aliases:["ls"],describe:"List bound projects",builder:(t)=>t.option("json",a),handler:async(t)=>{await l(t)}},b={command:"add <path>",aliases:["bind"],describe:"Bind a project folder",builder:(t)=>t.positional("path",{type:"string",demandOption:!0,describe:"Absolute or relative project folder"}).option("json",a),handler:async(t)=>{await u(t)}},h={command:"remove <path>",aliases:["rm","unbind"],describe:"Unbind a project folder",builder:(t)=>t.positional("path",{type:"string",demandOption:!0,describe:"Absolute or relative project folder"}).option("json",a),handler:async(t)=>{await j(t)}},y={command:"projects",aliases:["project"],describe:"Manage project bindings shared with Blade Web",builder:(t)=>t.command(P).command(b).command(h).demandCommand(1,"Choose list, add, or remove"),handler:()=>{return}};export{j as runProjectsRemove,l as runProjectsList,u as runProjectsAdd,y as projectsCommands,p as formatProjectList};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Zi as L,aj as _}from"./chunk-jsv3e4k6.js";import{execSync as F}from"child_process";import{existsSync as Q,readFileSync as O,realpathSync as b}from"fs";import*as V from"os";import*as H from"path";import{basename as J,isAbsolute as j,resolve as R}from"path";function G(z=_()){let q=z,M=f(q);return{workingDirectory:q,projectRoot:M,platform:`${V.platform()} (${V.arch()})`,nodeVersion:process.version,currentDate:new Date().toISOString().split("T")[0],homeDirectory:V.homedir()}}function Y(z,q){try{return F(q,{cwd:z,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch{return null}}function v(z={}){let{includeGitSnapshot:q=!0,includeDirectoryListing:M=!0,workingDirectory:W}=z,B=G(W),$=Q(H.join(B.projectRoot,".git")),T=J(process.env.SHELL||"unknown"),A=["package.json","tsconfig.json","BLADE.md",".env.example"].filter((K)=>Q(H.join(B.projectRoot,K))).map((K)=>`- \`${H.join(B.projectRoot,K)}\``),N=`# Environment
|
|
2
2
|
You have been invoked in the following environment:
|
|
3
3
|
- Primary working directory: ${B.workingDirectory}
|
|
4
4
|
- Is a git repository: ${$?"true":"false"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{vh as Q}from"./chunk-erhaedch.js";import{Ej as F,Gj as k,Jj as G}from"./chunk-5q4z0sfr.js";var V=k.String({minLength:1,maxLength:128,pattern:"^[A-Za-z0-9][A-Za-z0-9_-]*$"}),K=k.Array(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"}),{maxItems:128}),W=k.Object({description:k.String({minLength:1,maxLength:4096,pattern:".*\\S.*"}),prompt:k.String({minLength:1,maxLength:1e5,pattern:".*\\S.*"}),tools:k.Optional(K),disallowedTools:k.Optional(K),model:k.Optional(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"})),permissionMode:k.Optional(G(["default","acceptEdits","dontAsk","bypassPermissions","plan","ignore"])),maxTurns:k.Optional(k.Integer({minimum:1})),isolation:k.Optional(G(["none","worktree"]))},{additionalProperties:!1});function Z(R){let w;try{w=JSON.parse(R)}catch{throw Error("Invalid JSON provided to --agents")}if(w===null||Array.isArray(w)||typeof w!=="object")throw Error("--agents must be a JSON object");let H=Object.entries(w);if(H.length>64)throw Error("--agents supports at most 64 definitions");return H.map(([z,U])=>{if(!F(V,z).success)throw Error(`Invalid --agents name "${z}": use letters, numbers, hyphens, or underscores`);let I=F(W,U);if(!I.success)throw Error(`Invalid --agents definition for "${z}"`);let q=I.data;return{name:z,description:q.description.trim(),systemPrompt:q.prompt.trim(),tools:q.tools?[...new Set(q.tools.map((B)=>B.trim()))]:void 0,disallowedTools:q.disallowedTools?[...new Set(q.disallowedTools.map((B)=>B.trim()))]:void 0,model:q.model?.trim(),permissionMode:q.permissionMode===void 0?void 0:Q(q.permissionMode),maxTurns:q.maxTurns,isolation:q.isolation,source:"flag"}})}
|
|
2
2
|
export{Z as vf};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{V as I}from"./chunk-
|
|
1
|
+
import{V as I}from"./chunk-d0q5n5ea.js";import{ge as M}from"./chunk-qmveehgt.js";import P from"node:path";function w(s){let a=s.replace(/\s+/g," ").trim();return a.length<=72?a:`${a.slice(0,69)}...`}function W(s){let a=s.replace(/\s+/g," ").trim();return a.length<=500?a:`${a.slice(0,497)}...`}function A(s){return`task/${s.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class C{static async createSessionTask(s){if(!s.prompt.trim())throw Error("Task prompt must not be blank");if(!P.isAbsolute(s.sourceProjectPath))throw Error("Task source project path must be absolute");let a=P.resolve(s.sourceProjectPath),t;try{return t=s.isolation==="worktree"?await I.enter({sessionId:s.sessionId,workspaceRoot:a,name:A(s.sessionId)}):void 0,{metadata:await M.createSessionMetadata(s.sessionId,t?.workspaceRoot??a,{title:s.title?.trim()||w(s.prompt),taskPromptSummary:W(s.prompt),taskPriority:s.taskPriority,taskKind:s.taskKind,taskDueAt:s.taskDueAt,taskDispatch:s.dispatch,taskModelId:s.dispatch?.modelId,selectedModelId:s.dispatch?.modelId,permissionMode:s.dispatch?.permissionMode,reasoningEffort:s.dispatch?.reasoningEffort,serviceTier:s.dispatch?.serviceTier,responseVerbosity:s.dispatch?.responseVerbosity,communicationStyle:s.dispatch?.communicationStyle,communicationStyleDigest:s.dispatch?.communicationStyleDigest,projectInstructionsDigest:s.dispatch?.projectInstructionsDigest,taskRetriedFrom:s.retriedFrom,taskIsolation:s.isolation,taskSourceProjectPath:a,taskWorktree:t}),taskWorktree:t}}catch(k){if(t)await I.exit({sessionId:s.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw k}}}var $=256,V=8388608,x=30000;class i extends Error{kind;pendingItems;pendingBytes;constructor(s,a,t){super(a,t);this.kind=s;this.name="BoundedSerialEgressError",this.pendingItems=t?.pendingItems,this.pendingBytes=t?.pendingBytes}}function T(s){s.catch(()=>{return})}class K{options;pending=[];flushWaiters=[];pendingBytes=0;nextSequence=0;completedSequence=0;draining=!1;closed=!1;failure;activeWriteAbort;activeWriteStop;activeWriteTimeout;constructor(s){this.options=s;if(this.assertPositiveInteger(s.maxPendingItems,"maxPendingItems"),this.assertPositiveInteger(s.maxPendingBytes,"maxPendingBytes"),this.assertPositiveInteger(s.writeTimeoutMs,"writeTimeoutMs"),s.signal?.addEventListener("abort",this.handleAbort,{once:!0}),s.signal?.aborted)this.handleAbort()}offer(s){if(this.closed)return{accepted:!1,error:this.failure??new i("closed","Egress is already closed")};let a;try{a=this.options.sizeOf(s)}catch(h){return this.rejectAdmission(new i("invalid_size","Egress size calculation failed",{cause:h}))}if(!Number.isSafeInteger(a)||a<0)return this.rejectAdmission(new i("invalid_size","Egress size must be a non-negative safe integer"));if(a>this.options.maxPendingBytes)return this.rejectAdmission(new i("oversized",`Egress value requires ${a} bytes; limit is ${this.options.maxPendingBytes}`));if(this.pending.length>=this.options.maxPendingItems||this.pendingBytes+a>this.options.maxPendingBytes)return this.rejectAdmission(new i("overflow",`Egress pending limit exceeded (${this.pending.length} items, ${this.pendingBytes} bytes)`));let t,k,c=new Promise((h,m)=>{t=h,k=m});return T(c),this.nextSequence+=1,this.pending.push({value:s,bytes:a,sequence:this.nextSequence,resolve:t,reject:k,completion:c}),this.pendingBytes+=a,this.startDrain(),{accepted:!0,completion:c}}flush(){if(this.failure){let c=Promise.reject(this.failure);return T(c),c}let s=this.nextSequence;if(s<=this.completedSequence)return Promise.resolve();let a,t,k=new Promise((c,h)=>{a=c,t=h});return T(k),this.flushWaiters.push({targetSequence:s,resolve:a,reject:t}),k}close(s){let a=s instanceof i?s:new i("closed","Egress was closed",{cause:s});this.fail(a)}stats(){return{closed:this.closed,pendingItems:this.pending.length,pendingBytes:this.pendingBytes}}handleAbort=()=>{this.fail(new i("aborted","Egress was aborted",{cause:this.options.signal?.reason}))};rejectAdmission(s){return this.fail(s),{accepted:!1,error:s}}startDrain(){if(this.draining||this.closed)return;this.draining=!0;let s=this.drain();T(s)}async drain(){try{while(!this.closed){let s=this.pending[0];if(!s)return;try{await this.writeOne(s.value)}catch(a){this.fail(this.normalizeWriteError(a));return}if(this.closed||this.pending[0]!==s)return;this.pending.shift(),this.pendingBytes-=s.bytes,this.completedSequence=s.sequence,s.resolve(),this.settleFlushWaiters()}}finally{if(this.draining=!1,!this.closed&&this.pending.length>0)this.startDrain()}}async writeOne(s){let a=new AbortController;this.activeWriteAbort=a;let t,k,c=new Promise((S,f)=>{k=f});T(c),this.activeWriteStop=k;let h=Promise.resolve().then(()=>this.options.write(s,a.signal));T(h);let m=new Promise((S,f)=>{t=setTimeout(()=>{let D=new i("write_timeout",`Egress write timed out after ${this.options.writeTimeoutMs}ms`);a.abort(D),f(D)},this.options.writeTimeoutMs),this.activeWriteTimeout=t});T(m);try{await Promise.race([h,m,c])}finally{if(t!==void 0)clearTimeout(t);if(this.activeWriteTimeout===t)this.activeWriteTimeout=void 0;if(this.activeWriteAbort===a)this.activeWriteAbort=void 0;if(this.activeWriteStop===k)this.activeWriteStop=void 0}}normalizeWriteError(s){if(s instanceof i)return s;return new i("write_failed","Egress write failed",{cause:s})}fail(s){if(this.closed)return;if(s.pendingItems??=this.pending.length,s.pendingBytes??=this.pendingBytes,this.closed=!0,this.failure=s,this.options.signal?.removeEventListener("abort",this.handleAbort),this.activeWriteTimeout!==void 0)clearTimeout(this.activeWriteTimeout),this.activeWriteTimeout=void 0;this.activeWriteAbort?.abort(s),this.activeWriteStop?.(s),this.activeWriteAbort=void 0,this.activeWriteStop=void 0;let a=this.pending.splice(0);this.pendingBytes=0;for(let t of a)t.reject(s);for(let t of this.flushWaiters.splice(0))t.reject(s);try{this.options.onFailure?.(s)}catch{}}settleFlushWaiters(){for(let s=0;s<this.flushWaiters.length;){let a=this.flushWaiters[s];if(a.targetSequence>this.completedSequence){s+=1;continue}this.flushWaiters.splice(s,1),a.resolve()}}assertPositiveInteger(s,a){if(!Number.isSafeInteger(s)||s<=0)throw RangeError(`${a} must be a positive safe integer`)}}
|
|
2
2
|
export{C as B,$ as C,V as D,x as E,i as F,K as G};
|