blade-code 0.10.139 → 0.10.140
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-6qhbdcse.js → chunk-08z32sky.js} +2 -2
- package/dist/{chunk-mec8yedz.js → chunk-0c2y17xy.js} +1 -1
- package/dist/{chunk-x3c718v5.js → chunk-0kghtvxj.js} +2 -2
- package/dist/{chunk-3eskgvpy.js → chunk-0sx7ak0b.js} +1 -1
- package/dist/{chunk-sj4gz23a.js → chunk-15fpc0qg.js} +1 -1
- package/dist/{chunk-mtfjwsn2.js → chunk-19zsecpx.js} +2 -2
- package/dist/{chunk-7pg5y3pg.js → chunk-1myft5nb.js} +1 -1
- package/dist/chunk-1nreg14s.js +1 -0
- package/dist/{chunk-z9qv0d6k.js → chunk-2d3zksr0.js} +1 -1
- package/dist/{chunk-sdhdn0yx.js → chunk-2ff55pvt.js} +3 -3
- package/dist/{chunk-65c3vjwm.js → chunk-2g8avyq6.js} +1 -1
- package/dist/chunk-3kvt23m3.js +1 -0
- package/dist/chunk-4rh40xhc.js +1 -0
- package/dist/chunk-4xr4hz19.js +2 -0
- package/dist/{chunk-zz5n2qxk.js → chunk-50m1czz9.js} +1 -1
- package/dist/{chunk-earhezc8.js → chunk-5cw3bevx.js} +1 -1
- package/dist/{chunk-9m7d3ajv.js → chunk-5jq1mrqd.js} +1 -1
- package/dist/chunk-61yd46c0.js +1 -0
- package/dist/{chunk-8py443a5.js → chunk-6zxm9pen.js} +1 -1
- package/dist/{chunk-25r1v5rn.js → chunk-7eepxhcp.js} +34 -34
- package/dist/{chunk-jy7k2dwm.js → chunk-85b3kacc.js} +2 -2
- package/dist/chunk-8774agqd.js +1 -0
- package/dist/chunk-8brb7c6j.js +6 -0
- package/dist/{chunk-hrcz179j.js → chunk-8fx20am1.js} +2 -2
- package/dist/{chunk-16648v5c.js → chunk-8vqhcx3s.js} +1 -1
- package/dist/{chunk-6ezffjq1.js → chunk-9ced7jf0.js} +1 -1
- package/dist/chunk-abpmpyqa.js +1 -0
- package/dist/{chunk-yvmexv2c.js → chunk-ascjys4e.js} +1 -1
- package/dist/chunk-bb0z7c3g.js +1 -0
- package/dist/{chunk-5j68055h.js → chunk-c562kd2m.js} +1 -1
- package/dist/{chunk-bgzj85za.js → chunk-cf3dvysj.js} +1 -1
- package/dist/{chunk-bq6d0v5b.js → chunk-cww9pp1q.js} +2 -2
- package/dist/{chunk-7j4s1nrc.js → chunk-d1qe06f0.js} +1 -1
- package/dist/{chunk-40pd090k.js → chunk-e6j4vzta.js} +2 -2
- package/dist/{chunk-3ekz3zms.js → chunk-eh901zhx.js} +2 -2
- package/dist/{chunk-5w8pmsqe.js → chunk-eqe3smcg.js} +2 -2
- package/dist/{chunk-a5hkv8er.js → chunk-es0cbtx1.js} +2 -2
- package/dist/{chunk-gc4kj295.js → chunk-ffkzessq.js} +1 -1
- package/dist/{chunk-dv2m2xe5.js → chunk-g38d2ezm.js} +1 -1
- package/dist/{chunk-v2fewxvw.js → chunk-g4kydkyz.js} +2 -2
- package/dist/{chunk-qrv72yy6.js → chunk-g5scqxq3.js} +2 -2
- package/dist/{chunk-8rccn1y2.js → chunk-gq727fet.js} +1 -1
- package/dist/{chunk-5qwpdx3n.js → chunk-hj1yrssp.js} +1 -1
- package/dist/{chunk-d64b7wta.js → chunk-hvmrcd84.js} +1 -1
- package/dist/{chunk-zx78c1an.js → chunk-kmg8ad2j.js} +1 -1
- package/dist/{chunk-04t21rey.js → chunk-kxwc5wrx.js} +1 -1
- package/dist/chunk-m9dv5177.js +10 -0
- package/dist/{chunk-az08pq83.js → chunk-ma1mn6hn.js} +1 -1
- package/dist/{chunk-t88sfhjj.js → chunk-mnk0b4nz.js} +1 -1
- package/dist/chunk-mwgx87vw.js +1 -0
- package/dist/{chunk-cefmcwyv.js → chunk-n6tvswa8.js} +2 -2
- package/dist/{chunk-fbrdcveb.js → chunk-n8qg68y2.js} +1 -1
- package/dist/chunk-ntq4h4jh.js +1 -0
- package/dist/{chunk-1bqatrxs.js → chunk-nxsarfy6.js} +1 -1
- package/dist/{chunk-ft1bdqbs.js → chunk-pg7cgvs8.js} +2 -2
- package/dist/{chunk-1h3736q2.js → chunk-ppmy3n74.js} +219 -218
- package/dist/{chunk-grx6fv9w.js → chunk-pw9axk0e.js} +2 -2
- package/dist/{chunk-2jq9ed09.js → chunk-pwct7cj7.js} +1 -1
- package/dist/{chunk-esff371k.js → chunk-q9qts6bq.js} +2 -2
- package/dist/chunk-r324qme7.js +1 -0
- package/dist/{chunk-rhwkvx96.js → chunk-r4q06wbs.js} +1 -1
- package/dist/chunk-ra6ksfdy.js +1 -0
- package/dist/{chunk-dw0mewc2.js → chunk-rrtptbzv.js} +2 -2
- package/dist/{chunk-jb4hmk56.js → chunk-svsgtj41.js} +2 -2
- package/dist/{chunk-6j5v5emj.js → chunk-tagzy876.js} +6 -6
- package/dist/{chunk-516adpx6.js → chunk-tecbx0ek.js} +1 -1
- package/dist/chunk-tnts2de5.js +1 -0
- package/dist/chunk-w0710yj4.js +1 -0
- package/dist/{chunk-npc7jt96.js → chunk-w2m4yczv.js} +1 -1
- package/dist/{chunk-mh3ne2sf.js → chunk-w5057h27.js} +2 -2
- package/dist/chunk-we13xwds.js +180 -0
- package/dist/{chunk-f4cn6v8t.js → chunk-xagh2qb6.js} +2 -2
- package/dist/{chunk-05cv54r8.js → chunk-y5bqd8gh.js} +1 -1
- package/dist/{chunk-awheqy52.js → chunk-zfaenqqx.js} +2 -2
- package/dist/chunk-zp5097qk.js +2 -0
- package/dist/web/assets/ChatView-BlAGPVC-.js +63 -0
- package/dist/web/assets/{CodeBlockHighlighter-CYhxXWvb.js → CodeBlockHighlighter-BM1MZv6w.js} +1 -1
- package/dist/web/assets/{FilePreview-ByTaE1GR.js → FilePreview-P77KS9tr.js} +1 -1
- package/dist/web/assets/{KanbanBoard-KMmGvNPc.js → KanbanBoard-B0c7sE2y.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-C6lKOJaG.js → MarkdownRenderer-DHa0FqU0.js} +3 -3
- package/dist/web/assets/{ScrollArea-Bo6cZ3PH.js → ScrollArea-C6yf2fqq.js} +1 -1
- package/dist/web/assets/{SessionHistorySurface-Cymc4xw0.js → SessionHistorySurface-CXYBWqlN.js} +1 -1
- package/dist/web/assets/{SettingsModal-D36xhHwa.js → SettingsModal-BVjVlENY.js} +1 -1
- package/dist/web/assets/{Sidebar-DEGQINYb.js → Sidebar-DDW9Xs6e.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-BEISb7-8.js → TaskSwitcher-D74_5q1F.js} +1 -1
- package/dist/web/assets/{TerminalPanel-B7PXaRGh.js → TerminalPanel-DNEKapEi.js} +1 -1
- package/dist/web/assets/{archive-Dyn5Oz68.js → archive-Ao0WD7pU.js} +1 -1
- package/dist/web/assets/{arrow-left-mWU3P1zb.js → arrow-left-a5_iLemp.js} +1 -1
- package/dist/web/assets/{calendar-clock-B6b0Cb3d.js → calendar-clock-BKbdz6Cu.js} +1 -1
- package/dist/web/assets/{chevron-right-Cl6g5_0e.js → chevron-right-8qYRfCj4.js} +1 -1
- package/dist/web/assets/{chevrons-up-down-FKryGzO4.js → chevrons-up-down-BXNG4GvK.js} +1 -1
- package/dist/web/assets/{clock-3-CfVjvMmA.js → clock-3-DEL1ixyh.js} +1 -1
- package/dist/web/assets/{copy-CIYuf7du.js → copy-Bd5v-KkM.js} +1 -1
- package/dist/web/assets/{download-DecDFX8n.js → download-CIKvpDBW.js} +1 -1
- package/dist/web/assets/{external-link-DaSwvjf7.js → external-link-B33h3DQN.js} +1 -1
- package/dist/web/assets/{folder-DZtlKvFm.js → folder-lOczceoh.js} +1 -1
- package/dist/web/assets/index-hZ37pkxs.js +203 -0
- package/dist/web/assets/{pause-Bd-STGLc.js → pause-nnvVbgsj.js} +1 -1
- package/dist/web/assets/{pencil-BoTIqqxX.js → pencil-_yfoOmUq.js} +1 -1
- package/dist/web/assets/{play-C4ctis0t.js → play-BilJ7SDs.js} +1 -1
- package/dist/web/assets/{plus-D08TlGJu.js → plus-BqqpYKaK.js} +1 -1
- package/dist/web/assets/{session-events-DKjIMNKI.js → session-events-FPOvcMBw.js} +19 -19
- package/dist/web/assets/{settings-BGRhMFaU.js → settings-CmJXtYTH.js} +1 -1
- package/dist/web/assets/{team-CPme0l2K.js → team-Bb04o2Tb.js} +1 -1
- package/dist/web/assets/{teamService-CVCtTVfY.js → teamService-B5w9cpsa.js} +1 -1
- package/dist/web/assets/{terminal-D7GsyYki.js → terminal-DOjdChj0.js} +1 -1
- package/dist/web/index.html +1 -1
- package/package.json +1 -1
- package/dist/chunk-2agbk8ef.js +0 -1
- package/dist/chunk-2bty4510.js +0 -6
- package/dist/chunk-2f7nr9hh.js +0 -1
- package/dist/chunk-2t9vtt75.js +0 -1
- package/dist/chunk-3aaehgva.js +0 -1
- package/dist/chunk-3t5r41yh.js +0 -1
- package/dist/chunk-5xgyx25z.js +0 -2
- package/dist/chunk-gjc1hhhv.js +0 -1
- package/dist/chunk-gx4seq5c.js +0 -10
- package/dist/chunk-h2gp7smy.js +0 -1
- package/dist/chunk-mc2mr1kn.js +0 -2
- package/dist/chunk-mkckss82.js +0 -1
- package/dist/chunk-ntpwqfy3.js +0 -1
- package/dist/chunk-q82ntq7t.js +0 -1
- package/dist/chunk-recafw5r.js +0 -171
- package/dist/chunk-smjfqtws.js +0 -1
- package/dist/chunk-wazhd8bm.js +0 -1
- package/dist/chunk-wf4s1hp2.js +0 -1
- package/dist/web/assets/ChatView-CQnuGDqk.js +0 -63
- package/dist/web/assets/index-DQaqO-lw.js +0 -203
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{Qi as M,Ri as i,Ti as o}from"./chunk-zp5097qk.js";import{Cj as $,Dj as Z,Ej as b,Fj as K,yj as e}from"./chunk-pg7cgvs8.js";import{ak as p}from"./chunk-mnk0b4nz.js";var w=[{min:0,max:59},{min:0,max:23},{min:1,max:31},{min:1,max:12},{min:0,max:7}],Z1={Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6},l=new Map;function I(J,B,j){let Y=new Set;for(let H of J.split(",")){let[k,W]=H.split("/"),V=W?Number.parseInt(W,10):1;if(!Number.isInteger(V)||V<1)throw Error(`Invalid cron step in "${J}"`);let X=B,Q=j;if(k!=="*"&&k!=="")if(k.includes("-")){let[G,J1]=k.split("-");X=Number.parseInt(G,10),Q=Number.parseInt(J1,10)}else X=Number.parseInt(k,10),Q=X;if(!Number.isInteger(X)||!Number.isInteger(Q)||X<B||Q>j||X>Q)throw Error(`Invalid cron range "${k}" in field "${J}"`);for(let G=X;G<=Q;G+=V)Y.add(G)}return Y}function u(J){let B=J.trim().split(/\s+/);if(B.length!==5)throw Error(`Cron expression must have 5 fields (min hour dom mon dow), got ${B.length}`);let[j,Y,H,k,W]=B,V=I(W,w[4].min,w[4].max),X=new Set([...V].map((Q)=>Q===7?0:Q));return{minutes:I(j,w[0].min,w[0].max),hours:I(Y,w[1].min,w[1].max),daysOfMonth:I(H,w[2].min,w[2].max),months:I(k,w[3].min,w[3].max),daysOfWeek:X,domRestricted:H.trim()!=="*",dowRestricted:W.trim()!=="*"}}function B1(J,B){if(!B)return{minute:J.getMinutes(),hour:J.getHours(),dayOfMonth:J.getDate(),month:J.getMonth()+1,dayOfWeek:J.getDay()};let j=l.get(B);if(!j)j=new Intl.DateTimeFormat("en-US",{timeZone:B,month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",weekday:"short",hourCycle:"h23"}),l.set(B,j);let Y=Object.fromEntries(j.formatToParts(J).filter((H)=>H.type!=="literal").map((H)=>[H.type,H.value]));return{minute:Number(Y.minute),hour:Number(Y.hour),dayOfMonth:Number(Y.day),month:Number(Y.month),dayOfWeek:Z1[Y.weekday]??-1}}function K1(J,B,j){let Y=B1(B,j);if(!J.minutes.has(Y.minute))return!1;if(!J.hours.has(Y.hour))return!1;if(!J.months.has(Y.month))return!1;let H=J.daysOfMonth.has(Y.dayOfMonth),k=J.daysOfWeek.has(Y.dayOfWeek);if(J.domRestricted&&J.dowRestricted)return H||k;if(J.domRestricted)return H;if(J.dowRestricted)return k;return!0}function Y1(J,B,j){let Y=u(J),H=new Date(B.getTime());H.setSeconds(0,0),H.setMinutes(H.getMinutes()+1);let k=new Date(B.getTime());k.setFullYear(k.getFullYear()+4);while(H.getTime()<=k.getTime()){if(K1(Y,H,j))return new Date(H.getTime());H.setMinutes(H.getMinutes()+1)}return null}var d={s:1000,m:60000,h:3600000,d:86400000};function s1(J){let j=J.trim().toLowerCase().match(/^(\d+)\s*([smhd]?)$/);if(!j)return null;let Y=Number.parseInt(j[1],10);if(!Number.isInteger(Y)||Y<=0)return null;let H=j[2]||"m";return Y*d[H]}function j1(J){for(let B of["d","h","m","s"]){let j=d[B];if(J%j===0)return`${J/j}${B}`}return`${Math.round(J/1000)}s`}function U(J,B,j){switch(J.kind){case"cron":{if(!J.cron)return null;try{return Y1(J.cron,B,J.timezone)}catch{return null}}case"interval":{if(!J.intervalMs||J.intervalMs<=0)return null;let H=new Date((j??B).getTime()+J.intervalMs);return H.getTime()<=B.getTime()?new Date(B.getTime()+1000):H}case"once":{if(!J.runAt)return null;let Y=new Date(J.runAt);if(Number.isNaN(Y.getTime()))return null;return Y.getTime()>B.getTime()?Y:null}default:return null}}function F(J){switch(J.kind){case"cron":if(!J.cron)return"cron trigger requires a cron expression";try{if(u(J.cron),J.timezone)new Intl.DateTimeFormat("en-US",{timeZone:J.timezone}).format();return null}catch(B){return B instanceof Error?B.message:"invalid cron expression"}case"interval":if(!J.intervalMs||J.intervalMs<60000)return"interval trigger requires intervalMs >= 60000 (1 minute)";return null;case"once":{if(!J.runAt)return"once trigger requires runAt timestamp";let B=new Date(J.runAt);if(Number.isNaN(B.getTime()))return"once trigger runAt is not a valid date";return null}default:return"unknown trigger kind"}}function a1(J){switch(J.kind){case"cron":return`cron: ${J.cron??"?"}`;case"interval":return`every ${J.intervalMs?j1(J.intervalMs):"?"}`;case"once":return`once at ${J.runAt??"?"}`;default:return"unknown"}}import{mkdir as h1,readFile as c1}from"node:fs/promises";import $1 from"node:path";import{nanoid as g1}from"nanoid";import n1 from"write-file-atomic";var x=160,H1=240,m=$.String({pattern:"^[a-f0-9]{64}$"}),k1=Z($.Object({id:$.String({minLength:1,maxLength:128}),position:$.Integer({minimum:0,maximum:x-1}),queuedAt:$.String({minLength:20,maxLength:32}),kind:K(["user","internal"]),state:K(["pending","locked"]),delivery:K(["current_turn","next_turn","recovery"]),mutable:$.Boolean(),preview:$.Optional($.String({maxLength:H1})),previewTruncated:$.Boolean(),attachmentCount:$.Integer({minimum:0,maximum:20})},{additionalProperties:!1})),h=Z($.Object({version:m,pending:$.Integer({minimum:0,maximum:x}),mutable:$.Integer({minimum:0,maximum:x}),locked:$.Integer({minimum:0,maximum:x}),internal:$.Integer({minimum:0,maximum:x}),items:$.Array(k1,{maxItems:x})},{additionalProperties:!1})),Q1=$.Union([$.Object({type:$.Literal("remove"),messageId:$.String({minLength:1,maxLength:128})},{additionalProperties:!1}),$.Object({type:$.Literal("move"),messageId:$.String({minLength:1,maxLength:128}),toPosition:$.Integer({minimum:0,maximum:x-1})},{additionalProperties:!1})]),y1=Z($.Object({expectedVersion:m,operation:Q1},{additionalProperties:!1})),T1=Z($.Object({snapshot:h},{additionalProperties:!1})),X1=K(["revision_conflict","already_claimed","immutable_origin","immutable_boundary","not_found","runtime_unavailable","invalid_mutation","storage_unavailable"]),p1=Z($.Object({error:$.Object({code:X1,message:$.String({minLength:1,maxLength:256})},{additionalProperties:!1}),snapshot:h},{additionalProperties:!1}));var b1=K(["preferences","conventions","lessons","debugging"]),G1=$.Object({outcome:K(["nothing_to_store","disabled","failed"]),entries:$.Literal(0),topics:$.Tuple([])},{additionalProperties:!1}),W1=$.Object({outcome:$.Literal("written"),entries:$.Integer({minimum:1,maximum:20}),topics:$.Array(b1,{minItems:1,maxItems:4,uniqueItems:!0})},{additionalProperties:!1}),J0=Z($.Union([W1,G1]));var c=128,V1=128,w1=8,D1=1e6,z1=8640000000000000,D=$.Integer({minimum:0,maximum:D1}),L=$.Integer({minimum:0,maximum:z1}),x1=$.String({minLength:1,maxLength:c,pattern:"^[^\x00-\x1F]+$"}),O1=K(["starting","thinking","responding","executing_tools","compacting","continuing"]),q1=$.Refine($.Object({name:x1,kind:$.Optional(K(["readonly","write","execute"])),startedAt:L,progress:$.Optional(D),total:$.Optional(D)},{additionalProperties:!1}),(J)=>J.progress===void 0&&J.total===void 0||J.progress!==void 0&&J.total!==void 0&&J.progress<=J.total,()=>"progress and total must be present together with progress <= total"),v1=$.Refine($.Object({phase:O1,startedAt:L,updatedAt:L,turn:D,maxTurns:$.Union([D,$.Null()]),outputStarted:$.Boolean(),toolCallsStarted:D,toolCallsCompleted:D,activeTools:$.Array(q1,{maxItems:w1}),activeToolOverflow:D},{additionalProperties:!1}),(J)=>J.startedAt<=J.updatedAt&&J.toolCallsCompleted<=J.toolCallsStarted&&J.activeTools.length+J.activeToolOverflow<=J.toolCallsStarted-J.toolCallsCompleted,()=>"turn activity snapshot counters and timestamps are inconsistent"),K0=Z($.Object({version:$.Literal(1),generation:$.String({minLength:1,maxLength:V1,pattern:"^[^\x00-\x1F]+$"}),revision:D,snapshot:$.Union([v1,$.Null()])},{additionalProperties:!1}));function Y0(J){let B=[...J].filter((j)=>{let Y=j.codePointAt(0)??0;return Y>31&&Y!==127}).join("").trim().slice(0,c);if(!B)throw Error("Turn activity tool name is empty");return B}var g=16384;function H0(J){let B=/^\s*\/btw(?:\s+([\s\S]*))?\s*$/iu.exec(J);if(!B)return;return{question:(B[1]??"").trim()}}var O=Z(K(["default","autoEdit","yolo","plan"]));var A=Z(K(["user","assistant","system","tool"])),P1=Z($.Union([$.Object({type:$.Literal("text"),text:$.String()}),$.Object({type:$.Literal("image_url"),image_url:$.Object({url:$.String()})})])),s=$.Union([$.String(),$.Array(P1)]),W0=Z($.Object({id:$.String(),role:A,content:s,timestamp:$.Number(),metadata:$.Optional($.Record($.String(),$.Unknown())),thinkingContent:$.Optional($.String()),tool_call_id:$.Optional($.String()),name:$.Optional($.String()),tool_calls:$.Optional($.Unknown())})),f1=Z(K(["queued","running","completed","failed","cancelled","interrupted"])),N=Z(K(["local","worktree"])),R=Z(K(["high","medium","low"])),E=Z(K(["feature","bug","maintenance","research"])),I1=Z(K(["applied","discarded","conflicted"])),N1=Z($.Object({status:I1,updatedAt:$.String(),sourceCommit:$.Optional($.String()),changedFiles:$.Optional($.Integer({minimum:0})),message:$.Optional($.String())})),C1=Z($.Object({changedFiles:$.Integer({minimum:0}),additions:$.Integer({minimum:0}),deletions:$.Integer({minimum:0}),commits:$.Integer({minimum:0})})),U1=Z($.Object({path:$.String({minLength:1}),patch:$.String({maxLength:2097152}),additions:$.Integer({minimum:0}),deletions:$.Integer({minimum:0}),binary:$.Boolean(),truncated:$.Boolean()})),V0=Z($.Object({sessionId:$.String(),projectPath:$.String(),baseCommit:$.String(),files:$.Array(U1,{maxItems:100}),truncated:$.Boolean()})),F1=$.Union([$.String(),$.Number(),$.Boolean(),$.Array($.String())]),L1=Z($.Object({name:$.String(),type:K(["string","number","integer","boolean","select","multi-select"]),title:$.String(),description:$.Optional($.String()),required:$.Boolean(),defaultValue:$.Optional(F1),options:$.Optional($.Array($.Object({value:$.String(),label:$.String()}))),format:$.Optional(K(["date","uri","email","date-time"])),minimum:$.Optional($.Number()),maximum:$.Optional($.Number()),minLength:$.Optional($.Number()),maxLength:$.Optional($.Number()),minItems:$.Optional($.Number()),maxItems:$.Optional($.Number())})),w0=Z($.Object({serverName:$.String(),mode:K(["form","url"]),message:$.String(),fields:$.Optional($.Array(L1)),requestedSchema:$.Optional($.Record($.String(),$.Unknown())),url:$.Optional($.String()),domain:$.Optional($.String()),elicitationId:$.Optional($.String())})),M1=Z($.Object({type:K(["permission","question","elicitation"]),requestId:$.String()})),A1=Z($.Object({code:K(["authentication","permission","rate_limit","timeout","network","model_unavailable","context_limit","unsupported_input","workspace_unavailable","capacity","runtime"]),message:$.String({minLength:1,maxLength:500}),retryable:$.Boolean(),resource:$.Optional(K(["pending_count","pending_bytes","resident_runtimes"]))})),q=Z(K(["auto","off","minimal","low","medium","high","xhigh","max"])),v=Z(K(["auto","standard","fast","flex"])),P=Z(K(["auto","low","medium","high"])),z=Z($.Union([K(["auto","pragmatic","friendly","explanatory"]),$.String({minLength:7,maxLength:300,pattern:"^(?:(?:user|project):[a-z0-9][a-z0-9._-]{0,63}(?::[a-z0-9][a-z0-9._-]{0,63}){0,3}|plugin:[a-z0-9][a-z0-9._-]{0,63}:[a-z0-9][a-z0-9._-]{0,63}(?::[a-z0-9][a-z0-9._-]{0,63}){0,3})$"})])),C=Z($.Object({sessionId:$.String(),projectPath:$.String(),title:$.Optional($.String()),gitBranch:$.Optional($.String()),rootId:$.String(),parentId:$.Optional($.String()),relationType:$.Optional(K(["subagent","fork"])),resumedFrom:$.Optional($.String()),rootAgentId:$.Optional($.String()),resumeDepth:$.Optional($.Integer({minimum:0})),taskStatus:b(f1,"completed"),taskStatusReason:$.Optional($.String()),taskFailure:$.Optional(A1),taskStartedAt:$.Optional($.String()),taskCompletedAt:$.Optional($.String()),taskPromptSummary:$.Optional($.String()),taskPriority:$.Optional(R),taskKind:$.Optional(E),taskDueAt:$.Optional($.String()),taskModelId:$.Optional($.String()),selectedModelId:$.Optional($.String()),permissionMode:$.Optional(O),reasoningEffort:$.Optional(q),serviceTier:$.Optional(v),responseVerbosity:$.Optional(P),communicationStyle:$.Optional(z),communicationStyleDigest:$.Optional($.String({pattern:"^[a-f0-9]{64}$"})),projectInstructionsDigest:$.Optional($.String({pattern:"^[a-f0-9]{64}$"})),taskRetryAvailable:$.Optional($.Boolean()),taskRetriedFrom:$.Optional($.Object({sessionId:$.String(),projectPath:$.String()})),taskDelivery:$.Optional(N1),taskIsolation:$.Optional(N),taskSourceProjectPath:$.Optional($.String()),taskWorktreePath:$.Optional($.String()),taskWorktreeBranch:$.Optional($.String()),taskBaseCommit:$.Optional($.String()),taskDiffStat:$.Optional(C1),taskQueuePosition:$.Optional($.Integer({minimum:1})),taskQueueDepth:$.Optional($.Integer({minimum:0})),taskConcurrencyLimit:$.Optional($.Integer({minimum:1})),archivedAt:$.Optional($.String()),archivedBySessionId:$.Optional($.String()),pendingInteraction:$.Optional(M1),messageCount:$.Number(),firstMessageTime:$.String(),lastMessageTime:$.String(),hasErrors:$.Boolean()})),D0=Z($.Object({sessions:$.Array(C),nextCursor:$.Optional($.String())})),z0=Z($.Object({session:C,archivedSessionIds:$.Array($.String())})),x0=Z($.Object({session:C,restoredSessionIds:$.Array($.String())})),O0=Z($.Object({version:$.Union([$.Literal(1),$.Literal(2)]),sessionId:$.String(),goalId:$.String(),objective:$.String(),status:K(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"]),tokenBudget:$.Optional($.Number()),tokensUsed:$.Number(),timeUsedSeconds:$.Number(),continuationCount:$.Number(),statusReason:$.Optional($.String()),completionVerification:$.Optional($.Object({attempt:$.Integer({minimum:1}),status:K(["pending","pass","fail","partial"]),requestedAt:$.String(),completedAt:$.Optional($.String()),verifierSessionId:$.Optional($.String()),summary:$.Optional($.String()),evidenceSha256:$.Optional($.String({pattern:"^[a-f0-9]{64}$"}))})),prematureStop:$.Optional($.Object({pattern:$.Unsafe({type:"string"}),consecutiveCount:$.Integer({minimum:1}),detectedAt:$.String()})),verificationStall:$.Optional($.Unsafe({type:"object"})),executionFrontier:$.Optional($.Object({taskListId:$.String({minLength:1,maxLength:256}),total:$.Integer({minimum:0}),completed:$.Integer({minimum:0}),inProgress:$.Integer({minimum:0}),pending:$.Integer({minimum:0}),blocked:$.Integer({minimum:0}),nextTask:$.Optional($.Object({id:$.String({minLength:1}),subject:$.String({minLength:1,maxLength:512}),priority:K(["high","medium","low"])})),digestSha256:$.String({pattern:"^[a-f0-9]{64}$"}),observedAt:$.String()})),frontierStall:$.Optional($.Object({category:K(["waiting_dependency","same_task_no_effect","repeated_deferral"]),consecutiveCount:$.Integer({minimum:1,maximum:3}),digestSha256:$.String({pattern:"^[a-f0-9]{64}$"}),detectedAt:$.String()})),createdAt:$.String(),updatedAt:$.String()})),a=Z($.Object({role:A,content:s,metadata:$.Optional($.Unknown()),reasoningContent:$.Optional($.String()),thinkingContent:$.Optional($.String()),tool_call_id:$.Optional($.String()),name:$.Optional($.String()),tool_calls:$.Optional($.Unknown())})),q0=Z($.Object({session:C,messages:$.Array(a)})),t=Z(K(["conversation","code","both"])),R1=Z($.Object({messageId:$.String(),preview:$.String(),createdAt:$.String(),fileCount:$.Integer({minimum:0})})),v0=Z($.Object({targetMessageId:$.String({minLength:1}),mode:b(t,"conversation")})),P0=Z($.Object({checkpoint:R1,mode:t,removedTurns:$.Integer({minimum:1}),restoredFiles:$.Array($.String()),messages:$.Array(a)})),E1=K(["running","completed","failed","cancelled"]),n=Z($.Object({id:$.String(),subagentType:$.String(),description:$.String(),status:E1,background:$.Boolean(),rootAgentId:$.String(),resumedFrom:$.Optional($.String()),resumeDepth:$.Integer({minimum:0}),createdAt:$.Number(),lastActiveAt:$.Number(),completedAt:$.Optional($.Number()),restartRecovery:$.Optional($.Object({outcome:K(["completed","interrupted","failed"]),recoveredAt:$.Number()})),result:$.Optional($.Object({success:$.Boolean(),message:$.String(),error:$.Optional($.String()),verificationCommands:$.Optional($.Array($.String())),verificationVerdict:$.Optional(K(["pass","fail","partial"])),modifiedFiles:$.Optional($.Array($.String()))})),stats:$.Optional($.Object({tokens:$.Optional($.Number()),toolCalls:$.Optional($.Number()),duration:$.Optional($.Number())}))})),f0=Z($.Object({prompt:$.String({minLength:1,maxLength:32000,pattern:"\\S"})})),I0=Z($.Object({source:n,session:n})),N0=Z($.Object({sessionId:$.String(),projectPath:$.String()})),C0=Z($.Object({path:$.String(),name:$.String(),gitBranch:$.Optional($.String()),available:$.Boolean(),isCurrent:$.Boolean(),boundAt:$.String()})),U0=Z($.Union([$.Object({cancelled:$.Literal(!0)}),$.Object({cancelled:$.Literal(!1),path:$.String({minLength:1})})])),F0=Z($.Object({type:$.String(),seq:$.Optional($.Number()),properties:$.Record($.String(),$.Unknown())})),r=$.Object({type:K(["file","image","url"]),path:$.Optional($.String()),url:$.Optional($.String()),content:$.Optional($.String({maxLength:i})),mimeType:$.Optional($.String()),name:$.Optional($.String())}),y=$.Record($.String(),$.Unknown()),L0=Z($.Object({prompt:$.String({minLength:1,maxLength:32000,pattern:"\\S"}),title:$.Optional($.String({minLength:1,maxLength:200})),taskPriority:b(R,"medium"),taskKind:b(E,"feature"),taskDueAt:$.Optional($.String({minLength:1,maxLength:64})),projectPath:$.Optional($.String()),modelId:$.Optional($.String({minLength:1,maxLength:500})),reasoningEffort:$.Optional(q),serviceTier:$.Optional(v),responseVerbosity:$.Optional(P),communicationStyle:$.Optional(z),isolation:b(N,"worktree"),permissionMode:b(O,"default"),attachments:$.Optional($.Array(r,{maxItems:M})),outputSchema:$.Optional(y)})),M0=Z($.Object({title:$.Optional($.String({minLength:1,maxLength:200})),taskPriority:$.Optional(R),taskKind:$.Optional(E),taskDueAt:$.Optional($.Union([$.String({minLength:1,maxLength:64}),$.Null()]))})),A0=Z($.Object({session:C,runId:$.String(),messageId:$.String(),status:K(["queued","running"]),queuePosition:$.Optional($.Integer({minimum:1})),queueDepth:$.Optional($.Integer({minimum:0})),maxConcurrentTasks:$.Optional($.Integer({minimum:1}))})),R0=Z($.Object({action:K(["apply","discard"])})),_=Z($.Object({kind:K(["cron","interval","once"]),cron:$.Optional($.String({minLength:1,maxLength:120})),intervalMs:$.Optional($.Integer({minimum:60000})),runAt:$.Optional($.String({minLength:1,maxLength:40})),timezone:$.Optional($.String({minLength:1,maxLength:80}))})),_1=Z($.Object({modelId:$.Optional($.String({minLength:1,maxLength:500})),reasoningEffort:$.Optional(q),serviceTier:$.Optional(v),responseVerbosity:$.Optional(P),communicationStyle:$.Optional(z),isolation:b(N,"worktree"),permissionMode:b(O,"default")})),S=Z($.Object({id:$.String(),title:$.Optional($.String({minLength:1,maxLength:200})),prompt:$.String({minLength:1,maxLength:32000,pattern:"\\S"}),projectPath:$.String({minLength:1}),trigger:_,dispatch:_1,enabled:$.Boolean(),createdAt:$.String(),updatedAt:$.String(),nextRunAt:$.Union([$.String(),$.Null()]),expiresAt:$.Union([$.String(),$.Null()]),lastRunAt:$.Optional($.String()),lastRunSessionId:$.Optional($.String()),lastStatus:$.Optional(K(["queued","running","completed","failed","cancelled","interrupted","error"])),lastError:$.Optional($.String()),runCount:$.Integer({minimum:0})})),E0=Z($.Object({title:$.Optional($.String({minLength:1,maxLength:200})),prompt:$.String({minLength:1,maxLength:32000,pattern:"\\S"}),projectPath:$.String({minLength:1}),trigger:_,modelId:$.Optional($.String({minLength:1,maxLength:500})),reasoningEffort:$.Optional(q),serviceTier:$.Optional(v),responseVerbosity:$.Optional(P),communicationStyle:$.Optional(z),isolation:b(N,"worktree"),permissionMode:b(O,"default"),enabled:b($.Boolean(),!0)})),_0=Z($.Object({title:$.Optional($.String({minLength:1,maxLength:200})),prompt:$.Optional($.String({minLength:1,maxLength:32000,pattern:"\\S"})),trigger:$.Optional(_),modelId:$.Optional($.String({minLength:1,maxLength:500})),reasoningEffort:$.Optional(q),serviceTier:$.Optional(v),responseVerbosity:$.Optional(P),communicationStyle:$.Optional(z),isolation:$.Optional(N),permissionMode:$.Optional(O),enabled:$.Optional($.Boolean())})),S0=Z($.Object({schedules:$.Array(S)})),l0=Z($.Object({content:$.String({maxLength:o}),projectPath:$.Optional($.String()),modelId:$.Optional($.String({minLength:1,maxLength:500})),reasoningEffort:$.Optional(q),serviceTier:$.Optional(v),responseVerbosity:$.Optional(P),communicationStyle:$.Optional(z),permissionMode:$.Optional(O),attachments:$.Optional($.Array(r,{maxItems:M})),outputSchema:$.Optional(y)})),S1=K(["completed","failed","aborted","timed_out","spawn_error"]),l1=Z($.Object({version:$.Literal(1),command:$.String(),status:S1,exitCode:$.Union([$.Integer(),$.Null()]),durationMs:$.Number({minimum:0}),stdout:$.String(),stderr:$.String(),stdoutOmittedBytes:$.Integer({minimum:0}),stderrOmittedBytes:$.Integer({minimum:0}),binaryOutput:$.Boolean(),truncated:$.Boolean()})),u0=Z($.Object({command:$.String({minLength:1,maxLength:32768,pattern:"^(?![\\s\\S]*\\u0000)(?=[\\s\\S]*\\S)[\\s\\S]*$"}),projectPath:$.Optional($.String())})),d0=Z($.Object({executionId:$.String(),messageId:$.String(),record:l1,auxiliary:$.Boolean(),delivery:$.Optional(K(["current_turn","next_turn"])),queued:$.Optional($.Integer({minimum:0}))})),m0=Z($.Object({question:$.String({minLength:1,maxLength:g,pattern:"^(?![\\s\\S]*\\x00)(?=[\\s\\S]*\\S)[\\s\\S]*$"}),projectPath:$.Optional($.String())})),h0=Z($.Object({response:$.String({minLength:1}),durationMs:$.Number({minimum:0}),modelId:$.Optional($.String()),usage:$.Optional($.Object({promptTokens:$.Number({minimum:0}),completionTokens:$.Number({minimum:0}),totalTokens:$.Number({minimum:0}),reasoningTokens:$.Optional($.Number({minimum:0})),cacheCreationInputTokens:$.Optional($.Number({minimum:0})),cacheReadInputTokens:$.Optional($.Number({minimum:0})),costUsd:$.Optional($.Number({minimum:0}))}))})),c0=Z($.Object({projectPath:$.String(),kind:K(["uncommitted","base","commit"]),ref:$.Optional($.String({maxLength:200})),instructions:$.Optional($.String({maxLength:4000})),modelId:$.Optional($.String({minLength:1,maxLength:200}))})),g0=Z($.Object({reviewId:$.String(),status:$.Literal("running")})),n0=Z($.Object({messageId:$.String(),role:A,content:$.String(),timestamp:$.String()})),i0=Z($.Object({approved:$.Boolean(),remember:$.Optional($.Boolean()),scope:$.Optional(K(["once","session","project"])),targetMode:$.Optional(O),feedback:$.Optional($.String()),answers:$.Optional($.Record($.String(),$.Union([$.String(),$.Array($.String())]))),elicitation:$.Optional($.Object({action:K(["accept","decline","cancel"]),content:$.Optional($.Record($.String(),$.Union([$.String({maxLength:4000}),$.Number(),$.Boolean(),$.Array($.String({maxLength:1000}),{maxItems:100})]),{maxProperties:32}))}))})),u1=Z($.Object({id:z,name:$.String({minLength:1,maxLength:80}),description:$.String({minLength:1,maxLength:256}),source:K(["built-in","user","project","plugin"]),contentSha256:$.Optional($.String({pattern:"^[a-f0-9]{64}$"}))})),o0=Z($.Object({id:$.String(),displayName:$.Optional($.String()),provider:$.String(),model:$.String(),contextWindow:$.Optional($.Number()),maxTokens:$.Optional($.Number()),reasoning:$.Optional($.Boolean()),supportedReasoningEfforts:$.Optional($.Array(K(["off","minimal","low","medium","high","xhigh","max"]))),supportedServiceTiers:$.Optional($.Array(K(["standard","fast","flex"]))),supportedResponseVerbosities:$.Optional($.Array(K(["low","medium","high"]))),communicationStyles:$.Optional($.Array(u1,{maxItems:36})),input:$.Optional($.Array(K(["text","image"]))),overrides:$.Optional($.Object({baseUrl:$.Optional($.String()),temperature:$.Optional($.Number()),maxOutputTokens:$.Optional($.Number()),timeout:$.Optional($.Number()),streamIdleTimeout:$.Optional($.Number({minimum:1000}))}))})),s0=Z(K(["vs-dark","vs-light","hc-black"])),d1=Z(K(["light","dark","system"])),m1=Z($.Object({language:$.String(),codeTheme:$.String(),uiTheme:d1,autoSaveSessions:$.Boolean(),notifyBuild:$.Boolean(),notifyErrors:$.Boolean(),notifySounds:$.Boolean(),privacyTelemetry:$.Boolean(),privacyCrash:$.Boolean(),agentTeamsEnabled:$.Boolean(),communicationStyle:$.Optional(z)})),a0=Z($.Partial(m1));var T=e("Service"),i1=1;function o1(){return $1.join(p(),"schedules.json")}class f{filePath;static instance;static getInstance(){if(!f.instance)f.instance=new f;return f.instance}writeChain=Promise.resolve();constructor(J=o1()){this.filePath=J}async readFile(){try{let J=await c1(this.filePath,"utf-8"),B=JSON.parse(J);if(!B||!Array.isArray(B.schedules))return[];let j=[],Y=0;for(let H of B.schedules){let k=S.safeParse(H);if(k.success)j.push(k.data);else Y+=1}if(Y>0)T.warn(`[ScheduleStore] Ignored ${Y} invalid persisted schedule(s)`);return j}catch(J){let B=J;if(B.code!=="ENOENT")T.warn("[ScheduleStore] Failed to read schedules; treating as empty:",B);return[]}}async writeFile(J){await h1($1.dirname(this.filePath),{recursive:!0,mode:493});let B={version:i1,schedules:J};await n1(this.filePath,JSON.stringify(B,null,2),{mode:384})}serializeWrite(J){let B=this.writeChain.then(J,J);return this.writeChain=B.then(()=>{return},()=>{return}),B}async list(){return this.readFile()}async get(J){return(await this.readFile()).find((j)=>j.id===J)}async create(J){return this.serializeWrite(async()=>{let B=J.trigger.kind==="cron"&&!J.trigger.timezone?{...J.trigger,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}:J.trigger,j=F(B);if(j)throw Error(j);let Y=new Date;if(B.kind==="once"&&new Date(B.runAt).getTime()<=Y.getTime())throw Error("once trigger runAt must be in the future");let H=Y.toISOString(),k=U(B,Y),W={id:g1(10),title:J.title,prompt:J.prompt,projectPath:J.projectPath,trigger:B,dispatch:{modelId:J.modelId,reasoningEffort:J.reasoningEffort,serviceTier:J.serviceTier,responseVerbosity:J.responseVerbosity,communicationStyle:J.communicationStyle,isolation:J.isolation??"worktree",permissionMode:J.permissionMode??"default"},enabled:J.enabled??!0,createdAt:H,updatedAt:H,nextRunAt:k?k.toISOString():null,expiresAt:null,runCount:0},V=await this.readFile();return V.push(W),await this.writeFile(V),W})}async update(J,B){return this.serializeWrite(async()=>{let j=await this.readFile(),Y=j.findIndex((Q)=>Q.id===J);if(Y===-1)return;let H=j[Y];if(B.trigger){let Q=B.trigger.kind==="cron"&&!B.trigger.timezone?{...B.trigger,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}:B.trigger,G=F(Q);if(G)throw Error(G);if(Q.kind==="once"&&new Date(Q.runAt).getTime()<=Date.now())throw Error("once trigger runAt must be in the future");B={...B,trigger:Q}}let k={...H,...B,dispatch:B.dispatch?{...H.dispatch,...B.dispatch}:H.dispatch,updatedAt:new Date().toISOString()},W=!H.enabled,V=k.enabled,X=B.trigger!==void 0;if((X||W&&V)&&B.nextRunAt===void 0){let Q=new Date,G=U(k.trigger,Q);if(k.nextRunAt=G?G.toISOString():null,X)k.expiresAt=null}return j[Y]=k,await this.writeFile(j),k})}async remove(J){return this.serializeWrite(async()=>{let B=await this.readFile(),j=B.filter((Y)=>Y.id!==J);if(j.length===B.length)return!1;return await this.writeFile(j),!0})}async setEnabled(J,B){return this.update(J,{enabled:B})}}var b2=f.getInstance();
|
|
2
|
+
export{g as Ra,H0 as Sa,x as Ta,H1 as Ua,m as Va,h as Wa,Q1 as Xa,w1 as Ya,K0 as Za,Y0 as _a,J0 as $a,s1 as ab,U as bb,F as cb,a1 as db,V0 as eb,C as fb,v0 as gb,f0 as hb,L0 as ib,M0 as jb,A0 as kb,R0 as lb,S as mb,E0 as nb,_0 as ob,S0 as pb,l0 as qb,u0 as rb,m0 as sb,c0 as tb,f as ub,b2 as vb};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{N as GP}from"./chunk-1h3736q2.js";import{be as N}from"./chunk-cefmcwyv.js";import{Ie as r,Je as e,Me as L,Oe as PP,Re as l,Te as d,Ve as JP,Xe as QP,Ye as ZP,Ze as $P,_e as w}from"./chunk-a5hkv8er.js";import{af as t,bf as a,df as R,ff as y,gf as A,if as p}from"./chunk-awheqy52.js";import{Hj as q}from"./chunk-jb4hmk56.js";import{Zj as o,rk as s,sk as n}from"./chunk-t88sfhjj.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 l(P,J.sessionId,J.workspace.projectPath,N.projectionDeriverForSearch(),void 0,"local",Q);return}await d(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 l(P,Y.sessionId,Y.projectPath,Q,void 0,"local",J);await d(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-ppmy3n74.js";import{ee as N}from"./chunk-n6tvswa8.js";import{$e as ZP,Le as r,Me as e,Pe as L,Re as PP,Ue as l,We as d,Ye as JP,_e as QP,af as $P,bf as w}from"./chunk-es0cbtx1.js";import{df as t,ef as a,gf as R,if as y,jf as A,lf as p}from"./chunk-zfaenqqx.js";import{Kj as q}from"./chunk-svsgtj41.js";import{ak as o,uk as s,vk as n}from"./chunk-mnk0b4nz.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 l(P,J.sessionId,J.workspace.projectPath,N.projectionDeriverForSearch(),void 0,"local",Q);return}await d(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 l(P,Y.sessionId,Y.projectPath,Q,void 0,"local",J);await d(P,Q,J)}async listFallbackPage(P,J,Q,Z){if(Z)return this.registry.redeemCatalogCursor({token:Z,scopeKey:J,epoch:this.epoch,revision:"fallback",request:P,loader:async({boundary:G})=>{let Y=LP(G);return this.pageFallbackCatalog(Y.entries,P,J,Y.chainId)}});let $=await this.loadFallbackCatalog(P,Q);return this.pageFallbackCatalog($,P,J,`catalog-fallback:${F(16).toString("base64url")}`)}async loadFallbackCatalog(P,J){let Q=[];if(P.workspaceKind!=="acp-remote")for(let $ of await N.listValidatedLocalSurfaceCandidates(J)){J?.throwIfAborted();let Y=(await N.readValidatedLocalSurfaceSnapshot($.sessionId,$.projectPath,J)).summary;if(Boolean(Y.archivedAt)!==P.archived)continue;Q.push({locator:{version:2,sessionId:$.sessionId,workspace:{kind:"local",projectPath:$.projectPath}},summary:Y})}if(P.workspaceKind!=="local")for(let $ of await N.listValidatedRemoteSurfaceCandidates(J)){J?.throwIfAborted();let Y=(await N.readValidatedRemoteSurfaceSnapshot($,J)).summary;if(Boolean(Y.archivedAt)!==P.archived)continue;Q.push({locator:{version:2,sessionId:$.sessionId,workspace:{kind:"acp-remote",workspaceRef:$.workspaceRef}},summary:Y})}Q.sort(IP);let Z=Buffer.byteLength(JSON.stringify(Q));if(Q.length>TP||Z>DP)throw new z("session_surface_capacity");return Q}async pageFallbackCatalog(P,J,Q,Z){let $=P.slice(0,J.limit),G=P.slice($.length),V={sessions:$.map((X)=>R.parse({locator:X.locator,...X.summary,capabilities:X.locator.workspace.kind==="local"?UP(Boolean(X.summary.archivedAt)):RP(Boolean(X.summary.archivedAt))})),...G.length>0?{nextCursor:this.registry.issueCatalogCursor({chainId:Z,scopeKey:Q,epoch:this.epoch,revision:"fallback",boundary:{chainId:Z,entries:G},request:J})}:{}};if(G.length===0)this.registry.completeChain(Z);return y.parse(V)}async openFallback(P,J,Q){let Z=await this.resolveFallback(P,Q),$=Z.remoteCandidate?await N.readValidatedRemoteSurfaceSnapshot(Z.remoteCandidate,Q):await N.readValidatedLocalSurfaceSnapshot(Z.candidate.sessionId,Z.candidate.projectPath,Q),G=e($.entries,{...Z.remoteCandidate?r(Z.remoteCandidate.hostStateRoot,Z.remoteCandidate.descriptor):{privateRoots:[]},bladeStorageRoots:[o()]}),Y=h(G.slice(-J),L()),V=`history-fallback:${F(16).toString("base64url")}`,X=x(P),O=C("sha256").update(JSON.stringify($.entries)).digest("hex"),j=this.registry.issueSnapshotToken({chainId:V,locatorDigest:X,transcriptFingerprint:O,frozenSnapshot:G}),M={session:this.toSummary(Z),history:A.parse({messages:Y.messages,snapshot:j,truncated:Y.messages.length<G.length||Y.truncated||Y.messages.some((H)=>H.truncated===!0),...G.length>Y.messages.length&&Y.messages[0]?{olderCursor:this.registry.issueHistoryCursor({chainId:V,locatorDigest:X,transcriptFingerprint:O,nextSequence:v(Y.messages[0].id),snapshotToken:j,request:{expectedSnapshot:j,limit:J}})}:{}})};if(G.length<=Y.messages.length)this.registry.completeChain(V);return p.parse(M)}async readFallbackHistoryPage(P,J,Q){let Z=K(J.limit);if(!J.cursor||!J.expectedSnapshot)throw new z("invalid_session_surface_request");let $=x(P),G=await this.resolveFallback(P,Q),Y=G.remoteCandidate?await N.readValidatedRemoteSurfaceSnapshot(G.remoteCandidate,Q):await N.readValidatedLocalSurfaceSnapshot(G.candidate.sessionId,G.candidate.projectPath,Q),V=C("sha256").update(JSON.stringify(Y.entries)).digest("hex");await this.registry.assertSnapshotToken({token:J.expectedSnapshot,locatorDigest:$,transcriptFingerprint:V});let X={expectedSnapshot:J.expectedSnapshot,limit:Z};return this.registry.redeemHistoryCursor({token:J.cursor,locatorDigest:$,transcriptFingerprint:V,request:X,loader:async({nextSequence:O,frozenSnapshot:j})=>{let M=xP(j).filter((b)=>v(b.id)<O),H=h(M.slice(-Z),L()),u=await this.registry.assertSnapshotToken({token:J.expectedSnapshot,locatorDigest:$,transcriptFingerprint:V}),k=H.messages.length<M.length,VP={messages:H.messages,snapshot:J.expectedSnapshot,truncated:k||H.truncated||H.messages.some((b)=>b.truncated===!0),...k&&H.messages[0]?{olderCursor:this.registry.issueHistoryCursor({chainId:u.chainId,locatorDigest:$,transcriptFingerprint:V,nextSequence:v(H.messages[0].id),snapshotToken:J.expectedSnapshot,request:X})}:{}};if(!k)this.registry.completeChain(u.chainId);return A.parse(VP)}})}async resolveFallback(P,J){let Q=[];for(let G of[!1,!0]){let Y={archived:G,limit:zP,workspaceKind:P.workspace.kind};Q.push(...(await this.loadFallbackCatalog(Y,J)).filter((V)=>JSON.stringify(V.locator)===JSON.stringify(P)))}if(Q.length!==1)throw new z("session_surface_not_found");let Z=Q[0],$;if(P.workspace.kind==="acp-remote"){let G=P.workspace.workspaceRef;if($=(await N.listValidatedRemoteSurfaceCandidates(J)).find((Y)=>Y.sessionId===P.sessionId&&Y.workspaceRef===G),!$)throw new z("workspace_binding_mismatch")}return{candidate:{sourceKind:P.workspace.kind,projectPath:P.workspace.kind==="local"?P.workspace.projectPath:$.hostStateRoot,sessionId:P.sessionId,...P.workspace.kind==="acp-remote"?{publicWorkspaceRef:P.workspace.workspaceRef}:{},publicWorkspaceSortKey:"",surfaceDigest:i(Z),transcriptFingerprint:i(Z),lastMessageTime:Z.summary.lastMessageTime,sessionSortKey:"",summary:Z.summary},...$?{remoteCandidate:$}:{}}}async resolveFromProjection(P,J,Q){let Z=QP(P,J.sessionId).filter((G)=>J.workspace.kind==="local"?G.sourceKind==="local"&&G.projectPath===FP.resolve(J.workspace.projectPath):G.sourceKind==="acp-remote"&&G.publicWorkspaceRef===J.workspace.workspaceRef);if(Z.length!==1)throw new z(Z.length===0?"session_surface_not_found":"workspace_binding_mismatch");let $;if(J.workspace.kind==="acp-remote"){let G=J.workspace.workspaceRef;if($=(await N.listValidatedRemoteSurfaceCandidates(Q)).filter((Y)=>Y.sessionId===J.sessionId&&Y.workspaceRef===G),$.length===0)throw new z("workspace_binding_mismatch");if($.length>1)throw new z("session_surface_state_invalid")}return $?{candidate:Z[0],remoteCandidate:$[0]}:{candidate:Z[0]}}async resolveCandidate(P,J){if(P.sourceKind==="local")return{candidate:P};let Q=(await N.listValidatedRemoteSurfaceCandidates(J)).filter((Z)=>Z.sessionId===P.sessionId&&Z.workspaceRef===P.publicWorkspaceRef);if(Q.length!==1)throw new z(Q.length===0?"workspace_binding_mismatch":"session_surface_state_invalid");return{candidate:P,remoteCandidate:Q[0]}}toSummary(P){let J=P.candidate,Q=J.sourceKind==="local"?{version:2,sessionId:J.sessionId,workspace:{kind:"local",projectPath:J.projectPath}}:{version:2,sessionId:J.sessionId,workspace:{kind:"acp-remote",workspaceRef:J.publicWorkspaceRef}};return R.parse({locator:Q,...J.summary,capabilities:this.capabilitiesFor(P)})}capabilitiesFor(P){let J=P.candidate.summary.archivedAt!==void 0;if(!P.remoteCandidate)return{connection:"local",history:{read:!0,fork:!J},turn:J?{start:!1,reason:"archived"}:{start:!0},files:J?{readText:!1,writeText:!1,browse:"none",reason:"archived"}:{readText:!0,writeText:!0,browse:"tree"},terminal:J?{mode:"none",owner:"none",reason:"archived"}:{mode:"interactive",owner:"local"}};return{connection:GP.getRemoteSurfaceOwnerSnapshot(P.candidate.sessionId,P.remoteCandidate.descriptor).connection,history:{read:!0,fork:!J},turn:{start:!1,reason:J?"archived":"history-only"},files:{readText:!1,writeText:!1,browse:"none",reason:J?"archived":"history-only"},terminal:{mode:"none",owner:"none",reason:J?"archived":"history-only"}}}async requireDatabase(){if(this.database===null)return null;return this.database??await PP()}assertAvailable(){if(this.closed)throw new z("session_surface_unavailable")}}function K(P){let J=P??YP;if(!Number.isSafeInteger(J)||J<1||J>zP)throw new z("invalid_session_surface_request");return J}function I(P){try{let J=t.parse(P);if(!n(J.sessionId))throw Error("invalid");if(J.workspace.kind==="local"){if(s(J.workspace.projectPath)!==J.workspace.projectPath)throw Error("invalid")}return J}catch{throw new z("invalid_session_locator")}}function x(P){return C("sha256").update("session-surface-locator-v2\x00").update(JSON.stringify(P)).digest("hex")}function KP(P){if(!P||typeof P!=="object"||Array.isArray(P))throw new z("session_surface_cursor_invalid");let J=P;if(typeof J.lastMessageTime!=="string"||J.sourceKind!=="local"&&J.sourceKind!=="acp-remote"||typeof J.publicWorkspaceSortKey!=="string"||typeof J.sessionSortKey!=="string"||typeof J.chainId!=="string"||!J.chainId)throw new z("session_surface_cursor_invalid");return{lastMessageTime:J.lastMessageTime,sourceKind:J.sourceKind,publicWorkspaceSortKey:J.publicWorkspaceSortKey,sessionSortKey:J.sessionSortKey,chainId:J.chainId}}function h(P,J){let Q=[];for(let Z=P.length-1;Z>=0;Z-=1){let $=P[Z];if(!$)continue;let G=[$,...Q];if(Q.length>0&&Buffer.byteLength(JSON.stringify(G))>J)break;Q.unshift($)}return{messages:Q,truncated:Q.length<P.length}}function v(P){let J=/^surface-message:([0-9]+):/.exec(P),Q=J?Number(J[1]):Number.NaN;if(!Number.isSafeInteger(Q)||Q<=0)throw new z("session_surface_state_invalid");return Q}function xP(P){if(!Array.isArray(P))throw new z("session_surface_snapshot_changed");return P.map((J)=>{try{return a.parse(J)}catch{throw new z("session_surface_snapshot_changed")}})}function LP(P){if(!P||typeof P!=="object"||Array.isArray(P))throw new z("session_surface_cursor_invalid");let J=P;if(typeof J.chainId!=="string"||J.chainId.length===0||!Array.isArray(J.entries))throw new z("session_surface_cursor_invalid");let Q=J.entries.map((Z)=>{if(!Z||typeof Z!=="object"||Array.isArray(Z))throw new z("session_surface_cursor_invalid");let $=Z;return{locator:I($.locator),summary:wP($.summary)}});return{chainId:J.chainId,entries:Q}}function wP(P){let J={version:2,sessionId:"placeholder",workspace:{kind:"local",projectPath:"/"}},Q=R.parse({...P&&typeof P==="object"&&!Array.isArray(P)?P:{},locator:J,capabilities:UP(!1)}),{locator:Z,capabilities:$,...G}=Q;return G}function IP(P,J){if(P.summary.lastMessageTime>J.summary.lastMessageTime)return-1;if(P.summary.lastMessageTime<J.summary.lastMessageTime)return 1;if(P.locator.workspace.kind!==J.locator.workspace.kind)return P.locator.workspace.kind==="local"?-1:1;let Q=P.locator.workspace.kind==="local"?P.locator.workspace.projectPath:P.locator.workspace.workspaceRef,Z=J.locator.workspace.kind==="local"?J.locator.workspace.projectPath:J.locator.workspace.workspaceRef;if(Q<Z)return-1;if(Q>Z)return 1;return P.locator.sessionId<J.locator.sessionId?-1:P.locator.sessionId>J.locator.sessionId?1:0}function i(P){return C("sha256").update("session-surface-fallback-entry\x00").update(JSON.stringify(P)).digest("hex")}function UP(P){return{connection:"local",history:{read:!0,fork:!P},turn:P?{start:!1,reason:"archived"}:{start:!0},files:P?{readText:!1,writeText:!1,browse:"none",reason:"archived"}:{readText:!0,writeText:!0,browse:"tree"},terminal:P?{mode:"none",owner:"none",reason:"archived"}:{mode:"interactive",owner:"local"}}}function RP(P){return{connection:"offline",history:{read:!0,fork:!P},turn:{start:!1,reason:P?"archived":"history-only"},files:{readText:!1,writeText:!1,browse:"none",reason:P?"archived":"history-only"},terminal:{mode:"none",owner:"none",reason:P?"archived":"history-only"}}}function CP(P){if(P==="session_surface_cursor_invalid")return{message:"Session surface cursor is invalid",retryable:!1};if(P==="session_surface_snapshot_changed")return{message:"Session surface snapshot changed",retryable:!1};if(P==="session_surface_state_invalid")return{message:"Session surface state is invalid",retryable:!1};if(P==="session_surface_capability_unavailable")return{message:"Session surface capability is unavailable",retryable:!1};if(P==="session_surface_unavailable")return{message:"Session surface is unavailable",retryable:!0};if(P==="session_surface_not_found")return{message:"Session surface was not found",retryable:!1};if(P==="workspace_binding_mismatch")return{message:"Session workspace binding changed",retryable:!1};if(P==="session_surface_read_only")return{message:"Session surface is read only",retryable:!1};if(P==="session_surface_capacity")return{message:"Session surface capacity is exhausted",retryable:!0};if(P==="invalid_session_locator")return{message:"Session locator is invalid",retryable:!1};return{message:"Session surface request is invalid",retryable:!1}}function kP(P){if(P instanceof z)return P;if(P&&typeof P==="object"&&"code"in P&&typeof P.code==="string"){let J=P.code;if(J==="session_surface_cursor_invalid"||J==="session_surface_snapshot_changed"||J==="session_surface_capacity"||J==="session_surface_unavailable"||J==="session_surface_state_invalid")return new z(J);if(J==="acp_remote_workspace_state_invalid")return new z("session_surface_state_invalid")}return P instanceof Error?P:new z("session_surface_state_invalid")}
|
|
2
2
|
export{qP as e,EP as f,g,z as h,BP as i};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
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 _j,S as $j};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Ek as $,ak as F}from"./chunk-mnk0b4nz.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b as i,c as l,d as m}from"./chunk-tagzy876.js";import"./chunk-50m1czz9.js";import"./chunk-5jq1mrqd.js";import"./chunk-hj1yrssp.js";import"./chunk-cf3dvysj.js";import"./chunk-15fpc0qg.js";import"./chunk-ppmy3n74.js";import"./chunk-8vqhcx3s.js";import"./chunk-pwct7cj7.js";import"./chunk-4xr4hz19.js";import"./chunk-we13xwds.js";import"./chunk-0sx7ak0b.js";import"./chunk-n6tvswa8.js";import"./chunk-kmg8ad2j.js";import"./chunk-es0cbtx1.js";import"./chunk-zfaenqqx.js";import{vf as n}from"./chunk-eh901zhx.js";import"./chunk-08z32sky.js";import{Rf as s}from"./chunk-0kghtvxj.js";import"./chunk-v508x7cg.js";import"./chunk-c562kd2m.js";import"./chunk-pw9axk0e.js";import"./chunk-cww9pp1q.js";import"./chunk-8fx20am1.js";import"./chunk-hvmrcd84.js";import"./chunk-eqe3smcg.js";import"./chunk-xagh2qb6.js";import"./chunk-ascjys4e.js";import"./chunk-r4q06wbs.js";import"./chunk-ma1mn6hn.js";import"./chunk-2ff55pvt.js";import"./chunk-nxsarfy6.js";import"./chunk-e6j4vzta.js";import"./chunk-w2m4yczv.js";import"./chunk-zp5097qk.js";import"./chunk-g38d2ezm.js";import"./chunk-n8qg68y2.js";import"./chunk-pg7cgvs8.js";import"./chunk-svsgtj41.js";import"./chunk-2g8avyq6.js";import"./chunk-19zsecpx.js";import"./chunk-85b3kacc.js";import"./chunk-5cw3bevx.js";import"./chunk-mnk0b4nz.js";import"./chunk-tecbx0ek.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 +1 @@
|
|
|
1
|
-
import{$e as
|
|
1
|
+
import{$e as o,Ne as a,Oe as b,Pe as c,Qe as d,Re as e,Se as f,Te as g,Ue as h,Ve as i,We as j,Xe as k,Ye as l,Ze as m,_e as n,af as p,bf as q,cf as r}from"./chunk-es0cbtx1.js";import"./chunk-zfaenqqx.js";import"./chunk-nxsarfy6.js";import"./chunk-pg7cgvs8.js";import"./chunk-mnk0b4nz.js";import"./chunk-tecbx0ek.js";export{h as syncSession,j as syncAllAcpRemoteScopes,k as syncAll,i as syncAcpRemoteScope,r as searchProjectionText,f as resetProjectionDbCache,l as removeSessionFromProjection,m as rebuildProjectionIndex,q as readSessionSurfaceHistoryPage,o as readSessionSurfaceCatalogRevision,p as readSessionSurfaceCatalogPage,n as readSessionSurfaceCandidates,g as projectSessionSurfaceSummaryFields,c as getSessionSurfaceHistoryByteLimit,e as getProjectionDb,d as getIndexDbPath,a as __setProjectionIOForTesting,b as __resetProjectionIOForTesting};
|