@code-yeongyu/senpi 2026.11.2-1 → 2026.11.2-2
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/CHANGELOG.md +19 -0
- package/dist/bundle/chunks/{chunk-AMCDEC5A.js → chunk-B2LRAXQU.js} +2 -2
- package/dist/bundle/chunks/{chunk-D22YF34L.js → chunk-CQ3G57HE.js} +1 -1
- package/dist/bundle/chunks/{chunk-ZUVGFXCS.js → chunk-FVYWSBX3.js} +3 -3
- package/dist/bundle/chunks/{chunk-665UPAKG.js → chunk-H3BTMIH5.js} +6 -6
- package/dist/bundle/chunks/{chunk-KEJWNCLN.js → chunk-HUSQY3ID.js} +1 -1
- package/dist/bundle/chunks/{chunk-IBV4OVXQ.js → chunk-N6OHYIJR.js} +1 -1
- package/dist/bundle/chunks/{chunk-XZR4J6HM.js → chunk-PP52OWBB.js} +1 -1
- package/dist/bundle/chunks/{chunk-XVQISKHL.js → chunk-QV2IEA3B.js} +4 -4
- package/dist/bundle/chunks/{chunk-2V6BR24J.js → chunk-VEWJSPOZ.js} +1 -1
- package/dist/bundle/chunks/{cli-main-REFQSP6S.js → cli-main-6ZI4QO2Z.js} +1 -1
- package/dist/bundle/chunks/{host-command-Y3ZT6YLD.js → host-command-O3ALG2O3.js} +1 -1
- package/dist/bundle/chunks/{host-lifecycle-VW73K4WA.js → host-lifecycle-SGTVODHB.js} +1 -1
- package/dist/bundle/chunks/host-lifecycle.js +5 -5
- package/dist/bundle/chunks/{host-session-command-YDEUZBTX.js → host-session-command-4WRR5JSB.js} +1 -1
- package/dist/bundle/chunks/{interactive-mode-UZXPNJ4V.js → interactive-mode-TF7R35GK.js} +1 -1
- package/dist/bundle/chunks/{main-O5G75MYS.js → main-XLUYSOXP.js} +1 -1
- package/dist/bundle/chunks/{multi-session-host-AZKJYA2X.js → multi-session-host-CADYC2BS.js} +4 -3
- package/dist/bundle/chunks/{package-manager-cli-2YDUGJNR.js → package-manager-cli-I62KMIWK.js} +1 -1
- package/dist/bundle/chunks/{rpc-mode-KZD5HZNI.js → rpc-mode-T5GVMUBQ.js} +1 -1
- package/dist/bundle/chunks/{schedule-command-7LSJAINZ.js → schedule-command-YXGRN5CM.js} +1 -1
- package/dist/bundle/chunks/{session-control-endpoint-BG2KQ6MJ.js → session-control-endpoint-PREVS5UO.js} +1 -1
- package/dist/bundle/chunks/session-worker.js +63 -62
- package/dist/bundle/cli.js +2 -2
- package/dist/bundle/host-supervisor.js +5 -5
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/bundle/runtime-manifest.json +1 -1
- package/dist/core/session-recovery-identity.d.ts +12 -1
- package/dist/modes/rpc/compact-call-fold.d.ts +3 -1
- package/dist/modes/rpc/compact-call-fold.js +17 -6
- package/dist/modes/rpc/compact-call-identity.d.ts +13 -0
- package/dist/modes/rpc/compact-call-identity.js +30 -0
- package/dist/modes/rpc/compact-call-model.d.ts +14 -0
- package/dist/modes/rpc/compact-call-model.js +4 -0
- package/dist/modes/rpc/compact-call-table.d.ts +9 -0
- package/dist/modes/rpc/compact-call-table.js +20 -0
- package/dist/modes/rpc/compact-catalog-settled.d.ts +5 -0
- package/dist/modes/rpc/compact-catalog-settled.js +9 -2
- package/dist/modes/rpc/compact-lane-current.d.ts +2 -0
- package/dist/modes/rpc/compact-lane-current.js +4 -0
- package/dist/modes/rpc/compact-message-identity.d.ts +74 -0
- package/dist/modes/rpc/compact-message-identity.js +101 -0
- package/dist/modes/rpc/compact-session-calls.d.ts +5 -4
- package/dist/modes/rpc/compact-session-calls.js +13 -8
- package/dist/modes/rpc/compact-session-state.d.ts +2 -0
- package/dist/modes/rpc/compact-session-state.js +4 -0
- package/dist/modes/rpc/compact-settled-messages.d.ts +12 -4
- package/dist/modes/rpc/compact-settled-messages.js +18 -10
- package/dist/modes/rpc/connection-handler.js +1 -1
- package/dist/modes/rpc/connection-question-bridge.d.ts +2 -1
- package/dist/modes/rpc/connection-question-bridge.js +3 -1
- package/dist/modes/rpc/host-lifecycle-proxy.d.ts +9 -0
- package/dist/modes/rpc/host-lifecycle-proxy.js +29 -7
- package/dist/modes/rpc/rpc-question-types.d.ts +2 -0
- package/dist/modes/rpc/session-acceptance-compact.d.ts +17 -7
- package/dist/modes/rpc/session-acceptance-compact.js +20 -8
- package/dist/modes/rpc/session-acceptance-lane.d.ts +5 -0
- package/dist/modes/rpc/session-acceptance-lane.js +12 -11
- package/dist/modes/rpc/session-event-writer-destinations.d.ts +2 -1
- package/dist/modes/rpc/session-event-writer-destinations.js +24 -9
- package/dist/utils/version-check.js +9 -3
- package/docs/engine-socket/fixtures/admission-routes/i-live-identity.json +716 -0
- package/docs/engine-socket/fixtures/admission-routes/index.json +3 -1
- package/docs/engine-socket/fixtures/admission-routes/j-live-call-identity.json +1020 -0
- package/docs/rpc.md +66 -0
- package/package.json +6 -6
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{CompactSelection,EVENT_RESYNC_CAPABILITY,ExtensionTransportOwner,McpPresenterAuthority,SocketPeerRecovery,attachMcpGrantPresentation,correlatedRecord,declarationReply,effectStatusRecord,isCorrelatedReply,observeLifecycleDelivery,sessionQuestionBridges}from"./chunk-AMCDEC5A.js";import{RPC_ERROR_INVALID_SESSION_CONTEXT,RPC_ERROR_INVALID_SUBSCRIPTION,RPC_ERROR_SESSION_NOT_ATTACHED,RPC_ERROR_SUBSCRIPTION_LIMIT,RPC_ERROR_UNKNOWN_SUBSCRIPTION,RPC_ERROR_UNSUPPORTED_TRANSPORT}from"./chunk-VRKA3LIT.js";import{carriesMedia,normalizeJsonValue,omitNormalInlineMedia}from"./chunk-B255QWLT.js";import{BaseContentHash,compactUpdatesEnabled,fingerprintLine,parseSessionEntryLine}from"./chunk-ARNSNIED.js";import{bindPrivateMcpForms}from"./chunk-7ICGN62G.js";import{COMPACT_EVENTS_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,hostGeneration,hostInstanceId}from"./chunk-VOSHKGXG.js";import{external_exports}from"./chunk-KUPQO7MC.js";import{LegacyRecordDepthError,serializeJsonLine}from"./chunk-H52J72VA.js";import{acquireOwnershipSafeLock}from"./chunk-QEESHRTS.js";import{getAgentDir}from"./chunk-ISZ4EWIS.js";import{processIsLive,processStartTimeMs,readProcessIdentity}from"./chunk-O5RYI3IW.js";import{randomUUID as randomUUID4}from"node:crypto";import{tmpdir}from"node:os";import{join as join5}from"node:path";var CompactReadError=class extends Error{constructor(reason){super(`compact read refused (${reason})`),this.name="CompactReadError",this.reason=reason}},CompactReadLease=class{constructor(dispose,valid=()=>{}){this.released=!1,this.operations=0,this.dispose=dispose,this.valid=valid}assert(){if(this.released)throw new CompactReadError("released");this.valid()}async run(read){return this.assert(),this.hold(async()=>{let result=await read();return this.assert(),result})}async hold(read){if(this.released)throw new CompactReadError("released");this.operations++;try{return await read()}finally{--this.operations===0&&this.released&&this.dispose()}}retain(){if(this.released)throw new CompactReadError("released");this.operations++;let ended=!1;return()=>{ended||(ended=!0,--this.operations===0&&this.released&&this.dispose())}}release(){return this.released?!1:(this.released=!0,this.operations===0&&this.dispose(),!0)}};import{dirname as dirname2,join as join4}from"node:path";import{open as open4,rm as rm3}from"node:fs/promises";import{randomUUID as randomUUID3}from"node:crypto";import{randomUUID}from"node:crypto";import{constants as constants2}from"node:fs";import{lstat as lstat2,mkdir,open as open2,rename,rm}from"node:fs/promises";import{join as join2}from"node:path";import{execFile}from"node:child_process";import{constants}from"node:fs";import{lstat,open,readFile}from"node:fs/promises";import{join}from"node:path";import{promisify}from"node:util";var ROOT_MARKER=".compact-spool-owner",Owner=external_exports.object({bootNonce:external_exports.string().min(1),pid:external_exports.number().int().positive(),startTime:external_exports.string().min(1).refine(value=>processStartTimeMs(value)!==void 0)}),Marker=external_exports.object({kind:external_exports.enum(["scratch","live"]),token:external_exports.string().min(1),owner:Owner.nullable()}),boot,self;function bootNonce(){return boot??=(async()=>{switch(process.platform){case"darwin":return(await promisify(execFile)("/usr/sbin/sysctl",["-n","kern.bootsessionuuid"],{timeout:2e3})).stdout.trim()||null;case"linux":return(await readFile("/proc/sys/kernel/random/boot_id","utf8")).trim()||null;default:return null}})().catch(cause=>{if(cause instanceof Error)return null;throw cause}),boot}function currentRootOwner(){return self??=(async()=>{let bootNonceValue=await bootNonce();if(!bootNonceValue)return null;let start=await rootProcessIdentity(process.pid);return start.kind==="present"?{bootNonce:bootNonceValue,pid:process.pid,startTime:start.identity}:null})(),self}async function rootProcessIdentity(pid){try{return await readProcessIdentity(pid,process.platform,2e3,processIsLive,"UTC")}catch(cause){if(cause instanceof Error&&"syscall"in cause&&typeof cause.syscall=="string"&&/^spawn(?: |$)/.test(cause.syscall))return{kind:"error",error:cause};throw cause}}async function rootOwnerState(owner){let currentBoot=await bootNonce();if(!owner||!currentBoot)return"unknown";if(owner.bootNonce!==currentBoot)return"dead";let start=await rootProcessIdentity(owner.pid);switch(start.kind){case"absent":return processIsLive(owner.pid)?"unknown":"dead";case"present":return start.identity===owner.startTime?"alive":"dead";case"error":return"unknown"}}function privateRootStat(stat){return stat.isDirectory()&&!stat.isSymbolicLink()&&(process.getuid===void 0||stat.uid===process.getuid()&&(stat.mode&63)===0)}async function readRootMarker(dir){try{let path=join(dir,ROOT_MARKER),entry=await lstat(path);if(!entry.isFile()||entry.isSymbolicLink())return;let handle=await open(path,constants.O_RDONLY|(constants.O_NOFOLLOW??0));try{let stat=await handle.stat();if(!stat.isFile()||stat.size>8192||process.getuid!==void 0&&(stat.uid!==process.getuid()||(stat.mode&63)!==0))return;let parsed=Marker.safeParse(JSON.parse(await handle.readFile("utf8")));return parsed.success?parsed.data:void 0}finally{await handle.close()}}catch(cause){if(cause instanceof Error)return;throw cause}}var recoveryAgentDir=getAgentDir(),RecoveryStorageHealth=class{constructor(base){this.failures=0,this.cleared=0,this.dir=join2(base,`.senpi-recovery-health-${process.getuid?.()??"user"}`)}ensureDir(){return this.setup??=(async()=>{if(await mkdir(this.dir,{mode:448,recursive:!0}),!privateRootStat(await lstat2(this.dir)))throw new CompactReadError("ownership")})().catch(cause=>{throw this.setup=void 0,cause}),this.setup}get needsRecovery(){return this.failures>this.cleared}unavailable(){this.failures+=1}async revision(){return await this.ensureDir(),await this.readRevision()??this.advance()}async readRevision(){try{let handle=await open2(join2(this.dir,"revision"),constants2.O_RDONLY|(constants2.O_NOFOLLOW??0));try{let stat=await handle.stat();if(!stat.isFile()||stat.size>128)return;let text=(await handle.readFile("utf8")).trim();return/^(0|[1-9]\d*)$/.test(text)?text:void 0}finally{await handle.close()}}catch(cause){if(cause instanceof Error&&"code"in cause&&cause.code==="ENOENT")return"0";if(cause instanceof Error&&"code"in cause&&cause.code==="ELOOP")return;throw cause}}async recover(operation){await this.ensureDir();let through=this.failures;if(await operation(),through<=this.cleared)return this.revision();if(this.pending&&await this.pending,through<=this.cleared)return this.revision();this.pending=this.advance().then(revision=>(this.cleared=through,revision));try{return await this.pending}finally{this.pending=void 0}}async advance(){await this.ensureDir();let release=await acquireOwnershipSafeLock(join2(this.dir,"revision.lock")),temporary=join2(this.dir,`${randomUUID()}.tmp`);try{let next=String(BigInt(await this.readRevision()??"0")+1n),file=await open2(temporary,constants2.O_WRONLY|constants2.O_CREAT|constants2.O_EXCL|(constants2.O_NOFOLLOW??0),384);try{await file.writeFile(next),await file.sync()}finally{await file.close()}await rename(temporary,join2(this.dir,"revision"));let directory=await open2(this.dir,"r");try{await directory.sync()}finally{await directory.close()}return next}finally{try{await rm(temporary,{force:!0})}finally{await release()}}}};import{randomUUID as randomUUID2}from"node:crypto";import{lstat as lstat3,mkdir as mkdir2,rename as rename2,rm as rm2,rmdir,writeFile as writeFile2}from"node:fs/promises";import{dirname,join as join3}from"node:path";import{open as open3,readFile as readFile2,unlink,writeFile}from"node:fs/promises";var nodeCompactStorageIo={writeFile:(path,data)=>writeFile(path,data,{flag:"wx",mode:384}),readFile:async(path,range)=>{if(!range)return readFile2(path);let handle=await open3(path,"r");try{let{buffer,bytesRead}=await handle.read(Buffer.alloc(range.length),0,range.length,range.offset);return buffer.subarray(0,bytesRead)}finally{await handle.close()}},unlink:path=>unlink(path)};function describeCause(cause){try{return cause instanceof Error?cause.message:String(cause)}catch{return"unprintable failure cause"}}var CompactStorageReadError=class extends Error{constructor(operation,path,cause){super(`compact storage ${operation} failed for ${path}: ${describeCause(cause)}`,{cause}),this.name="CompactStorageReadError",this.operation=operation,this.path=path}};var MARKER=ROOT_MARKER,CompactSpoolRefusedError=class extends Error{constructor(reason,path,cause,cleanupFailure){let detail=cause===void 0?"":`: ${describeCause(cause)}`,kept=cleanupFailure===void 0?"":`; removing the directory failed: ${describeCause(cleanupFailure)}`;super(`compact spool directory refused (${reason}): ${path}${detail}${kept}`,{cause}),this.name="CompactSpoolRefusedError",this.reason=reason,this.path=path}};async function createSpoolDir(dir){await mkdir2(dirname(dir),{recursive:!0,mode:448});try{await mkdir2(dir,{mode:448})}catch(cause){throw cause.code==="EEXIST"?new CompactSpoolRefusedError("pre_existing",dir):cause}let token=randomUUID2(),temporary=join3(dir,`${MARKER}.${token}.tmp`);try{await writeFile2(temporary,JSON.stringify({kind:"scratch",token,owner:await currentRootOwner()}),{flag:"wx",mode:384}),await rename2(temporary,join3(dir,MARKER))}catch(cause){throw await abandonSpoolDir(dir,cause,temporary)}return token}async function abandonSpoolDir(dir,cause,temporary){try{return await rm2(temporary,{force:!0}),cause.code!=="EEXIST"&&await rm2(join3(dir,MARKER),{force:!0}),await rmdir(dir),new CompactSpoolRefusedError("marker_write_failed",dir,cause)}catch(cleanupFailure){return new CompactSpoolRefusedError("marker_write_failed",dir,cause,cleanupFailure)}}async function removeSpoolDir(dir,token){let owned=await lstat3(dir).catch(cause=>{if(cause.code!=="ENOENT")throw cause});if(owned===void 0)return;let refusal3=await refusalFor(dir,owned,token);if(refusal3)throw new CompactSpoolRefusedError(refusal3,dir);await rm2(dir,{recursive:!0,force:!0})}async function refusalFor(dir,owned,token){if(owned.isSymbolicLink())return"symlink";if(!owned.isDirectory())return"not_directory";let markerPath=join3(dir,MARKER),marker=await lstat3(markerPath).catch(()=>{});if(!marker?.isFile()||(await readRootMarker(dir))?.token!==token)return"marker_missing";let uid=process.getuid?.();if(uid!==void 0){if(owned.uid!==uid||marker.uid!==uid)return"foreign_owner";if(((owned.mode|marker.mode)&63)!==0)return"wide_mode"}}var RECLAIM_WORK_ALLOWANCE_BYTES=1024*1024,RECLAIM_RETRY_DELAYS_MS=[100,400,1600,6400,25600],FAILURE_HISTORY=32,FILE_PREFIX={spill_write:"leaf",value_write:"value",node_write:"node"},HALTING=new Set(["spill_write","value_write","node_write","spool_create"]),CompactSpoolStorage=class{assertReadable(){if(this.retired)throw new CompactReadError("retired")}beginRead(){this.assertReadable(),this.reads++,this.reading??=Promise.withResolvers();let done=!1;return()=>{done||(done=!0,--this.reads===0&&(this.reading?.resolve(),this.reading=void 0))}}constructor(dir,io,health=new RecoveryStorageHealth(recoveryAgentDir)){this.failures=[],this.nextFile=1,this.chain=Promise.resolve(),this.queued=0,this.spillQueued=!1,this.halted=!1,this.retired=!1,this.pendingIoCopyBytes=0,this.spillBytesWritten=0,this.reclaimDebtBytes=0,this.reads=0,this.dir=dir,this.io=io,this.health=health}async repair(){let revision=await this.health.recover(async()=>{let path=join4(dirname2(this.dir),`.senpi-repair-${randomUUID3()}`);try{let file=await open4(path,"wx",384);try{await file.writeFile("repair"),await file.sync()}finally{await file.close()}}finally{await rm3(path,{force:!0})}});return this.halted=!1,this.spoolToken===void 0&&(this.dirReady=void 0),this.scheduleSpill(),await this.idle(),revision}async idle(){for(;this.queued>0;)await this.chain}async retire(){this.retired=!0,await this.reading?.promise,await this.idle();let token=this.spoolToken;if(token!==void 0){try{await removeSpoolDir(this.dir,token)}catch(cause){throw this.fail("reclaim",this.dir,cause,0),cause}this.spoolToken=void 0,this.reclaimDebtBytes=0}}async readFile(path,bytes,operation,range){let done=this.beginRead();try{let result=await this.readCommittedFile(path,bytes,operation,range);return this.assertReadable(),result}finally{done()}}async readCommittedFile(path,bytes,operation,range){let data;try{data=await this.io.readFile(path,range)}catch(cause){throw this.readFailure(operation,path,cause)}if(data.byteLength!==bytes)throw this.readFailure(operation,path,new Error(`expected ${bytes} bytes, found ${data.byteLength}`));return data}async writeFile(data,operation,retainedInMemoryBytes){let path=await this.ensureDir(retainedInMemoryBytes);if(path===void 0)return;let file=join4(path,`${FILE_PREFIX[operation]??"page"}-${this.nextFile++}.bin`);this.pendingIoCopyBytes+=data.byteLength;try{return this.health.needsRecovery?await this.health.recover(()=>this.io.writeFile(file,data)):await this.io.writeFile(file,data),this.spillBytesWritten+=data.byteLength,file}catch(cause){try{this.fail(operation,file,cause,retainedInMemoryBytes)}finally{this.discard(file,data.byteLength)}return}finally{this.pendingIoCopyBytes-=data.byteLength}}discard(path,bytes){this.retired||(this.reclaimDebtBytes+=bytes,this.enqueue("reclaim",()=>this.reclaim(path,bytes,0)))}async reclaim(path,bytes,attempt){try{await this.io.unlink(path)}catch(cause){if(cause.code!=="ENOENT"){this.fail("reclaim",path,cause,0);let delay=RECLAIM_RETRY_DELAYS_MS[attempt];delay!==void 0&&setTimeout(()=>{this.retired||this.enqueue("reclaim",()=>this.reclaim(path,bytes,attempt+1))},delay).unref?.();return}}this.reclaimDebtBytes-=bytes,this.scheduleSpill()}get spillAllowed(){return!this.halted&&!this.retired}get spillStopped(){return this.halted||this.reclaimDebtBytes>RECLAIM_WORK_ALLOWANCE_BYTES}enqueue(operation,job){this.queued++,this.chain=this.chain.then(job).catch(cause=>{operation==="spill_write"&&(this.spillQueued=!1),!(this.retired&&cause instanceof CompactReadError&&cause.reason==="retired")&&this.fail(operation,this.dir,cause,0)}).finally(()=>{this.queued--})}ensureDir(retained){return this.dirReady??=createSpoolDir(this.dir).then(token=>(this.spoolToken=token,this.dir),cause=>{this.fail("spool_create",this.dir,cause,retained)}),this.dirReady}readFailure(operation,path,cause){return this.fail(operation,path,cause,0),new CompactStorageReadError(operation,path,cause)}fail(operation,path,cause,retained){(HALTING.has(operation)||operation==="page_write")&&this.health.unavailable(),HALTING.has(operation)&&(this.halted=!0),this.record({operation,path,cause:describeCause(cause),retainedInMemoryBytes:retained})}record(failure){this.failures.push(failure),this.failures.length>FAILURE_HISTORY&&this.failures.shift()}};var COMPACT_SEGMENT_BYTES=65536,CompactSegmentStorage=class extends CompactSpoolStorage{async writeSegment(texts,operation){let data=Buffer.from(texts.join(""),"utf16le"),path=await this.writeFile(data,operation,data.byteLength);if(path!==void 0)return{path,bytes:data.byteLength,operation,live:new Map,liveBytes:0,readers:0,rewritten:!1}}segmentRuns(entries){let runs=[],bytes=0;for(let[entry,size]of entries){let run=runs.at(-1);run&&bytes+size<=COMPACT_SEGMENT_BYTES?(run.push(entry),bytes+=size):(runs.push([entry]),bytes=size)}return runs}async writeSegments(texts,operation){let placements=[],written=[],complete=!1;try{for(let run of this.segmentRuns(texts.map((text,n)=>[n,text.length*2]))){let segment=await this.writeSegment(run.map(n=>texts[n]),operation);if(!segment)return;written.push(segment);let offset=0;for(let n of run)placements[n]=[segment,offset],offset+=texts[n].length*2}return complete=!0,placements}finally{if(!complete)for(let stray of written)this.discard(stray.path,stray.bytes)}}place(segment,id,offset,bytes){let slot={segment,offset,bytes};return segment.live.set(id,slot),segment.liveBytes+=bytes,slot}leave(id,slot){let segment=slot.segment;segment.live.delete(id),segment.liveBytes-=slot.bytes,this.settle(segment)}async readSlot(slot){let{segment,offset,bytes}=slot;segment.readers++;try{return await this.readFile(segment.path,bytes,"leaf_read",{offset,length:bytes})}finally{segment.readers--,this.settle(segment)}}settle(segment){segment.live.size?!segment.rewritten&&segment.liveBytes*2<segment.bytes&&(segment.rewritten=!0,this.enqueue("reclaim",()=>this.rewrite(segment))):segment.readers||this.discard(segment.path,segment.bytes)}async rewrite(segment){if(!this.spillAllowed||!segment.live.size)return;segment.readers++;let next,copied=0;try{let moving=[...segment.live].sort(([,a],[,b])=>a.offset-b.offset),texts=[];for(let n=0;n<moving.length;){let start=moving[n][1].offset,end=start,run=[];for(;n<moving.length&&moving[n][1].offset===end;n++)run.push(moving[n][1]),end+=moving[n][1].bytes;let data=await this.readFile(segment.path,end-start,"leaf_read",{offset:start,length:end-start});this.pendingIoCopyBytes+=data.byteLength,copied+=data.byteLength;for(let slot of run)texts.push(data.toString("utf16le",slot.offset-start,slot.offset-start+slot.bytes))}next=await this.writeSegment(texts,segment.operation);let offset=0;for(let[id,slot]of moving)next&&segment.live.delete(id)&&(segment.liveBytes-=slot.bytes,next.live.set(id,slot),next.liveBytes+=slot.bytes,slot.segment=next,slot.offset=offset),offset+=slot.bytes}catch(error){if(!(error instanceof CompactReadError&&error.reason==="retired"))throw error}finally{this.pendingIoCopyBytes-=copied,segment.readers--,this.settle(segment),next&&this.settle(next)}}};var CompactCommitDependencies=class{constructor(store,ready){this.pending=new Map,this.dependants=new Map,this.store=store,store.subscribeCommitted(id=>{let keys=this.dependants.get(id);this.dependants.delete(id);for(let key of keys??[]){let pending=this.pending.get(key);pending?.delete(id),pending?.size===0&&(this.pending.delete(key),ready(key))}})}get size(){return this.pending.size}has(key){return this.pending.has(key)}set(key,refs){this.delete(key);let pending=new Set(refs.filter(id=>!this.store.isCommitted(id)));if(pending.size!==0){this.pending.set(key,pending);for(let id of pending){let keys=this.dependants.get(id)??new Set;keys.add(key),this.dependants.set(id,keys)}}}delete(key){for(let id of this.pending.get(key)??[]){let keys=this.dependants.get(id);keys?.delete(key),keys?.size===0&&this.dependants.delete(id)}this.pending.delete(key)}};var CompactTextRoots=class{constructor(store){this.nodes=new Map,this.next=-1,this.store=store,this.pending=new CompactCommitDependencies(store,id=>store.committed(id))}get residentNodes(){return this.nodes.size}own(refs){if(refs.length===0)return 0;if(refs.length===1){let[ref]=refs;return this.store.adjust(ref,1,0),ref}let middle=Math.floor(refs.length/2),left=this.own(refs.slice(0,middle)),right=this.own(refs.slice(middle));if(left===0)return right;if(right===0)return left;let root=this.join(left,right);return this.store.adjust(left,-1,0),this.store.adjust(right,-1,0),root}units(id){return id===0?0:id>0?this.store.leafUnits(id):this.node(id).units}isCommitted(id){return this.nodes.has(id)&&!this.pending.has(id)}append(root,text,structured=!1){this.units(root);let leaf2=this.store.createLeaf(text,structured);if(root===0)return leaf2;let result=this.appendLeaf(root,leaf2);return this.store.adjust(root,-1,0),this.store.adjust(leaf2,-1,0),result}adjust(id,live,pins){let work=[[id,live,pins]];for(let next=work.pop();next;next=work.pop()){let[id2,live2,pins2]=next;if(id2>=0){this.store.adjust(id2,live2,pins2);continue}let node=this.node(id2),beforeLive=+(node.live>0),beforePin=+(node.live===0&&node.pins>0);if(node.live+live2<0||node.pins+pins2<0)throw new CompactReadError("ownership");node.live+=live2,node.pins+=pins2;let liveChange=+(node.live>0)-beforeLive,pinChange=+(node.live===0&&node.pins>0)-beforePin;(liveChange||pinChange)&&work.push([node.right,liveChange,pinChange],[node.left,liveChange,pinChange]),node.live===0&&node.pins===0&&(this.pending.delete(id2),this.nodes.delete(id2))}}async read(root,tail,offset,units,maxLeaves=2,valid=()=>this.store.assertReadable()){this.store.assertReadable(),valid();let length=this.units(root);if(!Number.isSafeInteger(offset)||!Number.isSafeInteger(units)||offset<0||units<0||offset+units>length+tail.length)throw new CompactReadError("range");if(units>COMPACT_LEAF_CODE_UNITS)throw new CompactReadError("size_limit");if(!Number.isSafeInteger(maxLeaves)||maxLeaves<1||maxLeaves>2)throw new CompactReadError("count_limit");let selected=[],visit=(id,start,end)=>{if(!(start>=end||id===0))if(id>0){if(selected.length===maxLeaves)throw new CompactReadError("count_limit");selected.push({id,offset:start,units:end-start})}else{let node=this.node(id),leftUnits=this.units(node.left);visit(node.left,start,Math.min(end,leftUnits)),visit(node.right,Math.max(0,start-leftUnits),end-leftUnits)}};visit(root,offset,Math.min(length,offset+units));let tailUnits=units===0?0:Math.max(0,offset+units-Math.max(offset,length));if(selected.length+ +(tailUnits>0)>maxLeaves)throw new CompactReadError("count_limit");this.store.adjust(root,0,1);let done=this.store.beginRead();try{let result="";for(let part of selected){let text=await this.store.readLeaf(part.id);valid(),result+=text.slice(part.offset,part.offset+part.units)}return valid(),result+tail.slice(Math.max(0,offset-length),Math.max(0,offset-length)+tailUnits)}finally{this.store.adjust(root,0,-1),done()}}node(id){let node=this.nodes.get(id);if(!node)throw new CompactReadError("ownership");return node}async*chunks(root,valid){if(valid(),root!==0)if(root>0){let text=await this.read(root,"",0,this.units(root),1,valid);valid(),yield text}else{let node=this.node(root);yield*this.chunks(node.left,valid),yield*this.chunks(node.right,valid)}}appendLeaf(root,leaf2){let node=this.nodes.get(root);if(!node||node.full)return this.join(root,leaf2);let right=this.appendLeaf(node.right,leaf2),result=this.join(node.left,right);return this.store.adjust(right,-1,0),result}height(id){return id>0?0:this.node(id).height}join(left,right){let id=this.next--;return this.nodes.set(id,{left,right,units:this.units(left)+this.units(right),height:1+Math.max(this.height(left),this.height(right)),full:this.height(left)===this.height(right)&&(this.nodes.get(left)?.full??!0)&&(this.nodes.get(right)?.full??!0),live:1,pins:0}),this.store.adjust(left,1,0),this.store.adjust(right,1,0),this.pending.set(id,[left,right]),id}};var COMPACT_LEAF_CODE_UNITS=32768,VALUE_FLUSH_BATCH=128,CompactWriteError=class extends Error{constructor(reason,limit){super(`compact write refused (${reason}${limit===void 0?"":`: depth above ${limit}`})`),this.name="CompactWriteError",this.reason=reason,this.limit=limit}},CompactContentStore=class extends CompactSegmentStorage{subscribeCommitted(listener){this.subscribers.add(listener)}committed(id){for(let listener of this.subscribers)listener(id)}leafUnits(id){let leaf2=this.leaves.get(id);if(!leaf2)throw new CompactReadError("ownership");return leaf2.units}constructor(options){super(options.dir,options.io??nodeCompactStorageIo,options.health),this.leaves=new Map,this.ramLeaves=new Set,this.ramValues=new Set,this.valueQueued=!1,this.structuredBytes={resident:0,spilled:0,pinned:0},this.nextLeafId=1,this.residentPayloadBytes=0,this.pinnedOnlyBytes=0,this.spilledLiveBytes=0,this.subscribers=new Set,this.text=new CompactTextRoots(this),this.spillAboveBytes=options.spillAboveBytes??4*1024*1024,this.spillTargetBytes=options.spillTargetBytes??2*1024*1024}createLeaf(text,value=!1){if(this.assertReadable(),text.length>COMPACT_LEAF_CODE_UNITS)throw new CompactWriteError("size_limit");let id=this.nextLeafId++;return this.leaves.set(id,{text,units:text.length,value,live:1,pins:0,state:"ram"}),(value?this.ramValues:this.ramLeaves).add(id),value?this.structuredBytes.resident+=text.length*2:this.residentPayloadBytes+=text.length*2,this.scheduleSpill(),id}ownFile(path,bytes){let id=this.createLeaf("",!0),leaf2=this.leaves.get(id);if(!leaf2)throw new CompactReadError("ownership");return leaf2.file={path,bytes},id}adjust(id,live,pins){if(id===0)return;if(id<0)return this.text.adjust(id,live,pins);let leaf2=this.leaves.get(id);if(!leaf2||leaf2.live+live<0||leaf2.pins+pins<0)throw new CompactReadError("ownership");let pinnedOnly=leaf2.live===0&&leaf2.pins>0;if(leaf2.live+=live,leaf2.pins+=pins,pinnedOnly!==(leaf2.live===0&&leaf2.pins>0)){let bytes=(pinnedOnly?-2:2)*leaf2.units;leaf2.value?this.structuredBytes.pinned+=bytes:this.pinnedOnlyBytes+=bytes}if(!(leaf2.live>0||leaf2.pins>0)){if(this.leaves.delete(id),leaf2.file&&this.discard(leaf2.file.path,leaf2.file.bytes),(leaf2.value?this.ramValues:this.ramLeaves).delete(id),leaf2.state==="committed"&&leaf2.slot){leaf2.value?this.structuredBytes.spilled-=leaf2.units*2:this.spilledLiveBytes-=leaf2.units*2,this.leave(id,leaf2.slot);return}leaf2.value?this.structuredBytes.resident-=leaf2.units*2:this.residentPayloadBytes-=leaf2.units*2}}isCommitted(id){return id<=0?id===0||this.text.isCommitted(id):this.leaves.get(id)?.state==="committed"}async readLeaf(id){this.assertReadable();let leaf2=this.leaves.get(id);if(!leaf2)throw new CompactReadError("ownership");this.adjust(id,0,1);try{if(leaf2.text!==void 0)return leaf2.text;if(!leaf2.slot)throw new CompactReadError("ownership");return(await this.readSlot(leaf2.slot)).toString("utf16le")}finally{this.adjust(id,0,-1)}}status(){return{structuredBytes:{...this.structuredBytes},residentPayloadBytes:this.residentPayloadBytes,pendingIoCopyBytes:this.pendingIoCopyBytes,pinnedOnlyBytes:this.pinnedOnlyBytes,spilledLiveBytes:this.spilledLiveBytes,spillBytesWritten:this.spillBytesWritten,reclaimDebtBytes:this.reclaimDebtBytes,spillFailureRetainedBytes:this.spillStopped?Math.max(0,this.residentPayloadBytes-this.spillTargetBytes):0,spillHalted:this.spillStopped,failures:[...this.failures]}}scheduleSpill(){!this.valueQueued&&this.spillAllowed&&this.ramValues.size&&this.reclaimDebtBytes<=RECLAIM_WORK_ALLOWANCE_BYTES&&(this.valueQueued=!0,this.enqueue("value_write",async()=>{try{await this.flushValues()}finally{this.valueQueued=!1}this.scheduleSpill()})),!(this.spillQueued||!this.spillAllowed||this.residentPayloadBytes<=this.spillAboveBytes)&&(this.reclaimDebtBytes>RECLAIM_WORK_ALLOWANCE_BYTES||(this.spillQueued=!0,this.enqueue("spill_write",()=>this.spillNext())))}async spillNext(){let[id]=this.ramLeaves;id!==void 0&&await this.flushLeaf(id),this.spillQueued=!1,this.residentPayloadBytes>this.spillTargetBytes&&(this.spillQueued=this.spillAllowed&&this.ramLeaves.size>0,this.spillQueued&&this.enqueue("spill_write",()=>this.spillNext()))}async flushValues(){if(this.spillStopped)return;let batch=[];for(let id of this.ramValues)if(batch.push([id,this.leafUnits(id)*2]),batch.length===VALUE_FLUSH_BATCH)break;await this.flushLeaves(this.segmentRuns(batch)[0]??[])}flushLeaf(id){return this.flushLeaves([id])}async flushLeaves(ids,operation){if(!this.spillAllowed)return;let batch=[];for(let id of ids){let leaf2=this.leaves.get(id);leaf2?.state!=="ram"||leaf2.text===void 0||(leaf2.state="pending",(leaf2.value?this.ramValues:this.ramLeaves).delete(id),batch.push([id,leaf2,leaf2.text]))}if(!batch.length)return;let placements;try{let texts=batch.map(([,,text])=>text);placements=await this.writeSegments(texts,operation??(batch[0][1].value?"value_write":"spill_write"))}finally{for(let[id,leaf2]of placements?[]:batch)leaf2.state="ram",this.leaves.get(id)===leaf2&&(leaf2.value?this.ramValues:this.ramLeaves).add(id)}if(!placements)return;let placed=[];for(let[n,[id,leaf2]]of batch.entries()){let[segment,offset]=placements[n],bytes=leaf2.units*2;this.leaves.get(id)===leaf2&&!this.retired&&(leaf2.state="committed",leaf2.text=void 0,leaf2.slot=this.place(segment,id,offset,bytes),leaf2.value?(this.structuredBytes.resident-=bytes,this.structuredBytes.spilled+=bytes):(this.residentPayloadBytes-=bytes,this.spilledLiveBytes+=bytes),placed.push(id))}for(let segment of new Set(placements.map(([segment2])=>segment2)))this.settle(segment);for(let id of placed)this.committed(id)}};import{createHash}from"node:crypto";var BOUNDED_ID=/^[A-Za-z0-9][A-Za-z0-9:_-]*$/,CONTENT_DIGEST=/^[0-9a-f]{64}$/,CONTENT_REF=/^c-[0-9]{16}(?::[0-9]{3})*$/,BASE_REF=/^c-[0-9]{16}:base$/,RESERVED_STEP=/:base(?::|$)/,refused=reason=>({ok:!1,reason});function parseBoundedId(value){return value.length===0?refused("empty"):Buffer.byteLength(value)>128?refused("overlong"):BOUNDED_ID.test(value)?{ok:!0,value}:refused("forbidden_character")}function parseContentDigest(value){return value.length===0?refused("empty"):CONTENT_DIGEST.test(value)?{ok:!0,value}:refused("malformed")}function parseContentRef(value){let bounded=parseBoundedId(value);return bounded.ok?RESERVED_STEP.test(value)?refused("reserved"):CONTENT_REF.test(value)?(value.length-18)/4>8?refused("too_deep"):{ok:!0,value}:refused("malformed"):bounded}function parseBaseRef(value){let bounded=parseBoundedId(value);return bounded.ok?BASE_REF.test(value)?{ok:!0,value}:refused("malformed"):bounded}function parsePageRef(value){let base=parseBaseRef(value);if(base.ok)return{ok:!0,value:{kind:"base",ref:base.value}};let content=parseContentRef(value);return content.ok?{ok:!0,value:{kind:"catalog",ref:content.value}}:content}function protocolId(value){let parsed=parseBoundedId(value);if(!parsed.ok)throw new RangeError(`not a bounded protocol id (${parsed.reason}): ${value.length} chars`);return parsed.value}function fixed(value,digits,bound,what){if(!Number.isSafeInteger(value)||value<0||value>=bound)throw new RangeError(`${what} out of range: ${value}`);return String(value).padStart(digits,"0")}function minted(value){let parsed=parseContentRef(value);if(!parsed.ok)throw new RangeError(`catalog ref ${parsed.reason}`);return parsed.value}var catalogRootRef=counter=>minted(`c-${fixed(counter,16,10**16,"catalog counter")}`),childRef=(parent,index)=>minted(`${parent}:${fixed(index,3,128,"catalog child index")}`);function baseRef(root){let parsed=parseBaseRef(`${root}:base`);if(!parsed.ok)throw new RangeError(`base ref ${parsed.reason}`);return parsed.value}var refSteps=ref=>ref.split(":").slice(1).map(Number);var CATALOG_FORMAT="senpi-recovery-catalog",CATALOG_VERSION=1,CATALOG_ENCODING="utf16le",CATALOG_NODE_MAX_UNITS=COMPACT_LEAF_CODE_UNITS,storedBytes=text=>Buffer.from(text,CATALOG_ENCODING);function catalogDigester(domain,length){let tag=Buffer.from(`${CATALOG_FORMAT}/${CATALOG_VERSION}/${CATALOG_ENCODING}/${domain}`,"ascii"),prefix=Buffer.alloc(1+tag.length+8);prefix.writeUInt8(tag.length,0),tag.copy(prefix,1),prefix.writeBigUInt64BE(BigInt(length),1+tag.length);let hash=createHash("sha256").update(prefix),fed=0;return{update:bytes=>{fed+=bytes.length,hash.update(bytes)},finish:()=>{if(fed!==length)throw new RangeError(`catalog digest fed ${fed} of ${length} bytes`);let parsed=parseContentDigest(hash.digest("hex"));if(!parsed.ok)throw new RangeError("sha256 produced a malformed digest");return parsed.value}}}function catalogDigest(domain,bytes){let digester=catalogDigester(domain,bytes.length);return digester.update(bytes),digester.finish()}var HEAD=`{"format":"${CATALOG_FORMAT}","version":${CATALOG_VERSION},"entries":[`,TAIL="]}",encodeEntry=entry=>`{"kind":"${entry.kind}","id":"${entry.id}","length":${entry.length},"digest":"${entry.digest}"}`,CatalogNodeWriter=class{constructor(){this.parts=[],this.units=HEAD.length+TAIL.length}get count(){return this.parts.length}push(entry){if(!Number.isSafeInteger(entry.length)||entry.length<0)throw new RangeError("catalog entry length");let part=encodeEntry(entry),units=this.units+part.length+ +(this.parts.length>0);return this.parts.length===128||units>CATALOG_NODE_MAX_UNITS?!1:(this.parts.push(part),this.units=units,!0)}encode(){return`${HEAD}${this.parts.join(",")}${TAIL}`}},CatalogNodeSchema=external_exports.object({format:external_exports.literal(CATALOG_FORMAT),version:external_exports.literal(CATALOG_VERSION),entries:external_exports.array(external_exports.object({kind:external_exports.string(),id:external_exports.string(),length:external_exports.number().int().nonnegative(),digest:external_exports.string()}).strict()).max(128)}).strict();function decodeCatalogNode(text){let json;try{json=JSON.parse(text)}catch(cause){if(cause instanceof SyntaxError)return{ok:!1,reason:"schema"};throw cause}let parsed=CatalogNodeSchema.safeParse(json);if(!parsed.success)return{ok:!1,reason:"schema"};let entries=[];for(let raw of parsed.data.entries){let kind=parseBoundedId(raw.kind),id=parseBoundedId(raw.id),digest2=parseContentDigest(raw.digest);if(!kind.ok||!id.ok||!digest2.ok)return{ok:!1,reason:"schema"};entries.push({kind:kind.value,id:id.value,length:raw.length,digest:digest2.value})}return{ok:!0,entries}}var FRAGMENT_MAX_BYTES=131072,FRAGMENT_ENVELOPE_MAX_BYTES=Math.ceil(FRAGMENT_MAX_BYTES/3)*4,isIndex=value=>Number.isSafeInteger(value)&&value>=0;function assertRange(offset,length,total){if(!isIndex(offset)||!isIndex(length))throw new CompactReadError("range");if(length>FRAGMENT_MAX_BYTES)throw new CompactReadError("size_limit");if(offset+length>total)throw new CompactReadError("range")}function startAtOrBefore(starts,count,offset){let low=0,high=count-1;for(;low<high;){let middle=low+high+1>>1;(starts[middle]??Number.POSITIVE_INFINITY)<=offset?low=middle:high=middle-1}return low}var FrozenLeafBytes=class{constructor(digest2,leaves,starts,read){this.peakResidentLeaves=0,this.resident=0,this.length=starts[leaves.length]??0,this.digest=digest2,this.leaves=leaves,this.starts=starts,this.read=read}async range(offset,length,valid){assertRange(offset,length,this.length);let out=Buffer.allocUnsafe(length),written=0;for(let index=startAtOrBefore(this.starts,this.leaves.length,offset);written<length;index++){let leaf2=this.leaves[index],start=this.starts[index];if(leaf2===void 0||start===void 0)throw new CompactReadError("integrity");this.peakResidentLeaves=Math.max(this.peakResidentLeaves,++this.resident);try{let stored=storedBytes(await this.read(leaf2));valid?.();let from=Math.max(0,offset-start);written+=stored.copy(out,written,from,Math.min(stored.length,from+length-written))}finally{this.resident-=1}}return out}};async function openFrozenBytes(entry,leaves,read,valid,signal){let digester=catalogDigester("leaf",entry.length),starts=[0],fed=0;for(let leaf2 of leaves){if(signal?.aborted)throw new CompactReadError("aborted");let stored=storedBytes(await read(leaf2));if(valid(),fed+=stored.length,fed>entry.length)throw new CompactReadError("integrity");digester.update(stored),starts.push(fed)}if(fed!==entry.length||digester.finish()!==entry.digest)throw new CompactReadError("integrity");return new FrozenLeafBytes(entry.digest,leaves,starts,read)}async function producePage(bytes,offset,valid){if(!isIndex(offset)||offset>=bytes.length&&bytes.length>0)throw new CompactReadError("range");let length=Math.min(FRAGMENT_MAX_BYTES,bytes.length-offset),page=await bytes.range(offset,length,valid),next=offset+length;return{offset,length,bytes:page,digest:catalogDigest("fragment",page),next:next<bytes.length?next:null,complete:next===bytes.length}}var SKIPPED=new Set(["undefined","function","symbol"]),isRecord=value=>typeof value=="object"&&value!==null&&!Array.isArray(value);function jsonSize(value){let bytes=0,units=0;for(let piece of walk(value))bytes+=Buffer.byteLength(piece),units+=piece.length;return{bytes,units}}function*jsonChunks(value,size){let pending="";for(let piece of walk(value))for(pending+=piece;pending.length>=size;)yield pending.slice(0,size),pending=pending.slice(size);pending.length>0&&(yield pending)}function*walk(value){let stack=[],pending={value};for(;;){if(pending){let current=pending.value;if(pending=void 0,Array.isArray(current))yield"[",stack.push({entries:current,array:!0,index:0});else if(isRecord(current)){yield"{";let members=Object.entries(current).filter(([,child])=>!SKIPPED.has(typeof child));stack.push({entries:members,array:!1,index:0})}else yield JSON.stringify(current)??"null"}let frame=stack.at(-1);if(!frame)return;if(frame.index===frame.entries.length){stack.pop(),yield frame.array?"]":"}";continue}frame.index>0&&(yield",");let entry=frame.entries[frame.index++];if(frame.array)pending={value:entry};else{let[key,child]=entry;yield`${JSON.stringify(key)}:`,pending={value:child}}}}function stageRecord(staging,record,content){let kind=protocolId("event"),id=protocolId("record");if(typeof content=="string")return staging.stage(kind,id,content.slice(0,-1));let chunks2="chunks"in content?content.chunks:()=>jsonChunks(record,FRAGMENT_MAX_BYTES/2),units="units"in content?content.units:0;if("chunks"in content)for(let chunk of chunks2())units+=chunk.length;let transfer=staging.begin(kind,id,units*2);try{for(let chunk of chunks2())transfer.append(chunk);return transfer.commit()}catch(cause){throw transfer.abort(),cause}}function assertNever(value){throw new Error(`unexpected recovery failure: ${JSON.stringify(value)}`)}function refusalReason(failure){switch(failure.kind){case"storage_unavailable":return failure.kind;case"repair_needed":return failure.reason;default:return assertNever(failure)}}var recovered=value=>({ok:!0,value}),repairNeeded=reason=>({kind:"repair_needed",reason}),storageUnavailable=reason=>({kind:"storage_unavailable",reason}),RecoveryRefusedError=class extends Error{constructor(failure){super(`recovery refused (${failure.kind}: ${failure.reason})`),this.name="RecoveryRefusedError",this.failure=failure}};var TRANSFER_STAGING_MAX_BYTES=64*1024*1024,FRAGMENT_MAX_UNITS=FRAGMENT_MAX_BYTES/2,TransferStagingError=class extends Error{constructor(reason){super(`transfer staging refused (${reason})`),this.name="TransferStagingError",this.reason=reason}},StagedReadError=class extends Error{constructor(reason,options){super(`staged read refused (${reason})`,options),this.name="StagedReadError",this.reason=reason}},StagedTransfer=class{constructor(store,entry,settle){this.leaves=[],this.leafDigests=[],this.fed=0,this.open=!0,this.store=store,this.entry=entry,this.settle=settle,this.digester=catalogDigester("leaf",entry.length)}append(text){this.assertOpen();let bytes=text.length*2;bytes>FRAGMENT_MAX_BYTES&&this.refuse("fragment_over_limit"),this.fed+bytes>this.entry.length&&this.refuse("length_mismatch");try{for(let at=0;at<text.length;at+=COMPACT_LEAF_CODE_UNITS){let piece=text.slice(at,at+COMPACT_LEAF_CODE_UNITS);this.leaves.push(this.store.createLeaf(piece)),this.leafDigests.push(catalogDigest("leaf",storedBytes(piece)))}}catch(cause){throw this.abort(),cause}this.digester.update(storedBytes(text)),this.fed+=bytes}commit(){this.assertOpen(),this.fed!==this.entry.length&&this.refuse("length_mismatch"),this.open=!1;let content={ref:{variant:"staged",entry:{...this.entry,digest:this.digester.finish()}},leaves:[...this.leaves],leafDigests:[...this.leafDigests]};return this.settle(content),content}abort(){if(this.open){this.open=!1;for(let leaf2 of this.leaves)this.store.adjust(leaf2,-1,0);this.settle(void 0)}}assertOpen(){if(!this.open)throw new TransferStagingError("staging_closed")}refuse(reason){throw this.abort(),new TransferStagingError(reason)}},TransferStaging=class{constructor(store,maxBytes=TRANSFER_STAGING_MAX_BYTES){this.transfers=new Set,this.staged=new Map,this.reserved=0,this.closed=!1,this.store=store,this.maxBytes=maxBytes}get stagedBytes(){return this.reserved}get residentBytes(){return this.store.status().residentPayloadBytes}begin(kind,id,length){if(this.closed)throw new TransferStagingError("staging_closed");if(!Number.isSafeInteger(length)||length<0||length%2!==0)throw new TransferStagingError("length_mismatch");if(this.reserved+length>this.maxBytes)throw new TransferStagingError("staging_over_byte_limit");this.reserved+=length;let transfer=new StagedTransfer(this.store,{kind,id,length},content=>{this.transfers.delete(transfer),content?this.staged.set(content,length):this.reserved-=length});return this.transfers.add(transfer),transfer}stage(kind,id,text){let transfer=this.begin(kind,id,text.length*2);try{for(let at=0;at<text.length;at+=FRAGMENT_MAX_UNITS)transfer.append(text.slice(at,at+FRAGMENT_MAX_UNITS));return transfer.commit()}catch(cause){throw transfer.abort(),cause}}adopt(content){let bytes=this.staged.get(content);if(bytes===void 0)throw new CompactReadError("ownership");this.staged.delete(content),this.reserved-=bytes}release(content){let bytes=this.staged.get(content);bytes!==void 0&&(this.staged.delete(content),this.reserved-=bytes);for(let leaf2 of content.leaves)this.store.adjust(leaf2,-1,0)}abandon(content){this.staged.has(content)&&this.release(content)}pin(content,pins){for(let leaf2 of content.leaves)this.store.adjust(leaf2,0,pins)}open(content,valid=()=>{}){return openFrozenBytes(content.ref.entry,content.leaves,leaf2=>this.store.readLeaf(leaf2),valid)}async*chunks(content,valid=()=>{}){let length=0;for(let[index,leaf2]of content.leaves.entries()){let text;try{text=await this.store.readLeaf(leaf2)}catch(cause){throw cause instanceof CompactStorageReadError||cause instanceof CompactReadError?new StagedReadError("segment_missing",{cause}):cause}if(valid(),catalogDigest("leaf",storedBytes(text))!==content.leafDigests[index])throw new StagedReadError("segment_mismatch");length+=text.length*2,yield text}if(length!==content.ref.entry.length)throw new StagedReadError("segment_mismatch")}spill(content){for(let leaf2 of content.leaves)this.store.enqueue("spill_write",()=>this.store.flushLeaf(leaf2))}status(){return{...this.store.status(),stagedBytes:this.reserved,openTransfers:this.transfers.size}}idle(){return this.store.idle()}close(){this.closed=!0;for(let transfer of[...this.transfers])transfer.abort();for(let content of[...this.staged.keys()])this.release(content);return this.store.retire()}};var COMPACT_RECORD_MAX_BYTES=2*FRAGMENT_MAX_BYTES,PEER_EVENT_LEASES_MAX=32,RELEASED_LEASES_REMEMBERED=256,EVENT_RECORD_COMPONENT="record",EventLeases=class{constructor(peerLimit=PEER_EVENT_LEASES_MAX){this.peers=new Map,this.shared=new WeakMap,this.ended=new Set,this.refusals=new Map,this.open=0,this.minted=0,this.released=0,this.duplicates=0,this.abandoned=0,this.contentBytes=0,this.peerLimit=peerLimit}onLeaseEnd(listener){this.ended.add(listener)}mint(caller,at,record,content){let peer=this.peers.get(caller.socketEpoch)??{held:new Map,released:new Map};if(peer.held.size>=this.peerLimit)return this.refuse("lease_limit");let shared=this.stage(record,content);if(!shared)return this.refuse("storage_unavailable");let{entry}=shared.content.ref,lease=Object.freeze({kind:"event",id:protocolId(`event:${caller.socketEpoch}:${++this.minted}`),admissionId:caller.admissionId,...at,componentRef:EVENT_RECORD_COMPONENT,length:entry.length,digest:entry.digest});shared.holders+=1;let held={lease,sessionId:caller.sessionId,shared,admissions:new Set([caller.admissionId]),reads:new CompactReadLease(()=>this.dispose(peer,held))};return peer.held.set(lease.id,held),this.peers.set(caller.socketEpoch,peer),this.open+=1,{ok:!0,value:lease}}claim(caller,leaseId,admissionId){let held=this.peers.get(caller.socketEpoch)?.held.get(leaseId);return!held||held.sessionId!==caller.sessionId||!held.admissions.has(admissionId)?{ok:!1,failure:repairNeeded("unknown_token")}:recovered(held)}async page(held,componentRef,offset,signal){let staging=this.staging;if(componentRef!==EVENT_RECORD_COMPONENT||!staging)return{ok:!1,failure:storageUnavailable("range")};try{return staging.store.health.needsRecovery&&await staging.store.repair(),recovered(await held.reads.run(async()=>{held.shared.opened??=staging.open(held.shared.content);let bytes=await held.shared.opened;if(signal?.aborted)throw new CompactReadError("aborted");return producePage(bytes,offset,()=>held.reads.assert())}))}catch(cause){if(held.shared.opened=void 0,cause instanceof StagedReadError)return{ok:!1,failure:storageUnavailable("integrity")};if(!(cause instanceof CompactReadError))throw cause;return{ok:!1,failure:cause.reason==="released"?repairNeeded("released"):storageUnavailable(cause.reason)}}}release(caller,leaseId,admissionId){let peer=this.peers.get(caller.socketEpoch),receipt=(outcome,remaining)=>recovered({lease:{kind:"event",id:leaseId},outcome,remaining});if(!peer)return{ok:!1,failure:repairNeeded("unknown_token")};let held=peer.held.get(leaseId);if(held?.sessionId===caller.sessionId&&held.admissions.delete(admissionId))return this.remember(peer,held,admissionId),held.admissions.size>0?receipt("held",held.admissions.size):(this.released+=1,held.reads.release(),receipt("released",0));let done=peer.released.get(leaseId);return done?.sessionId===caller.sessionId&&done.admissions.has(admissionId)?(this.duplicates+=1,receipt("duplicate",held?.admissions.size??0)):{ok:!1,failure:repairNeeded("unknown_token")}}abandon(socketEpoch,leaseId){let held=this.peers.get(socketEpoch)?.held.get(leaseId);!held||!held.reads.release()||(this.abandoned+=1)}forgetAdmission(caller,admissionId){for(let held of this.peers.get(caller.socketEpoch)?.held.values()??[])held.sessionId!==caller.sessionId||!held.admissions.delete(admissionId)||held.admissions.size===0&&this.abandon(caller.socketEpoch,held.lease.id)}forgetPeer(socketEpoch){let peer=this.peers.get(socketEpoch);this.peers.delete(socketEpoch);for(let held of peer?.held.values()??[])held.reads.release()}status(){return{open:this.open,peers:this.peers.size,minted:this.minted,released:this.released,duplicates:this.duplicates,abandoned:this.abandoned,contentBytes:this.contentBytes,refused:Object.fromEntries(this.refusals)}}stage(record,content){let existing=this.shared.get(record);if(existing&&existing.holders>0)return existing;this.staging??=new TransferStaging(new CompactContentStore({dir:join5(tmpdir(),`senpi-event-leases-${randomUUID4()}`)}));try{let staged=stageRecord(this.staging,record,content);this.staging.adopt(staged);let shared={content:staged,holders:0};return this.contentBytes+=staged.ref.entry.length,this.shared.set(record,shared),shared}catch(cause){if(cause instanceof TransferStagingError||cause instanceof CompactWriteError||cause instanceof CompactReadError){process.stderr.write(`senpi rpc event lease: record not staged (${cause.message})
|
|
2
|
+
import{CompactSelection,EVENT_RESYNC_CAPABILITY,ExtensionTransportOwner,McpPresenterAuthority,SocketPeerRecovery,attachMcpGrantPresentation,correlatedRecord,declarationReply,effectStatusRecord,isCorrelatedReply,observeLifecycleDelivery,sessionQuestionBridges}from"./chunk-B2LRAXQU.js";import{RPC_ERROR_INVALID_SESSION_CONTEXT,RPC_ERROR_INVALID_SUBSCRIPTION,RPC_ERROR_SESSION_NOT_ATTACHED,RPC_ERROR_SUBSCRIPTION_LIMIT,RPC_ERROR_UNKNOWN_SUBSCRIPTION,RPC_ERROR_UNSUPPORTED_TRANSPORT}from"./chunk-VRKA3LIT.js";import{carriesMedia,normalizeJsonValue,omitNormalInlineMedia}from"./chunk-B255QWLT.js";import{BaseContentHash,compactUpdatesEnabled,fingerprintLine,parseSessionEntryLine}from"./chunk-ARNSNIED.js";import{bindPrivateMcpForms}from"./chunk-7ICGN62G.js";import{COMPACT_EVENTS_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,hostGeneration,hostInstanceId}from"./chunk-VOSHKGXG.js";import{external_exports}from"./chunk-KUPQO7MC.js";import{LegacyRecordDepthError,serializeJsonLine}from"./chunk-H52J72VA.js";import{acquireOwnershipSafeLock}from"./chunk-QEESHRTS.js";import{getAgentDir}from"./chunk-ISZ4EWIS.js";import{processIsLive,processStartTimeMs,readProcessIdentity}from"./chunk-O5RYI3IW.js";import{randomUUID as randomUUID4}from"node:crypto";import{tmpdir}from"node:os";import{join as join5}from"node:path";var CompactReadError=class extends Error{constructor(reason){super(`compact read refused (${reason})`),this.name="CompactReadError",this.reason=reason}},CompactReadLease=class{constructor(dispose,valid=()=>{}){this.released=!1,this.operations=0,this.dispose=dispose,this.valid=valid}assert(){if(this.released)throw new CompactReadError("released");this.valid()}async run(read){return this.assert(),this.hold(async()=>{let result=await read();return this.assert(),result})}async hold(read){if(this.released)throw new CompactReadError("released");this.operations++;try{return await read()}finally{--this.operations===0&&this.released&&this.dispose()}}retain(){if(this.released)throw new CompactReadError("released");this.operations++;let ended=!1;return()=>{ended||(ended=!0,--this.operations===0&&this.released&&this.dispose())}}release(){return this.released?!1:(this.released=!0,this.operations===0&&this.dispose(),!0)}};import{dirname as dirname2,join as join4}from"node:path";import{open as open4,rm as rm3}from"node:fs/promises";import{randomUUID as randomUUID3}from"node:crypto";import{randomUUID}from"node:crypto";import{constants as constants2}from"node:fs";import{lstat as lstat2,mkdir,open as open2,rename,rm}from"node:fs/promises";import{join as join2}from"node:path";import{execFile}from"node:child_process";import{constants}from"node:fs";import{lstat,open,readFile}from"node:fs/promises";import{join}from"node:path";import{promisify}from"node:util";var ROOT_MARKER=".compact-spool-owner",Owner=external_exports.object({bootNonce:external_exports.string().min(1),pid:external_exports.number().int().positive(),startTime:external_exports.string().min(1).refine(value=>processStartTimeMs(value)!==void 0)}),Marker=external_exports.object({kind:external_exports.enum(["scratch","live"]),token:external_exports.string().min(1),owner:Owner.nullable()}),boot,self;function bootNonce(){return boot??=(async()=>{switch(process.platform){case"darwin":return(await promisify(execFile)("/usr/sbin/sysctl",["-n","kern.bootsessionuuid"],{timeout:2e3})).stdout.trim()||null;case"linux":return(await readFile("/proc/sys/kernel/random/boot_id","utf8")).trim()||null;default:return null}})().catch(cause=>{if(cause instanceof Error)return null;throw cause}),boot}function currentRootOwner(){return self??=(async()=>{let bootNonceValue=await bootNonce();if(!bootNonceValue)return null;let start=await rootProcessIdentity(process.pid);return start.kind==="present"?{bootNonce:bootNonceValue,pid:process.pid,startTime:start.identity}:null})(),self}async function rootProcessIdentity(pid){try{return await readProcessIdentity(pid,process.platform,2e3,processIsLive,"UTC")}catch(cause){if(cause instanceof Error&&"syscall"in cause&&typeof cause.syscall=="string"&&/^spawn(?: |$)/.test(cause.syscall))return{kind:"error",error:cause};throw cause}}async function rootOwnerState(owner){let currentBoot=await bootNonce();if(!owner||!currentBoot)return"unknown";if(owner.bootNonce!==currentBoot)return"dead";let start=await rootProcessIdentity(owner.pid);switch(start.kind){case"absent":return processIsLive(owner.pid)?"unknown":"dead";case"present":return start.identity===owner.startTime?"alive":"dead";case"error":return"unknown"}}function privateRootStat(stat){return stat.isDirectory()&&!stat.isSymbolicLink()&&(process.getuid===void 0||stat.uid===process.getuid()&&(stat.mode&63)===0)}async function readRootMarker(dir){try{let path=join(dir,ROOT_MARKER),entry=await lstat(path);if(!entry.isFile()||entry.isSymbolicLink())return;let handle=await open(path,constants.O_RDONLY|(constants.O_NOFOLLOW??0));try{let stat=await handle.stat();if(!stat.isFile()||stat.size>8192||process.getuid!==void 0&&(stat.uid!==process.getuid()||(stat.mode&63)!==0))return;let parsed=Marker.safeParse(JSON.parse(await handle.readFile("utf8")));return parsed.success?parsed.data:void 0}finally{await handle.close()}}catch(cause){if(cause instanceof Error)return;throw cause}}var recoveryAgentDir=getAgentDir(),RecoveryStorageHealth=class{constructor(base){this.failures=0,this.cleared=0,this.dir=join2(base,`.senpi-recovery-health-${process.getuid?.()??"user"}`)}ensureDir(){return this.setup??=(async()=>{if(await mkdir(this.dir,{mode:448,recursive:!0}),!privateRootStat(await lstat2(this.dir)))throw new CompactReadError("ownership")})().catch(cause=>{throw this.setup=void 0,cause}),this.setup}get needsRecovery(){return this.failures>this.cleared}unavailable(){this.failures+=1}async revision(){return await this.ensureDir(),await this.readRevision()??this.advance()}async readRevision(){try{let handle=await open2(join2(this.dir,"revision"),constants2.O_RDONLY|(constants2.O_NOFOLLOW??0));try{let stat=await handle.stat();if(!stat.isFile()||stat.size>128)return;let text=(await handle.readFile("utf8")).trim();return/^(0|[1-9]\d*)$/.test(text)?text:void 0}finally{await handle.close()}}catch(cause){if(cause instanceof Error&&"code"in cause&&cause.code==="ENOENT")return"0";if(cause instanceof Error&&"code"in cause&&cause.code==="ELOOP")return;throw cause}}async recover(operation){await this.ensureDir();let through=this.failures;if(await operation(),through<=this.cleared)return this.revision();if(this.pending&&await this.pending,through<=this.cleared)return this.revision();this.pending=this.advance().then(revision=>(this.cleared=through,revision));try{return await this.pending}finally{this.pending=void 0}}async advance(){await this.ensureDir();let release=await acquireOwnershipSafeLock(join2(this.dir,"revision.lock")),temporary=join2(this.dir,`${randomUUID()}.tmp`);try{let next=String(BigInt(await this.readRevision()??"0")+1n),file=await open2(temporary,constants2.O_WRONLY|constants2.O_CREAT|constants2.O_EXCL|(constants2.O_NOFOLLOW??0),384);try{await file.writeFile(next),await file.sync()}finally{await file.close()}await rename(temporary,join2(this.dir,"revision"));let directory=await open2(this.dir,"r");try{await directory.sync()}finally{await directory.close()}return next}finally{try{await rm(temporary,{force:!0})}finally{await release()}}}};import{randomUUID as randomUUID2}from"node:crypto";import{lstat as lstat3,mkdir as mkdir2,rename as rename2,rm as rm2,rmdir,writeFile as writeFile2}from"node:fs/promises";import{dirname,join as join3}from"node:path";import{open as open3,readFile as readFile2,unlink,writeFile}from"node:fs/promises";var nodeCompactStorageIo={writeFile:(path,data)=>writeFile(path,data,{flag:"wx",mode:384}),readFile:async(path,range)=>{if(!range)return readFile2(path);let handle=await open3(path,"r");try{let{buffer,bytesRead}=await handle.read(Buffer.alloc(range.length),0,range.length,range.offset);return buffer.subarray(0,bytesRead)}finally{await handle.close()}},unlink:path=>unlink(path)};function describeCause(cause){try{return cause instanceof Error?cause.message:String(cause)}catch{return"unprintable failure cause"}}var CompactStorageReadError=class extends Error{constructor(operation,path,cause){super(`compact storage ${operation} failed for ${path}: ${describeCause(cause)}`,{cause}),this.name="CompactStorageReadError",this.operation=operation,this.path=path}};var MARKER=ROOT_MARKER,CompactSpoolRefusedError=class extends Error{constructor(reason,path,cause,cleanupFailure){let detail=cause===void 0?"":`: ${describeCause(cause)}`,kept=cleanupFailure===void 0?"":`; removing the directory failed: ${describeCause(cleanupFailure)}`;super(`compact spool directory refused (${reason}): ${path}${detail}${kept}`,{cause}),this.name="CompactSpoolRefusedError",this.reason=reason,this.path=path}};async function createSpoolDir(dir){await mkdir2(dirname(dir),{recursive:!0,mode:448});try{await mkdir2(dir,{mode:448})}catch(cause){throw cause.code==="EEXIST"?new CompactSpoolRefusedError("pre_existing",dir):cause}let token=randomUUID2(),temporary=join3(dir,`${MARKER}.${token}.tmp`);try{await writeFile2(temporary,JSON.stringify({kind:"scratch",token,owner:await currentRootOwner()}),{flag:"wx",mode:384}),await rename2(temporary,join3(dir,MARKER))}catch(cause){throw await abandonSpoolDir(dir,cause,temporary)}return token}async function abandonSpoolDir(dir,cause,temporary){try{return await rm2(temporary,{force:!0}),cause.code!=="EEXIST"&&await rm2(join3(dir,MARKER),{force:!0}),await rmdir(dir),new CompactSpoolRefusedError("marker_write_failed",dir,cause)}catch(cleanupFailure){return new CompactSpoolRefusedError("marker_write_failed",dir,cause,cleanupFailure)}}async function removeSpoolDir(dir,token){let owned=await lstat3(dir).catch(cause=>{if(cause.code!=="ENOENT")throw cause});if(owned===void 0)return;let refusal3=await refusalFor(dir,owned,token);if(refusal3)throw new CompactSpoolRefusedError(refusal3,dir);await rm2(dir,{recursive:!0,force:!0})}async function refusalFor(dir,owned,token){if(owned.isSymbolicLink())return"symlink";if(!owned.isDirectory())return"not_directory";let markerPath=join3(dir,MARKER),marker=await lstat3(markerPath).catch(()=>{});if(!marker?.isFile()||(await readRootMarker(dir))?.token!==token)return"marker_missing";let uid=process.getuid?.();if(uid!==void 0){if(owned.uid!==uid||marker.uid!==uid)return"foreign_owner";if(((owned.mode|marker.mode)&63)!==0)return"wide_mode"}}var RECLAIM_WORK_ALLOWANCE_BYTES=1024*1024,RECLAIM_RETRY_DELAYS_MS=[100,400,1600,6400,25600],FAILURE_HISTORY=32,FILE_PREFIX={spill_write:"leaf",value_write:"value",node_write:"node"},HALTING=new Set(["spill_write","value_write","node_write","spool_create"]),CompactSpoolStorage=class{assertReadable(){if(this.retired)throw new CompactReadError("retired")}beginRead(){this.assertReadable(),this.reads++,this.reading??=Promise.withResolvers();let done=!1;return()=>{done||(done=!0,--this.reads===0&&(this.reading?.resolve(),this.reading=void 0))}}constructor(dir,io,health=new RecoveryStorageHealth(recoveryAgentDir)){this.failures=[],this.nextFile=1,this.chain=Promise.resolve(),this.queued=0,this.spillQueued=!1,this.halted=!1,this.retired=!1,this.pendingIoCopyBytes=0,this.spillBytesWritten=0,this.reclaimDebtBytes=0,this.reads=0,this.dir=dir,this.io=io,this.health=health}async repair(){let revision=await this.health.recover(async()=>{let path=join4(dirname2(this.dir),`.senpi-repair-${randomUUID3()}`);try{let file=await open4(path,"wx",384);try{await file.writeFile("repair"),await file.sync()}finally{await file.close()}}finally{await rm3(path,{force:!0})}});return this.halted=!1,this.spoolToken===void 0&&(this.dirReady=void 0),this.scheduleSpill(),await this.idle(),revision}async idle(){for(;this.queued>0;)await this.chain}async retire(){this.retired=!0,await this.reading?.promise,await this.idle();let token=this.spoolToken;if(token!==void 0){try{await removeSpoolDir(this.dir,token)}catch(cause){throw this.fail("reclaim",this.dir,cause,0),cause}this.spoolToken=void 0,this.reclaimDebtBytes=0}}async readFile(path,bytes,operation,range){let done=this.beginRead();try{let result=await this.readCommittedFile(path,bytes,operation,range);return this.assertReadable(),result}finally{done()}}async readCommittedFile(path,bytes,operation,range){let data;try{data=await this.io.readFile(path,range)}catch(cause){throw this.readFailure(operation,path,cause)}if(data.byteLength!==bytes)throw this.readFailure(operation,path,new Error(`expected ${bytes} bytes, found ${data.byteLength}`));return data}async writeFile(data,operation,retainedInMemoryBytes){let path=await this.ensureDir(retainedInMemoryBytes);if(path===void 0)return;let file=join4(path,`${FILE_PREFIX[operation]??"page"}-${this.nextFile++}.bin`);this.pendingIoCopyBytes+=data.byteLength;try{return this.health.needsRecovery?await this.health.recover(()=>this.io.writeFile(file,data)):await this.io.writeFile(file,data),this.spillBytesWritten+=data.byteLength,file}catch(cause){try{this.fail(operation,file,cause,retainedInMemoryBytes)}finally{this.discard(file,data.byteLength)}return}finally{this.pendingIoCopyBytes-=data.byteLength}}discard(path,bytes){this.retired||(this.reclaimDebtBytes+=bytes,this.enqueue("reclaim",()=>this.reclaim(path,bytes,0)))}async reclaim(path,bytes,attempt){try{await this.io.unlink(path)}catch(cause){if(cause.code!=="ENOENT"){this.fail("reclaim",path,cause,0);let delay=RECLAIM_RETRY_DELAYS_MS[attempt];delay!==void 0&&setTimeout(()=>{this.retired||this.enqueue("reclaim",()=>this.reclaim(path,bytes,attempt+1))},delay).unref?.();return}}this.reclaimDebtBytes-=bytes,this.scheduleSpill()}get spillAllowed(){return!this.halted&&!this.retired}get spillStopped(){return this.halted||this.reclaimDebtBytes>RECLAIM_WORK_ALLOWANCE_BYTES}enqueue(operation,job){this.queued++,this.chain=this.chain.then(job).catch(cause=>{operation==="spill_write"&&(this.spillQueued=!1),!(this.retired&&cause instanceof CompactReadError&&cause.reason==="retired")&&this.fail(operation,this.dir,cause,0)}).finally(()=>{this.queued--})}ensureDir(retained){return this.dirReady??=createSpoolDir(this.dir).then(token=>(this.spoolToken=token,this.dir),cause=>{this.fail("spool_create",this.dir,cause,retained)}),this.dirReady}readFailure(operation,path,cause){return this.fail(operation,path,cause,0),new CompactStorageReadError(operation,path,cause)}fail(operation,path,cause,retained){(HALTING.has(operation)||operation==="page_write")&&this.health.unavailable(),HALTING.has(operation)&&(this.halted=!0),this.record({operation,path,cause:describeCause(cause),retainedInMemoryBytes:retained})}record(failure){this.failures.push(failure),this.failures.length>FAILURE_HISTORY&&this.failures.shift()}};var COMPACT_SEGMENT_BYTES=65536,CompactSegmentStorage=class extends CompactSpoolStorage{async writeSegment(texts,operation){let data=Buffer.from(texts.join(""),"utf16le"),path=await this.writeFile(data,operation,data.byteLength);if(path!==void 0)return{path,bytes:data.byteLength,operation,live:new Map,liveBytes:0,readers:0,rewritten:!1}}segmentRuns(entries){let runs=[],bytes=0;for(let[entry,size]of entries){let run=runs.at(-1);run&&bytes+size<=COMPACT_SEGMENT_BYTES?(run.push(entry),bytes+=size):(runs.push([entry]),bytes=size)}return runs}async writeSegments(texts,operation){let placements=[],written=[],complete=!1;try{for(let run of this.segmentRuns(texts.map((text,n)=>[n,text.length*2]))){let segment=await this.writeSegment(run.map(n=>texts[n]),operation);if(!segment)return;written.push(segment);let offset=0;for(let n of run)placements[n]=[segment,offset],offset+=texts[n].length*2}return complete=!0,placements}finally{if(!complete)for(let stray of written)this.discard(stray.path,stray.bytes)}}place(segment,id,offset,bytes){let slot={segment,offset,bytes};return segment.live.set(id,slot),segment.liveBytes+=bytes,slot}leave(id,slot){let segment=slot.segment;segment.live.delete(id),segment.liveBytes-=slot.bytes,this.settle(segment)}async readSlot(slot){let{segment,offset,bytes}=slot;segment.readers++;try{return await this.readFile(segment.path,bytes,"leaf_read",{offset,length:bytes})}finally{segment.readers--,this.settle(segment)}}settle(segment){segment.live.size?!segment.rewritten&&segment.liveBytes*2<segment.bytes&&(segment.rewritten=!0,this.enqueue("reclaim",()=>this.rewrite(segment))):segment.readers||this.discard(segment.path,segment.bytes)}async rewrite(segment){if(!this.spillAllowed||!segment.live.size)return;segment.readers++;let next,copied=0;try{let moving=[...segment.live].sort(([,a],[,b])=>a.offset-b.offset),texts=[];for(let n=0;n<moving.length;){let start=moving[n][1].offset,end=start,run=[];for(;n<moving.length&&moving[n][1].offset===end;n++)run.push(moving[n][1]),end+=moving[n][1].bytes;let data=await this.readFile(segment.path,end-start,"leaf_read",{offset:start,length:end-start});this.pendingIoCopyBytes+=data.byteLength,copied+=data.byteLength;for(let slot of run)texts.push(data.toString("utf16le",slot.offset-start,slot.offset-start+slot.bytes))}next=await this.writeSegment(texts,segment.operation);let offset=0;for(let[id,slot]of moving)next&&segment.live.delete(id)&&(segment.liveBytes-=slot.bytes,next.live.set(id,slot),next.liveBytes+=slot.bytes,slot.segment=next,slot.offset=offset),offset+=slot.bytes}catch(error){if(!(error instanceof CompactReadError&&error.reason==="retired"))throw error}finally{this.pendingIoCopyBytes-=copied,segment.readers--,this.settle(segment),next&&this.settle(next)}}};var CompactCommitDependencies=class{constructor(store,ready){this.pending=new Map,this.dependants=new Map,this.store=store,store.subscribeCommitted(id=>{let keys=this.dependants.get(id);this.dependants.delete(id);for(let key of keys??[]){let pending=this.pending.get(key);pending?.delete(id),pending?.size===0&&(this.pending.delete(key),ready(key))}})}get size(){return this.pending.size}has(key){return this.pending.has(key)}set(key,refs){this.delete(key);let pending=new Set(refs.filter(id=>!this.store.isCommitted(id)));if(pending.size!==0){this.pending.set(key,pending);for(let id of pending){let keys=this.dependants.get(id)??new Set;keys.add(key),this.dependants.set(id,keys)}}}delete(key){for(let id of this.pending.get(key)??[]){let keys=this.dependants.get(id);keys?.delete(key),keys?.size===0&&this.dependants.delete(id)}this.pending.delete(key)}};var CompactTextRoots=class{constructor(store){this.nodes=new Map,this.next=-1,this.store=store,this.pending=new CompactCommitDependencies(store,id=>store.committed(id))}get residentNodes(){return this.nodes.size}own(refs){if(refs.length===0)return 0;if(refs.length===1){let[ref]=refs;return this.store.adjust(ref,1,0),ref}let middle=Math.floor(refs.length/2),left=this.own(refs.slice(0,middle)),right=this.own(refs.slice(middle));if(left===0)return right;if(right===0)return left;let root=this.join(left,right);return this.store.adjust(left,-1,0),this.store.adjust(right,-1,0),root}units(id){return id===0?0:id>0?this.store.leafUnits(id):this.node(id).units}isCommitted(id){return this.nodes.has(id)&&!this.pending.has(id)}append(root,text,structured=!1){this.units(root);let leaf2=this.store.createLeaf(text,structured);if(root===0)return leaf2;let result=this.appendLeaf(root,leaf2);return this.store.adjust(root,-1,0),this.store.adjust(leaf2,-1,0),result}adjust(id,live,pins){let work=[[id,live,pins]];for(let next=work.pop();next;next=work.pop()){let[id2,live2,pins2]=next;if(id2>=0){this.store.adjust(id2,live2,pins2);continue}let node=this.node(id2),beforeLive=+(node.live>0),beforePin=+(node.live===0&&node.pins>0);if(node.live+live2<0||node.pins+pins2<0)throw new CompactReadError("ownership");node.live+=live2,node.pins+=pins2;let liveChange=+(node.live>0)-beforeLive,pinChange=+(node.live===0&&node.pins>0)-beforePin;(liveChange||pinChange)&&work.push([node.right,liveChange,pinChange],[node.left,liveChange,pinChange]),node.live===0&&node.pins===0&&(this.pending.delete(id2),this.nodes.delete(id2))}}async read(root,tail,offset,units,maxLeaves=2,valid=()=>this.store.assertReadable()){this.store.assertReadable(),valid();let length=this.units(root);if(!Number.isSafeInteger(offset)||!Number.isSafeInteger(units)||offset<0||units<0||offset+units>length+tail.length)throw new CompactReadError("range");if(units>COMPACT_LEAF_CODE_UNITS)throw new CompactReadError("size_limit");if(!Number.isSafeInteger(maxLeaves)||maxLeaves<1||maxLeaves>2)throw new CompactReadError("count_limit");let selected=[],visit=(id,start,end)=>{if(!(start>=end||id===0))if(id>0){if(selected.length===maxLeaves)throw new CompactReadError("count_limit");selected.push({id,offset:start,units:end-start})}else{let node=this.node(id),leftUnits=this.units(node.left);visit(node.left,start,Math.min(end,leftUnits)),visit(node.right,Math.max(0,start-leftUnits),end-leftUnits)}};visit(root,offset,Math.min(length,offset+units));let tailUnits=units===0?0:Math.max(0,offset+units-Math.max(offset,length));if(selected.length+ +(tailUnits>0)>maxLeaves)throw new CompactReadError("count_limit");this.store.adjust(root,0,1);let done=this.store.beginRead();try{let result="";for(let part of selected){let text=await this.store.readLeaf(part.id);valid(),result+=text.slice(part.offset,part.offset+part.units)}return valid(),result+tail.slice(Math.max(0,offset-length),Math.max(0,offset-length)+tailUnits)}finally{this.store.adjust(root,0,-1),done()}}node(id){let node=this.nodes.get(id);if(!node)throw new CompactReadError("ownership");return node}async*chunks(root,valid){if(valid(),root!==0)if(root>0){let text=await this.read(root,"",0,this.units(root),1,valid);valid(),yield text}else{let node=this.node(root);yield*this.chunks(node.left,valid),yield*this.chunks(node.right,valid)}}appendLeaf(root,leaf2){let node=this.nodes.get(root);if(!node||node.full)return this.join(root,leaf2);let right=this.appendLeaf(node.right,leaf2),result=this.join(node.left,right);return this.store.adjust(right,-1,0),result}height(id){return id>0?0:this.node(id).height}join(left,right){let id=this.next--;return this.nodes.set(id,{left,right,units:this.units(left)+this.units(right),height:1+Math.max(this.height(left),this.height(right)),full:this.height(left)===this.height(right)&&(this.nodes.get(left)?.full??!0)&&(this.nodes.get(right)?.full??!0),live:1,pins:0}),this.store.adjust(left,1,0),this.store.adjust(right,1,0),this.pending.set(id,[left,right]),id}};var COMPACT_LEAF_CODE_UNITS=32768,VALUE_FLUSH_BATCH=128,CompactWriteError=class extends Error{constructor(reason,limit){super(`compact write refused (${reason}${limit===void 0?"":`: depth above ${limit}`})`),this.name="CompactWriteError",this.reason=reason,this.limit=limit}},CompactContentStore=class extends CompactSegmentStorage{subscribeCommitted(listener){this.subscribers.add(listener)}committed(id){for(let listener of this.subscribers)listener(id)}leafUnits(id){let leaf2=this.leaves.get(id);if(!leaf2)throw new CompactReadError("ownership");return leaf2.units}constructor(options){super(options.dir,options.io??nodeCompactStorageIo,options.health),this.leaves=new Map,this.ramLeaves=new Set,this.ramValues=new Set,this.valueQueued=!1,this.structuredBytes={resident:0,spilled:0,pinned:0},this.nextLeafId=1,this.residentPayloadBytes=0,this.pinnedOnlyBytes=0,this.spilledLiveBytes=0,this.subscribers=new Set,this.text=new CompactTextRoots(this),this.spillAboveBytes=options.spillAboveBytes??4*1024*1024,this.spillTargetBytes=options.spillTargetBytes??2*1024*1024}createLeaf(text,value=!1){if(this.assertReadable(),text.length>COMPACT_LEAF_CODE_UNITS)throw new CompactWriteError("size_limit");let id=this.nextLeafId++;return this.leaves.set(id,{text,units:text.length,value,live:1,pins:0,state:"ram"}),(value?this.ramValues:this.ramLeaves).add(id),value?this.structuredBytes.resident+=text.length*2:this.residentPayloadBytes+=text.length*2,this.scheduleSpill(),id}ownFile(path,bytes){let id=this.createLeaf("",!0),leaf2=this.leaves.get(id);if(!leaf2)throw new CompactReadError("ownership");return leaf2.file={path,bytes},id}adjust(id,live,pins){if(id===0)return;if(id<0)return this.text.adjust(id,live,pins);let leaf2=this.leaves.get(id);if(!leaf2||leaf2.live+live<0||leaf2.pins+pins<0)throw new CompactReadError("ownership");let pinnedOnly=leaf2.live===0&&leaf2.pins>0;if(leaf2.live+=live,leaf2.pins+=pins,pinnedOnly!==(leaf2.live===0&&leaf2.pins>0)){let bytes=(pinnedOnly?-2:2)*leaf2.units;leaf2.value?this.structuredBytes.pinned+=bytes:this.pinnedOnlyBytes+=bytes}if(!(leaf2.live>0||leaf2.pins>0)){if(this.leaves.delete(id),leaf2.file&&this.discard(leaf2.file.path,leaf2.file.bytes),(leaf2.value?this.ramValues:this.ramLeaves).delete(id),leaf2.state==="committed"&&leaf2.slot){leaf2.value?this.structuredBytes.spilled-=leaf2.units*2:this.spilledLiveBytes-=leaf2.units*2,this.leave(id,leaf2.slot);return}leaf2.value?this.structuredBytes.resident-=leaf2.units*2:this.residentPayloadBytes-=leaf2.units*2}}isCommitted(id){return id<=0?id===0||this.text.isCommitted(id):this.leaves.get(id)?.state==="committed"}async readLeaf(id){this.assertReadable();let leaf2=this.leaves.get(id);if(!leaf2)throw new CompactReadError("ownership");this.adjust(id,0,1);try{if(leaf2.text!==void 0)return leaf2.text;if(!leaf2.slot)throw new CompactReadError("ownership");return(await this.readSlot(leaf2.slot)).toString("utf16le")}finally{this.adjust(id,0,-1)}}status(){return{structuredBytes:{...this.structuredBytes},residentPayloadBytes:this.residentPayloadBytes,pendingIoCopyBytes:this.pendingIoCopyBytes,pinnedOnlyBytes:this.pinnedOnlyBytes,spilledLiveBytes:this.spilledLiveBytes,spillBytesWritten:this.spillBytesWritten,reclaimDebtBytes:this.reclaimDebtBytes,spillFailureRetainedBytes:this.spillStopped?Math.max(0,this.residentPayloadBytes-this.spillTargetBytes):0,spillHalted:this.spillStopped,failures:[...this.failures]}}scheduleSpill(){!this.valueQueued&&this.spillAllowed&&this.ramValues.size&&this.reclaimDebtBytes<=RECLAIM_WORK_ALLOWANCE_BYTES&&(this.valueQueued=!0,this.enqueue("value_write",async()=>{try{await this.flushValues()}finally{this.valueQueued=!1}this.scheduleSpill()})),!(this.spillQueued||!this.spillAllowed||this.residentPayloadBytes<=this.spillAboveBytes)&&(this.reclaimDebtBytes>RECLAIM_WORK_ALLOWANCE_BYTES||(this.spillQueued=!0,this.enqueue("spill_write",()=>this.spillNext())))}async spillNext(){let[id]=this.ramLeaves;id!==void 0&&await this.flushLeaf(id),this.spillQueued=!1,this.residentPayloadBytes>this.spillTargetBytes&&(this.spillQueued=this.spillAllowed&&this.ramLeaves.size>0,this.spillQueued&&this.enqueue("spill_write",()=>this.spillNext()))}async flushValues(){if(this.spillStopped)return;let batch=[];for(let id of this.ramValues)if(batch.push([id,this.leafUnits(id)*2]),batch.length===VALUE_FLUSH_BATCH)break;await this.flushLeaves(this.segmentRuns(batch)[0]??[])}flushLeaf(id){return this.flushLeaves([id])}async flushLeaves(ids,operation){if(!this.spillAllowed)return;let batch=[];for(let id of ids){let leaf2=this.leaves.get(id);leaf2?.state!=="ram"||leaf2.text===void 0||(leaf2.state="pending",(leaf2.value?this.ramValues:this.ramLeaves).delete(id),batch.push([id,leaf2,leaf2.text]))}if(!batch.length)return;let placements;try{let texts=batch.map(([,,text])=>text);placements=await this.writeSegments(texts,operation??(batch[0][1].value?"value_write":"spill_write"))}finally{for(let[id,leaf2]of placements?[]:batch)leaf2.state="ram",this.leaves.get(id)===leaf2&&(leaf2.value?this.ramValues:this.ramLeaves).add(id)}if(!placements)return;let placed=[];for(let[n,[id,leaf2]]of batch.entries()){let[segment,offset]=placements[n],bytes=leaf2.units*2;this.leaves.get(id)===leaf2&&!this.retired&&(leaf2.state="committed",leaf2.text=void 0,leaf2.slot=this.place(segment,id,offset,bytes),leaf2.value?(this.structuredBytes.resident-=bytes,this.structuredBytes.spilled+=bytes):(this.residentPayloadBytes-=bytes,this.spilledLiveBytes+=bytes),placed.push(id))}for(let segment of new Set(placements.map(([segment2])=>segment2)))this.settle(segment);for(let id of placed)this.committed(id)}};import{createHash}from"node:crypto";var BOUNDED_ID=/^[A-Za-z0-9][A-Za-z0-9:_-]*$/,CONTENT_DIGEST=/^[0-9a-f]{64}$/,CONTENT_REF=/^c-[0-9]{16}(?::[0-9]{3})*$/,BASE_REF=/^c-[0-9]{16}:base$/,RESERVED_STEP=/:base(?::|$)/,refused=reason=>({ok:!1,reason});function parseBoundedId(value){return value.length===0?refused("empty"):Buffer.byteLength(value)>128?refused("overlong"):BOUNDED_ID.test(value)?{ok:!0,value}:refused("forbidden_character")}function parseContentDigest(value){return value.length===0?refused("empty"):CONTENT_DIGEST.test(value)?{ok:!0,value}:refused("malformed")}function parseContentRef(value){let bounded=parseBoundedId(value);return bounded.ok?RESERVED_STEP.test(value)?refused("reserved"):CONTENT_REF.test(value)?(value.length-18)/4>8?refused("too_deep"):{ok:!0,value}:refused("malformed"):bounded}function parseBaseRef(value){let bounded=parseBoundedId(value);return bounded.ok?BASE_REF.test(value)?{ok:!0,value}:refused("malformed"):bounded}function parsePageRef(value){let base=parseBaseRef(value);if(base.ok)return{ok:!0,value:{kind:"base",ref:base.value}};let content=parseContentRef(value);return content.ok?{ok:!0,value:{kind:"catalog",ref:content.value}}:content}function protocolId(value){let parsed=parseBoundedId(value);if(!parsed.ok)throw new RangeError(`not a bounded protocol id (${parsed.reason}): ${value.length} chars`);return parsed.value}function fixed(value,digits,bound,what){if(!Number.isSafeInteger(value)||value<0||value>=bound)throw new RangeError(`${what} out of range: ${value}`);return String(value).padStart(digits,"0")}function minted(value){let parsed=parseContentRef(value);if(!parsed.ok)throw new RangeError(`catalog ref ${parsed.reason}`);return parsed.value}var catalogRootRef=counter=>minted(`c-${fixed(counter,16,10**16,"catalog counter")}`),childRef=(parent,index)=>minted(`${parent}:${fixed(index,3,128,"catalog child index")}`);function baseRef(root){let parsed=parseBaseRef(`${root}:base`);if(!parsed.ok)throw new RangeError(`base ref ${parsed.reason}`);return parsed.value}var refSteps=ref=>ref.split(":").slice(1).map(Number);var CATALOG_FORMAT="senpi-recovery-catalog",CATALOG_VERSION=1,CATALOG_ENCODING="utf16le",CATALOG_NODE_MAX_UNITS=COMPACT_LEAF_CODE_UNITS,storedBytes=text=>Buffer.from(text,CATALOG_ENCODING);function catalogDigester(domain,length){let tag=Buffer.from(`${CATALOG_FORMAT}/${CATALOG_VERSION}/${CATALOG_ENCODING}/${domain}`,"ascii"),prefix=Buffer.alloc(1+tag.length+8);prefix.writeUInt8(tag.length,0),tag.copy(prefix,1),prefix.writeBigUInt64BE(BigInt(length),1+tag.length);let hash=createHash("sha256").update(prefix),fed=0;return{update:bytes=>{fed+=bytes.length,hash.update(bytes)},finish:()=>{if(fed!==length)throw new RangeError(`catalog digest fed ${fed} of ${length} bytes`);let parsed=parseContentDigest(hash.digest("hex"));if(!parsed.ok)throw new RangeError("sha256 produced a malformed digest");return parsed.value}}}function catalogDigest(domain,bytes){let digester=catalogDigester(domain,bytes.length);return digester.update(bytes),digester.finish()}var HEAD=`{"format":"${CATALOG_FORMAT}","version":${CATALOG_VERSION},"entries":[`,TAIL="]}",encodeEntry=entry=>`{"kind":"${entry.kind}","id":"${entry.id}","length":${entry.length},"digest":"${entry.digest}"}`,CatalogNodeWriter=class{constructor(){this.parts=[],this.units=HEAD.length+TAIL.length}get count(){return this.parts.length}push(entry){if(!Number.isSafeInteger(entry.length)||entry.length<0)throw new RangeError("catalog entry length");let part=encodeEntry(entry),units=this.units+part.length+ +(this.parts.length>0);return this.parts.length===128||units>CATALOG_NODE_MAX_UNITS?!1:(this.parts.push(part),this.units=units,!0)}encode(){return`${HEAD}${this.parts.join(",")}${TAIL}`}},CatalogNodeSchema=external_exports.object({format:external_exports.literal(CATALOG_FORMAT),version:external_exports.literal(CATALOG_VERSION),entries:external_exports.array(external_exports.object({kind:external_exports.string(),id:external_exports.string(),length:external_exports.number().int().nonnegative(),digest:external_exports.string()}).strict()).max(128)}).strict();function decodeCatalogNode(text){let json;try{json=JSON.parse(text)}catch(cause){if(cause instanceof SyntaxError)return{ok:!1,reason:"schema"};throw cause}let parsed=CatalogNodeSchema.safeParse(json);if(!parsed.success)return{ok:!1,reason:"schema"};let entries=[];for(let raw of parsed.data.entries){let kind=parseBoundedId(raw.kind),id=parseBoundedId(raw.id),digest2=parseContentDigest(raw.digest);if(!kind.ok||!id.ok||!digest2.ok)return{ok:!1,reason:"schema"};entries.push({kind:kind.value,id:id.value,length:raw.length,digest:digest2.value})}return{ok:!0,entries}}var FRAGMENT_MAX_BYTES=131072,FRAGMENT_ENVELOPE_MAX_BYTES=Math.ceil(FRAGMENT_MAX_BYTES/3)*4,isIndex=value=>Number.isSafeInteger(value)&&value>=0;function assertRange(offset,length,total){if(!isIndex(offset)||!isIndex(length))throw new CompactReadError("range");if(length>FRAGMENT_MAX_BYTES)throw new CompactReadError("size_limit");if(offset+length>total)throw new CompactReadError("range")}function startAtOrBefore(starts,count,offset){let low=0,high=count-1;for(;low<high;){let middle=low+high+1>>1;(starts[middle]??Number.POSITIVE_INFINITY)<=offset?low=middle:high=middle-1}return low}var FrozenLeafBytes=class{constructor(digest2,leaves,starts,read){this.peakResidentLeaves=0,this.resident=0,this.length=starts[leaves.length]??0,this.digest=digest2,this.leaves=leaves,this.starts=starts,this.read=read}async range(offset,length,valid){assertRange(offset,length,this.length);let out=Buffer.allocUnsafe(length),written=0;for(let index=startAtOrBefore(this.starts,this.leaves.length,offset);written<length;index++){let leaf2=this.leaves[index],start=this.starts[index];if(leaf2===void 0||start===void 0)throw new CompactReadError("integrity");this.peakResidentLeaves=Math.max(this.peakResidentLeaves,++this.resident);try{let stored=storedBytes(await this.read(leaf2));valid?.();let from=Math.max(0,offset-start);written+=stored.copy(out,written,from,Math.min(stored.length,from+length-written))}finally{this.resident-=1}}return out}};async function openFrozenBytes(entry,leaves,read,valid,signal){let digester=catalogDigester("leaf",entry.length),starts=[0],fed=0;for(let leaf2 of leaves){if(signal?.aborted)throw new CompactReadError("aborted");let stored=storedBytes(await read(leaf2));if(valid(),fed+=stored.length,fed>entry.length)throw new CompactReadError("integrity");digester.update(stored),starts.push(fed)}if(fed!==entry.length||digester.finish()!==entry.digest)throw new CompactReadError("integrity");return new FrozenLeafBytes(entry.digest,leaves,starts,read)}async function producePage(bytes,offset,valid){if(!isIndex(offset)||offset>=bytes.length&&bytes.length>0)throw new CompactReadError("range");let length=Math.min(FRAGMENT_MAX_BYTES,bytes.length-offset),page=await bytes.range(offset,length,valid),next=offset+length;return{offset,length,bytes:page,digest:catalogDigest("fragment",page),next:next<bytes.length?next:null,complete:next===bytes.length}}var SKIPPED=new Set(["undefined","function","symbol"]),isRecord=value=>typeof value=="object"&&value!==null&&!Array.isArray(value);function jsonSize(value){let bytes=0,units=0;for(let piece of walk(value))bytes+=Buffer.byteLength(piece),units+=piece.length;return{bytes,units}}function*jsonChunks(value,size){let pending="";for(let piece of walk(value))for(pending+=piece;pending.length>=size;)yield pending.slice(0,size),pending=pending.slice(size);pending.length>0&&(yield pending)}function*walk(value){let stack=[],pending={value};for(;;){if(pending){let current=pending.value;if(pending=void 0,Array.isArray(current))yield"[",stack.push({entries:current,array:!0,index:0});else if(isRecord(current)){yield"{";let members=Object.entries(current).filter(([,child])=>!SKIPPED.has(typeof child));stack.push({entries:members,array:!1,index:0})}else yield JSON.stringify(current)??"null"}let frame=stack.at(-1);if(!frame)return;if(frame.index===frame.entries.length){stack.pop(),yield frame.array?"]":"}";continue}frame.index>0&&(yield",");let entry=frame.entries[frame.index++];if(frame.array)pending={value:entry};else{let[key,child]=entry;yield`${JSON.stringify(key)}:`,pending={value:child}}}}function stageRecord(staging,record,content){let kind=protocolId("event"),id=protocolId("record");if(typeof content=="string")return staging.stage(kind,id,content.slice(0,-1));let chunks2="chunks"in content?content.chunks:()=>jsonChunks(record,FRAGMENT_MAX_BYTES/2),units="units"in content?content.units:0;if("chunks"in content)for(let chunk of chunks2())units+=chunk.length;let transfer=staging.begin(kind,id,units*2);try{for(let chunk of chunks2())transfer.append(chunk);return transfer.commit()}catch(cause){throw transfer.abort(),cause}}function assertNever(value){throw new Error(`unexpected recovery failure: ${JSON.stringify(value)}`)}function refusalReason(failure){switch(failure.kind){case"storage_unavailable":return failure.kind;case"repair_needed":return failure.reason;default:return assertNever(failure)}}var recovered=value=>({ok:!0,value}),repairNeeded=reason=>({kind:"repair_needed",reason}),storageUnavailable=reason=>({kind:"storage_unavailable",reason}),RecoveryRefusedError=class extends Error{constructor(failure){super(`recovery refused (${failure.kind}: ${failure.reason})`),this.name="RecoveryRefusedError",this.failure=failure}};var TRANSFER_STAGING_MAX_BYTES=64*1024*1024,FRAGMENT_MAX_UNITS=FRAGMENT_MAX_BYTES/2,TransferStagingError=class extends Error{constructor(reason){super(`transfer staging refused (${reason})`),this.name="TransferStagingError",this.reason=reason}},StagedReadError=class extends Error{constructor(reason,options){super(`staged read refused (${reason})`,options),this.name="StagedReadError",this.reason=reason}},StagedTransfer=class{constructor(store,entry,settle){this.leaves=[],this.leafDigests=[],this.fed=0,this.open=!0,this.store=store,this.entry=entry,this.settle=settle,this.digester=catalogDigester("leaf",entry.length)}append(text){this.assertOpen();let bytes=text.length*2;bytes>FRAGMENT_MAX_BYTES&&this.refuse("fragment_over_limit"),this.fed+bytes>this.entry.length&&this.refuse("length_mismatch");try{for(let at=0;at<text.length;at+=COMPACT_LEAF_CODE_UNITS){let piece=text.slice(at,at+COMPACT_LEAF_CODE_UNITS);this.leaves.push(this.store.createLeaf(piece)),this.leafDigests.push(catalogDigest("leaf",storedBytes(piece)))}}catch(cause){throw this.abort(),cause}this.digester.update(storedBytes(text)),this.fed+=bytes}commit(){this.assertOpen(),this.fed!==this.entry.length&&this.refuse("length_mismatch"),this.open=!1;let content={ref:{variant:"staged",entry:{...this.entry,digest:this.digester.finish()}},leaves:[...this.leaves],leafDigests:[...this.leafDigests]};return this.settle(content),content}abort(){if(this.open){this.open=!1;for(let leaf2 of this.leaves)this.store.adjust(leaf2,-1,0);this.settle(void 0)}}assertOpen(){if(!this.open)throw new TransferStagingError("staging_closed")}refuse(reason){throw this.abort(),new TransferStagingError(reason)}},TransferStaging=class{constructor(store,maxBytes=TRANSFER_STAGING_MAX_BYTES){this.transfers=new Set,this.staged=new Map,this.reserved=0,this.closed=!1,this.store=store,this.maxBytes=maxBytes}get stagedBytes(){return this.reserved}get residentBytes(){return this.store.status().residentPayloadBytes}begin(kind,id,length){if(this.closed)throw new TransferStagingError("staging_closed");if(!Number.isSafeInteger(length)||length<0||length%2!==0)throw new TransferStagingError("length_mismatch");if(this.reserved+length>this.maxBytes)throw new TransferStagingError("staging_over_byte_limit");this.reserved+=length;let transfer=new StagedTransfer(this.store,{kind,id,length},content=>{this.transfers.delete(transfer),content?this.staged.set(content,length):this.reserved-=length});return this.transfers.add(transfer),transfer}stage(kind,id,text){let transfer=this.begin(kind,id,text.length*2);try{for(let at=0;at<text.length;at+=FRAGMENT_MAX_UNITS)transfer.append(text.slice(at,at+FRAGMENT_MAX_UNITS));return transfer.commit()}catch(cause){throw transfer.abort(),cause}}adopt(content){let bytes=this.staged.get(content);if(bytes===void 0)throw new CompactReadError("ownership");this.staged.delete(content),this.reserved-=bytes}release(content){let bytes=this.staged.get(content);bytes!==void 0&&(this.staged.delete(content),this.reserved-=bytes);for(let leaf2 of content.leaves)this.store.adjust(leaf2,-1,0)}abandon(content){this.staged.has(content)&&this.release(content)}pin(content,pins){for(let leaf2 of content.leaves)this.store.adjust(leaf2,0,pins)}open(content,valid=()=>{}){return openFrozenBytes(content.ref.entry,content.leaves,leaf2=>this.store.readLeaf(leaf2),valid)}async*chunks(content,valid=()=>{}){let length=0;for(let[index,leaf2]of content.leaves.entries()){let text;try{text=await this.store.readLeaf(leaf2)}catch(cause){throw cause instanceof CompactStorageReadError||cause instanceof CompactReadError?new StagedReadError("segment_missing",{cause}):cause}if(valid(),catalogDigest("leaf",storedBytes(text))!==content.leafDigests[index])throw new StagedReadError("segment_mismatch");length+=text.length*2,yield text}if(length!==content.ref.entry.length)throw new StagedReadError("segment_mismatch")}spill(content){for(let leaf2 of content.leaves)this.store.enqueue("spill_write",()=>this.store.flushLeaf(leaf2))}status(){return{...this.store.status(),stagedBytes:this.reserved,openTransfers:this.transfers.size}}idle(){return this.store.idle()}close(){this.closed=!0;for(let transfer of[...this.transfers])transfer.abort();for(let content of[...this.staged.keys()])this.release(content);return this.store.retire()}};var COMPACT_RECORD_MAX_BYTES=2*FRAGMENT_MAX_BYTES,PEER_EVENT_LEASES_MAX=32,RELEASED_LEASES_REMEMBERED=256,EVENT_RECORD_COMPONENT="record",EventLeases=class{constructor(peerLimit=PEER_EVENT_LEASES_MAX){this.peers=new Map,this.shared=new WeakMap,this.ended=new Set,this.refusals=new Map,this.open=0,this.minted=0,this.released=0,this.duplicates=0,this.abandoned=0,this.contentBytes=0,this.peerLimit=peerLimit}onLeaseEnd(listener){this.ended.add(listener)}mint(caller,at,record,content){let peer=this.peers.get(caller.socketEpoch)??{held:new Map,released:new Map};if(peer.held.size>=this.peerLimit)return this.refuse("lease_limit");let shared=this.stage(record,content);if(!shared)return this.refuse("storage_unavailable");let{entry}=shared.content.ref,lease=Object.freeze({kind:"event",id:protocolId(`event:${caller.socketEpoch}:${++this.minted}`),admissionId:caller.admissionId,...at,componentRef:EVENT_RECORD_COMPONENT,length:entry.length,digest:entry.digest});shared.holders+=1;let held={lease,sessionId:caller.sessionId,shared,admissions:new Set([caller.admissionId]),reads:new CompactReadLease(()=>this.dispose(peer,held))};return peer.held.set(lease.id,held),this.peers.set(caller.socketEpoch,peer),this.open+=1,{ok:!0,value:lease}}claim(caller,leaseId,admissionId){let held=this.peers.get(caller.socketEpoch)?.held.get(leaseId);return!held||held.sessionId!==caller.sessionId||!held.admissions.has(admissionId)?{ok:!1,failure:repairNeeded("unknown_token")}:recovered(held)}async page(held,componentRef,offset,signal){let staging=this.staging;if(componentRef!==EVENT_RECORD_COMPONENT||!staging)return{ok:!1,failure:storageUnavailable("range")};try{return staging.store.health.needsRecovery&&await staging.store.repair(),recovered(await held.reads.run(async()=>{held.shared.opened??=staging.open(held.shared.content);let bytes=await held.shared.opened;if(signal?.aborted)throw new CompactReadError("aborted");return producePage(bytes,offset,()=>held.reads.assert())}))}catch(cause){if(held.shared.opened=void 0,cause instanceof StagedReadError)return{ok:!1,failure:storageUnavailable("integrity")};if(!(cause instanceof CompactReadError))throw cause;return{ok:!1,failure:cause.reason==="released"?repairNeeded("released"):storageUnavailable(cause.reason)}}}release(caller,leaseId,admissionId){let peer=this.peers.get(caller.socketEpoch),receipt=(outcome,remaining)=>recovered({lease:{kind:"event",id:leaseId},outcome,remaining});if(!peer)return{ok:!1,failure:repairNeeded("unknown_token")};let held=peer.held.get(leaseId);if(held?.sessionId===caller.sessionId&&held.admissions.delete(admissionId))return this.remember(peer,held,admissionId),held.admissions.size>0?receipt("held",held.admissions.size):(this.released+=1,held.reads.release(),receipt("released",0));let done=peer.released.get(leaseId);return done?.sessionId===caller.sessionId&&done.admissions.has(admissionId)?(this.duplicates+=1,receipt("duplicate",held?.admissions.size??0)):{ok:!1,failure:repairNeeded("unknown_token")}}abandon(socketEpoch,leaseId){let held=this.peers.get(socketEpoch)?.held.get(leaseId);!held||!held.reads.release()||(this.abandoned+=1)}forgetAdmission(caller,admissionId){for(let held of this.peers.get(caller.socketEpoch)?.held.values()??[])held.sessionId!==caller.sessionId||!held.admissions.delete(admissionId)||held.admissions.size===0&&this.abandon(caller.socketEpoch,held.lease.id)}forgetPeer(socketEpoch){let peer=this.peers.get(socketEpoch);this.peers.delete(socketEpoch);for(let held of peer?.held.values()??[])held.reads.release()}status(){return{open:this.open,peers:this.peers.size,minted:this.minted,released:this.released,duplicates:this.duplicates,abandoned:this.abandoned,contentBytes:this.contentBytes,refused:Object.fromEntries(this.refusals)}}stage(record,content){let existing=this.shared.get(record);if(existing&&existing.holders>0)return existing;this.staging??=new TransferStaging(new CompactContentStore({dir:join5(tmpdir(),`senpi-event-leases-${randomUUID4()}`)}));try{let staged=stageRecord(this.staging,record,content);this.staging.adopt(staged);let shared={content:staged,holders:0};return this.contentBytes+=staged.ref.entry.length,this.shared.set(record,shared),shared}catch(cause){if(cause instanceof TransferStagingError||cause instanceof CompactWriteError||cause instanceof CompactReadError){process.stderr.write(`senpi rpc event lease: record not staged (${cause.message})
|
|
3
3
|
`);return}throw cause}}remember(peer,held,admissionId){let admissions=new Set([...peer.released.get(held.lease.id)?.admissions??[],admissionId]);peer.released.set(held.lease.id,{sessionId:held.sessionId,admissions});for(let oldest of peer.released.keys()){if(peer.released.size<=RELEASED_LEASES_REMEMBERED)break;peer.released.delete(oldest)}}dispose(peer,held){peer.held.delete(held.lease.id),this.open-=1,held.shared.holders-=1,held.shared.holders===0&&this.staging&&(this.staging.release(held.shared.content),this.contentBytes-=held.shared.content.ref.entry.length);for(let listener of this.ended)listener(held.lease.id)}refuse(reason){return this.refusals.set(reason,(this.refusals.get(reason)??0)+1),{ok:!1,reason}}};var MESSAGE_KEY="message",COMPACT_DELTA_TYPES=new Set(["text_delta","thinking_delta","toolcall_delta"]);function compactDelta(value){if(value.type!=="message_update"||!Object.hasOwn(value,"message"))return;let event=value.assistantMessageEvent;if(typeof event!="object"||event===null)return;let{type,contentIndex,delta}=event;if(!(typeof type!="string"||!COMPACT_DELTA_TYPES.has(type)||typeof contentIndex!="number"||typeof delta!="string"))return{type,contentIndex,delta}}function demoteToDeltaOnly(value){let event=value.assistantMessageEvent;return{...value,message:null,assistantMessageEvent:{...event,partial:null}}}function toolUpdateKey(value){return value.type==="tool_execution_update"&&typeof value.toolCallId=="string"?`tool:${value.toolCallId}`:void 0}import{AsyncLocalStorage}from"node:async_hooks";var requests=new AsyncLocalStorage;function captureAdmissionReply(){let scope=requests.getStore();return scope&&{id:scope.command.id,admissionId:scope.command.admissionId,peer:scope.peer}}function withAdmissionReply(scope,action){return scope===void 0?action():requests.run({command:scope,peer:scope.peer},action)}function withAdmissionRequest(command,peer,action){return compactUpdatesEnabled()?requests.run({command,peer},action):action()}function replyAdmission(id,peer,routes){let request=requests.getStore();if(!request||request.command.id!==id||request.peer!==peer)return null;let admissionId=request.command.admissionId;return admissionId===void 0?void 0:routes.find(route=>route===admissionId)??null}var BaselineBarrier=class{constructor(cursor,live){this.cancelled=!1,this.ended=!1,this.cursor=cursor,this.live=live}get active(){return!this.cancelled&&!this.ended&&this.live()}cancel(){this.cancelled=!0,this.end()}end(){this.ended||(this.ended=!0,this.cursor.release())}async deliver(write,head){try{if(!this.active)return;let line=await this.cursor.next();for(head!==void 0&&this.active&&await write(head);line!==void 0&&this.active;)await write(line),line=await this.cursor.next()}finally{this.end()}}};var blockedMsTotal=0;function recordLoopBlockedMs(driftMs){driftMs>0&&(blockedMsTotal+=driftMs)}function loopBlockedMark(){return blockedMsTotal}function loopBlockedMsSince(mark){return blockedMsTotal-mark}var SocketEventQueueStallError=class extends Error{constructor(pendingBytes,stallMs){super(`socket event queue stalled: peer did not drain ${pendingBytes} queued bytes within ${stallMs}ms`),this.name="SocketEventQueueStallError",this.pendingBytes=pendingBytes,this.stallMs=stallMs}},SocketEventQueueOverflowError=class extends Error{constructor(queuedBytes,incomingBytes,maxQueueBytes,incomingPreview){super(`socket event queue overflow: ${queuedBytes} queued + ${incomingBytes} incoming > ${maxQueueBytes} (incoming: ${incomingPreview})`),this.name="SocketEventQueueOverflowError",this.queuedBytes=queuedBytes,this.incomingBytes=incomingBytes,this.maxQueueBytes=maxQueueBytes,this.incomingPreview=incomingPreview}};function waitForDrainOrStall(peer,writtenBytes){return new Promise((resolve2,reject)=>{let timer,blockedMark=loopBlockedMark(),cleanup=()=>{clearTimeout(timer),peer.stopped.removeEventListener("abort",onStop)},onStop=()=>{cleanup(),resolve2()},onDeadline=()=>{let blockedMs=loopBlockedMsSince(blockedMark);if(blockedMs>0){blockedMark=loopBlockedMark(),timer=setTimeout(onDeadline,Math.min(blockedMs,peer.stallMs));return}try{if(peer.shedAndPing()){blockedMark=loopBlockedMark(),timer=setTimeout(onDeadline,peer.stallMs);return}}catch(cause){cleanup(),reject(cause);return}let stall=new SocketEventQueueStallError(peer.queuedBytes()+writtenBytes,peer.stallMs);try{peer.sink.writeRaw(`${JSON.stringify({type:"overflow",error:"stalled, resync required"})}
|
|
4
4
|
`)}catch{}cleanup(),reject(stall)};timer=setTimeout(onDeadline,peer.stallMs),peer.stopped.addEventListener("abort",onStop,{once:!0}),peer.sink.waitForBackpressure().then(()=>{cleanup(),resolve2()},cause=>{cleanup(),reject(cause)})})}var isBarrier=item=>"kind"in item,SocketEventQueue=class{constructor(){this.items=[],this.charged=0}get bytes(){return this.charged}get length(){return this.items.length}push(item){this.items.push(item),isBarrier(item)||(this.charged+=item.bytes)}shift(){let item=this.items.shift();return item!==void 0&&!isBarrier(item)&&(this.charged-=item.bytes),item}insertBefore(before,entry){let at=this.items.indexOf(before);at<0?this.items.push(entry):this.items.splice(at,0,entry),this.charged+=entry.bytes}supersede(key){let existing=this.items.find(item=>!isBarrier(item)&&item.key===key);existing===void 0||isBarrier(existing)||(existing.demotedLine!==void 0&&(this.charged-=existing.bytes,existing.line=existing.demotedLine,existing.bytes=Buffer.byteLength(existing.line),this.charged+=existing.bytes,existing.demotedLine=void 0,existing.onWritten?.(!1),existing.onWritten=void 0),existing.key=void 0)}retain(keep){let kept=[];for(let item of this.items)keep(item)?kept.push(item):isBarrier(item)?item.barrier.cancel():item.onWritten?.(!1);this.items=kept,this.charged=kept.reduce((bytes,item)=>isBarrier(item)?bytes:bytes+item.bytes,0)}clear(){for(let item of this.items)isBarrier(item)&&item.barrier.cancel();this.items.length=0,this.charged=0}};var SocketPeerShed=class{constructor(queue,mode){this.queue=queue,this.mode=mode}get isPending(){return this.pending!==void 0}get dropsRecords(){return this.pending!==void 0&&(this.mode==="drop"||this.pending.stale)}cut(reason,snapshot,live){this.queue.retain(item=>!isBarrier(item)&&item.reply);let cut=snapshot(reason);this.pending={kind:"recovery",reason,sessions:cut.sessions,barrier:new BaselineBarrier(cut,live),stale:!1},this.queue.push(this.pending)}supersede(){if(!this.pending||this.pending.stale)return;let recovery=this.pending;this.queue.retain(item=>isBarrier(item)?item===recovery:item.reply),recovery.barrier.cancel(),recovery.stale=!0}admitReply(entry){this.pending&&this.mode==="drop"?this.queue.insertBefore(this.pending,entry):this.queue.push(entry)}take(entry,snapshot,live){return entry.stale&&snapshot&&(entry.barrier=new BaselineBarrier(snapshot(entry.reason,entry.sessions),live)),this.pending===entry&&(this.pending=void 0),entry.barrier}clear(){this.pending=void 0}};var DEFAULT_QUEUE_BYTES=64*1024*1024,DEFAULT_STALL_MS=3e4,SocketEventSinkActor=class{constructor(sink,onFailure,maxQueueBytes=DEFAULT_QUEUE_BYTES,stallMs=DEFAULT_STALL_MS,shedMode="drop"){this.queue=new SocketEventQueue,this.closed=!1,this.recoveryEnabled=!1,this.frameBytes=0,this.stopped=new AbortController,this.sink=sink,this.onFailure=onFailure,this.maxQueueBytes=maxQueueBytes,this.shed=new SocketPeerShed(this.queue,shedMode),this.stallPeer={sink,stallMs,stopped:this.stopped.signal,queuedBytes:()=>this.queue.bytes,shedAndPing:()=>!this.recovery||!this.recoveryEnabled?!1:(this.cutOnce("stall"),this.recovery.ping(),!0)}}enableRecovery(snapshot){this.recoveryEnabled=!0,this.snapshot=snapshot,this.recovery??=new SocketPeerRecovery(line=>this.sink.writeRaw(line)),this.recovery.acknowledge()}disableRecovery(){this.recoveryEnabled=!1,this.recovery?.pending||(this.recovery=void 0)}installBaseline(cursor,live){if(this.closed||cursor.empty||this.shed.dropsRecords){cursor.release();return}this.queue.push({kind:"attach",barrier:new BaselineBarrier(cursor,live)}),this.drain()}enqueue(line,key,onWritten,demotedLine,reply=!1,held,current){if(this.closed)return;let bytes=Buffer.byteLength(line);if(this.shed.dropsRecords){reply?this.admitReply({line,bytes,onWritten,reply,current}):onWritten?.(!1);return}if(key!==void 0&&this.queue.supersede(key),!this.fits(bytes)){if(this.recovery&&this.recoveryEnabled){this.shed.isPending?this.shed.supersede():this.cut("overflow"),reply?this.admitReply({line,bytes,onWritten,reply,current}):onWritten?.(!1),this.drain();return}this.failOverflow(bytes,line);return}this.queue.push({line,bytes,key,demotedLine,onWritten,reply,held:this.shed.isPending?held:void 0,current}),this.drain()}async flush(){for(;this.draining;)await this.draining;if(this.failure!==void 0)throw this.failure}waitForAcceptance(){return Promise.resolve()}close(){this.closed=!0,this.dropQueue(),this.stopped.abort()}fits(bytes){return this.queue.bytes+this.frameBytes+bytes<=this.maxQueueBytes}admitReply(entry){if(!this.fits(entry.bytes)){this.recovery?.loseReply(),entry.onWritten?.(!1);return}this.shed.admitReply(entry),this.drain()}failOverflow(bytes,line){let overflow=new SocketEventQueueOverflowError(this.queue.bytes+this.frameBytes,bytes,this.maxQueueBytes,line.slice(0,120));this.closed=!0,this.dropQueue();try{this.sink.writeRaw(`${JSON.stringify({type:"overflow",error:"overflow, resync required"})}
|
|
5
5
|
`)}catch(cause){this.onFailure(cause)}this.onFailure(overflow)}dropQueue(){this.queue.clear(),this.attempt?.cancel(),this.shed.clear()}cutOnce(reason){this.recovery?.pending||this.cut(reason)}cut(reason){!this.recovery||!this.snapshot||(this.attempt?.cancel(),this.recovery.shed(reason),this.shed.cut(reason,this.snapshot,()=>!this.closed))}async write(line){this.sink.writeRaw(line),await waitForDrainOrStall(this.stallPeer,Buffer.byteLength(line))}async writeFrame(line){let bytes=Buffer.byteLength(line);if(!this.fits(bytes)){this.recovery&&this.recoveryEnabled?this.cutOnce("overflow"):this.failOverflow(bytes,line);return}this.frameBytes=bytes;try{await this.write(line)}finally{this.frameBytes=0}}async deliver(entry){if(entry.kind==="attach"){await this.stream(entry.barrier,line=>this.writeFrame(line));return}if(await waitForDrainOrStall(this.stallPeer,0),this.closed||!this.recovery)return;let barrier=this.shed.take(entry,this.snapshot,()=>!this.closed),gap=this.recovery.takeGap();this.recoveryEnabled||(this.recovery=void 0),await this.stream(barrier,line=>this.write(line),gap)}async stream(barrier,write,head){this.attempt=barrier;try{await barrier.deliver(write,head)}finally{barrier.end(),this.attempt===barrier&&(this.attempt=void 0)}}drain(){return this.draining?this.draining:(this.draining=(async()=>{try{for(;!this.closed&&this.queue.length>0;){let item=this.queue.shift();if(item===void 0)break;if(isBarrier(item)){try{await this.deliver(item)}finally{item.barrier.end()}continue}let written=(item.held?.()??!0)&&(item.current?.()??!0);written&&await this.write(item.line),item.onWritten?.(written)}}catch(cause){this.failure=cause,this.closed=!0,this.dropQueue(),this.onFailure(cause)}})().finally(()=>{this.draining=void 0,!this.closed&&this.queue.length>0&&this.drain()}),this.draining)}};var AdmissionRoutingActor=class extends SocketEventSinkActor{constructor(){super(...arguments),this.admissions=new Set,this.subscriptions=new Map,this.mirrorOwners=new Map,this.pendingMirrors=new Map,this.opened=new Map,this.retireAfterReply=new Map,this.terminal=new Map}close(){this.subscriptions.clear(),this.mirrorOwners.clear();for(let pending of this.pendingMirrors.values())pending.retire();this.pendingMirrors.clear(),this.admissions.clear(),this.opened.clear(),this.retireAfterReply.clear(),this.terminal.clear(),super.close()}remember(sessionId,checkpoints,socketEpoch){let stream=checkpoints.stream({socketEpoch,sessionId}),remembered=stream??this.terminal.get(sessionId),routes=remembered?.routes.filter(id=>this.admissions.has(id)||[...this.mirrorOwners.values()].includes(id))??[];return stream&&routes.length>0&&this.terminal.set(sessionId,{...stream,routes}),remembered?{...remembered,routes}:void 0}route(line,checkpoints,socketEpoch){if(this.admissions.size===0&&this.subscriptions.size===0&&this.mirrorOwners.size===0)return[line];let record=JSON.parse(line);if(typeof record.sessionId!="string"||record.admissionId!==void 0)return[line];if(typeof record.subscriptionId=="string"){let subscription=this.subscriptions.get(record.subscriptionId);return subscription===void 0?[line]:[serializeJsonLine({...record,admissionId:subscription,generation:0})]}let mirrors=record.type==="response"?[]:this.mirrorAdmissions?.(record.sessionId,String(record.type))??[],stream=this.remember(record.sessionId,checkpoints,socketEpoch),terminal2=record.type==="session_closed"||record.type==="session_parked",routes=[...new Set([...(stream?.routes??[]).filter(id=>this.admissions.has(id)||terminal2&&[...this.mirrorOwners.values()].includes(id)),...mirrors])];if(record.type==="response"&&typeof record.id=="string"){let admissionId=replyAdmission(record.id,this.peer,routes);return admissionId===null?[]:admissionId===void 0?[line]:[serializeJsonLine({...record,admissionId,generation:stream?.generation})]}return routes.length===0?[line]:routes.map(admissionId=>serializeJsonLine({...record,admissionId,generation:stream?.generation}))}deferRetire(id,retire){this.retireAfterReply.set(id,retire)}retireReplied(line){if(this.retireAfterReply.size===0)return;let record=JSON.parse(line);if(record.type!=="response"||typeof record.id!="string")return;let retire=this.retireAfterReply.get(record.id);this.retireAfterReply.delete(record.id),retire?.()}bind(checkpoints,socketEpoch,peer){this.peer=peer;let enqueue=super.enqueue.bind(this);this.enqueue=(line,key,written,demoted,reply,held)=>{let lines2=this.route(line,checkpoints,socketEpoch);if(this.retireReplied(line),lines2.length===0){written?.(!1);return}let replacements=demoted===void 0?void 0:this.route(demoted,checkpoints,socketEpoch),remaining=lines2.length,delivered=!1,receipt=ok=>{delivered||=ok,--remaining===0&&written?.(delivered)};for(let i=0;i<lines2.length;i++){let line2=lines2[i]??"",admissionId=Reflect.get(JSON.parse(line2),"admissionId"),pending=typeof admissionId=="string"?this.pendingMirrors.get(admissionId):void 0,deliver=()=>enqueue(lines2[i]??line2,key===void 0?void 0:`${key}:${i}`,receipt,replacements?.[i],reply,held);pending&&!reply?pending.enqueue(line2,deliver,()=>receipt(!1)):deliver()}}}};var CompactRequiredStreams=class{constructor(fanout,status){this.states=new WeakMap,this.fanout=fanout,this.status=status}sessions(peer){return this.status.requiredSessions(peer)}routes(peer,sessionId,type){let registered=this.fanout.get(peer),actor=registered?.actor;return!(actor instanceof AdmissionRoutingActor)||!registered?[]:[...new Set([...(this.fanout.checkpoints.stream({socketEpoch:registered.socketEpoch,sessionId})?.routes??[]).filter(id=>actor.admissions.has(id)),...this.status.mirrorAdmissions(peer,sessionId,type)])]}prepare(sessionId,record){let lane=this.fanout.acceptance.get(sessionId);if(!(!lane||lane.retired))for(let peer of this.fanout.connectionIds()){if(!this.fanout.connectionHas(peer,COMPACT_EVENTS_CAPABILITY))continue;let registered=this.fanout.get(peer),actor=registered?.actor;if(!(actor instanceof AdmissionRoutingActor)||!registered)continue;let routes=this.status.requiredAdmissions(peer,sessionId),caller={socketEpoch:registered.socketEpoch,sessionId};for(let admissionId of routes){if(this.fanout.checkpoints.stream(caller)?.routes.includes(admissionId))continue;if(!this.fanout.checkpoints.freeze({...caller,peer,admissionId,routeKind:"mirror"},lane,!0).ok){registered.connection.close?.();continue}}let stream=this.fanout.checkpoints.stream(caller);if(!stream?.routes.length)continue;let states=this.states.get(actor)??new Map;this.states.set(actor,states);let state=states.get(sessionId);if(state?.epoch!==lane.sessionEpoch&&(state={epoch:lane.sessionEpoch,dirty:!1},states.set(sessionId,state),state.seed=this.fanout.checkpoints.tokens().find(t=>t.admission.socketEpoch===caller.socketEpoch&&t.admission.sessionId===sessionId)),!record)continue;let type=String(Reflect.get(record,"type"));if(!(stream.routes.some(id=>actor.admissions.has(id))||this.status.mirrorAdmissions(peer,sessionId,type).length>0)){state.dirty=!0;continue}if(state.dirty){let frozen=this.fanout.checkpoints.freeze({...caller,peer,admissionId:stream.routes[0],routeKind:routes.length?"mirror":"ordinary"},lane);if(!frozen.ok){registered.connection.close?.();continue}state.seed=frozen.value.token,state.dirty=!1}}}takeSeed(peer,sessionId){let actor=this.fanout.get(peer)?.actor,state=actor instanceof AdmissionRoutingActor?this.states.get(actor)?.get(sessionId):void 0,seed=state?.seed;return state&&(state.seed=void 0),seed}forgetSession(sessionId){for(let peer of this.fanout.connectionIds()){let actor=this.fanout.get(peer)?.actor;actor instanceof AdmissionRoutingActor&&this.states.get(actor)?.delete(sessionId)}}};var LegacyRecordRefusals=class{constructor(){this.count=0}report(sessionId,refusal3){this.count+=1,process.stderr.write(`senpi rpc host: legacy record refused: ${refusal3.message} (session ${sessionId})
|
|
6
6
|
`)}};function enqueueLegacyRecord(writer,sessionId,record){try{return writer.enqueue(sessionId,record)}catch(cause){if(!(cause instanceof LegacyRecordDepthError))throw cause;return writer.legacyRefusals.report(sessionId,cause),!0}}var SecretInputPresentations=class{constructor(fanout,current,writeSole,flush){this.owners=new Map,this.soleCapabilities=[],this.fanout=fanout,this.current=current,this.writeSole=writeSole,this.flush=flush}handshake(capabilities){this.soleCapabilities=[...capabilities],this.recheck()}route(session){let capable=connection=>this.capable(connection);return{presenter:id=>this.owners.get(id)?.connection,select:(id,cancel)=>{let preferred=this.current(),attached=this.fanout.attachedConnections(session);if(preferred!==void 0&&(!attached.includes(preferred)||!capable(preferred)))return"client_unsupported";let connection=preferred??attached.find(capable);if(connection===void 0&&!(this.fanout.isEmpty()&&capable(void 0)))return this.fanout.isEmpty()?"client_unsupported":"no_presenter";this.owners.set(id,{session,connection,cancel})},accepts:id=>{let owner=this.owners.get(id);return owner?.session===session&&owner.connection===this.current()&&this.live(owner)},available:id=>{let owner=this.owners.get(id);return owner?.session===session&&this.live(owner)},send:(id,record)=>{let owner=this.owners.get(id);if(!owner||owner.session!==session||!this.live(owner)){owner?.cancel?.();return}let line=serializeJsonLine({...record,sessionId:session});owner.connection===void 0?this.writeSole(line):this.fanout.get(owner.connection)?.actor.enqueue(line,void 0,void 0,void 0,!0,void 0,()=>this.owners.get(id)===owner&&this.live(owner)&&(!("type"in record&&record.type==="extension_ui_request")||owner.cancel!==void 0)),this.flush()},settled:id=>{let owner=this.owners.get(id);owner&&(owner.cancel=void 0)},forget:id=>{this.owners.delete(id)},handshake:capabilities=>{this.current()===void 0&&this.handshake(capabilities)}}}recheck(){for(let owner of this.owners.values())this.live(owner)||owner.cancel?.()}detach(connection){for(let[id,owner]of this.owners)owner.connection===connection&&(owner.cancel?.(),this.owners.delete(id))}capable(connection){let caps=connection===void 0?this.soleCapabilities:this.fanout.getConnectionCapabilities(connection);return caps?.includes("secret_input_v1")===!0&&caps.includes("interactive_user")}live(owner){return this.capable(owner.connection)&&(owner.connection===void 0?this.fanout.isEmpty():this.fanout.attachedConnections(owner.session).includes(owner.connection))}};var RpcSecurityPresentations=class{#sessions=new Map;#attachments=new Map;constructor(fanout,inConnection,flush){this.fanout=fanout,this.inConnection=inConnection,this.flush=flush}bind(sessionId,durableId,notices,select){let previous=this.#sessions.get(sessionId);this.#stop(previous);let state={durableId,select,snapshot:notices.snapshot,registrations:new Map,grants:new Map,replayed:previous?.durableId===durableId?previous.replayed:new Map};this.#sessions.set(sessionId,state),state.stop=notices.subscribe(snapshot=>this.acceptSnapshot(sessionId,snapshot));for(let id of this.fanout.attachedConnections(sessionId))this.#register(id,state);return()=>{this.#sessions.get(sessionId)===state&&(this.#stop(state),this.#sessions.delete(sessionId))}}acceptSnapshot(sessionId,snapshot){let state=this.#sessions.get(sessionId);state===void 0&&(state={snapshot,registrations:new Map,grants:new Map,replayed:new Map},this.#sessions.set(sessionId,state)),state.snapshot=snapshot;for(let id of this.fanout.attachedConnections(sessionId))this.#replay(sessionId,id,snapshot)}attach(id,sessionId){let attached=this.#attachments.get(id)??new Set;if(attached.has(sessionId))return;attached.add(sessionId),this.#attachments.set(id,attached);let state=this.#sessions.get(sessionId);state!==void 0&&(this.#register(id,state),this.#replay(sessionId,id,state.snapshot))}detach(id,sessionId){this.#attachments.get(id)?.delete(sessionId),this.#attachments.get(id)?.size===0&&this.#attachments.delete(id);let state=this.#sessions.get(sessionId);state?.registrations.get(id)?.(),state?.registrations.delete(id),state?.replayed.delete(id),state!==void 0&&this.#cancelFor(state,id)}dropConnection(id){for(let sessionId of[...this.#attachments.get(id)??[]])this.detach(id,sessionId)}capabilitiesChanged(id){for(let sessionId of this.#attachments.get(id)??[]){let state=this.#sessions.get(sessionId);state!==void 0&&(this.#register(id,state),this.fanout.connectionHas(id,"grant_select")||this.#cancelFor(state,id))}}routeWorkerGrant(sessionId,requestId,preferred,fallbackCapabilities,cancel){let attached=this.fanout.attachedConnections(sessionId),connection=attached.includes(preferred??"")&&this.fanout.connectionHas(preferred,"grant_select")?preferred:attached.find(id=>this.fanout.connectionHas(id,"grant_select"));if(!(connection!==void 0||this.fanout.isEmpty()&&fallbackCapabilities.includes("grant_select")))return cancel(),{accepted:!1};let state=this.#sessions.get(sessionId);return state===void 0&&(state={snapshot:{generation:0,notices:[]},registrations:new Map,grants:new Map,replayed:new Map},this.#sessions.set(sessionId,state)),state.grants.set(requestId,{connection,cancel}),{accepted:!0,connection}}acceptWorkerResponse(sessionId,requestId,connection){let pending=this.#sessions.get(sessionId)?.grants.get(requestId);if(pending!==void 0)return!(pending.connection!==connection||connection!==void 0&&!this.fanout.connectionHas(connection,"grant_select"))}settleGrant(sessionId,requestId){this.#sessions.get(sessionId)?.grants.delete(requestId)}dropSession(sessionId){this.#stop(this.#sessions.get(sessionId)),this.#sessions.delete(sessionId);for(let[id,sessions]of this.#attachments)sessions.delete(sessionId),sessions.size===0&&this.#attachments.delete(id)}#register(id,state){if(!this.fanout.connectionHas(id,"grant_select")){state.registrations.get(id)?.(),state.registrations.delete(id);return}if(state.registrations.has(id)||state.select===void 0||state.durableId===void 0)return;let select=state.select;state.registrations.set(id,attachMcpGrantPresentation(state.durableId,(title,choices,opts)=>this.inConnection(id,()=>select(title,choices,opts))))}#replay(sessionId,id,snapshot){let target=this.fanout.get(id);if(target===void 0)return;let state=this.#sessions.get(sessionId),revision=JSON.stringify(snapshot);if(state?.replayed.get(id)!==revision){state?.replayed.set(id,revision);for(let notice of snapshot.notices)target.actor.enqueue(serializeJsonLine({type:"extension_ui_request",id:crypto.randomUUID(),sessionId,method:"notify",notifyType:"warning",message:notice.message}));this.flush()}}#cancelFor(state,id){for(let[requestId,pending]of state.grants)pending.connection===id&&(state.grants.delete(requestId),pending.cancel())}#stop(state){state?.stop?.();for(let stop of state?.registrations.values()??[])stop();for(let pending of state?.grants.values()??[])pending.cancel()}};import{tmpdir as tmpdir2}from"node:os";import{lstat as lstat4,readdir,rm as rm4}from"node:fs/promises";import{dirname as dirname3,join as join6,resolve}from"node:path";var ROOT_NAME=/^senpi-(?:transcript|settled|current|event-leases)-/;async function rootBytes(path){try{let stat=await lstat4(path);if(!stat.isDirectory()||stat.isSymbolicLink())return stat.size;let bytes=0;for(let name of await readdir(path)){let child=await rootBytes(join6(path,name));if(child===null)return null;bytes+=child}return bytes}catch(cause){if(cause instanceof Error)return null;throw cause}}async function sweepRecoveryRoots(base){if(process.platform==="win32")return{removed:0,unknown:[],failures:[],skipped:"windows_owner_and_nofollow_unavailable"};let ownedBase=resolve(base),unknown=[],failures=[],removed=0;for(let name of await readdir(ownedBase)){if(!ROOT_NAME.test(name))continue;let path=join6(ownedBase,name);if(dirname3(path)===ownedBase)try{let stat=await lstat4(path),marker=privateRootStat(stat)?await readRootMarker(path):void 0,owner=marker?await rootOwnerState(marker.owner):"unknown";if(marker?.kind==="scratch"&&owner==="dead"){let current=await lstat4(path);if(current.dev!==stat.dev||current.ino!==stat.ino||!privateRootStat(current))throw new Error("root identity changed during classification");await rm4(path,{recursive:!0}),removed+=1}else(!marker||owner==="unknown"||marker.kind==="live"&&owner==="dead")&&unknown.push({name,ageMs:Math.max(0,Date.now()-stat.mtimeMs),bytes:await rootBytes(path),reason:marker?.kind==="live"&&owner==="dead"?"live_owner_dead":"ownership_unknown"})}catch(cause){if(!(cause instanceof Error))throw cause;if("code"in cause&&cause.code==="ENOENT")continue;failures.push({name,operation:"reclaim",cause:cause.message})}}return{removed,unknown,failures}}async function startRecoveryCleanup(base){let result=await sweepRecoveryRoots(base).catch(cause=>{if(!(cause instanceof Error))throw cause;return{removed:0,unknown:[],failures:[{name:".",operation:"reclaim",cause:cause.message}]}});return(result.unknown.length||result.failures.length||result.skipped)&&process.stderr.write(`senpi rpc recovery roots: ${JSON.stringify(result)}
|
|
7
7
|
`),result}var FrozenFramesCursor=class{constructor(source,onRelease){this.index=0,this.released=!1,this.source=source,this.onRelease=onRelease}get empty(){return this.read().count===0}async next(){if(this.released)return;let frames=this.read();if(!(this.index>=frames.count))return frames.frame(this.index++)}release(){this.released||(this.released=!0,this.onRelease())}read(){return this.frames??=this.source(),this.frames}},GeneratedFramesCursor=class{constructor(empty,source,onRelease){this.released=!1,this.empty=empty,this.source=source,this.onRelease=onRelease}async next(){if(this.released)return;this.frames??=this.source();let step=await this.frames.next();return step.done?void 0:step.value}release(){this.released||(this.released=!0,this.frames?.return(void 0),this.onRelease())}};var REPORTED={storage_unavailable:!0,unknown_token:!1,released:!1,lane_retired:!1,stale_epoch:!1,peer_gone:!1,session_closed:!1,superseded_token:!1},isFrame=value=>typeof value=="object"&&value!==null&&!Array.isArray(value);function unavailable(sessionId,cause){let reason=cause instanceof Error?cause.message:String(cause);process.stderr.write(`senpi rpc legacy view: session ${sessionId} current view unavailable: ${reason}
|
|
8
|
-
`)}function blockValue(block,layout){let value=block.block??{};return layout==="current"||block.phase==="initial"||block.phase===void 0?value:"text"in value?{...value,text:""}:"thinking"in value?{...value,thinking:""}:value}function legacyMessage(message,layout){let fields=message.fields;if(!fields)return;if("content"in fields)return fields;let{role,...rest}=fields,content=[];for(let block of message.blocks)content[block.contentIndex]=blockValue(block,layout);return{...role===void 0?{}:{role},content,...rest}}function*blockFrames({contentIndex,text,phase,block},usage,resolved){if(phase===void 0||phase==="initial"||block===void 0)return;let ended=phase==="ended",resolvedToolName=resolved.get(contentIndex),update=(assistantMessageEvent,named2=!1)=>({type:"message_update",...usage===void 0?{}:{usage},assistantMessageEvent,...named2&&resolvedToolName!==void 0?{resolvedToolName}:{}});switch(block.type){case"text":case"thinking":{yield update({type:`${block.type}_start`,contentIndex}),text.length>0&&(yield update({type:`${block.type}_delta`,contentIndex,delta:text})),ended&&(yield update({type:`${block.type}_end`,contentIndex,content:text}));return}case"toolCall":{yield update({type:"toolcall_start",contentIndex,id:block.id,toolName:block.name},!0),text.length>0&&(yield update({type:"toolcall_delta",contentIndex,delta:text})),ended&&(yield update({type:"toolcall_end",contentIndex,toolCall:block},!0));return}default:return}}function*toolResetFrames(message){let usage=message.fields?.usage;for(let{contentIndex,text,phase,block}of message.blocks)phase!=="open"||block?.type!=="toolCall"||(yield{type:"message_tool_arguments_reset",contentIndex,rawArgumentPrefix:"",parsedThrough:0},text.length>0&&(yield{type:"message_update",...usage===void 0?{}:{usage},assistantMessageEvent:{type:"toolcall_delta",contentIndex,delta:text}}))}function*messageFrames(message,resolved){let start=legacyMessage(message,"start");if(start&&(yield{type:"message_start",message:start},!(!("role"in start)||start.role!=="assistant")))for(let block of message.blocks)yield*blockFrames(block,message.fields?.usage,resolved)}function remainingMs(dialog,now){return typeof dialog.deadlineAtMs=="number"?Math.max(0,dialog.deadlineAtMs-now):0}async function activeMessage({lane,root}){return root.activeMessageId===null?void 0:(await lane.readCurrentActive(root)).find(message=>message.messageId===root.activeMessageId)}async function resolvedNames({lane,root},messageId){let names=new Map;for(let call of(await lane.readCurrentCalls(root)).calls)call.owningMessageId===messageId&&call.contentIndex!==null&&call.resolvedName!==null&&names.set(call.contentIndex,call.resolvedName);return names}async function*attachFrames(sessionId,source,view,cancelled){let read;try{read=await source.hold(async()=>{let components2=await source.lane.readCurrentComponents(source.root),message2=await activeMessage(source),resolved2=message2?await resolvedNames(source,message2.messageId):new Map;return{components:components2,message:message2,resolved:resolved2}})}catch(cause){cancelled()||unavailable(sessionId,cause);return}let{components,message,resolved}=read,encode=frame=>serializeJsonLine(view.placeholders?omitNormalInlineMedia(frame):frame),tag=frame=>({...frame,sessionId});if(isFrame(components.lifecycle)&&(yield encode(tag(components.lifecycle))),message)for(let frame of messageFrames(message,resolved))yield encode(tag(frame));for(let dialog of components.dialogs)dialog.audience==="broadcast"&&isFrame(dialog.request)&&(yield encode({...tag(dialog.request),remainingMs:remainingMs(dialog,view.now)}))}function legacyAttachView(sessionId,source,view,onRelease){let current=source?.root.current,empty=source===void 0||current===void 0||current.components.lifecycle===void 0&¤t.components.dialogCounts.broadcast===0&&source.root.activeMessageId===null,released=!1,epoch=source?.lane.recoveryEpoch,cancelled=()=>released||source!==void 0&&!source.lane.holds(source.root)||source?.lane.recoveryEpoch!==epoch;return new GeneratedFramesCursor(empty,()=>source?attachFrames(sessionId,source,view,cancelled):(async function*(){})(),()=>{released=!0,onRelease()})}async function legacyResyncMessage(sessionId,source){if(!source)return{message:null};if(!source.ok)return REPORTED[refusalReason(source.failure)]&&unavailable(sessionId,source.failure.reason),{message:null};let{value}=source;return value.hold(async()=>{try{let message=await activeMessage(value),current=message&&legacyMessage(message,"current");return current?{message:current,frames:[...toolResetFrames(message)]}:{message:null}}catch(cause){return value.lane.holds(value.root)&&unavailable(sessionId,cause),{message:null}}})}import{createHmac,randomBytes,timingSafeEqual}from"node:crypto";var CURSOR_MAC_BYTES=16,CURSOR_VERSION="p1",DECIMAL="(?:0|[1-9][0-9]{0,15})",CURSOR=new RegExp(`^${CURSOR_VERSION}:${DECIMAL}:${DECIMAL}:[0-9a-f]{${CURSOR_MAC_BYTES*2}}$`),DOMAIN="senpi-recovery-cursor/1";function keyedAuthenticator(){let key=randomBytes(32);return text=>createHmac("sha256",key).update(text,"utf8").digest().subarray(0,CURSOR_MAC_BYTES)}var material=(binding,position)=>[DOMAIN,binding.socketEpoch,binding.sessionId,binding.tokenId,String(binding.generation),binding.componentRef,String(position.ordinal),String(position.offset)].map(field4=>`${Buffer.byteLength(field4)}:${field4}`).join("\0"),RecoveryCursors=class{constructor(){this.authenticate=keyedAuthenticator()}mint(binding,position){let mac=this.authenticate(material(binding,position)).toString("hex");return`${CURSOR_VERSION}:${position.ordinal}:${position.offset}:${mac}`}open(cursor,binding){if(!parseBoundedId(cursor).ok||!CURSOR.test(cursor))return;let[,ordinal,offset,mac]=cursor.split(":"),position={ordinal:Number(ordinal),offset:Number(offset)};if(!Number.isSafeInteger(position.ordinal)||!Number.isSafeInteger(position.offset))return;let expected=this.authenticate(material(binding,position)),presented=Buffer.from(mac??"","hex");return presented.length===expected.length&&timingSafeEqual(presented,expected)?position:void 0}};var SOCKET_PAGE_REQUESTS_MAX=8,HINTS={malformed_request:"new_request",busy:"retry",request_limit:"retry",request_mismatch:"new_request",invalid_cursor:"restart_from_catalog",cursor_out_of_range:"restart_from_catalog",ordinal_exhausted:"release_token",lease_kind_unsupported:"new_request"},named=request=>"lease"in request?request.lease?.id:request.token,sameRequest=(a,b)=>a.requestId===b.requestId&&a.componentRef===b.componentRef&&a.cursor===b.cursor&&named(a)===named(b),RecoveryPageRequests=class{constructor(checkpoints,cursors=new RecoveryCursors,events){this.tokens=new Map,this.outstanding=new Map,this.refusals=new Map,this.lifetimes=new Map,this.checkpoints=checkpoints,this.cursors=cursors,this.events=events,checkpoints.onTokenEnd(tokenId=>this.tokens.delete(tokenId)),events?.onLeaseEnd(leaseId=>this.tokens.delete(leaseId))}status(){let outstanding=0;for(let count of this.outstanding.values())outstanding+=count;let cachedBytes=0;for(let{current}of this.tokens.values())cachedBytes+=current?.answer.bytes.length??0;return{tokens:this.tokens.size,outstanding,cachedBytes,refused:Object.fromEntries(this.refusals)}}forgetPeer(socketEpoch){this.lifetimes.get(socketEpoch)?.abort(),this.lifetimes.delete(socketEpoch)}async request(caller,request,signal){let kind="lease"in request?request.lease?.kind:"checkpoint",fields=[request.requestId,request.admissionId,named(request),request.componentRef];if(kind!=="event"&&kind!=="checkpoint"||fields.some(field4=>typeof field4!="string"||!parseBoundedId(field4).ok))return this.refuse("malformed_request");if((this.outstanding.get(caller.socketEpoch)??0)>=SOCKET_PAGE_REQUESTS_MAX)return this.refuse("request_limit");let id=String(named(request)),source=kind==="event"?this.eventSource(caller,id,request.admissionId):this.checkpointSource(caller,id,request.admissionId);if(!source.ok)return source;let token=source.value,state=this.tokens.get(token.id)??{active:!1,ordinal:0,current:void 0};if(state.active)return this.refuse("busy");if(state.current?.request.requestId===request.requestId)return sameRequest(state.current.request,request)?{ok:!0,value:state.current.answer}:this.refuse("request_mismatch");let binding={socketEpoch:caller.socketEpoch,sessionId:caller.sessionId,tokenId:token.id,generation:token.generation,componentRef:request.componentRef},position=request.cursor===void 0?void 0:this.cursors.open(request.cursor,binding);if(request.cursor!==void 0&&position===void 0)return this.refuse("invalid_cursor");let last=position?.ordinal??state.ordinal;return Number.isSafeInteger(last+1)?position!==void 0&&position.ordinal!==state.ordinal?this.refuse("cursor_out_of_range"):(this.tokens.set(token.id,state),this.serve(caller,token,request,state,binding,position?.offset??0,signal)):this.refuse("ordinal_exhausted")}checkpointSource(caller,tokenId,admissionId){let token=this.checkpoints.tokens().find(each=>each.id===tokenId);if(!token||token.admission.socketEpoch!==caller.socketEpoch||token.admission.sessionId!==caller.sessionId||!this.checkpoints.stream(caller)?.routes.includes(admissionId))return{ok:!1,failure:repairNeeded("unknown_token")};let claimed=this.checkpoints.check(token,caller);if(!claimed.ok)return claimed;let{generation}=token.admission;return{ok:!0,value:{id:token.id,generation,label:{token:token.id,generation},read:(ref,offset,signal)=>this.checkpoints.readCatalogPage(token,caller,ref,offset,signal)}}}eventSource(caller,leaseId,admissionId){let events=this.events;if(!events)return{ok:!1,failure:repairNeeded("unknown_token")};let claimed=events.claim(caller,leaseId,admissionId);if(!claimed.ok)return claimed;let held=claimed.value;return{ok:!0,value:{id:held.lease.id,generation:0,label:{lease:{kind:"event",id:held.lease.id}},read:(ref,offset,signal)=>events.page(held,ref,offset,signal)}}}async serve(caller,token,request,state,binding,offset,signal){state.active=!0,this.outstanding.set(caller.socketEpoch,(this.outstanding.get(caller.socketEpoch)??0)+1);let lifetime=this.lifetimes.get(caller.socketEpoch)??new AbortController;this.lifetimes.set(caller.socketEpoch,lifetime);let budget=signal===void 0?lifetime.signal:AbortSignal.any([signal,lifetime.signal]),page;try{page=await token.read(request.componentRef,offset,budget)}finally{state.active=!1;let left=(this.outstanding.get(caller.socketEpoch)??1)-1;left>0?this.outstanding.set(caller.socketEpoch,left):(this.outstanding.delete(caller.socketEpoch),this.lifetimes.get(caller.socketEpoch)===lifetime&&this.lifetimes.delete(caller.socketEpoch))}if(page.ok||this.tokens.delete(token.id),!page.ok)return page;if(!this.tokens.has(token.id))return{ok:!1,failure:repairNeeded("released")};let ordinal=state.ordinal+1,answer={requestId:request.requestId,...token.label,componentRef:request.componentRef,ordinal,offset:page.value.offset,length:page.value.length,digest:page.value.digest,bytes:page.value.bytes.toString("base64"),cursor:page.value.next===null?null:this.cursors.mint(binding,{ordinal,offset:page.value.next}),complete:page.value.complete};return state.ordinal=ordinal,state.current={request,answer},{ok:!0,value:answer}}refuse(reason){return this.refusals.set(reason,(this.refusals.get(reason)??0)+1),{ok:!1,failure:{kind:"request_refused",reason,hint:HINTS[reason]}}}};var CATALOG_FAMILIES=["transcript","run","lifecycle","dialogs","opaque","active","calls","settled","identity","source"],FAMILY_SET=new Set(CATALOG_FAMILIES),PRODUCERS=["complete","partial"],PRODUCER_SET=new Set(PRODUCERS),FAMILY_PRODUCERS={transcript:"complete",run:"complete",lifecycle:"complete",dialogs:"complete",opaque:"complete",active:"complete",calls:"complete",settled:"complete",identity:"complete",source:"complete"};function familyProducers(transcript,refusedCorrelations){let entries=transcript.unavailable===null?{}:{transcript:"partial",opaque:"partial",source:"partial"};return{...FAMILY_PRODUCERS,...entries,...refusedCorrelations>0?{identity:"partial"}:{}}}var ENTRY_FAMILIES={session:"transcript",message:"transcript",thinking_level_change:"source",configuration_update:"source",model_change:"source",model_change_rejected:"source",usage:"source",compaction:"source",branch_summary:"source",custom:"source",custom_message:"source",context_edit:"source",label:"source",session_info:"source"},KNOWN_KINDS=new Map(Object.entries(ENTRY_FAMILIES)),entryFamily=kind=>KNOWN_KINDS.get(kind)??"opaque",familyId=family=>protocolId(family),memberId=(prefix,ordinal)=>protocolId(`${prefix}-${typeof ordinal=="number"?String(ordinal).padStart(16,"0"):ordinal}`),COMPLETE=Symbol("complete family registry");function familyRegistry(producers){let families=CATALOG_FAMILIES.map(family=>({family,producer:producers[family]})),incomplete=families.filter(({producer})=>producer!=="complete").map(({family})=>family),base={format:"senpi-recovery-families",version:1,families};return incomplete.length===0?{...base,assembly:"complete",[COMPLETE]:!0}:{...base,assembly:"incomplete",incomplete}}function assertCoverage(registry,emitted){if(registry.families.filter(({family,producer})=>producer==="complete"&&!emitted.has(family)).length>0)throw new CompactReadError("unavailable")}function*literalSteps(value){let stack=[],pending={value};for(;;){if(pending){let current=pending.value;if(pending=void 0,typeof current=="string")yield{kind:"string",text:current,more:!1};else if(typeof current=="object"&¤t!==null){let array=Array.isArray(current);yield{kind:"open",container:array?"array":"object"},stack.push({children:array?current:Object.entries(current).flat(),index:0})}else typeof current=="number"||typeof current=="boolean"||current===null?yield{kind:"scalar",value:current}:yield{kind:"scalar",value:null};continue}let frame=stack[stack.length-1];if(!frame)return;frame.index<frame.children.length?pending={value:frame.children[frame.index++]}:(stack.pop(),yield{kind:"close"})}}async function*objectSteps(fields){yield{kind:"open",container:"object"};for await(let[name,steps]of fields)yield{kind:"string",text:name,more:!1},yield*steps;yield{kind:"close"}}async function*arraySteps(items){yield{kind:"open",container:"array"};for await(let steps of items)yield*steps;yield{kind:"close"}}async function*storedSteps(store,leaves){for(let[index,leaf2]of leaves.entries())yield{kind:"raw",text:await store.readLeaf(leaf2),more:index+1<leaves.length}}var literalFields=value=>Object.entries(value).map(([name,item])=>[name,literalSteps(item)]);async function*textSteps(texts,roots,valid,suffix=""){for(let root of roots)for await(let chunk of texts.chunks(root,valid))yield{kind:"string",text:chunk,more:!0};yield{kind:"string",text:suffix,more:!1}}var fieldSteps=(values,fields,valid)=>objectSteps(Object.entries(fields).map(([name,ref])=>[name,values.walk(ref,valid)])),walkedSteps=(values,ref,valid)=>ref?values.walk(ref,valid):literalSteps(null);var CatalogComponentWriter=class{constructor(store){this.leaves=[],this.open="",this.store=store}push(text){let rest=text;for(;this.open.length+rest.length>COMPACT_LEAF_CODE_UNITS;){let take=COMPACT_LEAF_CODE_UNITS-this.open.length;this.seal(this.open+rest.slice(0,take)),rest=rest.slice(take)}this.open+=rest}finish(kind,id){this.open.length>0&&this.seal(this.open),this.open="";let owner=this.store.text.own(this.leaves);for(let leaf2 of this.leaves)this.store.adjust(leaf2,-1,0);return{kind,id,leaves:[...this.leaves],owner}}abort(){for(let leaf2 of this.leaves)this.store.adjust(leaf2,-1,0);this.leaves.length=0,this.open=""}seal(text){this.leaves.push(this.store.createLeaf(text,!0)),this.open=""}};async function*writtenComponent(store,kind,id,fill){let writer=new CatalogComponentWriter(store),component;try{await fill(writer),component=writer.finish(kind,id)}catch(cause){throw writer.abort(),cause}try{yield component}finally{store.adjust(component.owner,-1,0)}}var stepsComponent=(store,kind,id,steps)=>writtenComponent(store,kind,id,async writer=>{for await(let fragment of encodeValueSteps(steps))writer.push(fragment)}),emptyComponent=family=>({kind:familyId(family),id:familyId(family),leaves:[],owner:0}),HIGH_SURROGATE=/[\uD800-\uDBFF]$/;async function*encodeValueSteps(steps){let stack=[],carry="",inString=!1,inRaw=!1,separator=()=>{let frame=stack[stack.length-1];if(!frame)return"";let count=frame.emitted++;return frame.container==="array"?count>0?",":"":count===0?"":count%2===0?",":":"};for await(let step of steps)switch(step.kind){case"scalar":yield`${separator()}${JSON.stringify(step.value)}`;break;case"string":{let prefix=inString?"":`${separator()}"`,text=carry+step.text;carry="",step.more&&HIGH_SURROGATE.test(text)&&(carry=text.slice(-1),text=text.slice(0,-1)),inString=step.more,yield`${prefix}${JSON.stringify(text).slice(1,-1)}${step.more?"":'"'}`;break}case"raw":yield`${inRaw?"":separator()}${step.text}`,inRaw=step.more;break;case"open":yield`${separator()}${step.container==="array"?"[":"{"}`,stack.push({container:step.container,emitted:0});break;case"close":yield stack.pop()?.container==="array"?"]":"}";break;default:return assertNever2(step)}}function assertNever2(step){throw new Error(`unexpected value step: ${JSON.stringify(step)}`)}var CompactIndexTree=class{constructor(retain){this.residentNodes=0,this.allocatedNodes=0,this.retain=retain}get(root,key){let node=root;for(;node;){if(key===node.key)return node.value;node=key<node.key?node.left:node.right}}adjust(root,live,pins){if(!root)return;let wasLive=+(root.live>0),wasPinned=+(root.live===0&&root.pins>0);if(root.live+live<0||root.pins+pins<0)throw new CompactReadError("ownership");root.live+=live,root.pins+=pins;let l=+(root.live>0)-wasLive,p=+(root.live===0&&root.pins>0)-wasPinned;(l||p)&&(this.retain(root.value,l,p),this.adjust(root.left,l,p),this.adjust(root.right,l,p)),root.live===0&&root.pins===0&&this.residentNodes--}set(root,key,value){if(!root)return value===void 0?void 0:this.make(key,value,void 0,void 0);if(key===root.key){if(value!==void 0)return this.make(key,value,root.left,root.right);if(!root.left||!root.right){let child2=root.left??root.right;return this.adjust(child2,1,0),child2}let next=root.right;for(;next.left;)next=next.left;let right=this.set(root.right,next.key,void 0),result2=this.balance(next.key,next.value,root.left,right);return this.adjust(right,-1,0),result2}let leftward=key<root.key,child=this.set(leftward?root.left:root.right,key,value),result=this.balance(root.key,root.value,leftward?child:root.left,leftward?root.right:child);return this.adjust(child,-1,0),result}*entries(root,after){root&&((after===void 0||root.key>after)&&(yield*this.entries(root.left,after),yield[root.key,root.value]),yield*this.entries(root.right,after))}make(key,value,left,right){return this.adjust(left,1,0),this.adjust(right,1,0),this.retain(value,1,0),this.residentNodes++,this.allocatedNodes++,{key,value,left,right,live:1,pins:0,height:1+Math.max(left?.height??0,right?.height??0),size:1+(left?.size??0)+(right?.size??0)}}balance(key,value,left,right){if(left&&left.height>(right?.height??0)+1){let middle=left.right;if(middle&&middle.height>(left.left?.height??0)){let a=this.make(left.key,left.value,left.left,middle.left),b2=this.make(key,value,middle.right,right),result2=this.make(middle.key,middle.value,a,b2);return this.adjust(a,-1,0),this.adjust(b2,-1,0),result2}let b=this.make(key,value,left.right,right),result=this.make(left.key,left.value,left.left,b);return this.adjust(b,-1,0),result}if(right&&right.height>(left?.height??0)+1){let middle=right.left;if(middle&&middle.height>(right.right?.height??0)){let a2=this.make(key,value,left,middle.left),b=this.make(right.key,right.value,middle.right,right.right),result2=this.make(middle.key,middle.value,a2,b);return this.adjust(a2,-1,0),this.adjust(b,-1,0),result2}let a=this.make(key,value,left,right.left),result=this.make(right.key,right.value,a,right.right);return this.adjust(a,-1,0),result}return this.make(key,value,left,right)}};var VALUE_PAGE_ITEMS=128,VALUE_PAGE_CODE_UNITS=4096,INLINE_JSON_LENGTH=64,scalar=value=>value===null||typeof value=="boolean"||typeof value=="number"&&Number.isFinite(value),plain=value=>typeof value=="object"&&value!==null&&(Array.isArray(value)||Object.getPrototypeOf(value)===Object.prototype||Object.getPrototypeOf(value)===null);function ownValue(store,make,value){let owned=new Set,ancestors=new Set,stack=[],take=(page,children)=>{let ref=make(page);owned.add(ref.owner);for(let child of children)store.adjust(child.owner,-1,0),owned.delete(child.owner);return ref},ownString=text=>{let next;for(let end=text.length;end>0;end=Math.max(0,end-VALUE_PAGE_CODE_UNITS))next=take({kind:"string",text:text.slice(Math.max(0,end-VALUE_PAGE_CODE_UNITS),end),next},next?[next]:[]);if(!next)throw new CompactWriteError("unsupported_value");return next},open6=object=>{if(ancestors.has(object))throw new CompactWriteError("cycle");ancestors.add(object);let array=Array.isArray(object),entries=array?object:Object.entries(object);stack.push({object,array,entries,end:entries.length,children:[],index:0,refs:[],next:void 0}),slice(stack[stack.length-1])},slice=frame=>{let part=frame.entries.slice(Math.max(0,frame.end-VALUE_PAGE_ITEMS),frame.end);frame.children=frame.array?part:part.flat(),frame.index=0,frame.refs=[]},close=frame=>{let refs=frame.refs,items=frame.array?{kind:"array",items:refs,next:frame.next}:{kind:"object",items:pairs(refs),next:frame.next};if(frame.next=take(items,frame.next?[...refs,frame.next]:refs),frame.end>VALUE_PAGE_ITEMS){frame.end-=VALUE_PAGE_ITEMS,slice(frame);return}return stack.pop(),ancestors.delete(frame.object),frame.next};try{let pending={value},done;for(;;){if(pending){let current=pending.value;if(pending=void 0,scalar(current)||typeof current=="string"&&JSON.stringify(current).length<=INLINE_JSON_LENGTH)done={node:0,owner:0,value:current};else if(typeof current=="string")done=ownString(current);else if(plain(current))open6(current);else throw new CompactWriteError("unsupported_value")}let frame=stack[stack.length-1];if(done){if(!frame)return done;frame.refs.push(done),done=void 0}if(!frame)throw new CompactWriteError("unsupported_value");frame.index<frame.children.length?pending={value:frame.children[frame.index++]}:done=close(frame)}}catch(error){for(let owner of owned)store.adjust(owner,-1,0);throw error}}function pairs(refs){let fields=[];for(let index=0;index+1<refs.length;index+=2)fields.push([refs[index],refs[index+1]]);return fields}var __addDisposableResource=function(env,value,async){if(value!=null){if(typeof value!="object"&&typeof value!="function")throw new TypeError("Object expected.");var dispose,inner;if(async){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");dispose=value[Symbol.asyncDispose]}if(dispose===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");dispose=value[Symbol.dispose],async&&(inner=dispose)}if(typeof dispose!="function")throw new TypeError("Object not disposable.");inner&&(dispose=function(){try{inner.call(this)}catch(e){return Promise.reject(e)}}),env.stack.push({value,dispose,async})}else async&&env.stack.push({async:!0});return value},__disposeResources=(function(SuppressedError2){return function(env){function fail(e){env.error=env.hasError?new SuppressedError2(e,env.error,"An error was suppressed during disposal."):e,env.hasError=!0}var r,s=0;function next(){for(;r=env.stack.pop();)try{if(!r.async&&s===1)return s=0,env.stack.push(r),Promise.resolve().then(next);if(r.dispose){var result=r.dispose.call(r.value);if(r.async)return s|=2,Promise.resolve(result).then(next,function(e){return fail(e),next()})}else s|=1}catch(e){fail(e)}if(s===1)return env.hasError?Promise.reject(env.error):Promise.resolve();if(env.hasError)throw env.error}return next()}})(typeof SuppressedError=="function"?SuppressedError:function(error,suppressed,message){var e=new Error(message);return e.name="SuppressedError",e.error=error,e.suppressed=suppressed,e}),CompactValues=class{constructor(store){this.residentPages=0,this.peakResidentPages=0,this.store=store}record(fields){let entries=[...fields],next;for(let end=entries.length;end>0||!next;end=Math.max(0,end-128)){let items=entries.slice(Math.max(0,end-128),end).map(([key,value])=>[this.own(key),value]),ref=this.make({kind:"object",items,next});for(let[key]of items)this.store.adjust(key.owner,-1,0);if(next&&this.store.adjust(next.owner,-1,0),next=ref,end<=128)break}return next}own(value){return ownValue(this.store,page=>this.make(page),value)}async page(ref){this.residentPages++,this.peakResidentPages=Math.max(this.peakResidentPages,this.residentPages);try{let text=await this.store.readLeaf(ref.node);if(Buffer.byteLength(text)>65536)throw new CompactReadError("size_limit");let page=JSON.parse(text);if((page.kind==="object"||page.kind==="array")&&page.items.length>128)throw new CompactReadError("count_limit");return{value:page,[Symbol.dispose]:()=>{this.residentPages--}}}catch(error){throw this.residentPages--,error}}async*walk(ref,valid){let stack=[],pending=ref,chunked=!1;for(;;){if(pending){let env_1={stack:[],error:void 0,hasError:!1};try{if("value"in pending){yield typeof pending.value=="string"?{kind:"string",text:pending.value,more:!1}:{kind:"scalar",value:pending.value},pending=void 0;continue}let held=__addDisposableResource(env_1,await this.page(pending),!1);valid?.();let page=held.value;if(chunked&&page.kind!=="string")throw new CompactReadError("ownership");page.kind==="scalar"?(yield{kind:"scalar",value:page.value},pending=void 0):page.kind==="string"?(yield{kind:"string",text:page.text,more:page.next!==void 0},chunked=page.next!==void 0,pending=page.next):(yield{kind:"open",container:page.kind},stack.push({kind:page.kind,items:page.items.flat(),index:0,next:page.next}),pending=void 0);continue}catch(e_1){env_1.error=e_1,env_1.hasError=!0}finally{__disposeResources(env_1)}}let frame=stack[stack.length-1];if(!frame)return;if(frame.index<frame.items.length)pending=frame.items[frame.index++];else if(frame.next){let env_2={stack:[],error:void 0,hasError:!1};try{let held=__addDisposableResource(env_2,await this.page(frame.next),!1);valid?.();let page=held.value;if(page.kind!==frame.kind)throw new CompactReadError("ownership");frame.items=page.items.flat(),frame.index=0,frame.next=page.next}catch(e_2){env_2.error=e_2,env_2.hasError=!0}finally{__disposeResources(env_2)}}else stack.pop(),yield{kind:"close"}}}async read(ref,valid){if("value"in ref)return ref.value;let stack=[],text,settle=value=>{let parent=stack[stack.length-1];if(!parent)return value;if(Array.isArray(parent.value))parent.value.push(value);else if(parent.key===void 0){if(typeof value!="string")throw new CompactReadError("ownership");parent.key=value}else Object.defineProperty(parent.value,parent.key,{value,enumerable:!0,configurable:!0,writable:!0}),parent.key=void 0},result;for await(let step of this.walk(ref,valid))if(step.kind==="open")stack.push({value:step.container==="array"?[]:{},key:void 0});else if(step.kind==="close"){let frame=stack.pop();if(!frame)throw new CompactReadError("ownership");result=settle(frame.value)}else step.kind==="scalar"?result=settle(step.value):step.more?text=(text??"")+step.text:(result=settle((text??"")+step.text),text=void 0);return result}async*fields(ref,names,valid){let next=ref;for(;next;){let page=await this.objectPage(next,valid);for(let[key,value]of page.items)yield[await this.matchKey(key,names,valid),value,key];next=page.next}}async objectPage(ref,valid){let env_3={stack:[],error:void 0,hasError:!1};try{let held=__addDisposableResource(env_3,await this.page(ref),!1);if(valid?.(),held.value.kind!=="object")throw new CompactReadError("ownership");return held.value}catch(e_3){env_3.error=e_3,env_3.hasError=!0}finally{__disposeResources(env_3)}}async matchKey(key,names,valid){let candidates=[...names],read=0;for await(let step of this.walk(key,valid)){if(step.kind!=="string")throw new CompactReadError("ownership");if(candidates=candidates.filter(name=>name.startsWith(step.text,read)),read+=step.text.length,!step.more)return candidates.find(name=>name.length===read);if(candidates.length===0)return}throw new CompactReadError("ownership")}async merge(base,patch){let reversed,result,buffer=[],seen=new Set,flush=async()=>{let ref=this.make({kind:"object",items:buffer,next:reversed});if(reversed&&this.store.adjust(reversed.owner,-1,0),reversed=ref,buffer=[],await this.store.flushLeaf(ref.node),!this.store.isCommitted(ref.node))throw new CompactWriteError("storage_unavailable")};try{for await(let[name,value,key]of this.fields(base,new Set(patch.keys())))name!==void 0&&seen.add(name),buffer.push([key,name===void 0?value:patch.get(name)??value]),buffer.length===128&&await flush();for(let[name,value]of patch){if(seen.has(name))continue;let key=this.own(name);buffer.push([key,value]);try{await flush()}finally{this.store.adjust(key.owner,-1,0)}}for((buffer.length||!reversed)&&await flush();reversed;){let env_4={stack:[],error:void 0,hasError:!1};try{let page=__addDisposableResource(env_4,await this.page(reversed),!1).value;if(page.kind!=="object")throw new CompactReadError("ownership");let ref=this.make({kind:"object",items:page.items,next:result});if(result&&this.store.adjust(result.owner,-1,0),result=ref,await this.store.flushLeaf(ref.node),!this.store.isCommitted(ref.node))throw new CompactWriteError("storage_unavailable");let next=page.next;next&&this.store.adjust(next.owner,1,0),this.store.adjust(reversed.owner,-1,0),reversed=next}catch(e_4){env_4.error=e_4,env_4.hasError=!0}finally{__disposeResources(env_4)}}if(!result)throw new CompactReadError("ownership");return result}catch(error){throw reversed&&this.store.adjust(reversed.owner,-1,0),result&&this.store.adjust(result.owner,-1,0),error}}make(page){let children=page.kind==="object"?page.items.flat():page.kind==="array"?[...page.items]:[];page.kind!=="scalar"&&page.next&&children.push(page.next);let node=this.store.createLeaf(JSON.stringify(page),!0),owner=this.store.text.own([node,...children.map(ref=>ref.owner)]);return this.store.adjust(node,-1,0),{node,owner}}};var CompactComponentRoots=class{constructor(store,leavesOf){this.refs=new WeakMap,this.store=store,this.values=new CompactValues(store),this.leavesOf=leavesOf,this.tree=new CompactIndexTree((value,live,pins)=>store.adjust(value.owner,live,pins))}get residentNodes(){return this.tree.residentNodes}set(root,key,value){let ref=value&&this.values.own(value),owner=ref&&value?this.store.text.own([ref.owner,...this.leavesOf(value)]):0,header=this.tree.set(root.header,key,value&&ref?{value,ref,owner}:void 0);ref&&this.store.adjust(ref.owner,-1,0),this.store.adjust(owner,-1,0);let created=[],next=header?this.project(header,created):void 0;next&&this.store.adjust(next.owner,1,0);for(let ref2 of created)this.store.adjust(ref2.owner,-1,0);return this.tree.adjust(root.header,-1,0),root.ref&&this.store.adjust(root.ref.owner,-1,0),{header,ref:next}}release(root){this.store.enqueue("reclaim",async()=>{this.tree.adjust(root.header,-1,0),root.ref&&this.store.adjust(root.ref.owner,-1,0)})}async*rows(ref,valid){if(!ref)return;valid();let page=JSON.parse(await this.store.readLeaf(ref.node));valid(),yield*this.rows(page.left,valid);let key=await this.values.read(page.key,valid);if(typeof key!="string")throw new CompactReadError("ownership");yield[key,page.value],yield*this.rows(page.right,valid)}async*entries(ref,valid){for await(let[key,value]of this.rows(ref,valid)){let row=await this.values.read(value,valid);valid(),yield[key,row]}}project(node,created){let known=this.refs.get(node);if(known)return known;let left=node.left&&this.project(node.left,created),right=node.right&&this.project(node.right,created),key={node:0,owner:0,value:node.key},page=this.store.createLeaf(JSON.stringify({key,value:node.value.ref,left,right}),!0),owner=this.store.text.own([page,key.owner,node.value.owner,left?.owner??0,right?.owner??0]);this.store.adjust(page,-1,0);let ref={node:page,owner};return this.refs.set(node,ref),created.push(ref),ref}};var CALLS=familyId("calls"),SLOTS=new Set(["raw","hook","progress","result"]),leaf=value=>{if(typeof value!="number")throw new CompactReadError("ownership");return value};function flatSlot(steps){let[first]=steps;if(first?.kind==="scalar"&&first.value===null&&steps.length===1)return null;if(first?.kind!=="open"||first.container!=="object")throw new CompactReadError("ownership");let fields={},key,text="";for(let step of steps.slice(1,-1)){if(step.kind==="open"||step.kind==="close")throw new CompactReadError("ownership");if(step.kind==="string"&&step.more){text+=step.text;continue}let value=step.kind==="string"?text+step.text:step.value;if(text="",key!==void 0)fields[key]=value,key=void 0;else if(typeof value=="string")key=value;else throw new CompactReadError("ownership")}return fields}function rawSteps({store,valid},raw){return raw?.kind!=="owned"?literalSteps(raw):objectSteps([["kind",literalSteps("owned")],["text",textSteps(store.text,[leaf(raw.root),leaf(raw.tailRoot)],valid)]])}function slotRef(slot){return slot===null?null:"value"in slot?{node:0,owner:0,value:slot.value??null}:{node:leaf(slot.node),owner:leaf(slot.owner)}}var slotSteps=(reader,name,slot)=>name==="raw"?rawSteps(reader,slot):walkedSteps(reader.values,slotRef(slot),reader.valid);async function*headerSteps(reader,ref){let depth=0,key="",slot;for await(let step of reader.values.walk(ref,reader.valid)){let outer=depth;if(step.kind==="open"?depth+=1:step.kind==="close"&&(depth-=1),outer===0||depth===0){yield step;continue}if(key!==void 0){if(step.kind!=="string")throw new CompactReadError("ownership");if(key+=step.text,yield step,step.more)continue;slot=SLOTS.has(key)?{name:key,steps:[]}:void 0,key=void 0;continue}slot?slot.steps.push(step):yield step,!(depth!==1||step.kind==="string"&&step.more)&&(slot&&(yield*slotSteps(reader,slot.name,flatSlot(slot.steps))),slot=void 0,key="")}}async function*callsComponents(reader,calls){let roots=new CompactComponentRoots(reader.store,()=>[]),count=0;for await(let[order,ref]of roots.rows(calls.ref,reader.valid))yield*stepsComponent(reader.store,CALLS,memberId("call",order.replace(".","-")),headerSteps(reader,ref)),count+=1;count===0&&(yield emptyComponent("calls"))}var ACTIVE=familyId("active");function blockSteps({store,values,valid},block){let seeded=block.seeded;return objectSteps([["contentIndex",literalSteps(block.contentIndex)],["kind",literalSteps(block.kind)],["text",textSteps(store.text,[block.root,block.tailRoot??0],valid,block.tail)],["seeded",seeded?objectSteps([["type",literalSteps(seeded.type)],["phase",literalSteps(seeded.phase)],["parsedThrough",literalSteps(seeded.parsedThrough)],["fields",fieldSteps(values,seeded.fields,valid)],["signature",textSteps(store.text,[seeded.signature.root,seeded.signature.tailRoot],valid)]]):literalSteps(null)]])}async function*blockItems(reader,blocks,ref){for await(let[,block]of blocks.entries(ref,reader.valid))yield blockSteps(reader,block)}function messageSteps(reader,row,blocks){let{values,valid}=reader;return objectSteps([["messageId",literalSteps(row.messageId)],["fields",row.fields?fieldSteps(values,row.fields,valid):literalSteps(null)],["correlation",row.correlation?fieldSteps(values,row.correlation,valid):literalSteps(null)],["blocks",arraySteps(blockItems(reader,blocks,row.blocks))]])}async function*activeComponents(reader,active){let messages=new CompactComponentRoots(reader.store,()=>[]),blocks=new CompactComponentRoots(reader.store,()=>[]),count=0;for await(let[order,row]of messages.entries(active,reader.valid))yield*stepsComponent(reader.store,ACTIVE,memberId("message",Number(order)),messageSteps(reader,row,blocks)),count+=1;count===0&&(yield emptyComponent("active"))}var TRANSCRIPT=familyId("transcript"),OPAQUE=familyId("opaque"),BASE=protocolId("base");function baseRow(transcript){if(transcript.unavailable!==null||!transcript.base||transcript.base.count===0)return;let row={source:"file",first:0,count:transcript.base.count,idFingerprint:transcript.base.idFingerprint};return JSON.stringify(row)}async function*transcriptComponents(store,transcript,producers,valid){let hold=transcript.tail.hold(transcript.count,transcript.base?.count??0);try{yield*heldComponents(store,transcript,hold,producers,valid)}finally{hold.release()}}async function*heldComponents(store,transcript,hold,producers,valid){let descriptor={historyVersion:transcript.historyVersion,leafId:transcript.leafId,count:transcript.count,base:transcript.base&&{count:transcript.base.count,idFingerprint:transcript.base.idFingerprint},persisted:hold.persistence?.count??null,unavailable:transcript.unavailable};if(yield*textComponent(store,TRANSCRIPT,TRANSCRIPT,JSON.stringify(descriptor)),transcript.unavailable!==null)return;let base=baseRow(transcript);base!==void 0&&(yield*textComponent(store,TRANSCRIPT,BASE,base));let opaque=0;for(let{index,id,kind,parentId}of transcript.accepted){valid();let tail=hold.has(index),family=entryFamily(kind),line=JSON.stringify({index,id,source:tail?"tail":"file",parentId,kind,family});yield*textComponent(store,TRANSCRIPT,memberId("entry",index),line),family==="opaque"&&(opaque+=1,yield*tail?writtenComponent(store,OPAQUE,memberId("entry",index),async writer=>{for await(let chunk of hold.chunks(index,valid))writer.push(chunk)}):textComponent(store,OPAQUE,memberId("entry",index),line))}base!==void 0?yield*textComponent(store,OPAQUE,BASE,base):opaque===0&&producers.opaque==="complete"&&(yield{kind:OPAQUE,id:OPAQUE,leaves:[],owner:0})}var textComponent=(store,kind,id,text)=>writtenComponent(store,kind,id,writer=>writer.push(text));var SETTLED=familyId("settled"),IDENTITY=familyId("identity");function terminalSteps(settled,row,valid){let{kind:_kind,payload:payload2,call,...fields}=row;return objectSteps([...literalFields(fields),["payload",storedSteps(settled.store,payload2)],["call",walkedSteps(settled.values,call,valid)]])}async function*settledComponents(reader,settled){let count=0;for await(let member of settled.members(reader.valid)){if(member.kind!=="terminal")continue;let steps=terminalSteps(settled,member.row,reader.valid);yield*stepsComponent(reader.store,SETTLED,memberId("message",member.row.terminalSequence),steps),count+=1}count===0&&(yield emptyComponent("settled"))}async function*identityComponents(reader,root,settled){let{sessionEpoch,sequence,activeMessageId,turnId,correlation,refusedCorrelations}=root,identity={sessionEpoch,sequence,activeMessageId,turnId,correlation,refusedCorrelations};yield*textComponent(reader.store,IDENTITY,IDENTITY,JSON.stringify(identity));for await(let member of settled.members(reader.valid)){if(member.kind!=="owner")continue;let join7=JSON.stringify({messageId:member.messageId,entryId:member.entryId});yield*textComponent(reader.store,IDENTITY,memberId("join",member.ordinal),join7)}}var SOURCE=familyId("source"),BASE2=protocolId("base");async function*sourceComponents(reader,transcript,producers,settled){let count=0,accepted=transcript.unavailable===null?transcript.accepted:[],hold=transcript.tail.hold(transcript.count,transcript.base?.count??0);try{for(let{index,id,kind,parentId}of accepted){if(reader.valid(),entryFamily(kind)!=="source")continue;let head={index,id,parentId,kind,messageId:await settled.messageOf(id)},steps=objectSteps([...literalFields(head),["entry",hold.has(index)?rawSteps2(hold.chunks(index,reader.valid)):literalSteps(null)]]);yield*stepsComponent(reader.store,SOURCE,memberId("entry",index),steps),count+=1}}finally{hold.release()}let base=baseRow(transcript);base!==void 0?yield*textComponent(reader.store,SOURCE,BASE2,base):count===0&&producers.source==="complete"&&(yield emptyComponent("source"))}async function*rawSteps2(chunks2){let previous;for await(let chunk of chunks2)previous!==void 0&&(yield{kind:"raw",text:previous,more:!0}),previous=chunk;yield{kind:"raw",text:previous??"",more:!1}}var FAMILIES=protocolId("families"),RUN=familyId("run"),LIFECYCLE=familyId("lifecycle"),DIALOGS=familyId("dialogs");async function*checkpointComponents(cut,valid){let{store,values,root,settled}=cut,current=root.current;if(!current)throw new CompactReadError("unavailable");let reader={store,values,valid},producers=familyProducers(root.transcript,root.refusedCorrelations),registry=familyRegistry(producers);yield*textComponent(store,FAMILIES,FAMILIES,JSON.stringify(registry));let family=name=>{switch(name){case"transcript":return transcriptComponents(store,root.transcript,producers,valid);case"opaque":return none();case"run":{let{runState,dialogCounts}=current.components;return textComponent(store,RUN,RUN,JSON.stringify({runState,dialogCounts}))}case"lifecycle":{let ref=current.components.lifecycle;return ref?stepsComponent(store,LIFECYCLE,LIFECYCLE,values.walk(ref,valid)):one(name)}case"dialogs":return dialogComponents(reader,current.components.dialogs);case"active":return activeComponents(reader,current.active);case"calls":return callsComponents(reader,current.calls);case"settled":return settledComponents(reader,settled);case"identity":return identityComponents(reader,root,settled);case"source":return sourceComponents(reader,root.transcript,producers,settled);default:return assertNever3(name)}},emitted=new Set;for(let name of CATALOG_FAMILIES)for await(let component of family(name))emitted.add(component.kind),yield component;assertCoverage(registry,emitted)}async function*dialogComponents(reader,ref){let dialogs=new CompactComponentRoots(reader.store,()=>[]),count=0;for await(let[order,value]of dialogs.rows(ref,reader.valid)){let steps=reader.values.walk(value,reader.valid);yield*stepsComponent(reader.store,DIALOGS,memberId("dialog",Number(order)),steps),count+=1}count===0&&(yield emptyComponent("dialogs"))}async function*none(){}async function*one(family){yield emptyComponent(family)}function assertNever3(family){throw new Error(`unmapped catalog family: ${JSON.stringify(family)}`)}import{createHash as createHash2}from"node:crypto";import{open as open5}from"node:fs/promises";var DEFAULT_TRANSCRIPT_TAIL_BYTES=256*1024*1024,TRANSCRIPT_TAIL_RESIDENT_BYTES=32*1024*1024,TAIL_KIND=protocolId("transcript-tail"),TailBudget=class{constructor(max=DEFAULT_TRANSCRIPT_TAIL_BYTES){this.held=0,this.max=max}};function stageTailEntry(staging,budget,index,text){let bytes=text.length*2;if(!(budget.held+staging.stagedBytes+bytes>budget.max)&&!(staging.residentBytes+bytes>TRANSCRIPT_TAIL_RESIDENT_BYTES))try{return staging.stage(TAIL_KIND,protocolId(`entry-${index}`),text)}catch(cause){if(cause instanceof TransferStagingError)return;throw cause}}function stageBootstrap(staging,transitions){let staged=new Map,index=0;try{for(let transition of transitions){if(transition.kind==="replace"&&(index=0),transition.kind!=="append")continue;let text=transition.entry,content=text===void 0?null:stageTailEntry(staging,new TailBudget,index,text);if(index+=1,content===void 0)throw new TransferStagingError("staging_over_byte_limit");content&&staged.set(transition,content)}return staged}catch(cause){for(let content of staged.values())staging.release(content);if(cause instanceof TransferStagingError)return;throw cause}}var TranscriptTail=class{#staging;#budget;#cuts;#superseded;constructor(staging,persistence,budget=new TailBudget){this.entries=new Map,this.kept=new Map,this.retainedBytes=0,this.#cuts=new Map,this.#superseded=!1,this.#staging=staging,this.persistence=persistence,this.#budget=budget}stage(index,text){return stageTailEntry(this.#staging,this.#budget,index,text)}adopt(index,content){this.#staging.adopt(content),this.entries.set(index,content),this.retainedBytes+=content.ref.entry.length,this.#budget.held+=content.ref.entry.length}retainCut(count){this.#cuts.set(count,(this.#cuts.get(count)??0)+1)}supersede(){if(this.#superseded=!0,this.#cuts.size===0)return this.releaseAll();for(let content of this.entries.values())this.#staging.spill(content)}releaseCut(count){let left=(this.#cuts.get(count)??0)-1;if(left>0?this.#cuts.set(count,left):this.#cuts.delete(count),this.#superseded&&this.#cuts.size===0)return this.releaseAll();let reach=this.reach();for(let[index,content]of this.kept)index<reach||(this.kept.delete(index),this.free(content))}persisted(persistence,baseCount){this.persistence=persistence;let reach=this.reach();for(let[index,content]of this.entries){if(index+baseCount>=persistence.count)break;if(this.entries.delete(index),this.retainedBytes-=content.ref.entry.length,index>=reach){this.free(content);continue}this.kept.set(index,content),this.#staging.spill(content)}}releaseAll(){for(let content of[...this.entries.values(),...this.kept.values()])this.free(content);this.entries.clear(),this.kept.clear(),this.retainedBytes=0}hold(count,baseCount){let staging=this.#staging,own=index=>this.entries.get(index)??this.kept.get(index),fileCount=Math.min(count,Math.max(0,(this.persistence?.count??0)-baseCount));for(;fileCount>0&&own(fileCount-1);)fileCount-=1;let held=new Map;for(let index=fileCount;index<count;index++){let content=own(index);content&&held.set(index,content)}for(let content of held.values())staging.pin(content,1);let released=!1;return{fileCount,persistence:this.persistence,has:index=>held.has(index),chunks:(index,valid)=>{let content=held.get(index);if(!content)throw new RangeError(`transcript tail entry ${index} is not held`);return staging.chunks(content,valid)},release:()=>{if(!released){released=!0;for(let content of held.values())staging.pin(content,-1)}}}}free(content){this.#budget.held-=content.ref.entry.length,this.#staging.release(content)}reach(){let reach=0;for(let count of this.#cuts.keys())reach=Math.max(reach,count);return reach}};var DEFAULT_TRANSCRIPT_ANCESTRY_BYTES=8*1024*1024,ANCESTRY_RECORD_BYTES=40,KIND_NAME_BYTES=64,stringBytes=value=>value===""?0:Math.ceil((16+(Buffer.byteLength(value)===value.length?value.length:2*value.length))/8)*8,AcceptedEntries=class{constructor(ids,kinds,parents,count){this.ids=ids,this.kinds=kinds,this.parents=parents,this.count=count}idsBefore(end){return this.ids.slice(0,Math.min(end,this.count))}*[Symbol.iterator](){for(let index=0;index<this.count;index++)yield{index,id:this.ids[index],kind:this.kinds[index],parentId:this.parents[index]}}},AcceptedTranscript=class{constructor(staging){this.version=0,this.leafId=null,this.base=null,this.entryIds=[],this.kinds=[],this.parents=[],this.kindNames=new Map,this.ancestryBytes=0,this.budget=new TailBudget,this.unavailable=null,this.staging=staging,this.tail=new TranscriptTail(staging,null,this.budget)}get historyVersion(){return this.version}get available(){return this.unavailable===null}bootstrap(transitions){let staged=stageBootstrap(this.staging,transitions);if(!staged)return this.markUnavailable("transcript_tail_over_byte_limit");try{for(let transition of transitions)this.apply(transition,staged.get(transition))}finally{for(let content of staged.values())this.staging.abandon(content)}}apply(transition,staged){if(this.version+=1,transition.kind==="replace"){this.tail.supersede(),this.base=transition.base,this.entryIds=[],this.kinds=[],this.parents=[],this.kindNames=new Map,this.ancestryBytes=0,this.tail=new TranscriptTail(this.staging,transition.base,this.budget),this.unavailable=null,this.missingFrom=void 0;return}if(transition.kind==="unavailable"){this.markUnavailable(transition.reason);return}if(transition.kind==="persisted"){this.persisted(transition.persistence);return}if(!(this.unavailable!==null&&this.missingFrom===void 0))if(transition.kind==="append"){let index=this.entryIds.length;if(!this.retainAncestry(transition.id,transition.type,transition.parentId))return;transition.persistence&&this.persisted(transition.persistence);let unpersisted=index+(this.base?.count??0)>=(this.tail.persistence?.count??0);if(this.missingFrom===void 0&&unpersisted&&transition.entry!==void 0){let content=staged??this.tail.stage(index,transition.entry);content?this.tail.adopt(index,content):this.markUnavailable("transcript_tail_over_byte_limit",index)}this.leafId=transition.id}else this.leafId=transition.leafId}retainAncestry(id,type,parentId){let previous=this.entryIds.at(-1),shared=previous!==void 0&&previous===parentId,kind=this.kindNames.get(type),bytes=ANCESTRY_RECORD_BYTES+stringBytes(id)+(kind===void 0?KIND_NAME_BYTES+stringBytes(type):0)+(shared?0:stringBytes(parentId??""));return this.ancestryBytes+bytes>DEFAULT_TRANSCRIPT_ANCESTRY_BYTES?(this.markUnavailable("transcript_ancestry_over_byte_limit"),!1):(kind===void 0&&this.kindNames.set(type,type),this.entryIds.push(id),this.kinds.push(kind??type),this.parents.push(shared?previous:parentId),this.ancestryBytes+=bytes,!0)}markUnavailable(reason,missingFrom){this.missingFrom=this.unavailable===null?missingFrom:void 0,this.unavailable??=reason,process.stderr.write(`senpi rpc acceptance: transcript component unavailable: ${reason}
|
|
8
|
+
`)}function blockValue(block,layout){let value=block.block??{};return layout==="current"||block.phase==="initial"||block.phase===void 0?value:"text"in value?{...value,text:""}:"thinking"in value?{...value,thinking:""}:value}function legacyMessage(message,layout){let fields=message.fields;if(!fields)return;if("content"in fields)return fields;let{role,...rest}=fields,content=[];for(let block of message.blocks)content[block.contentIndex]=blockValue(block,layout);return{...role===void 0?{}:{role},content,...rest}}function*blockFrames({contentIndex,text,phase,block},usage,resolved){if(phase===void 0||phase==="initial"||block===void 0)return;let ended=phase==="ended",resolvedToolName=resolved.get(contentIndex),update=(assistantMessageEvent,named2=!1)=>({type:"message_update",...usage===void 0?{}:{usage},assistantMessageEvent,...named2&&resolvedToolName!==void 0?{resolvedToolName}:{}});switch(block.type){case"text":case"thinking":{yield update({type:`${block.type}_start`,contentIndex}),text.length>0&&(yield update({type:`${block.type}_delta`,contentIndex,delta:text})),ended&&(yield update({type:`${block.type}_end`,contentIndex,content:text}));return}case"toolCall":{yield update({type:"toolcall_start",contentIndex,id:block.id,toolName:block.name},!0),text.length>0&&(yield update({type:"toolcall_delta",contentIndex,delta:text})),ended&&(yield update({type:"toolcall_end",contentIndex,toolCall:block},!0));return}default:return}}function*toolResetFrames(message){let usage=message.fields?.usage;for(let{contentIndex,text,phase,block}of message.blocks)phase!=="open"||block?.type!=="toolCall"||(yield{type:"message_tool_arguments_reset",contentIndex,rawArgumentPrefix:"",parsedThrough:0},text.length>0&&(yield{type:"message_update",...usage===void 0?{}:{usage},assistantMessageEvent:{type:"toolcall_delta",contentIndex,delta:text}}))}function*messageFrames(message,resolved){let start=legacyMessage(message,"start");if(start&&(yield{type:"message_start",message:start},!(!("role"in start)||start.role!=="assistant")))for(let block of message.blocks)yield*blockFrames(block,message.fields?.usage,resolved)}function remainingMs(dialog,now){return typeof dialog.deadlineAtMs=="number"?Math.max(0,dialog.deadlineAtMs-now):0}async function activeMessage({lane,root}){return root.activeMessageId===null?void 0:(await lane.readCurrentActive(root)).find(message=>message.messageId===root.activeMessageId)}async function resolvedNames({lane,root},messageId){let names=new Map;for(let call of(await lane.readCurrentCalls(root)).calls)call.owningMessageId===messageId&&call.contentIndex!==null&&call.resolvedName!==null&&names.set(call.contentIndex,call.resolvedName);return names}async function*attachFrames(sessionId,source,view,cancelled){let read;try{read=await source.hold(async()=>{let components2=await source.lane.readCurrentComponents(source.root),message2=await activeMessage(source),resolved2=message2?await resolvedNames(source,message2.messageId):new Map;return{components:components2,message:message2,resolved:resolved2}})}catch(cause){cancelled()||unavailable(sessionId,cause);return}let{components,message,resolved}=read,encode=frame=>serializeJsonLine(view.placeholders?omitNormalInlineMedia(frame):frame),tag=frame=>({...frame,sessionId});if(isFrame(components.lifecycle)&&(yield encode(tag(components.lifecycle))),message)for(let frame of messageFrames(message,resolved))yield encode(tag(frame));for(let dialog of components.dialogs)dialog.audience==="broadcast"&&isFrame(dialog.request)&&(yield encode({...tag(dialog.request),remainingMs:remainingMs(dialog,view.now)}))}function legacyAttachView(sessionId,source,view,onRelease){let current=source?.root.current,empty=source===void 0||current===void 0||current.components.lifecycle===void 0&¤t.components.dialogCounts.broadcast===0&&source.root.activeMessageId===null,released=!1,epoch=source?.lane.recoveryEpoch,cancelled=()=>released||source!==void 0&&!source.lane.holds(source.root)||source?.lane.recoveryEpoch!==epoch;return new GeneratedFramesCursor(empty,()=>source?attachFrames(sessionId,source,view,cancelled):(async function*(){})(),()=>{released=!0,onRelease()})}async function legacyResyncMessage(sessionId,source){if(!source)return{message:null};if(!source.ok)return REPORTED[refusalReason(source.failure)]&&unavailable(sessionId,source.failure.reason),{message:null};let{value}=source;return value.hold(async()=>{try{let message=await activeMessage(value),current=message&&legacyMessage(message,"current");return current?{message:current,frames:[...toolResetFrames(message)]}:{message:null}}catch(cause){return value.lane.holds(value.root)&&unavailable(sessionId,cause),{message:null}}})}import{createHmac,randomBytes,timingSafeEqual}from"node:crypto";var CURSOR_MAC_BYTES=16,CURSOR_VERSION="p1",DECIMAL="(?:0|[1-9][0-9]{0,15})",CURSOR=new RegExp(`^${CURSOR_VERSION}:${DECIMAL}:${DECIMAL}:[0-9a-f]{${CURSOR_MAC_BYTES*2}}$`),DOMAIN="senpi-recovery-cursor/1";function keyedAuthenticator(){let key=randomBytes(32);return text=>createHmac("sha256",key).update(text,"utf8").digest().subarray(0,CURSOR_MAC_BYTES)}var material=(binding,position)=>[DOMAIN,binding.socketEpoch,binding.sessionId,binding.tokenId,String(binding.generation),binding.componentRef,String(position.ordinal),String(position.offset)].map(field4=>`${Buffer.byteLength(field4)}:${field4}`).join("\0"),RecoveryCursors=class{constructor(){this.authenticate=keyedAuthenticator()}mint(binding,position){let mac=this.authenticate(material(binding,position)).toString("hex");return`${CURSOR_VERSION}:${position.ordinal}:${position.offset}:${mac}`}open(cursor,binding){if(!parseBoundedId(cursor).ok||!CURSOR.test(cursor))return;let[,ordinal,offset,mac]=cursor.split(":"),position={ordinal:Number(ordinal),offset:Number(offset)};if(!Number.isSafeInteger(position.ordinal)||!Number.isSafeInteger(position.offset))return;let expected=this.authenticate(material(binding,position)),presented=Buffer.from(mac??"","hex");return presented.length===expected.length&&timingSafeEqual(presented,expected)?position:void 0}};var SOCKET_PAGE_REQUESTS_MAX=8,HINTS={malformed_request:"new_request",busy:"retry",request_limit:"retry",request_mismatch:"new_request",invalid_cursor:"restart_from_catalog",cursor_out_of_range:"restart_from_catalog",ordinal_exhausted:"release_token",lease_kind_unsupported:"new_request"},named=request=>"lease"in request?request.lease?.id:request.token,sameRequest=(a,b)=>a.requestId===b.requestId&&a.componentRef===b.componentRef&&a.cursor===b.cursor&&named(a)===named(b),RecoveryPageRequests=class{constructor(checkpoints,cursors=new RecoveryCursors,events){this.tokens=new Map,this.outstanding=new Map,this.refusals=new Map,this.lifetimes=new Map,this.checkpoints=checkpoints,this.cursors=cursors,this.events=events,checkpoints.onTokenEnd(tokenId=>this.tokens.delete(tokenId)),events?.onLeaseEnd(leaseId=>this.tokens.delete(leaseId))}status(){let outstanding=0;for(let count of this.outstanding.values())outstanding+=count;let cachedBytes=0;for(let{current}of this.tokens.values())cachedBytes+=current?.answer.bytes.length??0;return{tokens:this.tokens.size,outstanding,cachedBytes,refused:Object.fromEntries(this.refusals)}}forgetPeer(socketEpoch){this.lifetimes.get(socketEpoch)?.abort(),this.lifetimes.delete(socketEpoch)}async request(caller,request,signal){let kind="lease"in request?request.lease?.kind:"checkpoint",fields=[request.requestId,request.admissionId,named(request),request.componentRef];if(kind!=="event"&&kind!=="checkpoint"||fields.some(field4=>typeof field4!="string"||!parseBoundedId(field4).ok))return this.refuse("malformed_request");if((this.outstanding.get(caller.socketEpoch)??0)>=SOCKET_PAGE_REQUESTS_MAX)return this.refuse("request_limit");let id=String(named(request)),source=kind==="event"?this.eventSource(caller,id,request.admissionId):this.checkpointSource(caller,id,request.admissionId);if(!source.ok)return source;let token=source.value,state=this.tokens.get(token.id)??{active:!1,ordinal:0,current:void 0};if(state.active)return this.refuse("busy");if(state.current?.request.requestId===request.requestId)return sameRequest(state.current.request,request)?{ok:!0,value:state.current.answer}:this.refuse("request_mismatch");let binding={socketEpoch:caller.socketEpoch,sessionId:caller.sessionId,tokenId:token.id,generation:token.generation,componentRef:request.componentRef},position=request.cursor===void 0?void 0:this.cursors.open(request.cursor,binding);if(request.cursor!==void 0&&position===void 0)return this.refuse("invalid_cursor");let last=position?.ordinal??state.ordinal;return Number.isSafeInteger(last+1)?position!==void 0&&position.ordinal!==state.ordinal?this.refuse("cursor_out_of_range"):(this.tokens.set(token.id,state),this.serve(caller,token,request,state,binding,position?.offset??0,signal)):this.refuse("ordinal_exhausted")}checkpointSource(caller,tokenId,admissionId){let token=this.checkpoints.tokens().find(each=>each.id===tokenId);if(!token||token.admission.socketEpoch!==caller.socketEpoch||token.admission.sessionId!==caller.sessionId||!this.checkpoints.stream(caller)?.routes.includes(admissionId))return{ok:!1,failure:repairNeeded("unknown_token")};let claimed=this.checkpoints.check(token,caller);if(!claimed.ok)return claimed;let{generation}=token.admission;return{ok:!0,value:{id:token.id,generation,label:{token:token.id,generation},read:(ref,offset,signal)=>this.checkpoints.readCatalogPage(token,caller,ref,offset,signal)}}}eventSource(caller,leaseId,admissionId){let events=this.events;if(!events)return{ok:!1,failure:repairNeeded("unknown_token")};let claimed=events.claim(caller,leaseId,admissionId);if(!claimed.ok)return claimed;let held=claimed.value;return{ok:!0,value:{id:held.lease.id,generation:0,label:{lease:{kind:"event",id:held.lease.id}},read:(ref,offset,signal)=>events.page(held,ref,offset,signal)}}}async serve(caller,token,request,state,binding,offset,signal){state.active=!0,this.outstanding.set(caller.socketEpoch,(this.outstanding.get(caller.socketEpoch)??0)+1);let lifetime=this.lifetimes.get(caller.socketEpoch)??new AbortController;this.lifetimes.set(caller.socketEpoch,lifetime);let budget=signal===void 0?lifetime.signal:AbortSignal.any([signal,lifetime.signal]),page;try{page=await token.read(request.componentRef,offset,budget)}finally{state.active=!1;let left=(this.outstanding.get(caller.socketEpoch)??1)-1;left>0?this.outstanding.set(caller.socketEpoch,left):(this.outstanding.delete(caller.socketEpoch),this.lifetimes.get(caller.socketEpoch)===lifetime&&this.lifetimes.delete(caller.socketEpoch))}if(page.ok||this.tokens.delete(token.id),!page.ok)return page;if(!this.tokens.has(token.id))return{ok:!1,failure:repairNeeded("released")};let ordinal=state.ordinal+1,answer={requestId:request.requestId,...token.label,componentRef:request.componentRef,ordinal,offset:page.value.offset,length:page.value.length,digest:page.value.digest,bytes:page.value.bytes.toString("base64"),cursor:page.value.next===null?null:this.cursors.mint(binding,{ordinal,offset:page.value.next}),complete:page.value.complete};return state.ordinal=ordinal,state.current={request,answer},{ok:!0,value:answer}}refuse(reason){return this.refusals.set(reason,(this.refusals.get(reason)??0)+1),{ok:!1,failure:{kind:"request_refused",reason,hint:HINTS[reason]}}}};var CATALOG_FAMILIES=["transcript","run","lifecycle","dialogs","opaque","active","calls","settled","identity","source"],FAMILY_SET=new Set(CATALOG_FAMILIES),PRODUCERS=["complete","partial"],PRODUCER_SET=new Set(PRODUCERS),FAMILY_PRODUCERS={transcript:"complete",run:"complete",lifecycle:"complete",dialogs:"complete",opaque:"complete",active:"complete",calls:"complete",settled:"complete",identity:"complete",source:"complete"};function familyProducers(transcript,refusedCorrelations){let entries=transcript.unavailable===null?{}:{transcript:"partial",opaque:"partial",source:"partial"};return{...FAMILY_PRODUCERS,...entries,...refusedCorrelations>0?{identity:"partial"}:{}}}var ENTRY_FAMILIES={session:"transcript",message:"transcript",thinking_level_change:"source",configuration_update:"source",model_change:"source",model_change_rejected:"source",usage:"source",compaction:"source",branch_summary:"source",custom:"source",custom_message:"source",context_edit:"source",label:"source",session_info:"source"},KNOWN_KINDS=new Map(Object.entries(ENTRY_FAMILIES)),entryFamily=kind=>KNOWN_KINDS.get(kind)??"opaque",familyId=family=>protocolId(family),memberId=(prefix,ordinal)=>protocolId(`${prefix}-${typeof ordinal=="number"?String(ordinal).padStart(16,"0"):ordinal}`),COMPLETE=Symbol("complete family registry");function familyRegistry(producers){let families=CATALOG_FAMILIES.map(family=>({family,producer:producers[family]})),incomplete=families.filter(({producer})=>producer!=="complete").map(({family})=>family),base={format:"senpi-recovery-families",version:1,families};return incomplete.length===0?{...base,assembly:"complete",[COMPLETE]:!0}:{...base,assembly:"incomplete",incomplete}}function assertCoverage(registry,emitted){if(registry.families.filter(({family,producer})=>producer==="complete"&&!emitted.has(family)).length>0)throw new CompactReadError("unavailable")}function*literalSteps(value){let stack=[],pending={value};for(;;){if(pending){let current=pending.value;if(pending=void 0,typeof current=="string")yield{kind:"string",text:current,more:!1};else if(typeof current=="object"&¤t!==null){let array=Array.isArray(current);yield{kind:"open",container:array?"array":"object"},stack.push({children:array?current:Object.entries(current).flat(),index:0})}else typeof current=="number"||typeof current=="boolean"||current===null?yield{kind:"scalar",value:current}:yield{kind:"scalar",value:null};continue}let frame=stack[stack.length-1];if(!frame)return;frame.index<frame.children.length?pending={value:frame.children[frame.index++]}:(stack.pop(),yield{kind:"close"})}}async function*objectSteps(fields){yield{kind:"open",container:"object"};for await(let[name,steps]of fields)yield{kind:"string",text:name,more:!1},yield*steps;yield{kind:"close"}}async function*arraySteps(items){yield{kind:"open",container:"array"};for await(let steps of items)yield*steps;yield{kind:"close"}}async function*storedSteps(store,leaves){for(let[index,leaf2]of leaves.entries())yield{kind:"raw",text:await store.readLeaf(leaf2),more:index+1<leaves.length}}var literalFields=value=>Object.entries(value).map(([name,item])=>[name,literalSteps(item)]);async function*textSteps(texts,roots,valid,suffix=""){for(let root of roots)for await(let chunk of texts.chunks(root,valid))yield{kind:"string",text:chunk,more:!0};yield{kind:"string",text:suffix,more:!1}}var fieldSteps=(values,fields,valid)=>objectSteps(Object.entries(fields).map(([name,ref])=>[name,values.walk(ref,valid)])),walkedSteps=(values,ref,valid)=>ref?values.walk(ref,valid):literalSteps(null);var CatalogComponentWriter=class{constructor(store){this.leaves=[],this.open="",this.store=store}push(text){let rest=text;for(;this.open.length+rest.length>COMPACT_LEAF_CODE_UNITS;){let take=COMPACT_LEAF_CODE_UNITS-this.open.length;this.seal(this.open+rest.slice(0,take)),rest=rest.slice(take)}this.open+=rest}finish(kind,id){this.open.length>0&&this.seal(this.open),this.open="";let owner=this.store.text.own(this.leaves);for(let leaf2 of this.leaves)this.store.adjust(leaf2,-1,0);return{kind,id,leaves:[...this.leaves],owner}}abort(){for(let leaf2 of this.leaves)this.store.adjust(leaf2,-1,0);this.leaves.length=0,this.open=""}seal(text){this.leaves.push(this.store.createLeaf(text,!0)),this.open=""}};async function*writtenComponent(store,kind,id,fill){let writer=new CatalogComponentWriter(store),component;try{await fill(writer),component=writer.finish(kind,id)}catch(cause){throw writer.abort(),cause}try{yield component}finally{store.adjust(component.owner,-1,0)}}var stepsComponent=(store,kind,id,steps)=>writtenComponent(store,kind,id,async writer=>{for await(let fragment of encodeValueSteps(steps))writer.push(fragment)}),emptyComponent=family=>({kind:familyId(family),id:familyId(family),leaves:[],owner:0}),HIGH_SURROGATE=/[\uD800-\uDBFF]$/;async function*encodeValueSteps(steps){let stack=[],carry="",inString=!1,inRaw=!1,separator=()=>{let frame=stack[stack.length-1];if(!frame)return"";let count=frame.emitted++;return frame.container==="array"?count>0?",":"":count===0?"":count%2===0?",":":"};for await(let step of steps)switch(step.kind){case"scalar":yield`${separator()}${JSON.stringify(step.value)}`;break;case"string":{let prefix=inString?"":`${separator()}"`,text=carry+step.text;carry="",step.more&&HIGH_SURROGATE.test(text)&&(carry=text.slice(-1),text=text.slice(0,-1)),inString=step.more,yield`${prefix}${JSON.stringify(text).slice(1,-1)}${step.more?"":'"'}`;break}case"raw":yield`${inRaw?"":separator()}${step.text}`,inRaw=step.more;break;case"open":yield`${separator()}${step.container==="array"?"[":"{"}`,stack.push({container:step.container,emitted:0});break;case"close":yield stack.pop()?.container==="array"?"]":"}";break;default:return assertNever2(step)}}function assertNever2(step){throw new Error(`unexpected value step: ${JSON.stringify(step)}`)}var CompactIndexTree=class{constructor(retain){this.residentNodes=0,this.allocatedNodes=0,this.retain=retain}get(root,key){let node=root;for(;node;){if(key===node.key)return node.value;node=key<node.key?node.left:node.right}}adjust(root,live,pins){if(!root)return;let wasLive=+(root.live>0),wasPinned=+(root.live===0&&root.pins>0);if(root.live+live<0||root.pins+pins<0)throw new CompactReadError("ownership");root.live+=live,root.pins+=pins;let l=+(root.live>0)-wasLive,p=+(root.live===0&&root.pins>0)-wasPinned;(l||p)&&(this.retain(root.value,l,p),this.adjust(root.left,l,p),this.adjust(root.right,l,p)),root.live===0&&root.pins===0&&this.residentNodes--}set(root,key,value){if(!root)return value===void 0?void 0:this.make(key,value,void 0,void 0);if(key===root.key){if(value!==void 0)return this.make(key,value,root.left,root.right);if(!root.left||!root.right){let child2=root.left??root.right;return this.adjust(child2,1,0),child2}let next=root.right;for(;next.left;)next=next.left;let right=this.set(root.right,next.key,void 0),result2=this.balance(next.key,next.value,root.left,right);return this.adjust(right,-1,0),result2}let leftward=key<root.key,child=this.set(leftward?root.left:root.right,key,value),result=this.balance(root.key,root.value,leftward?child:root.left,leftward?root.right:child);return this.adjust(child,-1,0),result}*entries(root,after){root&&((after===void 0||root.key>after)&&(yield*this.entries(root.left,after),yield[root.key,root.value]),yield*this.entries(root.right,after))}make(key,value,left,right){return this.adjust(left,1,0),this.adjust(right,1,0),this.retain(value,1,0),this.residentNodes++,this.allocatedNodes++,{key,value,left,right,live:1,pins:0,height:1+Math.max(left?.height??0,right?.height??0),size:1+(left?.size??0)+(right?.size??0)}}balance(key,value,left,right){if(left&&left.height>(right?.height??0)+1){let middle=left.right;if(middle&&middle.height>(left.left?.height??0)){let a=this.make(left.key,left.value,left.left,middle.left),b2=this.make(key,value,middle.right,right),result2=this.make(middle.key,middle.value,a,b2);return this.adjust(a,-1,0),this.adjust(b2,-1,0),result2}let b=this.make(key,value,left.right,right),result=this.make(left.key,left.value,left.left,b);return this.adjust(b,-1,0),result}if(right&&right.height>(left?.height??0)+1){let middle=right.left;if(middle&&middle.height>(right.right?.height??0)){let a2=this.make(key,value,left,middle.left),b=this.make(right.key,right.value,middle.right,right.right),result2=this.make(middle.key,middle.value,a2,b);return this.adjust(a2,-1,0),this.adjust(b,-1,0),result2}let a=this.make(key,value,left,right.left),result=this.make(right.key,right.value,a,right.right);return this.adjust(a,-1,0),result}return this.make(key,value,left,right)}};var VALUE_PAGE_ITEMS=128,VALUE_PAGE_CODE_UNITS=4096,INLINE_JSON_LENGTH=64,scalar=value=>value===null||typeof value=="boolean"||typeof value=="number"&&Number.isFinite(value),plain=value=>typeof value=="object"&&value!==null&&(Array.isArray(value)||Object.getPrototypeOf(value)===Object.prototype||Object.getPrototypeOf(value)===null);function ownValue(store,make,value){let owned=new Set,ancestors=new Set,stack=[],take=(page,children)=>{let ref=make(page);owned.add(ref.owner);for(let child of children)store.adjust(child.owner,-1,0),owned.delete(child.owner);return ref},ownString=text=>{let next;for(let end=text.length;end>0;end=Math.max(0,end-VALUE_PAGE_CODE_UNITS))next=take({kind:"string",text:text.slice(Math.max(0,end-VALUE_PAGE_CODE_UNITS),end),next},next?[next]:[]);if(!next)throw new CompactWriteError("unsupported_value");return next},open6=object=>{if(ancestors.has(object))throw new CompactWriteError("cycle");ancestors.add(object);let array=Array.isArray(object),entries=array?object:Object.entries(object);stack.push({object,array,entries,end:entries.length,children:[],index:0,refs:[],next:void 0}),slice(stack[stack.length-1])},slice=frame=>{let part=frame.entries.slice(Math.max(0,frame.end-VALUE_PAGE_ITEMS),frame.end);frame.children=frame.array?part:part.flat(),frame.index=0,frame.refs=[]},close=frame=>{let refs=frame.refs,items=frame.array?{kind:"array",items:refs,next:frame.next}:{kind:"object",items:pairs(refs),next:frame.next};if(frame.next=take(items,frame.next?[...refs,frame.next]:refs),frame.end>VALUE_PAGE_ITEMS){frame.end-=VALUE_PAGE_ITEMS,slice(frame);return}return stack.pop(),ancestors.delete(frame.object),frame.next};try{let pending={value},done;for(;;){if(pending){let current=pending.value;if(pending=void 0,scalar(current)||typeof current=="string"&&JSON.stringify(current).length<=INLINE_JSON_LENGTH)done={node:0,owner:0,value:current};else if(typeof current=="string")done=ownString(current);else if(plain(current))open6(current);else throw new CompactWriteError("unsupported_value")}let frame=stack[stack.length-1];if(done){if(!frame)return done;frame.refs.push(done),done=void 0}if(!frame)throw new CompactWriteError("unsupported_value");frame.index<frame.children.length?pending={value:frame.children[frame.index++]}:done=close(frame)}}catch(error){for(let owner of owned)store.adjust(owner,-1,0);throw error}}function pairs(refs){let fields=[];for(let index=0;index+1<refs.length;index+=2)fields.push([refs[index],refs[index+1]]);return fields}var __addDisposableResource=function(env,value,async){if(value!=null){if(typeof value!="object"&&typeof value!="function")throw new TypeError("Object expected.");var dispose,inner;if(async){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");dispose=value[Symbol.asyncDispose]}if(dispose===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");dispose=value[Symbol.dispose],async&&(inner=dispose)}if(typeof dispose!="function")throw new TypeError("Object not disposable.");inner&&(dispose=function(){try{inner.call(this)}catch(e){return Promise.reject(e)}}),env.stack.push({value,dispose,async})}else async&&env.stack.push({async:!0});return value},__disposeResources=(function(SuppressedError2){return function(env){function fail(e){env.error=env.hasError?new SuppressedError2(e,env.error,"An error was suppressed during disposal."):e,env.hasError=!0}var r,s=0;function next(){for(;r=env.stack.pop();)try{if(!r.async&&s===1)return s=0,env.stack.push(r),Promise.resolve().then(next);if(r.dispose){var result=r.dispose.call(r.value);if(r.async)return s|=2,Promise.resolve(result).then(next,function(e){return fail(e),next()})}else s|=1}catch(e){fail(e)}if(s===1)return env.hasError?Promise.reject(env.error):Promise.resolve();if(env.hasError)throw env.error}return next()}})(typeof SuppressedError=="function"?SuppressedError:function(error,suppressed,message){var e=new Error(message);return e.name="SuppressedError",e.error=error,e.suppressed=suppressed,e}),CompactValues=class{constructor(store){this.residentPages=0,this.peakResidentPages=0,this.store=store}record(fields){let entries=[...fields],next;for(let end=entries.length;end>0||!next;end=Math.max(0,end-128)){let items=entries.slice(Math.max(0,end-128),end).map(([key,value])=>[this.own(key),value]),ref=this.make({kind:"object",items,next});for(let[key]of items)this.store.adjust(key.owner,-1,0);if(next&&this.store.adjust(next.owner,-1,0),next=ref,end<=128)break}return next}own(value){return ownValue(this.store,page=>this.make(page),value)}async page(ref){this.residentPages++,this.peakResidentPages=Math.max(this.peakResidentPages,this.residentPages);try{let text=await this.store.readLeaf(ref.node);if(Buffer.byteLength(text)>65536)throw new CompactReadError("size_limit");let page=JSON.parse(text);if((page.kind==="object"||page.kind==="array")&&page.items.length>128)throw new CompactReadError("count_limit");return{value:page,[Symbol.dispose]:()=>{this.residentPages--}}}catch(error){throw this.residentPages--,error}}async*walk(ref,valid){let stack=[],pending=ref,chunked=!1;for(;;){if(pending){let env_1={stack:[],error:void 0,hasError:!1};try{if("value"in pending){yield typeof pending.value=="string"?{kind:"string",text:pending.value,more:!1}:{kind:"scalar",value:pending.value},pending=void 0;continue}let held=__addDisposableResource(env_1,await this.page(pending),!1);valid?.();let page=held.value;if(chunked&&page.kind!=="string")throw new CompactReadError("ownership");page.kind==="scalar"?(yield{kind:"scalar",value:page.value},pending=void 0):page.kind==="string"?(yield{kind:"string",text:page.text,more:page.next!==void 0},chunked=page.next!==void 0,pending=page.next):(yield{kind:"open",container:page.kind},stack.push({kind:page.kind,items:page.items.flat(),index:0,next:page.next}),pending=void 0);continue}catch(e_1){env_1.error=e_1,env_1.hasError=!0}finally{__disposeResources(env_1)}}let frame=stack[stack.length-1];if(!frame)return;if(frame.index<frame.items.length)pending=frame.items[frame.index++];else if(frame.next){let env_2={stack:[],error:void 0,hasError:!1};try{let held=__addDisposableResource(env_2,await this.page(frame.next),!1);valid?.();let page=held.value;if(page.kind!==frame.kind)throw new CompactReadError("ownership");frame.items=page.items.flat(),frame.index=0,frame.next=page.next}catch(e_2){env_2.error=e_2,env_2.hasError=!0}finally{__disposeResources(env_2)}}else stack.pop(),yield{kind:"close"}}}async read(ref,valid){if("value"in ref)return ref.value;let stack=[],text,settle=value=>{let parent=stack[stack.length-1];if(!parent)return value;if(Array.isArray(parent.value))parent.value.push(value);else if(parent.key===void 0){if(typeof value!="string")throw new CompactReadError("ownership");parent.key=value}else Object.defineProperty(parent.value,parent.key,{value,enumerable:!0,configurable:!0,writable:!0}),parent.key=void 0},result;for await(let step of this.walk(ref,valid))if(step.kind==="open")stack.push({value:step.container==="array"?[]:{},key:void 0});else if(step.kind==="close"){let frame=stack.pop();if(!frame)throw new CompactReadError("ownership");result=settle(frame.value)}else step.kind==="scalar"?result=settle(step.value):step.more?text=(text??"")+step.text:(result=settle((text??"")+step.text),text=void 0);return result}async*fields(ref,names,valid){let next=ref;for(;next;){let page=await this.objectPage(next,valid);for(let[key,value]of page.items)yield[await this.matchKey(key,names,valid),value,key];next=page.next}}async objectPage(ref,valid){let env_3={stack:[],error:void 0,hasError:!1};try{let held=__addDisposableResource(env_3,await this.page(ref),!1);if(valid?.(),held.value.kind!=="object")throw new CompactReadError("ownership");return held.value}catch(e_3){env_3.error=e_3,env_3.hasError=!0}finally{__disposeResources(env_3)}}async matchKey(key,names,valid){let candidates=[...names],read=0;for await(let step of this.walk(key,valid)){if(step.kind!=="string")throw new CompactReadError("ownership");if(candidates=candidates.filter(name=>name.startsWith(step.text,read)),read+=step.text.length,!step.more)return candidates.find(name=>name.length===read);if(candidates.length===0)return}throw new CompactReadError("ownership")}async merge(base,patch){let reversed,result,buffer=[],seen=new Set,flush=async()=>{let ref=this.make({kind:"object",items:buffer,next:reversed});if(reversed&&this.store.adjust(reversed.owner,-1,0),reversed=ref,buffer=[],await this.store.flushLeaf(ref.node),!this.store.isCommitted(ref.node))throw new CompactWriteError("storage_unavailable")};try{for await(let[name,value,key]of this.fields(base,new Set(patch.keys())))name!==void 0&&seen.add(name),buffer.push([key,name===void 0?value:patch.get(name)??value]),buffer.length===128&&await flush();for(let[name,value]of patch){if(seen.has(name))continue;let key=this.own(name);buffer.push([key,value]);try{await flush()}finally{this.store.adjust(key.owner,-1,0)}}for((buffer.length||!reversed)&&await flush();reversed;){let env_4={stack:[],error:void 0,hasError:!1};try{let page=__addDisposableResource(env_4,await this.page(reversed),!1).value;if(page.kind!=="object")throw new CompactReadError("ownership");let ref=this.make({kind:"object",items:page.items,next:result});if(result&&this.store.adjust(result.owner,-1,0),result=ref,await this.store.flushLeaf(ref.node),!this.store.isCommitted(ref.node))throw new CompactWriteError("storage_unavailable");let next=page.next;next&&this.store.adjust(next.owner,1,0),this.store.adjust(reversed.owner,-1,0),reversed=next}catch(e_4){env_4.error=e_4,env_4.hasError=!0}finally{__disposeResources(env_4)}}if(!result)throw new CompactReadError("ownership");return result}catch(error){throw reversed&&this.store.adjust(reversed.owner,-1,0),result&&this.store.adjust(result.owner,-1,0),error}}make(page){let children=page.kind==="object"?page.items.flat():page.kind==="array"?[...page.items]:[];page.kind!=="scalar"&&page.next&&children.push(page.next);let node=this.store.createLeaf(JSON.stringify(page),!0),owner=this.store.text.own([node,...children.map(ref=>ref.owner)]);return this.store.adjust(node,-1,0),{node,owner}}};var CompactComponentRoots=class{constructor(store,leavesOf){this.refs=new WeakMap,this.store=store,this.values=new CompactValues(store),this.leavesOf=leavesOf,this.tree=new CompactIndexTree((value,live,pins)=>store.adjust(value.owner,live,pins))}get residentNodes(){return this.tree.residentNodes}set(root,key,value){let ref=value&&this.values.own(value),owner=ref&&value?this.store.text.own([ref.owner,...this.leavesOf(value)]):0,header=this.tree.set(root.header,key,value&&ref?{value,ref,owner}:void 0);ref&&this.store.adjust(ref.owner,-1,0),this.store.adjust(owner,-1,0);let created=[],next=header?this.project(header,created):void 0;next&&this.store.adjust(next.owner,1,0);for(let ref2 of created)this.store.adjust(ref2.owner,-1,0);return this.tree.adjust(root.header,-1,0),root.ref&&this.store.adjust(root.ref.owner,-1,0),{header,ref:next}}release(root){this.store.enqueue("reclaim",async()=>{this.tree.adjust(root.header,-1,0),root.ref&&this.store.adjust(root.ref.owner,-1,0)})}async*rows(ref,valid){if(!ref)return;valid();let page=JSON.parse(await this.store.readLeaf(ref.node));valid(),yield*this.rows(page.left,valid);let key=await this.values.read(page.key,valid);if(typeof key!="string")throw new CompactReadError("ownership");yield[key,page.value],yield*this.rows(page.right,valid)}async*entries(ref,valid){for await(let[key,value]of this.rows(ref,valid)){let row=await this.values.read(value,valid);valid(),yield[key,row]}}project(node,created){let known=this.refs.get(node);if(known)return known;let left=node.left&&this.project(node.left,created),right=node.right&&this.project(node.right,created),key={node:0,owner:0,value:node.key},page=this.store.createLeaf(JSON.stringify({key,value:node.value.ref,left,right}),!0),owner=this.store.text.own([page,key.owner,node.value.owner,left?.owner??0,right?.owner??0]);this.store.adjust(page,-1,0);let ref={node:page,owner};return this.refs.set(node,ref),created.push(ref),ref}};var CALLS=familyId("calls"),SLOTS=new Set(["raw","hook","progress","result"]),leaf=value=>{if(typeof value!="number")throw new CompactReadError("ownership");return value};function flatSlot(steps){let[first]=steps;if(first?.kind==="scalar"&&first.value===null&&steps.length===1)return null;if(first?.kind!=="open"||first.container!=="object")throw new CompactReadError("ownership");let fields={},key,text="";for(let step of steps.slice(1,-1)){if(step.kind==="open"||step.kind==="close")throw new CompactReadError("ownership");if(step.kind==="string"&&step.more){text+=step.text;continue}let value=step.kind==="string"?text+step.text:step.value;if(text="",key!==void 0)fields[key]=value,key=void 0;else if(typeof value=="string")key=value;else throw new CompactReadError("ownership")}return fields}function rawSteps({store,valid},raw){return raw?.kind!=="owned"?literalSteps(raw):objectSteps([["kind",literalSteps("owned")],["text",textSteps(store.text,[leaf(raw.root),leaf(raw.tailRoot)],valid)]])}function slotRef(slot){return slot===null?null:"value"in slot?{node:0,owner:0,value:slot.value??null}:{node:leaf(slot.node),owner:leaf(slot.owner)}}var slotSteps=(reader,name,slot)=>name==="raw"?rawSteps(reader,slot):walkedSteps(reader.values,slotRef(slot),reader.valid);async function*headerSteps(reader,ref){let depth=0,key="",slot;for await(let step of reader.values.walk(ref,reader.valid)){let outer=depth;if(step.kind==="open"?depth+=1:step.kind==="close"&&(depth-=1),outer===0||depth===0){yield step;continue}if(key!==void 0){if(step.kind!=="string")throw new CompactReadError("ownership");if(key+=step.text,yield step,step.more)continue;slot=SLOTS.has(key)?{name:key,steps:[]}:void 0,key=void 0;continue}slot?slot.steps.push(step):yield step,!(depth!==1||step.kind==="string"&&step.more)&&(slot&&(yield*slotSteps(reader,slot.name,flatSlot(slot.steps))),slot=void 0,key="")}}async function*callsComponents(reader,calls){let roots=new CompactComponentRoots(reader.store,()=>[]),count=0;for await(let[order,ref]of roots.rows(calls.ref,reader.valid))yield*stepsComponent(reader.store,CALLS,memberId("call",order.replace(".","-")),headerSteps(reader,ref)),count+=1;count===0&&(yield emptyComponent("calls"))}var ACTIVE=familyId("active");function blockSteps({store,values,valid},block){let seeded=block.seeded;return objectSteps([["contentIndex",literalSteps(block.contentIndex)],["kind",literalSteps(block.kind)],["text",textSteps(store.text,[block.root,block.tailRoot??0],valid,block.tail)],["seeded",seeded?objectSteps([["type",literalSteps(seeded.type)],["phase",literalSteps(seeded.phase)],["parsedThrough",literalSteps(seeded.parsedThrough)],["fields",fieldSteps(values,seeded.fields,valid)],["signature",textSteps(store.text,[seeded.signature.root,seeded.signature.tailRoot],valid)]]):literalSteps(null)]])}async function*blockItems(reader,blocks,ref){for await(let[,block]of blocks.entries(ref,reader.valid))yield blockSteps(reader,block)}function messageSteps(reader,row,blocks){let{values,valid}=reader;return objectSteps([["messageId",literalSteps(row.messageId)],["fields",row.fields?fieldSteps(values,row.fields,valid):literalSteps(null)],["correlation",row.correlation?fieldSteps(values,row.correlation,valid):literalSteps(null)],["blocks",arraySteps(blockItems(reader,blocks,row.blocks))]])}async function*activeComponents(reader,active){let messages=new CompactComponentRoots(reader.store,()=>[]),blocks=new CompactComponentRoots(reader.store,()=>[]),count=0;for await(let[order,row]of messages.entries(active,reader.valid))yield*stepsComponent(reader.store,ACTIVE,memberId("message",Number(order)),messageSteps(reader,row,blocks)),count+=1;count===0&&(yield emptyComponent("active"))}var TRANSCRIPT=familyId("transcript"),OPAQUE=familyId("opaque"),BASE=protocolId("base");function baseRow(transcript){if(transcript.unavailable!==null||!transcript.base||transcript.base.count===0)return;let row={source:"file",first:0,count:transcript.base.count,idFingerprint:transcript.base.idFingerprint};return JSON.stringify(row)}async function*transcriptComponents(store,transcript,producers,valid){let hold=transcript.tail.hold(transcript.count,transcript.base?.count??0);try{yield*heldComponents(store,transcript,hold,producers,valid)}finally{hold.release()}}async function*heldComponents(store,transcript,hold,producers,valid){let descriptor={historyVersion:transcript.historyVersion,leafId:transcript.leafId,count:transcript.count,base:transcript.base&&{count:transcript.base.count,idFingerprint:transcript.base.idFingerprint},persisted:hold.persistence?.count??null,unavailable:transcript.unavailable};if(yield*textComponent(store,TRANSCRIPT,TRANSCRIPT,JSON.stringify(descriptor)),transcript.unavailable!==null)return;let base=baseRow(transcript);base!==void 0&&(yield*textComponent(store,TRANSCRIPT,BASE,base));let opaque=0;for(let{index,id,kind,parentId}of transcript.accepted){valid();let tail=hold.has(index),family=entryFamily(kind),line=JSON.stringify({index,id,source:tail?"tail":"file",parentId,kind,family});yield*textComponent(store,TRANSCRIPT,memberId("entry",index),line),family==="opaque"&&(opaque+=1,yield*tail?writtenComponent(store,OPAQUE,memberId("entry",index),async writer=>{for await(let chunk of hold.chunks(index,valid))writer.push(chunk)}):textComponent(store,OPAQUE,memberId("entry",index),line))}base!==void 0?yield*textComponent(store,OPAQUE,BASE,base):opaque===0&&producers.opaque==="complete"&&(yield{kind:OPAQUE,id:OPAQUE,leaves:[],owner:0})}var textComponent=(store,kind,id,text)=>writtenComponent(store,kind,id,writer=>writer.push(text));var SETTLED=familyId("settled"),IDENTITY=familyId("identity"),settledMember=terminalSequence=>memberId("message",terminalSequence),joinMember=ordinal=>memberId("join",ordinal);function terminalSteps(settled,row,valid){let{kind:_kind,payload:payload2,call,...fields}=row;return objectSteps([...literalFields(fields),["payload",storedSteps(settled.store,payload2)],["call",walkedSteps(settled.values,call,valid)]])}async function*settledComponents(reader,settled){let count=0;for await(let member of settled.members(reader.valid)){if(member.kind!=="terminal")continue;let steps=terminalSteps(settled,member.row,reader.valid);yield*stepsComponent(reader.store,SETTLED,settledMember(member.row.terminalSequence),steps),count+=1}count===0&&(yield emptyComponent("settled"))}async function*identityComponents(reader,root,settled){let{sessionEpoch,sequence,activeMessageId,turnId,correlation,refusedCorrelations}=root,identity={sessionEpoch,sequence,activeMessageId,turnId,correlation,refusedCorrelations};yield*textComponent(reader.store,IDENTITY,IDENTITY,JSON.stringify(identity));for await(let member of settled.members(reader.valid)){if(member.kind!=="owner")continue;let join7=JSON.stringify({messageId:member.messageId,entryId:member.entryId});yield*textComponent(reader.store,IDENTITY,joinMember(member.ordinal),join7)}}var SOURCE=familyId("source"),BASE2=protocolId("base");async function*sourceComponents(reader,transcript,producers,settled){let count=0,accepted=transcript.unavailable===null?transcript.accepted:[],hold=transcript.tail.hold(transcript.count,transcript.base?.count??0);try{for(let{index,id,kind,parentId}of accepted){if(reader.valid(),entryFamily(kind)!=="source")continue;let head={index,id,parentId,kind,messageId:await settled.messageOf(id)},steps=objectSteps([...literalFields(head),["entry",hold.has(index)?rawSteps2(hold.chunks(index,reader.valid)):literalSteps(null)]]);yield*stepsComponent(reader.store,SOURCE,memberId("entry",index),steps),count+=1}}finally{hold.release()}let base=baseRow(transcript);base!==void 0?yield*textComponent(reader.store,SOURCE,BASE2,base):count===0&&producers.source==="complete"&&(yield emptyComponent("source"))}async function*rawSteps2(chunks2){let previous;for await(let chunk of chunks2)previous!==void 0&&(yield{kind:"raw",text:previous,more:!0}),previous=chunk;yield{kind:"raw",text:previous??"",more:!1}}var FAMILIES=protocolId("families"),RUN=familyId("run"),LIFECYCLE=familyId("lifecycle"),DIALOGS=familyId("dialogs");async function*checkpointComponents(cut,valid){let{store,values,root,settled}=cut,current=root.current;if(!current)throw new CompactReadError("unavailable");let reader={store,values,valid},producers=familyProducers(root.transcript,root.refusedCorrelations),registry=familyRegistry(producers);yield*textComponent(store,FAMILIES,FAMILIES,JSON.stringify(registry));let family=name=>{switch(name){case"transcript":return transcriptComponents(store,root.transcript,producers,valid);case"opaque":return none();case"run":{let{runState,dialogCounts}=current.components;return textComponent(store,RUN,RUN,JSON.stringify({runState,dialogCounts}))}case"lifecycle":{let ref=current.components.lifecycle;return ref?stepsComponent(store,LIFECYCLE,LIFECYCLE,values.walk(ref,valid)):one(name)}case"dialogs":return dialogComponents(reader,current.components.dialogs);case"active":return activeComponents(reader,current.active);case"calls":return callsComponents(reader,current.calls);case"settled":return settledComponents(reader,settled);case"identity":return identityComponents(reader,root,settled);case"source":return sourceComponents(reader,root.transcript,producers,settled);default:return assertNever3(name)}},emitted=new Set;for(let name of CATALOG_FAMILIES)for await(let component of family(name))emitted.add(component.kind),yield component;assertCoverage(registry,emitted)}async function*dialogComponents(reader,ref){let dialogs=new CompactComponentRoots(reader.store,()=>[]),count=0;for await(let[order,value]of dialogs.rows(ref,reader.valid)){let steps=reader.values.walk(value,reader.valid);yield*stepsComponent(reader.store,DIALOGS,memberId("dialog",Number(order)),steps),count+=1}count===0&&(yield emptyComponent("dialogs"))}async function*none(){}async function*one(family){yield emptyComponent(family)}function assertNever3(family){throw new Error(`unmapped catalog family: ${JSON.stringify(family)}`)}import{createHash as createHash2}from"node:crypto";import{open as open5}from"node:fs/promises";var DEFAULT_TRANSCRIPT_TAIL_BYTES=256*1024*1024,TRANSCRIPT_TAIL_RESIDENT_BYTES=32*1024*1024,TAIL_KIND=protocolId("transcript-tail"),TailBudget=class{constructor(max=DEFAULT_TRANSCRIPT_TAIL_BYTES){this.held=0,this.max=max}};function stageTailEntry(staging,budget,index,text){let bytes=text.length*2;if(!(budget.held+staging.stagedBytes+bytes>budget.max)&&!(staging.residentBytes+bytes>TRANSCRIPT_TAIL_RESIDENT_BYTES))try{return staging.stage(TAIL_KIND,protocolId(`entry-${index}`),text)}catch(cause){if(cause instanceof TransferStagingError)return;throw cause}}function stageBootstrap(staging,transitions){let staged=new Map,index=0;try{for(let transition of transitions){if(transition.kind==="replace"&&(index=0),transition.kind!=="append")continue;let text=transition.entry,content=text===void 0?null:stageTailEntry(staging,new TailBudget,index,text);if(index+=1,content===void 0)throw new TransferStagingError("staging_over_byte_limit");content&&staged.set(transition,content)}return staged}catch(cause){for(let content of staged.values())staging.release(content);if(cause instanceof TransferStagingError)return;throw cause}}var TranscriptTail=class{#staging;#budget;#cuts;#superseded;constructor(staging,persistence,budget=new TailBudget){this.entries=new Map,this.kept=new Map,this.retainedBytes=0,this.#cuts=new Map,this.#superseded=!1,this.#staging=staging,this.persistence=persistence,this.#budget=budget}stage(index,text){return stageTailEntry(this.#staging,this.#budget,index,text)}adopt(index,content){this.#staging.adopt(content),this.entries.set(index,content),this.retainedBytes+=content.ref.entry.length,this.#budget.held+=content.ref.entry.length}retainCut(count){this.#cuts.set(count,(this.#cuts.get(count)??0)+1)}supersede(){if(this.#superseded=!0,this.#cuts.size===0)return this.releaseAll();for(let content of this.entries.values())this.#staging.spill(content)}releaseCut(count){let left=(this.#cuts.get(count)??0)-1;if(left>0?this.#cuts.set(count,left):this.#cuts.delete(count),this.#superseded&&this.#cuts.size===0)return this.releaseAll();let reach=this.reach();for(let[index,content]of this.kept)index<reach||(this.kept.delete(index),this.free(content))}persisted(persistence,baseCount){this.persistence=persistence;let reach=this.reach();for(let[index,content]of this.entries){if(index+baseCount>=persistence.count)break;if(this.entries.delete(index),this.retainedBytes-=content.ref.entry.length,index>=reach){this.free(content);continue}this.kept.set(index,content),this.#staging.spill(content)}}releaseAll(){for(let content of[...this.entries.values(),...this.kept.values()])this.free(content);this.entries.clear(),this.kept.clear(),this.retainedBytes=0}hold(count,baseCount){let staging=this.#staging,own=index=>this.entries.get(index)??this.kept.get(index),fileCount=Math.min(count,Math.max(0,(this.persistence?.count??0)-baseCount));for(;fileCount>0&&own(fileCount-1);)fileCount-=1;let held=new Map;for(let index=fileCount;index<count;index++){let content=own(index);content&&held.set(index,content)}for(let content of held.values())staging.pin(content,1);let released=!1;return{fileCount,persistence:this.persistence,has:index=>held.has(index),chunks:(index,valid)=>{let content=held.get(index);if(!content)throw new RangeError(`transcript tail entry ${index} is not held`);return staging.chunks(content,valid)},release:()=>{if(!released){released=!0;for(let content of held.values())staging.pin(content,-1)}}}}free(content){this.#budget.held-=content.ref.entry.length,this.#staging.release(content)}reach(){let reach=0;for(let count of this.#cuts.keys())reach=Math.max(reach,count);return reach}};var DEFAULT_TRANSCRIPT_ANCESTRY_BYTES=8*1024*1024,ANCESTRY_RECORD_BYTES=40,KIND_NAME_BYTES=64,stringBytes=value=>value===""?0:Math.ceil((16+(Buffer.byteLength(value)===value.length?value.length:2*value.length))/8)*8,AcceptedEntries=class{constructor(ids,kinds,parents,count){this.ids=ids,this.kinds=kinds,this.parents=parents,this.count=count}idsBefore(end){return this.ids.slice(0,Math.min(end,this.count))}*[Symbol.iterator](){for(let index=0;index<this.count;index++)yield{index,id:this.ids[index],kind:this.kinds[index],parentId:this.parents[index]}}},AcceptedTranscript=class{constructor(staging){this.version=0,this.leafId=null,this.base=null,this.entryIds=[],this.kinds=[],this.parents=[],this.kindNames=new Map,this.ancestryBytes=0,this.budget=new TailBudget,this.unavailable=null,this.staging=staging,this.tail=new TranscriptTail(staging,null,this.budget)}get historyVersion(){return this.version}get available(){return this.unavailable===null}bootstrap(transitions){let staged=stageBootstrap(this.staging,transitions);if(!staged)return this.markUnavailable("transcript_tail_over_byte_limit");try{for(let transition of transitions)this.apply(transition,staged.get(transition))}finally{for(let content of staged.values())this.staging.abandon(content)}}apply(transition,staged){if(this.version+=1,transition.kind==="replace"){this.tail.supersede(),this.base=transition.base,this.entryIds=[],this.kinds=[],this.parents=[],this.kindNames=new Map,this.ancestryBytes=0,this.tail=new TranscriptTail(this.staging,transition.base,this.budget),this.unavailable=null,this.missingFrom=void 0;return}if(transition.kind==="unavailable"){this.markUnavailable(transition.reason);return}if(transition.kind==="persisted"){this.persisted(transition.persistence);return}if(!(this.unavailable!==null&&this.missingFrom===void 0))if(transition.kind==="append"){let index=this.entryIds.length;if(!this.retainAncestry(transition.id,transition.type,transition.parentId))return;transition.persistence&&this.persisted(transition.persistence);let unpersisted=index+(this.base?.count??0)>=(this.tail.persistence?.count??0);if(this.missingFrom===void 0&&unpersisted&&transition.entry!==void 0){let content=staged??this.tail.stage(index,transition.entry);content?this.tail.adopt(index,content):this.markUnavailable("transcript_tail_over_byte_limit",index)}this.leafId=transition.id}else this.leafId=transition.leafId}retainAncestry(id,type,parentId){let previous=this.entryIds.at(-1),shared=previous!==void 0&&previous===parentId,kind=this.kindNames.get(type),bytes=ANCESTRY_RECORD_BYTES+stringBytes(id)+(kind===void 0?KIND_NAME_BYTES+stringBytes(type):0)+(shared?0:stringBytes(parentId??""));return this.ancestryBytes+bytes>DEFAULT_TRANSCRIPT_ANCESTRY_BYTES?(this.markUnavailable("transcript_ancestry_over_byte_limit"),!1):(kind===void 0&&this.kindNames.set(type,type),this.entryIds.push(id),this.kinds.push(kind??type),this.parents.push(shared?previous:parentId),this.ancestryBytes+=bytes,!0)}markUnavailable(reason,missingFrom){this.missingFrom=this.unavailable===null?missingFrom:void 0,this.unavailable??=reason,process.stderr.write(`senpi rpc acceptance: transcript component unavailable: ${reason}
|
|
9
9
|
`)}freeze(){return Object.freeze({historyVersion:this.version,leafId:this.leafId,base:this.base,accepted:new AcceptedEntries(this.entryIds,this.kinds,this.parents,this.entryIds.length),ancestryBytes:this.ancestryBytes,tail:this.tail,count:this.entryIds.length,unavailable:this.unavailable})}persisted(persistence){this.tail.persisted(persistence,this.base?.count??0),this.missingFrom!==void 0&&persistence.count-(this.base?.count??0)>=this.entryIds.length&&(this.missingFrom=void 0,this.unavailable=null)}release(){this.tail.releaseAll()}};var ANCHOR_BYTES=20,CLOSING_BYTES=8,FNV_OFFSET=2166136261,FNV_PRIME=16777619,BASE_ROW_TABLE_BYTES=DEFAULT_TRANSCRIPT_ANCESTRY_BYTES;function fnv1a(hash,bytes){let next=hash;for(let index=0;index<bytes.length;index++)next=Math.imul(next^(bytes[index]??0),FNV_PRIME)>>>0;return next}var BaseRowTable=class{constructor(count,budget=BASE_ROW_TABLE_BYTES){this.fileEnd=0;let fits=Math.floor((budget-CLOSING_BYTES)/ANCHOR_BYTES);if(!Number.isSafeInteger(fits)||fits<1)throw new RangeError(`base row table budget too small: ${budget}`);this.count=count,this.rowsPerAnchor=Math.max(1,Math.ceil(count/fits)),this.anchors=Math.ceil(count/this.rowsPerAnchor),this.starts=new Float64Array(this.anchors+1),this.fileStarts=new Float64Array(this.anchors),this.hashes=new Uint32Array(this.anchors)}get tableBytes(){return this.starts.byteLength+this.fileStarts.byteLength+this.hashes.byteLength}get length(){return this.starts[this.anchors]??0}walk(offset,mode){let table=this,k=this.rowsPerAnchor,group=mode==="record"?0:startAtOrBefore(this.starts,this.anchors,offset),hash=FNV_OFFSET,mismatch=()=>new CompactReadError("base_fingerprint_mismatch");return{row:group*k,at:this.starts[group]??0,fileStart:this.fileStarts[group]??0,add(line,row){if(this.row%k===0){if(mode==="record")table.fileStarts[group]=line.start,table.starts[group]=this.at;else if(line.start!==table.fileStarts[group])throw mismatch();hash=FNV_OFFSET}if(hash=fnv1a(hash,row),Object.assign(this,{row:this.row+1,at:this.at+row.length}),mode==="record"&&(table.fileEnd=line.end),this.row%k!==0&&this.row!==table.count)return!1;if(mode==="record")table.hashes[group]=hash,table.starts[group+1]=this.at;else if(hash!==table.hashes[group]||this.at!==table.starts[group+1])throw mismatch();return group+=1,!0}}}};var READ_BYTES=64*1024,NEWLINE=10;function baseStream(transcript,catalogRoot,ref){let base=transcript.base;if(ref!==baseRef(catalogRoot)||transcript.unavailable!==null||base===null||base.count===0)throw new CompactReadError("range");return base}async function openIdentified(base,end){let handle;try{handle=await open5(base.fileIdentity.path,"r")}catch(cause){throw cause instanceof Error?new CompactReadError("base_file_missing"):cause}try{let stat=await handle.stat({bigint:!0});if(String(stat.dev)!==base.fileIdentity.dev||String(stat.ino)!==base.fileIdentity.ino)throw new CompactReadError("base_file_replaced");if(end!==void 0&&stat.size<BigInt(end))throw new CompactReadError("base_file_truncated");return handle}catch(cause){throw await handle.close(),cause}}async function*lines(handle,from,check){let buffer=Buffer.allocUnsafe(READ_BYTES),carried=[],start=from,position=from;for(;;){let{bytesRead}=await handle.read(buffer,0,READ_BYTES,position);if(check(),bytesRead===0)break;let chunk=buffer.subarray(0,bytesRead),at=0;for(let newline=chunk.indexOf(NEWLINE);newline!==-1;newline=chunk.indexOf(NEWLINE,at)){let end=position+newline;yield{start,end,text:Buffer.concat([...carried,chunk.subarray(at,newline)]).toString("utf8")},carried=[],at=newline+1,start=end+1}at<bytesRead&&carried.push(Buffer.from(chunk.subarray(at))),position+=bytesRead}carried.length>0&&(yield{start,end:position,text:Buffer.concat(carried).toString("utf8")})}var field=(entry,key)=>typeof entry=="object"&&entry!==null?Reflect.get(entry,key):void 0;function stampedRow(index,entry){let kind=String(field(entry,"type")),parentId=field(entry,"parentId");return storedBytes(`${JSON.stringify({index,id:String(field(entry,"id")),source:"file",parentId:typeof parentId=="string"?parentId:null,kind,family:entryFamily(kind)})}
|
|
10
10
|
`)}var FrozenBaseBytes=class{constructor(base,digest2,rows){this.peakResidentLeaves=0,this.peakRangeRows=0,this.resident=0,this.base=base,this.digest=digest2,this.rows=rows,this.length=rows.length}get rowsPerAnchor(){return this.rows.rowsPerAnchor}get tableBytes(){return this.rows.tableBytes}async range(offset,length,valid){assertRange(offset,length,this.length);let out=Buffer.allocUnsafe(length),end=offset+length,handle=await openIdentified(this.base,this.rows.fileEnd);try{let walk2=this.rows.walk(offset,"verify"),rows=0;for await(let line of lines(handle,walk2.fileStart,()=>valid?.())){let entry=parseSessionEntryLine(line.text);if(entry){this.peakResidentLeaves=Math.max(this.peakResidentLeaves,++this.resident);try{let from=walk2.at,row=stampedRow(walk2.row,entry),closed=walk2.add(line,row),first=Math.max(offset,from),last=Math.min(end,from+row.length);if(last>first&&row.copy(out,first-offset,first-from,last-from),this.peakRangeRows=Math.max(this.peakRangeRows,++rows),closed&&walk2.at>=end)return out}finally{this.resident-=1}}}throw new CompactReadError("base_file_truncated")}finally{await handle.close()}}};async function openBaseBytes(base,valid,signal,budget=BASE_ROW_TABLE_BYTES){let check=()=>{if(signal?.aborted)throw new CompactReadError("aborted");valid()},handle=await openIdentified(base);try{let rows=new BaseRowTable(base.count,budget),walk2=rows.walk(0,"record"),fingerprint=createHash2("sha256"),content=new BaseContentHash;for await(let line of lines(handle,0,check)){let entry=parseSessionEntryLine(line.text);if(entry&&(fingerprint.update(fingerprintLine(entry)),content.line(line.text),walk2.add(line,stampedRow(walk2.row,entry)),walk2.row===base.count))break}if(walk2.row<base.count)throw new CompactReadError("base_file_truncated");let digest2=parseContentDigest(fingerprint.digest("hex"));if(!digest2.ok||digest2.value!==base.idFingerprint||content.digest()!==base.contentFingerprint)throw new CompactReadError("base_fingerprint_mismatch");return new FrozenBaseBytes(base,digest2.value,rows)}finally{await handle.close()}}var openLeaf=height=>({tokens:[],units:`{"h":${height},"v":[]}`.length}),headToken=head=>`{"s":${head.side},"d":"${head.digest}"}`,CatalogPointerWriter=class{constructor(create){this.open=[],this.create=create}node(node,head){this.push(0,`{"n":${node},"s":${head.side},"d":"${head.digest}"}`)}component(leaves){this.push(0,`{"c":${leaves.length}}`);for(let leaf2 of leaves)this.push(0,String(leaf2))}finish(){this.level(0);for(let height=0;;height++){if(height===this.open.length-1)return this.seal(height);this.push(height+1,headToken(this.seal(height)))}}level(height){return this.open[height]??(this.open[height]=openLeaf(height))}push(height,token){let open6=this.level(height),units=open6.units+token.length+ +(open6.tokens.length>0);if(units>COMPACT_LEAF_CODE_UNITS)return this.push(height+1,headToken(this.seal(height))),this.push(height,token);open6.tokens.push(token),open6.units=units}seal(height){let text=`{"h":${height},"v":[${this.level(height).tokens.join(",")}]}`;return this.open[height]=openLeaf(height),{side:this.create(text),digest:catalogDigest("pointer",storedBytes(text))}}},Id=external_exports.number().int().positive(),SideLeafSchema=external_exports.object({h:external_exports.number().int().nonnegative(),v:external_exports.array(external_exports.unknown())}).strict(),DataSchema=external_exports.array(external_exports.union([Id,external_exports.object({c:external_exports.number().int().nonnegative()}).strict(),external_exports.object({n:Id,s:Id,d:external_exports.string()}).strict()])),IndexSchema=external_exports.array(external_exports.object({s:Id,d:external_exports.string()}).strict()).min(1),corrupt=()=>new CompactReadError("integrity");function digest(raw){let parsed=parseContentDigest(raw);if(!parsed.ok)throw corrupt();return parsed.value}function decode(schema,value){let parsed=schema.safeParse(value);if(!parsed.success)throw corrupt();return parsed.data}async function*tokens(read,head,height){let text=await read(head.side);if(catalogDigest("pointer",storedBytes(text))!==head.digest)throw corrupt();let json;try{json=JSON.parse(text)}catch(cause){throw cause instanceof SyntaxError?corrupt():cause}let leaf2=decode(SideLeafSchema,json);if(height!==void 0&&leaf2.h!==height)throw corrupt();if(leaf2.h===0){yield*decode(DataSchema,leaf2.v);return}for(let below of decode(IndexSchema,leaf2.v))yield*tokens(read,{side:below.s,digest:digest(below.d)},leaf2.h-1)}async function catalogPointer(read,head,step){let child=0,skip=0,wanted=0,leaves;for await(let token of tokens(read,head)){if(leaves||skip>0){if(typeof token!="number")throw corrupt();if(!leaves)skip--;else if(leaves.push(token)===wanted)return{kind:"component",leaves};continue}if(typeof token=="number")throw corrupt();let here=child++;if("n"in token){if(here===step)return{kind:"node",node:token.n,head:{side:token.s,digest:digest(token.d)}}}else if(here!==step)skip=token.c;else{if(token.c===0)return{kind:"component",leaves:[]};leaves=[],wanted=token.c}}if(leaves||skip>0)throw corrupt()}function componentBytes(read){if(read.kind!=="component")throw new CompactReadError("range");return read.bytes}var NODE=protocolId("node"),CompactRecoveryCatalog=class{constructor(){this.buffered=0,this.peakBuffered=0}async build(store,ref,components,valid=()=>{}){let held=new Set,transfer=id=>{store.adjust(id,-1,0),held.delete(id)},newLevel=()=>{let sides=[],pointers=new CatalogPointerWriter(text=>{let side=store.createLeaf(text,!0);return held.add(side),sides.push(side),side});return{writer:new CatalogNodeWriter,pointers,sides,owners:[]}},levels=[],at=level=>levels[level]??(levels[level]=newLevel()),count=0,nodes=0,seal=level=>{let sealed=at(level),text=sealed.writer.encode(),node=store.createLeaf(text,!0);held.add(node);let head=sealed.pointers.finish(),owner=store.text.own([node,...sealed.sides,...sealed.owners]);held.add(owner);for(let taken of[node,...sealed.sides,...sealed.owners])transfer(taken);levels[level]=newLevel(),this.buffered-=sealed.writer.count;let bytes=storedBytes(text),id=protocolId(`node-${String(++nodes).padStart(16,"0")}`);return{entry:{kind:NODE,id,length:bytes.length,digest:catalogDigest("node",bytes)},node,head,owner}},place=(level,entry,child,owner)=>{if(!at(level).writer.push(entry)){let sealed=seal(level);if(place(level+1,sealed.entry,sealed,sealed.owner),!at(level).writer.push(entry))throw new CompactReadError("size_limit")}this.peakBuffered=Math.max(this.peakBuffered,++this.buffered);let open6=at(level);level===0&&owner!==0&&(store.adjust(owner,1,0),held.add(owner)),open6.owners.push(owner),"leaves"in child?open6.pointers.component(child.leaves):open6.pointers.node(child.node,child.head)};try{for await(let component of components)place(0,await this.describe(store,component,valid),component,component.owner),count+=1;for(let level=0;;level++){at(level);let top=level===levels.length-1,sealed=seal(level);if(!top){place(level+1,sealed.entry,sealed,sealed.owner);continue}let root=await this.root(store,ref,sealed,level+1,count,nodes);return held.delete(root.owner),root}}catch(cause){for(let{writer}of levels)this.buffered-=writer.count;for(let id of held)store.adjust(id,-1,0);throw cause}}async read(store,root,ref,valid=()=>{},signal){if(ref!==root.ref&&!ref.startsWith(`${root.ref}:`))throw new CompactReadError("range");let steps=refSteps(ref),node=root.node,head={side:root.side,digest:root.sideDigest},expected=root,here=root.ref;for(let depth=0;;depth++){let text=depth===0?await store.readLeaf(node):await this.stored(store,node);if(catalogDigest(depth===0?"root":"node",storedBytes(text))!==expected.digest)throw new CompactReadError("integrity");let decoded=decodeCatalogNode(text);if(!decoded.ok)throw new CompactReadError("integrity");let step=steps[depth];if(step===void 0)return{kind:"node",ref:here,entries:decoded.entries,digest:expected.digest,length:expected.length};let entry=decoded.entries[step];if(!entry)throw new CompactReadError("range");let pointer=await catalogPointer(side=>this.stored(store,side),head,step);if(!pointer)throw new CompactReadError("integrity");if(here=childRef(here,step),pointer.kind==="component"){if(depth+1!==steps.length)throw new CompactReadError("range");let bytes=await openFrozenBytes(entry,pointer.leaves,leaf2=>this.stored(store,leaf2),valid,signal);return{kind:"component",ref:here,entry,bytes}}node=pointer.node,head=pointer.head,expected=entry}}release(store,root){store.adjust(root.owner,-1,0)}async stored(store,id){try{return await store.readLeaf(id)}catch(cause){throw cause instanceof CompactReadError&&cause.reason==="ownership"?new CompactReadError("integrity"):cause}}async describe(store,component,valid){let length=component.leaves.reduce((sum,leaf2)=>sum+store.leafUnits(leaf2)*2,0),digester=catalogDigester("leaf",length);for(let leaf2 of component.leaves)digester.update(storedBytes(await store.readLeaf(leaf2))),valid();return{kind:component.kind,id:component.id,length,digest:digester.finish()}}async root(store,ref,{node,head,owner},depth,components,nodes){let bytes=storedBytes(await store.readLeaf(node)),digest2=catalogDigest("root",bytes);return{ref,node,side:head.side,sideDigest:head.digest,owner,digest:digest2,length:bytes.length,depth,components,nodes}}};var TEXT_FIELDS=["socketEpoch","admissionId","session","sessionEpoch","token","leaf","activeMessage","turn"];var FrozenRootPinnedError=class extends Error{constructor(tokenId,holder){super(`frozen root already pinned by token ${holder}; token ${tokenId} cannot pin it`),this.name="FrozenRootPinnedError",this.tokenId=tokenId,this.holder=holder}},VerifiedComponents=class{constructor(){this.roots=new Map,this.pinned=new Map}get size(){let size=0;for(let{components}of this.roots.values())size+=components.size;return size}pin(tokenId,root){let held=this.roots.get(root);if(held){if(held.token!==tokenId)throw new FrozenRootPinnedError(tokenId,held.token);return}this.roots.set(root,{token:tokenId,components:new Map}),this.pinned.set(tokenId,root)}get(root,ref){return this.roots.get(root)?.components.get(ref)}set(tokenId,root,ref,bytes){let held=this.roots.get(root);if(held){if(held.token!==tokenId)throw new FrozenRootPinnedError(tokenId,held.token);held.components.set(ref,bytes)}}drop(tokenId){let root=this.pinned.get(tokenId);root&&(this.pinned.delete(tokenId),this.roots.delete(root))}};async function manifestPage(manifest,offset){if(offset!==0)throw new CompactReadError("range");let bytes=Buffer.from(JSON.stringify(await manifest),"utf16le");if(bytes.length>65536)throw new CompactReadError("size_limit");return{offset:0,length:bytes.length,bytes,digest:catalogDigest("fragment",bytes),next:null,complete:!0}}var MANIFEST=protocolId("manifest"),chunks=value=>{let parts=[];for(let start=0;start<value.length;start+=COMPACT_LEAF_CODE_UNITS)parts.push(value.slice(start,start+COMPACT_LEAF_CODE_UNITS));return parts},RecoveryManifests=class{constructor(){this.catalogs=new CompactRecoveryCatalog,this.building=new Map,this.ready=new Map,this.verified=new VerifiedComponents,this.counter=0}manifest(token,lane,root,valid){let pending=this.building.get(token.id);return pending||(pending=this.build(token,lane,root,valid),this.building.set(token.id,pending),pending.then(built=>this.ready.set(token.id,built),()=>this.building.delete(token.id))),pending.then(built=>built.manifest)}read(tokenId,lane,root,ref){let parsed=parseContentRef(ref),built=this.ready.get(tokenId);if(!parsed.ok||!built)throw new CompactReadError("range");return lane.cutStorage(root,(store,valid)=>this.catalogs.read(store,built.root,parsed.value,valid))}get verifiedComponents(){return this.verified.size}pin(tokenId,root){this.verified.pin(tokenId,root)}page(token,lane,root,ref,offset,signal){if(ref==="manifest")return manifestPage(this.manifest(token,lane,root,()=>{}),offset);let tokenId=token.id,target=parsePageRef(ref),built=this.ready.get(tokenId);if(!target.ok||!built)throw new CompactReadError("range");return lane.cutStorage(root,async(store,valid)=>{store.health.needsRecovery&&await store.repair();let bytes=this.verified.get(root,target.value.ref);return bytes||(bytes=target.value.kind==="base"?await openBaseBytes(baseStream(root.transcript,built.manifest.catalogRoot,target.value.ref),valid,signal):componentBytes(await this.catalogs.read(store,built.root,target.value.ref,valid,signal)),this.ready.get(tokenId)===built&&this.verified.set(tokenId,root,target.value.ref,bytes)),producePage(bytes,offset,valid)})}release(tokenId){let built=this.ready.get(tokenId);this.ready.delete(tokenId),this.building.delete(tokenId),this.verified.drop(tokenId),built&&this.catalogs.release(built.store,built.root)}build(token,lane,root,valid){let ref=catalogRootRef(++this.counter),strings={socketEpoch:token.admission.socketEpoch,admissionId:token.admission.admissionId,session:token.admission.sessionId,sessionEpoch:token.admission.sessionEpoch,token:token.id,leaf:token.cut.leafId,activeMessage:token.cut.activeMessageId,turn:token.cut.turnId};return lane.cutStorage(root,async(store,cutValid)=>{let texts=new Map,oversized=[],owned=[];for(let field4 of TEXT_FIELDS){let value=strings[field4];if(value===null){texts.set(field4,null);continue}let bounded=parseBoundedId(value);if(bounded.ok){texts.set(field4,{id:bounded.value});continue}let leaves=chunks(value).map(chunk=>store.createLeaf(chunk));owned.push(...leaves);let component={kind:MANIFEST,id:protocolId(field4),leaves,owner:store.text.own(leaves)};oversized.push({field:field4,component})}try{let check=()=>{cutValid(),valid()},cut={store,values:new CompactValues(store),root,settled:lane.settledOf(root)},components=async function*(){yield*oversized.map(({component})=>component),yield*checkpointComponents(cut,check)},built=await this.catalogs.build(store,ref,components(),check);return await this.assemble(store,token,ref,built,oversized,texts)}finally{for(let{component}of oversized)store.adjust(component.owner,-1,0);for(let leaf2 of owned)store.adjust(leaf2,-1,0)}})}async assemble(store,token,ref,built,oversized,texts){try{let leftmost=ref;for(let level=1;level<built.depth;level++)leftmost=childRef(leftmost,0);let node=oversized.length?await this.catalogs.read(store,built,leftmost):void 0;for(let[index,{field:field4,component}]of oversized.entries()){let entry=node?.kind==="node"?node.entries[index]:void 0;if(!entry||entry.kind!==component.kind||entry.id!==component.id)throw new CompactReadError("ownership");texts.set(field4,{ref:childRef(leftmost,index),length:entry.length,digest:entry.digest})}let text=field4=>{let value=texts.get(field4);if(value===void 0)throw new CompactReadError("ownership");return value},required=field4=>text(field4)??raise();return{manifest:{format:"senpi-recovery-manifest",version:1,socketEpoch:required("socketEpoch"),admissionId:required("admissionId"),routeKind:token.admission.routeKind,session:required("session"),sessionEpoch:required("sessionEpoch"),generation:token.admission.generation,sequence:token.cut.sequence,historyVersion:token.cut.historyVersion,token:required("token"),leaf:text("leaf"),activeMessage:text("activeMessage"),turn:text("turn"),checkpointDigest:built.digest,catalogRoot:ref,catalogRootLength:built.length},root:built,store}}catch(cause){throw this.catalogs.release(store,built),cause}}};function raise(){throw new CompactReadError("ownership")}var keyOf=({socketEpoch,sessionId})=>`${socketEpoch}\0${sessionId}`,RecoveryStreams=class{constructor(){this.streams=new Map,this.routed=new Map}get size(){return this.streams.size}get(caller){return this.streams.get(keyOf(caller))}join(route){let stream=this.streams.get(keyOf(route));stream&&this.addRoute(stream,route.admissionId)}routes(socketEpoch,admissionId){return this.routed.get(socketEpoch)?.has(admissionId)===!0}describe(caller){let stream=this.get(caller);if(!stream)return;let{sessionEpoch,generation}=stream;return{sessionEpoch,generation,routes:[...stream.routes]}}next(route,sessionEpoch,tokenId,generation){let key=keyOf(route),existing=this.streams.get(key);existing&&existing.sessionEpoch!==sessionEpoch&&this.drop(key,existing);let stream=existing?.sessionEpoch===sessionEpoch?existing:{socketEpoch:route.socketEpoch,sessionId:route.sessionId,sessionEpoch,generation,routes:new Set,current:void 0};this.streams.set(key,stream),stream.generation=generation,this.addRoute(stream,route.admissionId);let retired=existing?.current;return stream.current=tokenId,retired===void 0?{}:{retired}}forgetPeer(socketEpoch){for(let[key,stream]of this.streams)stream.socketEpoch===socketEpoch&&this.drop(key,stream)}forgetSession(sessionId){for(let[key,stream]of this.streams)stream.sessionId===sessionId&&this.drop(key,stream)}retireRoute(caller,admissionId){let stream=this.streams.get(keyOf(caller));stream&&this.removeRoute(stream,admissionId)}addRoute(stream,admissionId){if(stream.routes.has(admissionId))return;stream.routes.add(admissionId);let routed=this.routed.get(stream.socketEpoch)??new Map;routed.set(admissionId,(routed.get(admissionId)??0)+1),this.routed.set(stream.socketEpoch,routed)}removeRoute(stream,admissionId){if(!stream.routes.delete(admissionId))return;let routed=this.routed.get(stream.socketEpoch),remaining=(routed?.get(admissionId)??1)-1;remaining>0?routed?.set(admissionId,remaining):routed?.delete(admissionId),routed?.size===0&&this.routed.delete(stream.socketEpoch)}drop(key,stream){for(let admissionId of[...stream.routes])this.removeRoute(stream,admissionId);this.streams.delete(key)}};function retiredTokenFailure(stream,admission){return stream?stream.sessionEpoch!==admission.sessionEpoch?{kind:"repair_needed",reason:"stale_epoch"}:stream.generation!==admission.generation?{kind:"repair_needed",reason:"superseded_token",newerGeneration:stream.generation}:{kind:"repair_needed",reason:"unknown_token"}:{kind:"repair_needed",reason:"unknown_token"}}function tokenStaleness(stream,token,lane){if(!stream&&lane.retirement==="close")return{kind:"repair_needed",reason:"session_closed"};if(lane.retired)return{kind:"repair_needed",reason:"lane_retired"};if(!stream)return{kind:"repair_needed",reason:"peer_gone"};if(lane.sessionEpoch!==token.cut.sessionEpoch||stream.sessionEpoch!==token.admission.sessionEpoch)return{kind:"repair_needed",reason:"stale_epoch"};if(stream.generation!==token.admission.generation)return{kind:"repair_needed",reason:"superseded_token",newerGeneration:stream.generation}}var RecoveryCheckpoints=class{constructor(){this.checkpoints=new Map,this.issued=new WeakMap,this.streams=new RecoveryStreams,this.manifests=new RecoveryManifests,this.refusals=new Map,this.unavailable=new Map,this.ended=new Set,this.minted=0,this.frozen=0,this.reclaimed=0}get open(){return this.checkpoints.size}tokens(){return[...this.checkpoints.values()].map(({token})=>token)}stream(caller){return this.streams.describe(caller)}routesAdmission(socketEpoch,admissionId){return this.streams.routes(socketEpoch,admissionId)}onTokenEnd(listener){this.ended.add(listener)}status(){return{open:this.checkpoints.size,streams:this.streams.size,frozen:this.frozen,reclaimed:this.reclaimed,refused:Object.fromEntries(this.refusals),unavailable:Object.fromEntries(this.unavailable)}}freeze(route,lane,join7=!1){if(lane.retired)return this.refuse(repairNeeded("lane_retired"));let current=join7?this.checkpoints.get(this.streams.get(route)?.current??""):void 0;if(current&&this.check(current.token,route).ok)return this.streams.join(route),recovered(current);let root=lane.freeze();if(root.current===void 0)return lane.release(root),this.refuse(storageUnavailable("compact_state_unavailable"));let generation=lane.generations.next();if(generation===void 0)return lane.release(root),this.refuse(storageUnavailable("unavailable"));let id=`${route.socketEpoch}:${++this.minted}`;this.manifests.pin(id,root);let{retired}=this.streams.next(route,root.sessionEpoch,id,generation),admission=Object.freeze({...route,sessionEpoch:root.sessionEpoch,generation}),token=Object.freeze({kind:"checkpoint",id,admission,cut:Object.freeze({sessionEpoch:root.sessionEpoch,sequence:root.sequence,historyVersion:root.transcript.historyVersion,leafId:root.transcript.leafId,activeMessageId:root.activeMessageId,turnId:root.turnId})}),lease=new CompactReadLease(()=>{this.manifests.release(token.id),lane.release(root),this.checkpoints.delete(token.id);for(let listener of this.ended)listener(token.id)},()=>{let stale=this.staleness(token,lane);if(stale)throw new RecoveryRefusedError(stale)}),checkpoint={token,lane,root,lease,hold:read=>lease.hold(read),retain:()=>({lane,root,hold:read=>read(),end:lease.retain()})};return this.issued.set(token,admission),this.checkpoints.set(token.id,checkpoint),this.frozen+=1,this.reclaim(retired),recovered(checkpoint)}release(token){this.checkpoints.get(token.id)?.lease.release()}forgetPeer(socketEpoch){this.streams.forgetPeer(socketEpoch);for(let{token}of[...this.checkpoints.values()])token.admission.socketEpoch===socketEpoch&&this.reclaim(token.id)}forgetSession(sessionId){this.streams.forgetSession(sessionId)}retireRoute(caller,admissionId,_retirement){let current=this.streams.get(caller)?.current;if(this.streams.retireRoute(caller,admissionId),!((this.streams.get(caller)?.routes.size??0)>0)){this.reclaim(current);for(let{token}of[...this.checkpoints.values()]){let{socketEpoch,sessionId,admissionId:minter}=token.admission;socketEpoch===caller.socketEpoch&&sessionId===caller.sessionId&&minter===admissionId&&this.reclaim(token.id)}}}check(token,caller){let claimed=this.claim(token,caller);return claimed.ok?recovered(token):claimed}transcript(token,caller){let claimed=this.claim(token,caller);if(!claimed.ok)return claimed;let{transcript}=claimed.value.root;return transcript.unavailable===null?recovered(transcript):this.refuse(storageUnavailable(transcript.unavailable))}readSettled(token,caller){return this.read(token,caller,(lane,root)=>lane.readSettled(root))}readCurrent(token,caller){return this.read(token,caller,(lane,root)=>lane.readCurrent(root))}readComponents(token,caller){return this.read(token,caller,(lane,root)=>lane.readCurrentComponents(root))}readActive(token,caller){return this.read(token,caller,(lane,root)=>lane.readCurrentActive(root))}readCalls(token,caller){return this.read(token,caller,(lane,root)=>lane.readCurrentCalls(root))}catalog(token,caller){return this.read(token,caller,(lane,root,lease)=>this.manifests.manifest(token,lane,root,()=>lease.assert()))}readCatalog(token,caller,ref){return this.read(token,caller,(lane,root)=>this.manifests.read(token.id,lane,root,ref))}readCatalogPage(token,caller,ref,offset,signal){return this.read(token,caller,(lane,root)=>this.manifests.page(token,lane,root,ref,offset,signal))}get verifiedComponents(){return this.manifests.verifiedComponents}async read(token,caller,component){let claimed=this.claim(token,caller);if(!claimed.ok)return claimed;let{lease,lane,root}=claimed.value;try{return recovered(await lease.run(()=>component(lane,root,lease)))}catch(cause){return this.refused(token,lane,cause)}}reclaim(id){id!==void 0&&this.checkpoints.get(id)?.lease.release()&&(this.reclaimed+=1)}claim(token,caller){let admission=this.issued.get(token);if(admission?.socketEpoch!==caller.socketEpoch||admission.sessionId!==caller.sessionId)return this.refuse(repairNeeded("unknown_token"));let checkpoint=this.checkpoints.get(token.id);if(!checkpoint)return this.refuse(retiredTokenFailure(this.streams.get(admission),admission));try{checkpoint.lease.assert()}catch(cause){return this.refused(token,checkpoint.lane,cause)}return recovered(checkpoint)}staleness(token,lane){return tokenStaleness(this.streams.get(token.admission),token,lane)}refused(token,lane,cause){let stale=this.staleness(token,lane);if(stale)return this.refuse(stale);if(cause instanceof RecoveryRefusedError)return this.refuse(cause.failure);if(cause instanceof CompactReadError)return this.refuse(cause.reason==="released"?repairNeeded("released"):storageUnavailable(cause.reason));throw cause}refuse(failure){let reason=refusalReason(failure);return this.refusals.set(reason,(this.refusals.get(reason)??0)+1),failure.kind==="storage_unavailable"&&this.unavailable.set(failure.reason,(this.unavailable.get(failure.reason)??0)+1),{ok:!1,failure}}};function snapshotPlaceholderLine(record){if(record.placeholderLine!==void 0)return record.placeholderLine;if(!record.mayCarryMedia)return record.line;let source=JSON.parse(record.line),redacted=omitNormalInlineMedia(source);return record.placeholderLine=redacted===source?record.line:serializeJsonLine(redacted),record.placeholderLine}var LegacyReplayStore=class{constructor(){this.sessionSnapshots=new Map,this.lifecycleSnapshots=new Map,this.pendingQuestions=new Map,this.cursors=0,this.track=onRelease=>(this.cursors+=1,()=>{this.cursors-=1,onRelease()})}get openCursors(){return this.cursors}pendingQuestionCount(sessionId){return this.pendingQuestions.get(sessionId)?.size??0}remember(sessionId,value,line,placeholderLine){let record={line,placeholderLine,hasMessage:value.message!=null,mayCarryMedia:carriesMedia(value)};if(value.type==="session_lifecycle"){this.lifecycleSnapshots.set(sessionId,record);return}if(value.type==="extension_ui_request"&&value.method==="question"&&typeof value.id=="string"){let pending=this.pendingQuestions.get(sessionId)??new Map;pending.set(value.id,{...value}),this.pendingQuestions.set(sessionId,pending);return}if(value.type==="question_resolved"&&typeof value.id=="string"){this.pendingQuestions.get(sessionId)?.delete(value.id);return}if(value.type==="question_updated"&&typeof value.id=="string"){let frame=this.pendingQuestions.get(sessionId)?.get(value.id);frame&&Object.assign(frame,{deadlineAtMs:value.deadlineAtMs,remainingMs:value.remainingMs});return}let event=value.assistantMessageEvent;value.type==="message_start"||value.type==="message_update"&&event?.type==="text_start"?this.sessionSnapshots.set(sessionId,[record]):this.sessionSnapshots.has(sessionId)&&this.sessionSnapshots.get(sessionId)?.push(record),value.type==="message_end"&&this.sessionSnapshots.delete(sessionId)}forget(sessionId){this.pendingQuestions.delete(sessionId),this.sessionSnapshots.delete(sessionId),this.lifecycleSnapshots.delete(sessionId)}freezeAttach(sessionId,view){let lifecycle=this.lifecycleSnapshots.get(sessionId),records=this.sessionSnapshots.get(sessionId)??[],length=records.length,head=lifecycle===void 0?0:1,questions=[...this.pendingQuestions.get(sessionId)?.values()??[]].map(frame=>serializeJsonLine({...frame,remainingMs:typeof frame.deadlineAtMs=="number"?Math.max(0,frame.deadlineAtMs-view.now):0})),variant=record=>view.placeholders?snapshotPlaceholderLine(record):record.line,frames={count:head+length+questions.length,frame:index=>{if(lifecycle!==void 0&&index===0)return serializeJsonLine(observeLifecycleDelivery(JSON.parse(lifecycle.line)));let at=index-head;return at<length?variant(records[at]):questions[at-length]}};return new FrozenFramesCursor(()=>frames,this.track(view.onRelease))}latestMessage(sessionId){let record=this.sessionSnapshots.get(sessionId)?.findLast(record2=>record2.hasMessage),frozen=record===void 0?void 0:JSON.parse(record.line);return typeof frozen=="object"&&frozen!==null&&"message"in frozen?frozen.message:null}};var ResyncCursor=class extends GeneratedFramesCursor{constructor(sessions,source,onRelease){super(sessions.length===0,source,onRelease),this.sessions=sessions}};async function*resyncFrames(entries,messageOf,view){for(let sessionId of entries()){let closed=view.closedNow(sessionId),{message,frames=[]}=closed?{message:null}:await messageOf(sessionId),resync={type:"resync_required",sessionId,reason:view.reason,message,...closed?{closed:!0}:{}};for(let frame of[resync,...frames.map(frame2=>({...frame2,sessionId}))])yield serializeJsonLine(view.placeholders?omitNormalInlineMedia(frame):frame)}}function resyncCut(sessions,entries,messageOf,view,track){return new ResyncCursor(sessions,()=>resyncFrames(entries,messageOf,view),track(view.onRelease))}var admissionOf=ordinal=>`attach-${ordinal}`,SessionRecoveryPins=class{constructor(acceptance,checkpoints,replay,peers,shedMode){this.acceptance=acceptance,this.checkpoints=checkpoints,this.replay=replay,this.peers=peers,this.shedMode=shedMode}pin(id,sessionIds){let socketEpoch=this.peers.socketEpoch(id);return sessionIds.flatMap(sessionId=>{let lane=this.acceptance.get(sessionId),ordinal=this.peers.ordinals(id)?.get(sessionId);if(!lane||socketEpoch===void 0)return[];let admissionId=this.checkpoints.stream({socketEpoch,sessionId})?.routes[0]??(ordinal===void 0?void 0:admissionOf(ordinal));if(admissionId===void 0)return[];let route={socketEpoch,admissionId,routeKind:ordinal===void 0?"mirror":"ordinary",peer:id,sessionId};return[{sessionId,lane,sessionEpoch:lane.sessionEpoch,outcome:this.checkpoints.freeze(route,lane)}]})}unpin(pinned){for(let{outcome}of pinned)outcome.ok&&this.checkpoints.release(outcome.value.token)}retire(id,sessionId){let socketEpoch=this.peers.socketEpoch(id),ordinal=this.peers.ordinals(id)?.get(sessionId);socketEpoch!==void 0&&ordinal!==void 0&&this.checkpoints.retireRoute({socketEpoch,sessionId},admissionOf(ordinal),"client_detach")}resync(id,reason,carried=[]){let capture=this.shedMode==="capture",required=capture?this.peers.required?.(id)??[]:[],attached=[...new Set([...this.peers.ordinals(id)?.keys()??[],...required])],ordinals=new Map(this.peers.ordinals(id)),pinned=this.pin(id,attached),roots=new Map(pinned.map(({sessionId,outcome})=>[sessionId,outcome.ok?recovered(outcome.value.retain()):outcome])),view={reason,placeholders:this.peers.has(id,MEDIA_PLACEHOLDERS_CAPABILITY),closedNow:sessionId=>capture?!(this.peers.required?.(id)?.includes(sessionId)||ordinals.has(sessionId)&&this.peers.ordinals(id)?.get(sessionId)===ordinals.get(sessionId)):!(this.peers.ordinals(id)?.has(sessionId)??!1),onRelease:()=>{for(let root of roots.values())root.ok&&root.value.end();this.unpin(pinned)}},sessions=capture?[...new Set([...carried,...attached])]:attached;return resyncCut(sessions,capture?()=>sessions:()=>[...new Set([...sessions,...this.peers.ordinals(id)?.keys()??[]])],sessionId=>this.acceptance.has(sessionId)?legacyResyncMessage(sessionId,roots.get(sessionId)):Promise.resolve({message:this.replay.latestMessage(sessionId)}),view,this.replay.track)}};var BROADCAST_LIFECYCLE_RECORDS=new Set(["agent_start","agent_settled","agent_idle","session_opened","session_closed","session_lifecycle"]),SessionEventFanout=class{constructor(){this.startupCleanup=compactUpdatesEnabled()?startRecoveryCleanup(tmpdir2()):void 0,this.acceptance=new Map,this.replay=new LegacyReplayStore,this.checkpoints=new RecoveryCheckpoints,this.events=compactUpdatesEnabled()?new EventLeases:void 0,this.pages=compactUpdatesEnabled()?new RecoveryPageRequests(this.checkpoints,void 0,this.events):void 0,this.socketEpochs=0,this.shedMode=compactUpdatesEnabled()?"capture":"drop",this.connections=new Map,this.connectionCapabilities=new Map,this.connectionSessions=new Map,this.attachOrdinal=0,this.attachViews=new Set,this.registeredCapabilityConnections=new Set,this.pins=new SessionRecoveryPins(this.acceptance,this.checkpoints,this.replay,{socketEpoch:id=>this.connections.get(id)?.socketEpoch,ordinals:id=>this.connectionSessions.get(id),required:id=>this.requiredSessions?.(id)??[],has:(id,capability)=>this.connectionHas(id,capability)},this.shedMode)}registerConnection(id,connection,options={}){this.unregisterConnection(id);let owner=new ExtensionTransportOwner,socketEpoch=`socket-${++this.socketEpochs}`,Actor=this.pages?AdmissionRoutingActor:SocketEventSinkActor,actor=new Actor(connection,cause=>{this.connections.get(id)?.actor===actor&&(owner.retire(),this.connections.delete(id),this.connectionCapabilities.delete(id),this.connectionSessions.delete(id),this.registeredCapabilityConnections.delete(id),this.pages?.forgetPeer(socketEpoch),this.checkpoints.forgetPeer(socketEpoch),this.events?.forgetPeer(socketEpoch),this.onConnectionClosed?.(id)),process.stderr.write(`senpi rpc connection ${id} event queue failed; closing: ${cause instanceof Error?cause.message:String(cause)}
|
|
11
11
|
`),connection.close?.()},options.maxQueueBytes,options.stallMs,this.shedMode);actor instanceof AdmissionRoutingActor&&actor.bind(this.checkpoints,socketEpoch,id),this.connections.set(id,{connection,actor,socketEpoch,owner,selection:new CompactSelection}),this.connectionCapabilities.set(id,new Set),this.connectionSessions.set(id,new Map)}unregisterConnection(id){let registered=this.connections.get(id);registered&&(registered.owner.retire(),registered.actor.close(),this.pages?.forgetPeer(registered.socketEpoch),this.checkpoints.forgetPeer(registered.socketEpoch),this.events?.forgetPeer(registered.socketEpoch),this.connections.delete(id),this.connectionCapabilities.delete(id),this.connectionSessions.delete(id),this.registeredCapabilityConnections.delete(id))}attachConnectionToSession(id,sessionId,compact=!1){let registered=this.connections.get(id);if(!registered)return;let sessions=this.connectionSessions.get(id)??new Map;if(sessions.has(sessionId))return;let ordinal=++this.attachOrdinal;if(sessions.set(sessionId,ordinal),this.connectionSessions.set(id,sessions),compact)return;let pinned=this.pins.pin(id,[sessionId]),first=pinned[0],source=first?.outcome.ok?first.outcome.value:void 0;source&&this.attachViews.add(source.root);let release=()=>{source&&this.attachViews.delete(source.root),this.pins.unpin(pinned)},view={placeholders:this.connectionHas(id,MEDIA_PLACEHOLDERS_CAPABILITY),now:Date.now()},cursor=this.acceptance.has(sessionId)?legacyAttachView(sessionId,source,view,this.replay.track(release)):this.replay.freezeAttach(sessionId,{...view,onRelease:release});registered.actor.installBaseline(cursor,()=>this.connections.get(id)?.actor===registered.actor&&this.connectionSessions.get(id)?.get(sessionId)===ordinal&&pinned.every(({lane,sessionEpoch})=>lane.sessionEpoch===sessionEpoch))}detachConnectionFromSession(id,sessionId){this.pins.retire(id,sessionId),this.connectionSessions.get(id)?.delete(sessionId)}setConnectionCapabilities(id,capabilities){let registered=this.connections.get(id);if(!registered)return;let accepted=registered.selection.wireCapabilities(capabilities,this.events!==void 0);this.connectionCapabilities.set(id,new Set(accepted)),this.registeredCapabilityConnections.add(id),capabilities.includes(EVENT_RESYNC_CAPABILITY)?registered.actor.enableRecovery((reason,carried)=>this.pins.resync(id,reason,carried)):registered.actor.disableRecovery()}clearConnectionCapabilities(id){this.connections.has(id)&&(this.connectionCapabilities.set(id,new Set),this.registeredCapabilityConnections.delete(id))}hasRegisteredConnectionCapabilities(id){return this.registeredCapabilityConnections.has(id)}getConnectionCapabilities(id){if(this.registeredCapabilityConnections.has(id))return[...this.connectionCapabilities.get(id)??[]]}connectionHas(id,capability){return id===void 0?!1:this.connectionCapabilities.get(id)?.has(capability)??!1}targets(sessionId,targetId,isTargeted,recordType){return isTargeted?[targetId]:typeof recordType=="string"&&BROADCAST_LIFECYCLE_RECORDS.has(recordType)?this.connections.size>0?[...this.connections.keys()]:[void 0]:this.connections.size>0?[...this.connections.keys()].filter(id=>this.connectionSessions.get(id)?.has(sessionId)):[void 0]}attachmentOf(id,sessionId,isTargeted,recordType){if(!(isTargeted||typeof recordType=="string"&&BROADCAST_LIFECYCLE_RECORDS.has(recordType)))return this.attachment(id,sessionId)}admissionOf(id,sessionId){let ordinal=this.connectionSessions.get(id)?.get(sessionId);return ordinal===void 0?void 0:admissionOf(ordinal)}get(id){return this.connections.get(id)}values(){return this.connections.values()}isEmpty(){return this.connections.size===0}broadcast(line){for(let{actor}of this.connections.values())actor.enqueue(line)}connectionIds(){return[...this.connections.keys()]}attachedConnections(sessionId){return[...this.connections.keys()].filter(id=>this.connectionSessions.get(id)?.has(sessionId))}pendingQuestionCount(sessionId){let lane=this.acceptance.get(sessionId);return lane?lane.openBroadcastDialogs:this.replay.pendingQuestionCount(sessionId)}deliverToSession(sessionId,line){for(let[id,{actor}]of this.connections){let held=this.attachment(id,sessionId);(held||this.requiredSessions?.(id).includes(sessionId))&&actor.enqueue(line,void 0,void 0,void 0,!1,held)}}rememberSnapshot(sessionId,value,line,placeholderLine){this.acceptance.has(sessionId)||this.replay.remember(sessionId,value,line,placeholderLine)}forgetSession(sessionId){this.onSessionForgotten?.(sessionId);for(let{actor,socketEpoch}of this.connections.values())actor instanceof AdmissionRoutingActor&&actor.remember(sessionId,this.checkpoints,socketEpoch);this.checkpoints.forgetSession(sessionId),this.acceptance.get(sessionId)?.retire("close",this.attachViews),this.acceptance.delete(sessionId),this.replay.forget(sessionId)}attachment(id,sessionId){let ordinal=this.connectionSessions.get(id)?.get(sessionId);return ordinal===void 0?void 0:()=>this.connectionSessions.get(id)?.get(sessionId)===ordinal}};import{AsyncLocalStorage as AsyncLocalStorage2}from"node:async_hooks";var SessionConnectionContext=class{constructor(ownerOf){this.storage=new AsyncLocalStorage2,this.ownerOf=ownerOf}run(id,task){return this.storage.run({id,owner:this.ownerOf(id)},task)}runCaptured(id,identity,task){let owner=this.ownerOf(id),binding=owner?.ownerId===identity.ownerId?owner.peek(identity.bindingGeneration):void 0;return this.storage.run({id,owner:binding===void 0?void 0:owner,binding},task)}runIssued(id,binding,task){return this.storage.run({id,owner:void 0,binding},task)}getStore(){return this.storage.getStore()?.id}transportOf(id){return this.ownerOf(id)}get transport(){return this.storage.getStore()?.owner}get owner(){return this.storage.getStore()?.binding}withBinding(generation,task){let captured=this.storage.getStore();return captured?.owner?this.storage.run({...captured,binding:captured.owner.capture(generation)},task):task()}isCurrent(){return this.currentGuard()()}currentGuard(){let captured=this.storage.getStore();return captured?()=>captured.owner!==void 0&&this.ownerOf(captured.id)===captured.owner&&!captured.owner.retired&&captured.binding?.retired!==!0:()=>!0}};var SessionOpenTurns=class{constructor(){this.open=new Map,this.settling=new Set}note(sessionId,type,reason){if(type==="agent_start")this.open.set(sessionId,(this.open.get(sessionId)??0)+1),this.settling.delete(sessionId);else if(type==="agent_settled"&&reason!=="session_closed"){let left=(this.open.get(sessionId)??0)-1;left>0?this.open.set(sessionId,left):(this.open.delete(sessionId),this.settling.add(sessionId))}else type==="agent_idle"&&this.settling.delete(sessionId)}take(sessionId){let owed=(this.open.get(sessionId)??0)+(this.settling.has(sessionId)?1:0);return this.open.delete(sessionId),this.settling.delete(sessionId),owed}};var SessionRecordAccounting=class{constructor(){this.count=0,this.bytes=0}append(queue,value,key,resolve2,reject){let line=serializeJsonLine(value),byteLength=Buffer.byteLength(line),node={value,line,byteLength,key,previous:queue.tail,resolve:resolve2,reject};return queue.tail?queue.tail.next=node:queue.head=node,queue.tail=node,this.count++,this.bytes+=byteLength,node}replace(node,value){let line=serializeJsonLine(value),byteLength=Buffer.byteLength(line);this.bytes+=byteLength-node.byteLength,node.value=value,node.line=line,node.byteLength=byteLength}unlink(queue,node){node.previous?node.previous.next=node.next:queue.head=node.next,node.next?node.next.previous=node.previous:queue.tail=node.previous,node.key&&queue.latestByKey.get(node.key)===node&&queue.latestByKey.delete(node.key),node.previous=void 0,node.next=void 0,this.count--,this.bytes-=node.byteLength}};function statusRecord(subscription,sessionId,derived,lastChange,lastEffect){let{context,...rest}=derived;return{type:"session_status",subscriptionId:subscription.id,seq:subscription.seq,sessionId,...rest,...subscription.options.includeContext?{context}:{},...lastEffect!==void 0?{lastEffect}:{},lastChange,...subscription.seq>0&&subscription.options.admissionId!==void 0?{admissionId:subscription.options.admissionId,generation:0}:{}}}var MIRROR_PENDING_LIMITS={entries:128,bytes:1048576},MirrorPending=class{constructor(){this.records=[],this.bytes=0,this.active=!1}status(){return{entries:this.records.length,bytes:this.bytes}}enqueue(line,deliver,drop){if(this.reason){drop?.();return}if(this.active){deliver();return}let bytes=Buffer.byteLength(line);if(this.records.length>=MIRROR_PENDING_LIMITS.entries||this.bytes+bytes>MIRROR_PENDING_LIMITS.bytes){this.reason="admission_limit",this.clear(),drop?.();return}this.bytes+=bytes,this.records.push({deliver,drop})}activate(){if(this.reason||this.active)return;this.active=!0;let records=this.records;this.records=[],this.bytes=0;for(let record of records)record.deliver()}retire(reason="attempt_cancelled"){this.reason??=reason,this.clear()}clear(){for(let record of this.records)record.drop?.();this.records=[],this.bytes=0}};function liveStatus(runtime,fanout){return(fanout.pendingQuestions??0)>0||runtime.pendingQuestions>0?"waiting_input":runtime.isCompacting?"compacting":runtime.isStreaming?"running":"idle"}function statusOf(entry,runtime,fanout,terminal2){if(terminal2!==void 0)return terminal2.status;switch(entry.state){case"opening":return"opening";case"closing":case"quarantined":case"closed":return"closed";case"open":return runtime===void 0?"opening":liveStatus(runtime,fanout);default:{let exhaustive=entry.state;throw new Error(`unexpected session state ${String(exhaustive)}`)}}}function deriveSessionStatus(entry,runtime,fanout,terminal2,cause){let status=statusOf(entry,runtime,fanout,terminal2),reason=terminal2?.reason??(status==="idle"&&cause==="abort"?"aborted":void 0);return{status,...reason!==void 0?{reason}:{},kind:entry.kind,cwd:entry.cwd,attachments:Math.max(0,entry.attachments),...entry.durableSessionId!==void 0?{durableSessionId:entry.durableSessionId}:{},...entry.sessionPath!==void 0?{sessionPath:entry.sessionPath}:{},...entry.name!==void 0?{name:entry.name}:{},...runtime?.model!==void 0?{model:{provider:runtime.model.provider,id:runtime.model.id}}:{},...runtime?.thinkingLevel!==void 0?{thinkingLevel:runtime.thinkingLevel}:{},pendingQueue:{steering:runtime?.steering??0,followUp:runtime?.followUp??0},context:entry.context}}function terminalOfLifecycle(record){let reason=typeof record.reason=="string"?record.reason:void 0;if(record.type==="session_parked")return{status:"unloaded",reason:reason==="unloaded"?"unload_session":"idle"};if(record.type==="session_closed")return reason==="handoff_parked"?{status:"unloaded",reason:"handoff"}:reason===void 0?{status:"closed"}:{status:"closed",reason}}function causeOfRecord(record){switch(record.type){case"agent_start":return"prompt";case"agent_end":return"agent_end";case"agent_idle":return"agent_idle";case"session_abort":return"abort";case"queue_update":return"queue";case"model_changed":case"thinking_level_changed":return"set_model";case"session_replaced":return"replace";case"session_parked":return"park";case"session_closed":return"close";case"question_resolved":return"question";case"extension_ui_request":return record.method==="question"?"question":void 0;case"compaction_start":case"compaction_end":return"compaction";default:return}}function matchingMirrors(subscriptions,sessionId,recordType,entryView2,dialogs=!1){let candidates=[...subscriptions].filter(subscription=>(!dialogs||subscription.options.dialogs===!0)&&(recordType==="snapshot_marker"||dialogs?subscription.options.mirror.kind!=="none":mirrorsRecord(subscription.options.mirror,recordType)));if(candidates.length===0)return[];let entry=entryView2();return entry?candidates.filter(s=>subscriptionMatches(s.options,sessionId,entry)):[]}var MAX_SELECTOR_IDS=1024,MAX_MIRROR_TYPES=64,RECORD_TYPE_PATTERN=/^[a-z][a-z0-9_]{0,63}$/;function refusal(reason,action){return{refusal:{reason,action}}}function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function parseSelector(value){if(value===void 0||value==="all")return{selector:{kind:"all"}};let action='send sessions: "all", { ids: [<sessionId | durableSessionId | sessionPath>] } or { childrenOf: <durableSessionId> }';if(!isRecord2(value))return refusal('sessions must be "all" or an object',action);if("ids"in value&&!("childrenOf"in value)){let ids=value.ids;return!Array.isArray(ids)||ids.length===0||ids.length>MAX_SELECTOR_IDS?refusal(`sessions.ids must be a non-empty array of at most ${MAX_SELECTOR_IDS} strings`,action):ids.every(id=>typeof id=="string"&&id.length>0)?{selector:{kind:"ids",ids:new Set(ids)}}:refusal("every sessions.ids entry must be a non-empty string",action)}if("childrenOf"in value&&!("ids"in value)){let parent=value.childrenOf;return typeof parent!="string"||parent.length===0?refusal("sessions.childrenOf must be a non-empty durable session id",action):{selector:{kind:"childrenOf",parent}}}return refusal("sessions must name exactly one of ids or childrenOf",action)}function parseMirror(value){if(value===void 0||value==="none")return{mirror:{kind:"none"}};if(value==="all")return{mirror:{kind:"all"}};let action='send mirror: "none", "all" or an array of record types such as ["message_update"]';return!Array.isArray(value)||value.length===0||value.length>MAX_MIRROR_TYPES?refusal(`mirror must be "none", "all" or a non-empty array of at most ${MAX_MIRROR_TYPES} record types`,action):value.every(type=>typeof type=="string"&&RECORD_TYPE_PATTERN.test(type))?{mirror:{kind:"types",types:new Set(value)}}:refusal(`every mirror entry must be a record type matching ${RECORD_TYPE_PATTERN.source}`,action)}function optionalBoolean(value,field4){return value===void 0||typeof value=="boolean"?value:{reason:`${field4} must be a boolean`,action:`send ${field4}: true or false, or omit it`}}function parseSubscription(request){let selector=parseSelector(request.sessions);if("refusal"in selector)return selector;let mirror=parseMirror(request.mirror);if("refusal"in mirror)return mirror;let includeWorkers=optionalBoolean(request.include_workers,"include_workers");if(typeof includeWorkers=="object")return{refusal:includeWorkers};let includeContext=optionalBoolean(request.include_context,"include_context");if(typeof includeContext=="object")return{refusal:includeContext};let dialogs=optionalBoolean(request.dialogs,"dialogs");if(typeof dialogs=="object")return{refusal:dialogs};let effects=optionalBoolean(request.effects,"effects");return typeof effects=="object"?{refusal:effects}:{options:{selector:selector.selector,dialogs:dialogs??!1,includeWorkers:includeWorkers??selector.selector.kind==="childrenOf",includeContext:includeContext??!1,mirror:mirror.mirror,effects:effects??selector.selector.kind==="childrenOf"}}}function subscriptionMatches(options,sessionId,entry){if(entry.kind==="worker"&&!options.includeWorkers)return!1;let selector=options.selector;switch(selector.kind){case"all":return!0;case"ids":return selector.ids.has(sessionId)||entry.durableSessionId!==void 0&&selector.ids.has(entry.durableSessionId)||entry.sessionPath!==void 0&&selector.ids.has(entry.sessionPath);case"childrenOf":{let lineage=entry.openContext??entry.context;return(lineage.parent_session_id??lineage.root_session_id)===selector.parent}default:{let exhaustive=selector;throw new Error(`unexpected selector ${String(exhaustive)}`)}}}function mirrorsRecord(mirror,recordType){switch(mirror.kind){case"none":return!1;case"all":return!0;case"types":return mirror.types.has(recordType);default:{let exhaustive=mirror;throw new Error(`unexpected mirror ${String(exhaustive)}`)}}}function matchingStatusConnections(subscriptions,sessionId,entry){let matches=new Map;if(entry)for(let subscription of subscriptions)subscriptionMatches(subscription.options,sessionId,entry)&&matches.set(subscription.connectionId,(matches.get(subscription.connectionId)??!1)||subscription.options.includeContext);return matches}var MAX_SUBSCRIPTIONS_PER_CONNECTION=64,SessionStatusStream=class{constructor(delivery){this.subscriptions=new Map,this.pendings=new Map,this.terminals=new Map,this.lastViews=new Map,this.lastChanges=new Map,this.nextSubscription=0,this.delivery=delivery}setSource(source){this.source=source}setLastEffectProvider(provider){this.lastEffect=provider}get size(){return this.subscriptions.size}connectionSize(connectionId){let count=0;for(let pending of this.pendings.values())pending.connectionId===connectionId&&count++;for(let subscription of this.subscriptions.values())subscription.connectionId===connectionId&&count++;return count}subscribe(connectionId,options,snapshotSink){let pending={id:`sub-${++this.nextSubscription}`,connectionId,options,seq:0,lines:[],...options.admissionId===void 0?{}:{buffer:new MirrorPending}};this.pendings.set(pending.id,pending);let at=snapshotSink?(this.delivery.now?.()??new Date).toISOString():void 0,rows=()=>this.snapshotRows(pending,at);try{snapshotSink&&snapshotSink(rows,pending.id)}catch(cause){throw this.unsubscribe(connectionId,pending.id),cause}return{subscriptionId:pending.id,snapshot:snapshotSink?[]:[...rows()],seq:pending.seq}}*snapshotRows(pending,at){for(let sessionId of this.source?.sessionIds()??[]){let view=this.currentView(sessionId);if(view===void 0||!subscriptionMatches(pending.options,sessionId,view.entry))continue;let derived=this.derive(sessionId,view);yield this.recordFor(pending,sessionId,derived,this.lastChangeOf(sessionId,at))}}activate(subscriptionId){let pending=this.pendings.get(subscriptionId);if(pending===void 0)return;this.pendings.delete(subscriptionId);let subscription={id:pending.id,connectionId:pending.connectionId,options:pending.options,seq:pending.seq};this.subscriptions.set(subscription.id,subscription),pending.buffer?.activate();for(let line of pending.lines)this.delivery.enqueue(subscription.connectionId,line);pending.lines.length=0}unsubscribe(connectionId,subscriptionId){let pending=this.pendings.get(subscriptionId);return pending!==void 0?pending.connectionId!==connectionId?!1:(this.pendings.delete(subscriptionId),pending.buffer?.retire(),this.onSubscriptionEnd?.(connectionId,subscriptionId),!0):this.subscriptions.get(subscriptionId)?.connectionId!==connectionId?!1:(this.subscriptions.delete(subscriptionId),this.onSubscriptionEnd?.(connectionId,subscriptionId),!0)}dropConnection(connectionId){for(let[id,pending]of this.pendings)pending.connectionId===connectionId&&this.unsubscribe(connectionId,id);for(let[id,subscription]of this.subscriptions)subscription.connectionId===connectionId&&this.unsubscribe(connectionId,id)}pendingBuffer(subscriptionId){return this.pendings.get(subscriptionId)?.buffer}queue(pending,line){pending.buffer?pending.buffer.enqueue(line,()=>this.delivery.enqueue(pending.connectionId,line)):pending.lines.push(line)}publish(sessionId,cause,by,contextOnly=!1){let change={at:(this.delivery.now?.()??new Date).toISOString(),cause,by};if(this.lastChanges.set(sessionId,change),this.subscriptions.size===0&&this.pendings.size===0)return;let view=this.currentView(sessionId);if(view===void 0)return;let derived=this.derive(sessionId,view,cause);for(let pending of this.pendings.values())contextOnly&&!pending.options.includeContext||subscriptionMatches(pending.options,sessionId,view.entry)&&(pending.seq+=1,this.queue(pending,serializeJsonLine(this.recordFor(pending,sessionId,derived,change))));for(let subscription of this.subscriptions.values()){if(contextOnly&&!subscription.options.includeContext||!subscriptionMatches(subscription.options,sessionId,view.entry))continue;subscription.seq+=1;let record=this.recordFor(subscription,sessionId,derived,change);this.delivery.enqueue(subscription.connectionId,serializeJsonLine(record))||this.subscriptions.delete(subscription.id)}}publishEffect(sessionId,status){if(this.subscriptions.size===0&&this.pendings.size===0)return;let view=this.currentView(sessionId);if(view===void 0)return;let at=status.updatedAt??status.acceptedAt??(this.delivery.now?.()??new Date).toISOString();for(let pending of this.pendings.values())!pending.options.effects||!subscriptionMatches(pending.options,sessionId,view.entry)||(pending.seq+=1,this.queue(pending,serializeJsonLine(effectStatusRecord(pending,sessionId,status,at))));for(let subscription of this.subscriptions.values()){if(!subscription.options.effects||!subscriptionMatches(subscription.options,sessionId,view.entry))continue;subscription.seq+=1;let line=serializeJsonLine(effectStatusRecord(subscription,sessionId,status,at));this.delivery.enqueue(subscription.connectionId,line)||this.subscriptions.delete(subscription.id)}}seal(sessionId,terminal2,cause,by){this.terminals.set(sessionId,terminal2),this.publish(sessionId,cause,by)}forget(sessionId){this.terminals.delete(sessionId),this.lastViews.delete(sessionId),this.lastChanges.delete(sessionId)}dialogTargets(sessionId){return this.mirrorTargets(sessionId,"ui_request_pending",!0)}mirrorTargets(sessionId,recordType,dialogs=!1){return[...new Set(this.mirrorSubscriptions(sessionId,recordType,dialogs).map(s=>s.connectionId))]}mirrorAdmissions(peer,sessionId,recordType){return this.mirrorSubscriptions(sessionId,recordType).flatMap(s=>s.connectionId===peer&&s.options.admissionId!==void 0?[s.options.admissionId]:[])}mirrorSubscriptions(sessionId,recordType,dialogs=!1){return matchingMirrors([...this.pendings.values(),...this.subscriptions.values()],sessionId,recordType,()=>this.source?.entryView(sessionId)??this.lastViews.get(sessionId)?.entry,dialogs)}matchingConnections(sessionId){return matchingStatusConnections(this.subscriptions.values(),sessionId,this.currentView(sessionId)?.entry)}requiredAdmissions(peer,sessionId){return this.mirrorSubscriptions(sessionId,"snapshot_marker").flatMap(s=>s.connectionId===peer&&s.options.admissionId!==void 0?[s.options.admissionId]:[])}requiredSessions(peer){return(this.source?.sessionIds()??[]).filter(id=>this.requiredAdmissions(peer,id).length>0)}currentView(sessionId){let live=this.source?.view(sessionId);return live!==void 0&&this.lastViews.set(sessionId,live),live??this.lastViews.get(sessionId)}derive(sessionId,view,cause){return deriveSessionStatus(view.entry,view.runtime,{pendingQuestions:this.delivery.pendingQuestions(sessionId)},this.terminals.get(sessionId),cause)}lastChangeOf(sessionId,at){return this.lastChanges.get(sessionId)??{at:at??(this.delivery.now?.()??new Date).toISOString(),cause:"open",by:"host"}}recordFor(subscription,sessionId,derived,lastChange){return statusRecord(subscription,sessionId,derived,lastChange,this.lastEffect?.(sessionId))}};var SessionStructuredLanes=class{constructor(){this.receivers=new Map}observe(sessionId,receiver){let receivers=this.receivers.get(sessionId)??new Set;return receivers.add(receiver),this.receivers.set(sessionId,receivers),()=>{receivers.delete(receiver),receivers.size===0&&this.receivers.get(sessionId)===receivers&&this.receivers.delete(sessionId)}}accept(sessionId,record){for(let receiver of[...this.receivers.get(sessionId)??[]])receiver(record)}};var SurfaceDigestDedupe=class{constructor(){this.connections=new Map}announce(connectionId,sessionId,previous,digest2){let sessions=this.connections.get(connectionId);if(sessions===void 0&&(sessions=new Map,this.connections.set(connectionId,sessions)),previous===digest2)return!1;let tell=!0;for(let[other,announced]of sessions)if(!(other===sessionId||announced.last!==digest2)&&announced.previous===previous){tell=!1;break}return sessions.set(sessionId,{last:digest2,previous}),tell}dropConnection(connectionId){this.connections.delete(connectionId)}forgetSession(sessionId){for(let sessions of this.connections.values())sessions.delete(sessionId)}};var SessionEventWriterState=class{get pendingCloseRecordCount(){return this.reservedCloseRecords}get pendingCloseByteLength(){return this.reservedCloseBytes}constructor(writeRaw,waitOrSchedule,scheduleFlush){this.structuredLanes=new SessionStructuredLanes,this.legacyRefusals=new LegacyRecordRefusals,this.presenterConnections=new Map,this.presenterBindings=new Map,this.records=new SessionRecordAccounting,this.queues=new Map,this.fanout=new SessionEventFanout,this.connectionContext=new SessionConnectionContext(id=>this.fanout.get(id)?.owner),this.securityPresentations=new RpcSecurityPresentations(this.fanout,(id,task)=>this.withConnection(id,task),()=>this.requestFlush()),this.workerSecurityBridge=!1,this.controlQueue={latestByKey:new Map,ready:!1},this.readyQueues=[],this.sealedSessions=new Set,this.workerSessions=new Set,this.openTurns=new SessionOpenTurns,this.status=new SessionStatusStream({enqueue:(connectionId,line)=>{let actor=this.fanout.get(connectionId)?.actor;return actor===void 0?!1:(actor.enqueue(line),this.requestFlush(),!0)},pendingQuestions:sessionId=>this.fanout.pendingQuestionCount(sessionId)}),this.surfaceDedupe=new SurfaceDigestDedupe,this.mediaPersisters=new Map,this.flushScheduled=!1,this.controlOverflowReported=!1,this.closeOverflowReported=!1,this.closeOverflowActors=new WeakSet,this.reservedCloseRecords=0,this.reservedCloseBytes=0,this.secretPresentations=new SecretInputPresentations(this.fanout,()=>this.currentConnection(),line=>this.writeRaw(line),()=>this.requestFlush()),this.fanout.onConnectionClosed=id=>{this.secretPresentations.detach(id),this.securityPresentations.dropConnection(id);let sender=this.presenterConnections.get(id);sender&&this.presenterAuthority?.detach(sender),this.presenterConnections.delete(id)},this.writeRaw=writeRaw,waitOrSchedule&&scheduleFlush===void 0&&waitOrSchedule.length>0?this.scheduleFlush=waitOrSchedule:(this.waitForBackpressure=waitOrSchedule,this.scheduleFlush=scheduleFlush??(flush=>queueMicrotask(()=>{flush()})))}};var settleActors=actors=>Promise.all(actors.map(actor=>actor.flush().catch(()=>{}))).then(()=>{}),acceptActors=actors=>Promise.all(actors.map(actor=>actor.waitForAcceptance())).then(()=>{}),MAX_SHARED_STDIO_QUEUE_BYTES=64*1024*1024,MAX_SHARED_STDIO_QUEUE_RECORDS=4096,SessionEventWriterLanes=class extends SessionEventWriterState{get bufferedRecordCount(){return this.records.count+(this.inFlight?1:0)}get bufferedByteLength(){return this.records.bytes+(this.inFlight?.node.byteLength??0)}flush(){if(this.failure!==void 0)return Promise.reject(this.failure);if(this.flushScheduled=!1,this.drainPromise)return this.drainPromise;if(this.readyQueues.length===0)return settleActors([...this.fanout.values()].map(({actor})=>actor));let resolveDrain,rejectDrain,drain=new Promise((resolve2,reject)=>{resolveDrain=resolve2,rejectDrain=reject});return this.drainPromise=drain,this.drainUntilEmpty().then(resolveDrain,rejectDrain),drain.then(()=>{this.drainPromise===drain&&(this.drainPromise=void 0),this.readyQueues.length>0&&this.requestFlush()},cause=>{this.drainPromise===drain&&(this.drainPromise=void 0),this.fail(cause)}),drain}async drainUntilEmpty(){do await this.drainReadyQueues();while(this.readyQueues.length>0);await settleActors([...this.fanout.values()].map(({actor})=>actor)),this.controlOverflowReported=!1,this.reservedCloseRecords===0&&(this.closeOverflowReported=!1)}async drainReadyQueues(){for(;this.readyQueues.length>0;){let queue=this.readyQueues.shift();queue.ready=!1;let node=queue.head;if(node){this.records.unlink(queue,node),this.inFlight={queue,node};try{let connection=queue.targetId?this.fanout.get(queue.targetId)?.connection:void 0,writeRaw=connection?.writeRaw??this.writeRaw,waitForBackpressure=connection?.waitForBackpressure??this.waitForBackpressure;!connection&&queue.targetId||(writeRaw(node.line),waitForBackpressure&&await waitForBackpressure()),node.resolve?.()}catch(cause){throw node.reject?.(cause),cause}finally{this.inFlight=void 0}if(queue.head)this.markReady(queue);else if(queue.sessionId||queue.targetId)for(let[key,candidate]of this.queues)candidate===queue&&this.queues.delete(key)}}}exceedsStdioCapacity(line){return this.bufferedRecordCount+this.reservedCloseRecords>=MAX_SHARED_STDIO_QUEUE_RECORDS||this.bufferedByteLength+this.reservedCloseBytes+Buffer.byteLength(line)>MAX_SHARED_STDIO_QUEUE_BYTES}connectionQueue(targetId){let key=`connection:${targetId}`,queue=this.queues.get(key);return queue||(queue={targetId,latestByKey:new Map,ready:!1},this.queues.set(key,queue)),queue}appendSessionRecord(sessionId,value,targetId){let key=`${targetId??"default"}:${sessionId}`,queue=this.queues.get(key);if(queue||(queue={sessionId,targetId,latestByKey:new Map,ready:!1},this.queues.set(key,queue)),compactDelta(value)){let previousFull=queue.latestByKey.get(MESSAGE_KEY);previousFull&&this.demoteAndMerge(queue,previousFull);let node=this.records.append(queue,value,MESSAGE_KEY);queue.latestByKey.set(MESSAGE_KEY,node),this.markReady(queue);return}let toolKey=toolUpdateKey(value);if(toolKey){let previous=queue.latestByKey.get(toolKey);previous&&this.records.unlink(queue,previous);let node=this.records.append(queue,value,toolKey);queue.latestByKey.set(toolKey,node),this.markReady(queue);return}queue.latestByKey.clear(),this.records.append(queue,value),this.markReady(queue)}demoteAndMerge(queue,node){this.records.replace(node,demoteToDeltaOnly(node.value));let current=compactDelta(node.value),preceding=node.previous,previous=preceding?compactDelta(preceding.value):void 0;if(preceding&&previous&¤t&&preceding.value.message===null&&previous.type===current.type&&previous.contentIndex===current.contentIndex){let precedingEvent=preceding.value.assistantMessageEvent;this.records.replace(preceding,{...preceding.value,assistantMessageEvent:{...precedingEvent,delta:previous.delta+current.delta}}),this.records.unlink(queue,node)}}markReady(queue){queue.ready||this.inFlight?.queue===queue||!queue.head||(queue.ready=!0,this.readyQueues.push(queue))}requestFlush(){this.failure!==void 0||this.flushScheduled||this.drainPromise||(this.flushScheduled=!0,this.scheduleFlush(()=>this.flush()))}fail(cause){if(this.failure===void 0){this.failure=cause;for(let queue of this.allQueues())for(let node=queue.head;node;node=node.next)node.reject?.(cause)}}*allQueues(){yield*this.queues.values(),yield this.controlQueue}};var SessionEventWriterConnections=class extends SessionEventWriterLanes{isTargetedRecord(record){return record.type==="response"||record.type==="bash_execution_update"||record.type==="host_request"||record.type==="relocation_due"||record.type==="extension_ui_request"&&["select","confirm","input","editor"].includes(String(record.method))}isSessionSealed(sessionId){return this.sealedSessions.has(sessionId)}registerConnection(id,connection,options={}){let previousPresenter=this.presenterConnections.get(id);if(previousPresenter&&this.presenterAuthority?.detach(previousPresenter),this.fanout.registerConnection(id,connection,options),this.presenterAuthority){let sender=this.presenterAuthority.connect(id,frame=>{if(!this.fanout.get(id))return!1;try{return connection.writeRaw(serializeJsonLine(frame)),connection.waitForBackpressure().catch(()=>this.presenterAuthority?.detach(sender)),!0}catch{return this.presenterAuthority?.detach(sender),!1}});this.presenterConnections.set(id,sender)}}unregisterConnection(id){this.secretPresentations.detach(id);let sender=this.presenterConnections.get(id);sender&&this.presenterAuthority?.detach(sender),this.presenterConnections.delete(id),this.securityPresentations.dropConnection(id),this.fanout.unregisterConnection(id),this.status.dropConnection(id),this.surfaceDedupe.dropConnection(id)}attachConnectionToSession(id,sessionId,compact=!1){this.fanout.attachConnectionToSession(id,sessionId,compact),this.hasConnection(id)&&this.securityPresentations.attach(id,sessionId);let sender=this.presenterConnections.get(id),binding=this.presenterBindings.get(sessionId);sender&&binding&&this.presenterAuthority?.attach(sender,binding)}detachConnectionFromSession(id,sessionId){let sender=this.presenterConnections.get(id),binding=this.presenterBindings.get(sessionId);sender&&binding&&this.presenterAuthority?.detach(sender,binding),this.fanout.detachConnectionFromSession(id,sessionId),this.secretPresentations.recheck(),this.securityPresentations.detach(id,sessionId)}hasConnection(id){return this.fanout.get(id)!==void 0}setConnectionCapabilities(id,capabilities){if(this.fanout.setConnectionCapabilities(id,capabilities),this.secretPresentations.recheck(),this.securityPresentations.capabilitiesChanged(id),!capabilities.includes("interactive_user")||!capabilities.includes("mcp_form_presenter_v1")){let sender=this.presenterConnections.get(id);sender&&this.presenterAuthority?.withdraw(sender)}}clearConnectionCapabilities(id){let sender=this.presenterConnections.get(id);sender&&this.presenterAuthority?.withdraw(sender),this.fanout.clearConnectionCapabilities(id),this.secretPresentations.recheck(),this.securityPresentations.capabilitiesChanged(id)}bindSecurityPresentations(sessionId,durableId,notices,ui){if(!this.fanout.isEmpty())return this.securityPresentations.bind(sessionId,durableId,notices,ui.select)}acceptWorkerSecuritySnapshot(sessionId,snapshot){this.securityPresentations.acceptSnapshot(sessionId,snapshot)}routeWorkerGrant(sessionId,requestId,preferred,capabilities,cancel){return this.securityPresentations.routeWorkerGrant(sessionId,requestId,preferred,capabilities,cancel)}acceptWorkerGrantResponse(sessionId,id,connection){return this.securityPresentations.acceptWorkerResponse(sessionId,id,connection)}settleGrantDialog(sessionId,id){this.securityPresentations.settleGrant(sessionId,id)}hasRegisteredConnectionCapabilities(id){return this.fanout.hasRegisteredConnectionCapabilities(id)}compactSelection(id){return this.fanout.get(id)?.selection}getConnectionCapabilities(id){return this.fanout.getConnectionCapabilities(id)}setSessionMedia(sessionId,persister){persister===void 0?this.mediaPersisters.delete(sessionId):this.mediaPersisters.set(sessionId,persister)}enqueueCanonical(_sessionId,_control){}canonicalUnavailable(_sessionId,_cause){}registerAcceptance(sessionId,lane){this.sealedSessions.has(sessionId)||this.fanout.acceptance.set(sessionId,lane),this.fanout.events&&(lane.beforeAccept=record=>this.prepareDelivery(sessionId,record))}setSessionKind(sessionId,kind){kind==="worker"?this.workerSessions.add(sessionId):this.workerSessions.delete(sessionId)}async flushConnection(id){let target=this.fanout.get(id);target&&await settleActors([target.actor])}withConnection(id,task){return this.connectionContext.run(id,task)}currentConnection(){return this.connectionContext.getStore()}waitForSessionBackpressure(sessionId){return this.fanout.isEmpty()?this.flush():acceptActors(this.sessionActors(sessionId))}sessionActors(sessionId){return[...new Set([...this.fanout.targets(sessionId,this.currentConnection(),!1,void 0),this.currentConnection()])].flatMap(target=>{let registered=target===void 0?void 0:this.fanout.get(target);return registered?[registered.actor]:[]})}};var SessionEventWriterPresenters=class extends SessionEventWriterConnections{enableMcpPresenters(){return this.presenterAuthority??=new McpPresenterAuthority,this.presenterAuthority}get mcpPresenters(){return this.presenterAuthority}getMcpPresenterConnection(id){return this.presenterConnections.get(id)}findMcpPresenterConnection(nonce){return[...this.presenterConnections.values()].find(connection=>connection.nonce===nonce)}getMcpFormBinding(sessionId){return this.presenterBindings.get(sessionId)}bindMcpForms(sessionId,durableId,ui,admit){let authority=this.presenterAuthority;if(!authority)return;let binding=authority.bind(sessionId,durableId,admit);this.presenterBindings.set(sessionId,binding);for(let id of this.fanout.attachedConnections(sessionId)){let connection=this.presenterConnections.get(id);connection&&authority.attach(connection,binding)}return bindPrivateMcpForms(ui,binding),()=>{binding.dispose(),this.presenterBindings.get(sessionId)===binding&&this.presenterBindings.delete(sessionId)}}};function sessionOpenedLines(record){let{context,...plain2}=record;return{plain:serializeJsonLine(plain2),withContext:serializeJsonLine(context===void 0?plain2:{...plain2,context})}}var SessionEventWriterLifecycle=class extends SessionEventWriterPresenters{changeActor(fallback){return this.connectionContext.getStore()===void 0?fallback:"client"}publishSessionOpened(record){if(this.prepareDelivery(record.sessionId),this.fanout.isEmpty()){let{context:_context,...wire}=record;this.appendSessionRecord(record.sessionId,{...wire}),this.requestFlush();return}let lines2=sessionOpenedLines(record),subscribers=this.status.matchingConnections(record.sessionId),recipients=record.kind==="worker"?new Set([...this.fanout.attachedConnections(record.sessionId),...subscribers.keys()]):new Set(this.fanout.connectionIds());for(let id of recipients)this.fanout.get(id)?.actor.enqueue(subscribers.get(id)===!0?lines2.withContext:lines2.plain);this.requestFlush()}closeSession(sessionId,response,reason,sessionPath){if(this.presenterBindings.get(sessionId)?.dispose(),this.presenterBindings.delete(sessionId),!this.settleBeforeSeal(sessionId))return;this.sealedSessions.add(sessionId),this.securityPresentations.dropSession(sessionId),this.fanout.forgetSession(sessionId),this.mediaPersisters.delete(sessionId);let targetId=this.connectionContext.getStore(),lifecycle={type:"session_closed",sessionId,...reason&&{reason},...sessionPath&&{sessionPath}};this.fanout.isEmpty()?this.appendSessionRecord(sessionId,lifecycle):this.workerSessions.has(sessionId)?this.fanout.deliverToSession(sessionId,serializeJsonLine(lifecycle)):this.fanout.broadcast(serializeJsonLine(lifecycle)),this.sealStatus(sessionId,lifecycle);let taggedResponse={...response,sessionId},registered=targetId===void 0?void 0:this.fanout.get(targetId);registered?registered.actor.enqueue(serializeJsonLine(taggedResponse),void 0,void 0,void 0,isCorrelatedReply(response)):this.appendSessionRecord(sessionId,taggedResponse,targetId),this.requestFlush()}sealRolledBackOpen(sessionId,sessionPath){this.sealLifecycle(sessionId,{type:"session_closed",sessionId,reason:"error",...sessionPath!==void 0&&{sessionPath}})}sealLifecycle(sessionId,lifecycle,attachedOnly=!1){this.presenterBindings.get(sessionId)?.dispose(),this.presenterBindings.delete(sessionId),this.settleBeforeSeal(sessionId)&&(this.sealedSessions.add(sessionId),this.securityPresentations.dropSession(sessionId),this.fanout.forgetSession(sessionId),this.mediaPersisters.delete(sessionId),this.fanout.isEmpty()?this.appendSessionRecord(sessionId,lifecycle):attachedOnly||this.workerSessions.has(sessionId)?this.fanout.deliverToSession(sessionId,serializeJsonLine(lifecycle)):this.fanout.broadcast(serializeJsonLine(lifecycle)),this.sealStatus(sessionId,lifecycle),this.requestFlush())}sealStatus(sessionId,lifecycle){let terminal2=terminalOfLifecycle(lifecycle),cause=causeOfRecord(lifecycle);terminal2!==void 0&&cause!==void 0&&this.status.seal(sessionId,terminal2,cause,this.changeActor("host"))}reserveCloseResponse(sessionId,response,records=2){let bytes=Buffer.byteLength(serializeJsonLine({...response,sessionId}))+(records===2?Buffer.byteLength(serializeJsonLine({type:"session_closed",sessionId,reason:"client_close"})):0);if(this.bufferedRecordCount+this.reservedCloseRecords+records>MAX_SHARED_STDIO_QUEUE_RECORDS||this.bufferedByteLength+this.reservedCloseBytes+bytes>MAX_SHARED_STDIO_QUEUE_BYTES){let overflow={type:"overflow",command:"close_session",error:"rpc_close_output_overflow, resync required"},targetId=this.currentConnection();if(targetId!==void 0){let actor=this.fanout.get(targetId)?.actor;actor&&!this.closeOverflowActors.has(actor)&&(this.closeOverflowActors.add(actor),actor.enqueue(serializeJsonLine(overflow),void 0,()=>this.closeOverflowActors.delete(actor)))}else this.closeOverflowReported||(this.closeOverflowReported=!0,this.records.append(this.controlQueue,overflow),this.markReady(this.controlQueue),this.requestFlush());return}this.reservedCloseRecords+=records,this.reservedCloseBytes+=bytes;let active=!0,release=()=>{active&&(active=!1,this.reservedCloseRecords-=records,this.reservedCloseBytes-=bytes)};return{release,complete:(terminal2,reason)=>{active&&(release(),terminal2&&!this.sealedSessions.has(sessionId)?this.closeSession(sessionId,response,reason):this.appendClosedResponse(sessionId,response))}}}enqueueClosedResponse(sessionId,response){this.reserveCloseResponse(sessionId,response,1)?.complete(!1)}appendClosedResponse(sessionId,response){let targetId=this.connectionContext.getStore(),taggedResponse={...response,sessionId},registered=targetId===void 0?void 0:this.fanout.get(targetId);registered?registered.actor.enqueue(serializeJsonLine(taggedResponse),void 0,void 0,void 0,isCorrelatedReply(response)):this.appendSessionRecord(sessionId,taggedResponse,targetId),this.requestFlush()}forgetSession(sessionId){this.sealedSessions.delete(sessionId),this.openTurns.take(sessionId),this.workerSessions.delete(sessionId),this.fanout.forgetSession(sessionId),this.mediaPersisters.delete(sessionId),this.status.forget(sessionId),this.surfaceDedupe.forgetSession(sessionId)}};var SessionEventWriterRecovery=class extends SessionEventWriterLifecycle{constructor(){super(...arguments),this.required=new CompactRequiredStreams(this.fanout,this.status)}prepareDelivery(sessionId,record){this.fanout.requiredSessions=peer=>this.required.sessions(peer),this.fanout.onSessionForgotten=id=>this.required.forgetSession(id),this.required.prepare(sessionId,record)}holdsAdmission(peer,admissionId,sessionId){let actor=this.fanout.get(peer)?.actor;if(!(actor instanceof AdmissionRoutingActor))return!1;for(let[subscriptionId,id]of actor.subscriptions)if(id===admissionId&&(sessionId===void 0||subscriptionId===sessionId))return!0;return sessionId!==void 0&&this.isCompactSubscription(peer,admissionId,sessionId)?!0:actor.admissions.has(admissionId)?sessionId===void 0||this.ordinaryRoute(peer,sessionId)?.routes.includes(admissionId)===!0:!1}unregisterAdmission(peer,admissionId){let actor=this.fanout.get(peer)?.actor;actor instanceof AdmissionRoutingActor&&actor.admissions.delete(admissionId)}ordinaryRoute(peer,sessionId){let registered=this.fanout.get(peer),actor=registered?.actor;return registered&&actor instanceof AdmissionRoutingActor?actor.remember(sessionId,this.fanout.checkpoints,registered.socketEpoch):void 0}registerSubscription(peer,admissionId,subscriptionId){let actor=this.fanout.get(peer)?.actor;if(!(actor instanceof AdmissionRoutingActor))return;actor.subscriptions.set(subscriptionId,admissionId),actor.mirrorOwners.set(subscriptionId,admissionId);let pending=this.status.pendingBuffer(subscriptionId);pending&&actor.pendingMirrors.set(admissionId,pending);for(let sessionId of this.status.requiredSessions(peer))this.prepareDelivery(sessionId);this.status.onSubscriptionEnd=(owner,id)=>this.retireMirror(owner,id),actor.mirrorAdmissions=(sessionId,type)=>{let ids=this.status.mirrorAdmissions(peer,sessionId,type),socketEpoch=this.socketEpochOf(peer),lane=this.recoveryLane(sessionId);return ids.filter(id=>!lane||lane.retired?actor.remember(sessionId,this.recoveryCheckpoints,socketEpoch??"")?.routes.includes(id)===!0:(socketEpoch&&this.recoveryCheckpoints.stream({socketEpoch,sessionId})?.routes.includes(id)||socketEpoch&&lane&&this.recoveryCheckpoints.freeze({socketEpoch,sessionId,peer,admissionId:id,routeKind:"mirror"},lane,!0).ok||(actor.pendingMirrors.get(id)?.retire("storage_unavailable"),process.stderr.write(`senpi rpc mirror checkpoint unavailable (${type}); closing connection
|
|
12
|
-
`),this.fanout.get(peer)?.connection.close?.()),!0))}}retireMirror(peer,subscriptionId){let registered=this.fanout.get(peer),actor=registered?.actor;if(!(actor instanceof AdmissionRoutingActor)||!registered)return;let admissionId=actor.mirrorOwners.get(subscriptionId);if(admissionId!==void 0){actor.pendingMirrors.get(admissionId)?.retire(),actor.pendingMirrors.delete(admissionId),actor.mirrorOwners.delete(subscriptionId),this.unregisterSubscription(peer,subscriptionId);for(let sessionId of this.fanout.acceptance.keys())this.recoveryCheckpoints.retireRoute({socketEpoch:registered.socketEpoch,sessionId},admissionId,"mirror_unsubscribed")}}unregisterSubscription(peer,subscriptionId){let registered=this.fanout.get(peer),actor=registered?.actor;if(!(actor instanceof AdmissionRoutingActor))return;let admissionId=actor.subscriptions.get(subscriptionId);actor.subscriptions.delete(subscriptionId),admissionId!==void 0&®istered&&this.recoveryEvents?.forgetAdmission({socketEpoch:registered.socketEpoch,sessionId:subscriptionId},admissionId)}isCompactSubscription(peer,admissionId,subscriptionId){let actor=this.fanout.get(peer)?.actor;return typeof admissionId=="string"&&actor instanceof AdmissionRoutingActor&&(actor.subscriptions.get(subscriptionId)===admissionId||[...actor.mirrorOwners.values()].includes(admissionId)&&this.recoveryCheckpoints.stream({socketEpoch:this.socketEpochOf(peer)??"",sessionId:subscriptionId})?.routes.includes(admissionId)===!0)}registerAdmission(peer,admissionId,sessionId){let registered=this.fanout.get(peer);registered?.actor instanceof AdmissionRoutingActor&&(registered.actor.admissions.add(admissionId),registered.actor.remember(sessionId,this.fanout.checkpoints,registered.socketEpoch))}installAdmissionBaseline(peer,cursor,live){let actor=this.fanout.get(peer)?.actor;actor?actor.installBaseline(cursor,live):cursor.release()}recoveryLane(sessionId){return this.fanout.acceptance.get(sessionId)}routesAdmission(socketEpoch,admissionId){return this.recoveryCheckpoints.routesAdmission(socketEpoch,admissionId)}supersedeOpen(peer,sessionId,admissionId,end){let registered=this.fanout.get(peer),actor=registered?.actor;if(!registered||!(actor instanceof AdmissionRoutingActor))return;let previous=actor.opened.get(sessionId);actor.opened.set(sessionId,{admissionId,end});let stream=this.recoveryCheckpoints.stream({socketEpoch:registered.socketEpoch,sessionId});return previous&&previous.admissionId!==admissionId&&stream?.routes.includes(previous.admissionId)?previous.end:void 0}detachConnectionFromSession(id,sessionId){let registered=this.fanout.get(id),actor=registered?.actor,opened=actor instanceof AdmissionRoutingActor?actor.opened.get(sessionId):void 0,caller=registered&&{socketEpoch:registered.socketEpoch,sessionId};if(caller&&actor instanceof AdmissionRoutingActor&&opened&&actor.opened.delete(sessionId),caller&&actor instanceof AdmissionRoutingActor&&opened&&this.routesStream(caller,opened.admissionId)){let retire=()=>{this.recoveryCheckpoints.retireRoute(caller,opened.admissionId,"client_detach"),actor.admissions.delete(opened.admissionId)},request=captureAdmissionReply();request?.id!==void 0&&request.peer===id&&request.admissionId===opened.admissionId?actor.deferRetire(request.id,retire):retire()}super.detachConnectionFromSession(id,sessionId)}routesStream(caller,admissionId){return this.recoveryCheckpoints.stream(caller)?.routes.includes(admissionId)===!0}get openLegacyViews(){return this.fanout.replay.openCursors}get recoveryCheckpoints(){return this.fanout.checkpoints}get recoveryPages(){return this.fanout.pages}get recoveryEvents(){return this.fanout.events}socketEpochOf(id){return this.fanout.get(id)?.socketEpoch}};import{randomUUID as randomUUID5}from"node:crypto";var TERMINAL_PHASE="completed-awaiting-entry",CALL_RECORDS=new Set(["tool_execution_start","tool_execution_update","tool_execution_end","tool_hook_status","turn_end","agent_settled","message_end"]),CALL_ONLY_RECORDS=new Set(["tool_execution_update","tool_execution_end","tool_hook_status","agent_settled"]);function runtimeItemKey(scope,creationSequence,k){return`${scope.sessionEpoch}:${creationSequence}.${k}`}function callOrder(creationSequence,k){return`${String(creationSequence).padStart(16,"0")}.${String(k).padStart(4,"0")}`}function callLeaves(call){return[call.hook?.owner??0,call.progress?.owner??0,call.result?.owner??0,...call.raw?.kind==="owned"?[call.raw.root,call.raw.tailRoot]:[]]}function terminal(call){return call.phase===TERMINAL_PHASE}var COMPONENT_RECORDS=new Set(["agent_start","agent_end","session_lifecycle","extension_ui_request","question_updated","question_resolved","ui_request_settled"]),TARGETED=new Set(["select","confirm","input","editor"]),field2=(record,key)=>Reflect.get(record,key),deadline=record=>{let value=field2(record,"deadlineAtMs");return typeof value=="number"?{deadlineAtMs:value}:{}},CompactCurrentComponents=class{constructor(store){this.runState="idle",this.dialogs={header:void 0,ref:void 0},this.open=new Map,this.opened=0,this.store=store,this.values=new CompactValues(store),this.dialogRoots=new CompactComponentRoots(store,()=>[])}get openBroadcast(){let count=0;for(let{dialog}of this.open.values())dialog.audience==="broadcast"&&count++;return count}apply(record){switch(field2(record,"type")){case"agent_start":case"agent_end":this.runState=field2(record,"type")==="agent_start"?"running":"idle";return;case"session_lifecycle":{let next=this.values.own(record);this.lifecycle&&this.store.adjust(this.lifecycle.owner,-1,0),this.lifecycle=next;return}case"extension_ui_request":{let id=field2(record,"id"),method=String(field2(record,"method"));if(typeof id!="string"||method!=="question"&&!TARGETED.has(method)||this.open.has(id))return;let broadcast=method==="question",dialog={id,audience:broadcast?"broadcast":"targeted",method,...deadline(record),...broadcast?{request:record}:{}};return this.put(id,String(this.opened++).padStart(16,"0"),dialog)}case"question_updated":{let id=String(field2(record,"id")),open6=this.open.get(id);open6&&this.put(id,open6.order,{...open6.dialog,...deadline(record)});return}default:{let id=String(field2(record,"id")??field2(record,"uiRequestId")),open6=this.open.get(id);if(!open6)return;this.dialogs=this.dialogRoots.set(this.dialogs,open6.order,void 0),this.open.delete(id)}}}freeze(){for(let ref of[this.lifecycle,this.dialogs.ref])ref&&this.store.adjust(ref.owner,0,1);let broadcast=this.openBroadcast;return{runState:this.runState,lifecycle:this.lifecycle,dialogs:this.dialogs.ref,dialogCounts:{broadcast,targeted:this.open.size-broadcast}}}release(frozen){for(let ref of[frozen.lifecycle,frozen.dialogs])ref&&this.store.adjust(ref.owner,0,-1)}async read(frozen,valid){let lifecycle=frozen.lifecycle?await this.values.read(frozen.lifecycle,valid):null;valid();let dialogs=[];for await(let[,dialog]of this.dialogRoots.entries(frozen.dialogs,valid))dialogs.push(dialog);return{runState:frozen.runState,lifecycle,dialogs,dialogCounts:frozen.dialogCounts}}put(id,order,dialog){this.dialogs=this.dialogRoots.set(this.dialogs,order,dialog),this.open.set(id,{order,dialog})}};var SEQUENCED=new Set(["agent_start","agent_end","turn_start","turn_end","message_start","message_update","message_end","tool_execution_start","tool_execution_update","tool_execution_end","entry_appended","session_abort","transcript_write_failed",...COMPONENT_RECORDS,...CALL_RECORDS]);function field3(record,key){return key in record?Reflect.get(record,key):void 0}function turnScoped(type,record){if(type==="turn_end"||type.startsWith("tool_execution_"))return!0;if(!type.startsWith("message_"))return!1;let role=field3(Object(field3(record,"message")),"role");return role==="assistant"||role==="toolResult"}function admitRecord(current,record,type,at,folds=!0){let turnId=type==="turn_start"||at.turnId===null&&turnScoped(type,record)?randomUUID5():at.turnId,next=at.sequence+1,call=folds&&CALL_RECORDS.has(type)?current.foldCall(record,next,turnId):void 0;if(!(call&&!call.changed&&CALL_ONLY_RECORDS.has(type)))return{sequence:next,turnId,call}}function correlationChange(standing,turnId,record){let identified="clientMessageId"in record||"clientTurnId"in record;if(!identified&&(standing===null||!correlatedRecord(record))||!identified&&turnId!==null&&field3(record,"type")!=="turn_start")return;let next={clientMessageId:field3(record,"clientMessageId"),clientTurnId:field3(record,"clientTurnId"),clientMessages:field3(record,"clientMessages")},current=standing,currentMessages=current?.clientMessages,nextMessages=next.clientMessages;if(!(current!==null&¤t.clientMessageId===next.clientMessageId&¤t.clientTurnId===next.clientTurnId&&(currentMessages===nextMessages||Array.isArray(currentMessages)&&Array.isArray(nextMessages)&¤tMessages.length===nextMessages.length&¤tMessages.every((identity,index)=>field3(Object(identity),"clientMessageId")===field3(Object(nextMessages[index]),"clientMessageId")&&field3(Object(identity),"clientTurnId")===field3(Object(nextMessages[index]),"clientTurnId")))))return next}var MATERIALIZER_ENVELOPE_MAX_BYTES=16384;function materializerLine(fanout,required,peer,sessionId,record){let lane=fanout.acceptance.get(sessionId),registered=fanout.get(peer);if(!lane||!registered||!fanout.events)return;let caller={socketEpoch:registered.socketEpoch,sessionId},stream=fanout.checkpoints.stream(caller);if(!stream?.routes.length||!SEQUENCED.has(String(Reflect.get(record,"type"))))return;let routes=required.routes(peer,sessionId,String(Reflect.get(record,"type")));if(!routes.length)return;let at={sessionEpoch:lane.sessionEpoch,sequence:lane.acceptedSequence},owner=routes[0],content=compactDelta(record)?demoteToDeltaOnly(record):record,minted2=fanout.events.mint({...caller,admissionId:owner},at,record,{chunks:()=>payload(content)});if(!minted2.ok)return registered.connection.close?.(),{line:serializeJsonLine({type:"event_lease_refused",sessionId,reason:minted2.reason}),atomic:!0,undelivered:()=>{}};let held=fanout.events.claim(caller,minted2.value.id,owner);if(held.ok)for(let route of routes)held.value.admissions.add(route);let seed=required.takeSeed(peer,sessionId),line=serializeJsonLine({type:Reflect.get(record,"type"),sessionId,eventLease:minted2.value,materializer:{...at,generation:stream.generation,payload:minted2.value,controls:seed?[{kind:"seed",token:seed.id,sequence:seed.cut.sequence}]:[]}});if(Buffer.byteLength(line)+512>MATERIALIZER_ENVELOPE_MAX_BYTES)throw fanout.events.abandon(caller.socketEpoch,minted2.value.id),new RangeError("materializer envelope exceeded H");return{line,atomic:!0,undelivered:written=>{written||fanout.events?.abandon(caller.socketEpoch,minted2.value.id)}}}function payload(record){return jsonChunks(record,65536)}var RecordLine=class{constructor(record,encoded){this.record=record,this.encoded=encoded}get text(){return this.encoded??=serializeJsonLine(this.record),this.encoded}get built(){return this.encoded}},SessionEventWriterDestinations=class extends SessionEventWriterRecovery{deliver(sessionId,record,tagged,line,targets,mirrors,isTargeted,current){let redacted=targets.some(target=>this.fanout.connectionHas(target,MEDIA_PLACEHOLDERS_CAPABILITY))?omitNormalInlineMedia(tagged,this.mediaPersisters.get(sessionId)):tagged,placeholderLine=redacted===tagged?void 0:serializeJsonLine(redacted),placeholder=new RecordLine(redacted,placeholderLine);!isTargeted&&!this.fanout.acceptance.has(sessionId)&&this.fanout.rememberSnapshot(sessionId,tagged,line.text,placeholderLine);for(let target of targets){if(target!==void 0&&!this.fanout.get(target))continue;let registered=target===void 0?void 0:this.fanout.get(target),wants=placeholderLine!==void 0&&this.fanout.connectionHas(target,MEDIA_PLACEHOLDERS_CAPABILITY);if(registered&&target!==void 0){let out=this.eventLine(target,sessionId,wants?redacted:tagged,wants?placeholder:line),keyed=!out.atomic&&compactDelta(tagged)!==void 0&&tagged.message!==null;registered.actor.enqueue(out.line,keyed?MESSAGE_KEY:void 0,out.undelivered,keyed?serializeJsonLine(demoteToDeltaOnly(tagged)):void 0,isCorrelatedReply(tagged),mirrors.includes(target)?void 0:this.fanout.attachmentOf(target,sessionId,isTargeted,record.type),current)}else this.appendSessionRecord(sessionId,wants?redacted:tagged,target)}}eventLine(target,sessionId,record,line){let reply=declarationReply(record,this.compactSelection(target));if(reply!==void 0&&reply!==record)return{line:serializeJsonLine(reply)};let events=this.fanout.events,lane=this.fanout.acceptance.get(sessionId);if(!lane&&this.compactSelection(target)?.selected&&this.status.mirrorTargets(sessionId,String(Reflect.get(record,"type"))).includes(target))return{line:serializeJsonLine({type:"compact_refused",sessionId,reason:"compact_endpoint_unsupported"}),undelivered:()=>this.fanout.get(target)?.connection.close?.()};let admissionId=this.ordinaryRoute(target,sessionId)?.routes[0]??this.fanout.admissionOf(target,sessionId),socketEpoch=this.fanout.get(target)?.socketEpoch;if(!events||!lane||admissionId===void 0||socketEpoch===void 0)return{line:line.text};if(!this.fanout.connectionHas(target,COMPACT_EVENTS_CAPABILITY))return{line:line.text};let materializer=materializerLine(this.fanout,this.required,target,sessionId,record);if(materializer)return materializer;let built=line.built,size=built===void 0?jsonSize(record):{bytes:Buffer.byteLength(built)-1,units:built.length-1};if(size.bytes+1<=COMPACT_RECORD_MAX_BYTES)return{line:line.text};let at={sessionEpoch:lane.sessionEpoch,sequence:lane.acceptedSequence},routes=this.ordinaryRoute(target,sessionId)?.routes??[],owner=routes[0]??admissionId,minted2=events.mint({socketEpoch,sessionId,admissionId:owner},at,record,built??size);if(minted2.ok){let{id}=minted2.value,held=events.claim({socketEpoch,sessionId},id,owner);if(held.ok)for(let route of routes)held.value.admissions.add(route);return{line:serializeJsonLine({type:Reflect.get(record,"type"),sessionId,eventLease:minted2.value}),undelivered:written=>{written||events.abandon(socketEpoch,id)}}}return process.stderr.write(`senpi rpc connection ${target} event lease refused (${minted2.reason}); closing
|
|
13
|
-
`),this.fanout.get(target)?.connection.close?.(),{line:serializeJsonLine({type:"event_lease_refused",sessionId,reason:minted2.reason})}}};var SessionEventWriter=class extends SessionEventWriterDestinations{secretInputRoute(sessionId){return this.secretPresentations.route(sessionId)}setSoleSecretCapabilities(capabilities){this.secretPresentations.handshake(capabilities)}handleMcpForm(value){if(!this.presenterAuthority||typeof value!="object"||value===null||!("type"in value)||typeof value.type!="string"||!value.type.startsWith("mcp_form_")&&value.type!=="mcp_presenter_context")return!1;let id=this.currentConnection(),sender=id===void 0?void 0:this.presenterConnections.get(id),context=value.type==="mcp_presenter_context"&&"sessionId"in value&&typeof value.sessionId=="string"&&sender?this.presenterAuthority?.connectionContext(sender,value.sessionId):void 0,reply=value.type==="mcp_presenter_context"?context?{ok:!0,context}:{error:"presenter_not_authorized"}:sender&&this.presenterAuthority?this.presenterAuthority.receive(sender,value):{error:"presenter_not_authorized"},connection=id===void 0?void 0:this.fanout.get(id)?.connection;if(connection)try{connection.writeRaw(serializeJsonLine({type:"mcp_form_reply",..."id"in value&&typeof value.id=="string"?{id:value.id}:{},...reply}))}catch{sender&&this.presenterAuthority?.detach(sender)}return!0}enqueue(sessionId,value){if(declarationReply(value,void 0)===void 0)return!0;if(this.sealedSessions.has(sessionId))return!1;let targetId=this.connectionContext.getStore(),record=normalizeJsonValue(value).value,isTargeted=this.isTargetedRecord(record),current=isTargeted?this.connectionContext.currentGuard():void 0;if(current?.()===!1)return!0;let tagged={...observeLifecycleDelivery(record),sessionId},line=new RecordLine(tagged);if(record.type==="snapshot_marker"||record.type==="ui_request_pending"||record.type==="ui_request_settled"){let targets2=record.type==="snapshot_marker"?this.status.mirrorTargets(sessionId,"snapshot_marker").filter(id=>id===targetId):this.status.dialogTargets(sessionId);for(let target of targets2)this.fanout.get(target)?.actor.enqueue(line.text);return targets2.length>0&&this.requestFlush(),!0}if(this.fanout.isEmpty()&&this.exceedsStdioCapacity(line.text))return this.closeSession(sessionId,{type:"response",command:"close_session",success:!1,error:"session_output_overflow, resync required"},"error"),!1;this.openTurns.note(sessionId,record.type,record.reason);let attached=this.fanout.targets(sessionId,targetId,isTargeted,record.type),mirrors=isTargeted?[]:this.status.mirrorTargets(sessionId,String(record.type)),targets=mirrors.length===0?attached:[...new Set([...attached,...mirrors])];this.deliver(sessionId,record,tagged,line,targets,mirrors,isTargeted,current);let cause=isTargeted?void 0:causeOfRecord(record);return cause!==void 0&&this.status.publish(sessionId,cause,this.changeActor("agent")),this.afterRecord?.(sessionId),this.requestFlush(),!0}publishLoadedSurfacesChanged(sessionId,previous,digest2){if(this.fanout.isEmpty()){this.enqueue(sessionId,{type:"loaded_surfaces_changed"});return}if(this.sealedSessions.has(sessionId))return;let line=serializeJsonLine({type:"loaded_surfaces_changed",sessionId});for(let id of this.fanout.attachedConnections(sessionId)){if(!this.surfaceDedupe.announce(id,sessionId,previous,digest2))continue;let held=this.fanout.attachmentOf(id,sessionId,!1,"loaded_surfaces_changed");this.fanout.get(id)?.actor.enqueue(line,void 0,void 0,void 0,!1,held)}this.requestFlush()}enqueueControl(value,targetOverride){let peer=targetOverride??this.currentConnection(),reply=declarationReply(value,peer===void 0?void 0:this.compactSelection(peer));if(reply===void 0)return Promise.resolve();if(value=reply,this.failure!==void 0)return Promise.reject(this.failure);let targetId=targetOverride??this.connectionContext.getStore(),registered=targetId===void 0?void 0:this.fanout.get(targetId);if(registered)return registered.actor.enqueue(serializeJsonLine(value),void 0,void 0,void 0,isCorrelatedReply(value)),this.requestFlush(),Promise.resolve();if(this.exceedsStdioCapacity(serializeJsonLine(value)))return this.controlOverflowReported||(this.controlOverflowReported=!0,this.records.append(this.controlQueue,{type:"overflow",error:"rpc_control_output_overflow, resync required"}),this.markReady(this.controlQueue),this.requestFlush()),Promise.reject(new Error("rpc_control_output_overflow, resync required"));let queue=targetId===void 0?this.controlQueue:this.connectionQueue(targetId),completion=new Promise((resolve2,reject)=>{this.records.append(queue,{...value},void 0,resolve2,reject)});return this.markReady(queue),this.requestFlush(),completion}sendOpenQueued(connection,record){let wire={type:"queued",for_request:record.for_request,position:record.position,in_flight:record.in_flight},target=this.fanout.get(connection);target!==void 0&&(target.actor.enqueue(serializeJsonLine(wire)),this.requestFlush())}broadcastHostRecord(record){let wire;switch(record.type){case"host_superseded":wire={type:"host_superseded",instanceId:record.instanceId,generation:record.generation,successor:record.successor};break;case"host_stalled":wire={type:"host_stalled",driftMs:record.driftMs,...record.sessionId!==void 0?{sessionId:record.sessionId}:{},...record.tool!==void 0?{tool:record.tool}:{}};break;case"host_memory_pressure":wire={type:"host_memory_pressure",rssMb:record.rssMb,...record.footprintMb!==void 0?{footprintMb:record.footprintMb}:{},...record.measure!==void 0?{measure:record.measure}:{},sessions:record.sessions,...record.main!==void 0?{main:record.main}:{},...record.kernels!==void 0?{kernels:record.kernels}:{}};break;case"host_trimmed":wire={type:"host_trimmed",footprintBeforeMb:record.footprintBeforeMb,footprintAfterMb:record.footprintAfterMb,measure:record.measure,collected:record.collected,sessions:record.sessions,pauseMs:record.pauseMs};break;case"subscription_limits":wire={type:"subscription_limits",provider:record.provider,account:record.account,windows:record.windows,reportedAt:record.reportedAt,...record.plan===void 0?{}:{plan:record.plan},...record.error===void 0?{}:{error:record.error}};break;default:{let exhaustive=record;throw new Error(`unexpected host record ${exhaustive}`)}}this.fanout.isEmpty()?(this.records.append(this.controlQueue,wire),this.markReady(this.controlQueue)):this.fanout.broadcast(serializeJsonLine(wire)),this.requestFlush()}parkSession(sessionId,sessionPath,reason){this.sealLifecycle(sessionId,{type:"session_parked",sessionId,sessionPath,reason})}releaseSession(sessionId,sessionPath){this.sealLifecycle(sessionId,{type:"session_closed",sessionId,reason:"released",sessionPath})}settleBeforeSeal(sessionId){if(this.sealedSessions.has(sessionId))return!1;for(let owed=this.openTurns.take(sessionId);owed>0;owed-=1)this.enqueue(sessionId,{type:"agent_settled",reason:"session_closed"});return!this.sealedSessions.has(sessionId)}};function socketSink(socket){let needsDrain=!1,cut=!1;return{writeRaw(chunk){!cut&&!socket.destroyed&&(needsDrain=!socket.write(chunk))},close(){if(cut||(cut=!0,socket.destroyed))return;socket.end();let grace=setTimeout(()=>socket.destroy(),5e3);grace.unref(),socket.once("close",()=>clearTimeout(grace))},waitForBackpressure(){return socket.destroyed||!needsDrain?Promise.resolve():(needsDrain=!1,new Promise(resolve2=>{let done=()=>{socket.off("drain",done),socket.off("close",done),resolve2()};socket.once("drain",done),socket.once("close",done)}))}}}var SESSION_CONTEXT_PATCH_LIMITS={keyPattern:/^[a-z][a-z0-9_]{0,63}$/,valueChars:256,overlayBytes:4096},RESERVED_SESSION_CONTEXT_KEYS=new Set(["host_socket","host_instance","shard_key","tree_key","parent_session_id","root_session_id"]);function refuse(reason,action){return{refusal:{reason,action}}}function applyContextPatch(overlay,patch){let shape='send patch as an object of lowercase keys to string, number, boolean or null values, e.g. { "task_status": "running" }';if(typeof patch!="object"||patch===null||Array.isArray(patch))return refuse("patch must be an object",shape);let entries=Object.entries(patch);if(entries.length===0)return refuse("patch has no keys",shape);let merged={...overlay};for(let[key,value]of entries){if(!SESSION_CONTEXT_PATCH_LIMITS.keyPattern.test(key))return refuse(`key "${key}" must match ${SESSION_CONTEXT_PATCH_LIMITS.keyPattern.source}`,"rename the key to lowercase letters, digits and underscores");if(RESERVED_SESSION_CONTEXT_KEYS.has(key))return refuse(`key "${key}" is set by the host and cannot be patched`,"drop that key from the patch; the host keeps it current");if(typeof value=="string"&&value.length>SESSION_CONTEXT_PATCH_LIMITS.valueChars)return refuse(`value for "${key}" is ${value.length} characters, at most ${SESSION_CONTEXT_PATCH_LIMITS.valueChars} are accepted`,"shorten the value or store it elsewhere and publish a reference");if(typeof value=="number"&&!Number.isFinite(value))return refuse(`value for "${key}" must be a finite number`,shape);if(value!==null&&typeof value!="string"&&typeof value!="number"&&typeof value!="boolean")return refuse(`value for "${key}" must be a string, number, boolean or null`,shape);merged[key]=value}let bytes=Buffer.byteLength(JSON.stringify(merged));return bytes>SESSION_CONTEXT_PATCH_LIMITS.overlayBytes?refuse(`patched context would be ${bytes} bytes, at most ${SESSION_CONTEXT_PATCH_LIMITS.overlayBytes} are accepted`,"remove keys with null or shorten values before adding more"):{overlay:merged}}function publishedSessionContext(base,overlay){if(overlay===void 0)return base;let published={...base};for(let[key,value]of Object.entries(overlay))value===null?delete published[key]:published[key]=value;return published}function modelOf(model){return model===void 0?void 0:{provider:model.provider,id:model.id}}function sessionRuntimeView(session,pendingQuestions){let model=modelOf(session.model);return{isStreaming:session.isStreaming===!0,isCompacting:session.isCompacting===!0,...model!==void 0?{model}:{},...session.thinkingLevel!==void 0?{thinkingLevel:session.thinkingLevel}:{},steering:typeof session.getSteeringMessages=="function"?session.getSteeringMessages().length:0,followUp:typeof session.getFollowUpMessages=="function"?session.getFollowUpMessages().length:0,pendingQuestions:pendingQuestions??sessionQuestionBridges.get(session)?.pendingQuestions()?.length??0}}function runtimeView(entry){let session=entry.runtime?.session;if(session!==void 0)return sessionRuntimeView(session);let state=entry.worker?.snapshot?.state;if(state===void 0)return;let model=modelOf(state.model??void 0);return{isStreaming:state.isStreaming,isCompacting:state.isCompacting,...model!==void 0?{model}:{},...state.thinkingLevel!==void 0?{thinkingLevel:state.thinkingLevel}:{},steering:state.steering.length,followUp:state.followUp.length,pendingQuestions:state.pendingQuestions?.length??0}}function entryView(entry){let session=entry.runtime?.session,state=entry.worker?.snapshot?.state,durableSessionId=session?.sessionId??state?.sessionId??entry.durableSessionId,sessionPath=session?.sessionFile??state?.sessionFile??entry.sessionPath,name=session?.sessionManager.getSessionName()??state?.sessionName;return{state:entry.state,kind:entry.kind,cwd:entry.cwd,attachments:entry.attachments,...durableSessionId!==void 0?{durableSessionId}:{},...sessionPath!==void 0?{sessionPath}:{},...name!==void 0?{name}:{},context:publishedSessionContext(entry.context,entry.contextOverlay),openContext:entry.context}}function registryStatusSource(registry){return{sessionIds:()=>registry.list().map(row=>row.sessionId),entryView:sessionId=>{let entry=registry.peek(sessionId);return entry===void 0?void 0:entryView(entry)},view:sessionId=>{let entry=registry.peek(sessionId);if(entry===void 0)return;let runtime=runtimeView(entry);return runtime===void 0?{entry:entryView(entry)}:{entry:entryView(entry),runtime}}}}function refusal2(id,command,code,detail){return{id,type:"response",command,success:!1,error:`${code}: ${detail.reason}`,errorCode:code,errorData:{reason:detail.reason,action:detail.action}}}function answerSubscribeSessions(command,connectionId,stream,snapshotSink){if(connectionId===void 0)return{answer:refusal2(command.id,command.type,RPC_ERROR_UNSUPPORTED_TRANSPORT,{reason:"stdio has no per-connection identity to deliver a subscription to",action:"connect to the host socket (senpi --mode rpc --listen) and subscribe there"})};if(stream.connectionSize(connectionId)>=MAX_SUBSCRIPTIONS_PER_CONNECTION)return{answer:refusal2(command.id,command.type,RPC_ERROR_SUBSCRIPTION_LIMIT,{reason:`this connection already holds ${MAX_SUBSCRIPTIONS_PER_CONNECTION} subscriptions`,action:"unsubscribe_sessions the ones you no longer read, then subscribe again"})};let parsed=parseSubscription(command);if("refusal"in parsed)return{answer:refusal2(command.id,command.type,RPC_ERROR_INVALID_SUBSCRIPTION,parsed.refusal)};let options=snapshotSink?{...parsed.options,admissionId:command.admissionId}:parsed.options,subscribed=stream.subscribe(connectionId,options,snapshotSink);return{answer:{id:command.id,type:"response",command:"subscribe_sessions",success:!0,data:{subscriptionId:subscribed.subscriptionId,snapshot:subscribed.snapshot,seq:subscribed.seq,hostGeneration:String(hostGeneration(process.env)),hostInstanceId:hostInstanceId()}},activate:subscribed.subscriptionId}}function answerUnsubscribeSessions(command,connectionId,stream){return connectionId===void 0?refusal2(command.id,command.type,RPC_ERROR_UNSUPPORTED_TRANSPORT,{reason:"stdio has no per-connection identity holding any subscription",action:"connect to the host socket (senpi --mode rpc --listen) and manage subscriptions there"}):typeof command.subscriptionId=="string"&&stream.unsubscribe(connectionId,command.subscriptionId)?{id:command.id,type:"response",command:"unsubscribe_sessions",success:!0}:refusal2(command.id,command.type,RPC_ERROR_UNKNOWN_SUBSCRIPTION,{reason:"this connection holds no subscription with that id",action:"send the subscriptionId your subscribe_sessions answer returned, on the same connection"})}function notAttachedRefusal(command){return refusal2(command.id,command.type,RPC_ERROR_SESSION_NOT_ATTACHED,{reason:"this connection is not attached to that session",action:"attach first with open_session { sessionPath }, then patch its context"})}function answerSetSessionContext(command,entry,stream){let applied=applyContextPatch(entry.contextOverlay,command.patch);return"refusal"in applied?refusal2(command.id,command.type,RPC_ERROR_INVALID_SESSION_CONTEXT,applied.refusal):(entry.contextOverlay=applied.overlay,stream.publish(command.sessionId,"context","client",!0),{id:command.id,type:"response",command:"set_session_context",success:!0,data:{context:publishedSessionContext(entry.context,entry.contextOverlay)}})}export{applyContextPatch,publishedSessionContext,parseBoundedId,protocolId,CompactReadError,CompactReadLease,privateRootStat,recoveryAgentDir,RecoveryStorageHealth,CompactStorageReadError,CompactCommitDependencies,COMPACT_LEAF_CODE_UNITS,CompactWriteError,CompactContentStore,FRAGMENT_MAX_BYTES,FRAGMENT_ENVELOPE_MAX_BYTES,TRANSFER_STAGING_MAX_BYTES,TransferStagingError,TransferStaging,AcceptedTranscript,CompactIndexTree,CompactValues,TERMINAL_PHASE,CALL_RECORDS,runtimeItemKey,callOrder,callLeaves,terminal,CompactComponentRoots,COMPONENT_RECORDS,CompactCurrentComponents,SEQUENCED,field3 as field,admitRecord,correlationChange,recordLoopBlockedMs,enqueueLegacyRecord,sessionRuntimeView,registryStatusSource,GeneratedFramesCursor,jsonChunks,refusal2 as refusal,answerSubscribeSessions,answerUnsubscribeSessions,notAttachedRefusal,answerSetSessionContext,captureAdmissionReply,withAdmissionReply,withAdmissionRequest,storageUnavailable,SessionEventWriter,socketSink};
|
|
12
|
+
`),this.fanout.get(peer)?.connection.close?.()),!0))}}retireMirror(peer,subscriptionId){let registered=this.fanout.get(peer),actor=registered?.actor;if(!(actor instanceof AdmissionRoutingActor)||!registered)return;let admissionId=actor.mirrorOwners.get(subscriptionId);if(admissionId!==void 0){actor.pendingMirrors.get(admissionId)?.retire(),actor.pendingMirrors.delete(admissionId),actor.mirrorOwners.delete(subscriptionId),this.unregisterSubscription(peer,subscriptionId);for(let sessionId of this.fanout.acceptance.keys())this.recoveryCheckpoints.retireRoute({socketEpoch:registered.socketEpoch,sessionId},admissionId,"mirror_unsubscribed")}}unregisterSubscription(peer,subscriptionId){let registered=this.fanout.get(peer),actor=registered?.actor;if(!(actor instanceof AdmissionRoutingActor))return;let admissionId=actor.subscriptions.get(subscriptionId);actor.subscriptions.delete(subscriptionId),admissionId!==void 0&®istered&&this.recoveryEvents?.forgetAdmission({socketEpoch:registered.socketEpoch,sessionId:subscriptionId},admissionId)}isCompactSubscription(peer,admissionId,subscriptionId){let actor=this.fanout.get(peer)?.actor;return typeof admissionId=="string"&&actor instanceof AdmissionRoutingActor&&(actor.subscriptions.get(subscriptionId)===admissionId||[...actor.mirrorOwners.values()].includes(admissionId)&&this.recoveryCheckpoints.stream({socketEpoch:this.socketEpochOf(peer)??"",sessionId:subscriptionId})?.routes.includes(admissionId)===!0)}registerAdmission(peer,admissionId,sessionId){let registered=this.fanout.get(peer);registered?.actor instanceof AdmissionRoutingActor&&(registered.actor.admissions.add(admissionId),registered.actor.remember(sessionId,this.fanout.checkpoints,registered.socketEpoch))}installAdmissionBaseline(peer,cursor,live){let actor=this.fanout.get(peer)?.actor;actor?actor.installBaseline(cursor,live):cursor.release()}recoveryLane(sessionId){return this.fanout.acceptance.get(sessionId)}routesAdmission(socketEpoch,admissionId){return this.recoveryCheckpoints.routesAdmission(socketEpoch,admissionId)}supersedeOpen(peer,sessionId,admissionId,end){let registered=this.fanout.get(peer),actor=registered?.actor;if(!registered||!(actor instanceof AdmissionRoutingActor))return;let previous=actor.opened.get(sessionId);actor.opened.set(sessionId,{admissionId,end});let stream=this.recoveryCheckpoints.stream({socketEpoch:registered.socketEpoch,sessionId});return previous&&previous.admissionId!==admissionId&&stream?.routes.includes(previous.admissionId)?previous.end:void 0}detachConnectionFromSession(id,sessionId){let registered=this.fanout.get(id),actor=registered?.actor,opened=actor instanceof AdmissionRoutingActor?actor.opened.get(sessionId):void 0,caller=registered&&{socketEpoch:registered.socketEpoch,sessionId};if(caller&&actor instanceof AdmissionRoutingActor&&opened&&actor.opened.delete(sessionId),caller&&actor instanceof AdmissionRoutingActor&&opened&&this.routesStream(caller,opened.admissionId)){let retire=()=>{this.recoveryCheckpoints.retireRoute(caller,opened.admissionId,"client_detach"),actor.admissions.delete(opened.admissionId)},request=captureAdmissionReply();request?.id!==void 0&&request.peer===id&&request.admissionId===opened.admissionId?actor.deferRetire(request.id,retire):retire()}super.detachConnectionFromSession(id,sessionId)}routesStream(caller,admissionId){return this.recoveryCheckpoints.stream(caller)?.routes.includes(admissionId)===!0}get openLegacyViews(){return this.fanout.replay.openCursors}get recoveryCheckpoints(){return this.fanout.checkpoints}get recoveryPages(){return this.fanout.pages}get recoveryEvents(){return this.fanout.events}socketEpochOf(id){return this.fanout.get(id)?.socketEpoch}};import{randomUUID as randomUUID5}from"node:crypto";var TERMINAL_PHASE="completed-awaiting-entry",CALL_RECORDS=new Set(["tool_execution_start","tool_execution_update","tool_execution_end","tool_hook_status","turn_end","agent_settled","message_end"]),CALL_ONLY_RECORDS=new Set(["tool_execution_update","tool_execution_end","tool_hook_status","agent_settled"]);function runtimeItemKey(scope,creationSequence,k){return`${scope.sessionEpoch}:${creationSequence}.${k}`}var CALL_UNKNOWN=Object.freeze({callUnknown:!0});function callIdentity(call){return call?{runtimeItemKey:call.runtimeItemKey}:CALL_UNKNOWN}function callOrder(creationSequence,k){return`${String(creationSequence).padStart(16,"0")}.${String(k).padStart(4,"0")}`}function callLeaves(call){return[call.hook?.owner??0,call.progress?.owner??0,call.result?.owner??0,...call.raw?.kind==="owned"?[call.raw.root,call.raw.tailRoot]:[]]}function terminal(call){return call.phase===TERMINAL_PHASE}var COMPONENT_RECORDS=new Set(["agent_start","agent_end","session_lifecycle","extension_ui_request","question_updated","question_resolved","ui_request_settled"]),TARGETED=new Set(["select","confirm","input","editor"]),field2=(record,key)=>Reflect.get(record,key),deadline=record=>{let value=field2(record,"deadlineAtMs");return typeof value=="number"?{deadlineAtMs:value}:{}},CompactCurrentComponents=class{constructor(store){this.runState="idle",this.dialogs={header:void 0,ref:void 0},this.open=new Map,this.opened=0,this.store=store,this.values=new CompactValues(store),this.dialogRoots=new CompactComponentRoots(store,()=>[])}get openBroadcast(){let count=0;for(let{dialog}of this.open.values())dialog.audience==="broadcast"&&count++;return count}apply(record){switch(field2(record,"type")){case"agent_start":case"agent_end":this.runState=field2(record,"type")==="agent_start"?"running":"idle";return;case"session_lifecycle":{let next=this.values.own(record);this.lifecycle&&this.store.adjust(this.lifecycle.owner,-1,0),this.lifecycle=next;return}case"extension_ui_request":{let id=field2(record,"id"),method=String(field2(record,"method"));if(typeof id!="string"||method!=="question"&&!TARGETED.has(method)||this.open.has(id))return;let broadcast=method==="question",dialog={id,audience:broadcast?"broadcast":"targeted",method,...deadline(record),...broadcast?{request:record}:{}};return this.put(id,String(this.opened++).padStart(16,"0"),dialog)}case"question_updated":{let id=String(field2(record,"id")),open6=this.open.get(id);open6&&this.put(id,open6.order,{...open6.dialog,...deadline(record)});return}default:{let id=String(field2(record,"id")??field2(record,"uiRequestId")),open6=this.open.get(id);if(!open6)return;this.dialogs=this.dialogRoots.set(this.dialogs,open6.order,void 0),this.open.delete(id)}}}freeze(){for(let ref of[this.lifecycle,this.dialogs.ref])ref&&this.store.adjust(ref.owner,0,1);let broadcast=this.openBroadcast;return{runState:this.runState,lifecycle:this.lifecycle,dialogs:this.dialogs.ref,dialogCounts:{broadcast,targeted:this.open.size-broadcast}}}release(frozen){for(let ref of[frozen.lifecycle,frozen.dialogs])ref&&this.store.adjust(ref.owner,0,-1)}async read(frozen,valid){let lifecycle=frozen.lifecycle?await this.values.read(frozen.lifecycle,valid):null;valid();let dialogs=[];for await(let[,dialog]of this.dialogRoots.entries(frozen.dialogs,valid))dialogs.push(dialog);return{runState:frozen.runState,lifecycle,dialogs,dialogCounts:frozen.dialogCounts}}put(id,order,dialog){this.dialogs=this.dialogRoots.set(this.dialogs,order,dialog),this.open.set(id,{order,dialog})}};var SEQUENCED=new Set(["agent_start","agent_end","turn_start","turn_end","message_start","message_update","message_end","tool_execution_start","tool_execution_update","tool_execution_end","entry_appended","session_abort","transcript_write_failed",...COMPONENT_RECORDS,...CALL_RECORDS]);function field3(record,key){return key in record?Reflect.get(record,key):void 0}function turnScoped(type,record){if(type==="turn_end"||type.startsWith("tool_execution_"))return!0;if(!type.startsWith("message_"))return!1;let role=field3(Object(field3(record,"message")),"role");return role==="assistant"||role==="toolResult"}function admitRecord(current,record,type,at,folds=!0){let turnId=type==="turn_start"||at.turnId===null&&turnScoped(type,record)?randomUUID5():at.turnId,next=at.sequence+1,call=folds&&CALL_RECORDS.has(type)?current.foldCall(record,next,turnId):void 0;if(!(call&&!call.changed&&CALL_ONLY_RECORDS.has(type)))return{sequence:next,turnId,call}}function correlationChange(standing,turnId,record){let identified="clientMessageId"in record||"clientTurnId"in record;if(!identified&&(standing===null||!correlatedRecord(record))||!identified&&turnId!==null&&field3(record,"type")!=="turn_start")return;let next={clientMessageId:field3(record,"clientMessageId"),clientTurnId:field3(record,"clientTurnId"),clientMessages:field3(record,"clientMessages")},current=standing,currentMessages=current?.clientMessages,nextMessages=next.clientMessages;if(!(current!==null&¤t.clientMessageId===next.clientMessageId&¤t.clientTurnId===next.clientTurnId&&(currentMessages===nextMessages||Array.isArray(currentMessages)&&Array.isArray(nextMessages)&¤tMessages.length===nextMessages.length&¤tMessages.every((identity,index)=>field3(Object(identity),"clientMessageId")===field3(Object(nextMessages[index]),"clientMessageId")&&field3(Object(identity),"clientTurnId")===field3(Object(nextMessages[index]),"clientTurnId")))))return next}var MATERIALIZER_ENVELOPE_MAX_BYTES=16384;function materializerLine(fanout,required,peer,sessionId,record){let lane=fanout.acceptance.get(sessionId),registered=fanout.get(peer);if(!lane||!registered||!fanout.events)return;let caller={socketEpoch:registered.socketEpoch,sessionId},stream=fanout.checkpoints.stream(caller);if(!stream?.routes.length||!SEQUENCED.has(String(Reflect.get(record,"type"))))return;let routes=required.routes(peer,sessionId,String(Reflect.get(record,"type")));if(!routes.length)return;let at={sessionEpoch:lane.sessionEpoch,sequence:lane.acceptedSequence},owner=routes[0],content=compactDelta(record)?demoteToDeltaOnly(record):record,minted2=fanout.events.mint({...caller,admissionId:owner},at,record,{chunks:()=>payload(content)});if(!minted2.ok)return registered.connection.close?.(),{line:serializeJsonLine({type:"event_lease_refused",sessionId,reason:minted2.reason}),atomic:!0,undelivered:()=>{}};let held=fanout.events.claim(caller,minted2.value.id,owner);if(held.ok)for(let route of routes)held.value.admissions.add(route);let seed=required.takeSeed(peer,sessionId),line=serializeJsonLine({type:Reflect.get(record,"type"),sessionId,eventLease:minted2.value,materializer:{...at,generation:stream.generation,payload:minted2.value,controls:seed?[{kind:"seed",token:seed.id,sequence:seed.cut.sequence}]:[]}});if(Buffer.byteLength(line)+512>MATERIALIZER_ENVELOPE_MAX_BYTES)throw fanout.events.abandon(caller.socketEpoch,minted2.value.id),new RangeError("materializer envelope exceeded H");return{line,atomic:!0,undelivered:written=>{written||fanout.events?.abandon(caller.socketEpoch,minted2.value.id)}}}function payload(record){return jsonChunks(record,65536)}var CALL_NAMED_RECORDS=new Set(["tool_execution_start","tool_execution_update","tool_execution_end","tool_hook_status"]),streamEvent=record=>Object(Reflect.get(record,"assistantMessageEvent"));function streamsCall(record){let kind=Reflect.get(streamEvent(record),"type");return Reflect.get(record,"type")==="message_update"&&typeof kind=="string"&&kind.startsWith("toolcall_")}function toolcallIndex(record){let index=Reflect.get(streamEvent(record),"contentIndex");return streamsCall(record)&&typeof index=="number"?index:void 0}function unvouchedCall(record){return CALL_NAMED_RECORDS.has(String(Reflect.get(record,"type")))||streamsCall(record)?CALL_UNKNOWN:void 0}var RecordLine=class{constructor(record,encoded){this.record=record,this.encoded=encoded}get text(){return this.encoded??=serializeJsonLine(this.record),this.encoded}get built(){return this.encoded}},SessionEventWriterDestinations=class extends SessionEventWriterRecovery{deliver(sessionId,record,tagged,line,targets,mirrors,isTargeted,current){let redacted=targets.some(target=>this.fanout.connectionHas(target,MEDIA_PLACEHOLDERS_CAPABILITY))?omitNormalInlineMedia(tagged,this.mediaPersisters.get(sessionId)):tagged,placeholderLine=redacted===tagged?void 0:serializeJsonLine(redacted),placeholder=new RecordLine(redacted,placeholderLine);!isTargeted&&!this.fanout.acceptance.has(sessionId)&&this.fanout.rememberSnapshot(sessionId,tagged,line.text,placeholderLine);let copies=new Map;for(let target of targets){if(target!==void 0&&!this.fanout.get(target))continue;let registered=target===void 0?void 0:this.fanout.get(target),wants=placeholderLine!==void 0&&this.fanout.connectionHas(target,MEDIA_PLACEHOLDERS_CAPABILITY);if(registered&&target!==void 0){let out=this.eventLine(target,sessionId,wants?redacted:tagged,wants?placeholder:line,copies),keyed=!out.atomic&&compactDelta(tagged)!==void 0&&tagged.message!==null;registered.actor.enqueue(out.line,keyed?MESSAGE_KEY:void 0,out.undelivered,keyed?serializeJsonLine(demoteToDeltaOnly(out.record??tagged)):void 0,isCorrelatedReply(tagged),mirrors.includes(target)?void 0:this.fanout.attachmentOf(target,sessionId,isTargeted,record.type),current)}else this.appendSessionRecord(sessionId,wants?redacted:tagged,target)}}eventLine(target,sessionId,record,line,copies){let reply=declarationReply(record,this.compactSelection(target));if(reply!==void 0&&reply!==record)return{line:serializeJsonLine(reply)};let events=this.fanout.events,lane=this.fanout.acceptance.get(sessionId);if(!lane&&this.compactSelection(target)?.selected&&this.status.mirrorTargets(sessionId,String(Reflect.get(record,"type"))).includes(target))return{line:serializeJsonLine({type:"compact_refused",sessionId,reason:"compact_endpoint_unsupported"}),undelivered:()=>this.fanout.get(target)?.connection.close?.()};let admissionId=this.ordinaryRoute(target,sessionId)?.routes[0]??this.fanout.admissionOf(target,sessionId),socketEpoch=this.fanout.get(target)?.socketEpoch;if(!events||!lane||admissionId===void 0||socketEpoch===void 0)return{line:line.text};if(!this.fanout.connectionHas(target,COMPACT_EVENTS_CAPABILITY))return{line:line.text};let copy=copies.get(record);if(!copy){let identity2=lane.identities.of(record.type,lane.acceptedSequence)??unvouchedCall(record),stamped2=identity2?{...record,...identity2}:record;copy={stamped:stamped2,line:identity2?new RecordLine(stamped2):line},copies.set(record,copy)}let{stamped,line:stampedLine}=copy,identity=stamped!==record,materializer=materializerLine(this.fanout,this.required,target,sessionId,stamped);if(materializer)return materializer;let built=stampedLine.built,size=built===void 0?jsonSize(stamped):{bytes:Buffer.byteLength(built)-1,units:built.length-1};if(size.bytes+1<=COMPACT_RECORD_MAX_BYTES)return{line:stampedLine.text,...identity?{record:stamped}:{}};let at={sessionEpoch:lane.sessionEpoch,sequence:lane.acceptedSequence},routes=this.ordinaryRoute(target,sessionId)?.routes??[],owner=routes[0]??admissionId,minted2=events.mint({socketEpoch,sessionId,admissionId:owner},at,stamped,built??size);if(minted2.ok){let{id}=minted2.value,held=events.claim({socketEpoch,sessionId},id,owner);if(held.ok)for(let route of routes)held.value.admissions.add(route);return{line:serializeJsonLine({type:Reflect.get(record,"type"),sessionId,eventLease:minted2.value}),...identity?{record:stamped}:{},undelivered:written=>{written||events.abandon(socketEpoch,id)}}}return process.stderr.write(`senpi rpc connection ${target} event lease refused (${minted2.reason}); closing
|
|
13
|
+
`),this.fanout.get(target)?.connection.close?.(),{line:serializeJsonLine({type:"event_lease_refused",sessionId,reason:minted2.reason})}}};var SessionEventWriter=class extends SessionEventWriterDestinations{secretInputRoute(sessionId){return this.secretPresentations.route(sessionId)}setSoleSecretCapabilities(capabilities){this.secretPresentations.handshake(capabilities)}handleMcpForm(value){if(!this.presenterAuthority||typeof value!="object"||value===null||!("type"in value)||typeof value.type!="string"||!value.type.startsWith("mcp_form_")&&value.type!=="mcp_presenter_context")return!1;let id=this.currentConnection(),sender=id===void 0?void 0:this.presenterConnections.get(id),context=value.type==="mcp_presenter_context"&&"sessionId"in value&&typeof value.sessionId=="string"&&sender?this.presenterAuthority?.connectionContext(sender,value.sessionId):void 0,reply=value.type==="mcp_presenter_context"?context?{ok:!0,context}:{error:"presenter_not_authorized"}:sender&&this.presenterAuthority?this.presenterAuthority.receive(sender,value):{error:"presenter_not_authorized"},connection=id===void 0?void 0:this.fanout.get(id)?.connection;if(connection)try{connection.writeRaw(serializeJsonLine({type:"mcp_form_reply",..."id"in value&&typeof value.id=="string"?{id:value.id}:{},...reply}))}catch{sender&&this.presenterAuthority?.detach(sender)}return!0}enqueue(sessionId,value){if(declarationReply(value,void 0)===void 0)return!0;if(this.sealedSessions.has(sessionId))return!1;let targetId=this.connectionContext.getStore(),record=normalizeJsonValue(value).value,isTargeted=this.isTargetedRecord(record),current=isTargeted?this.connectionContext.currentGuard():void 0;if(current?.()===!1)return!0;let tagged={...observeLifecycleDelivery(record),sessionId},line=new RecordLine(tagged);if(record.type==="snapshot_marker"||record.type==="ui_request_pending"||record.type==="ui_request_settled"){let targets2=record.type==="snapshot_marker"?this.status.mirrorTargets(sessionId,"snapshot_marker").filter(id=>id===targetId):this.status.dialogTargets(sessionId);for(let target of targets2)this.fanout.get(target)?.actor.enqueue(line.text);return targets2.length>0&&this.requestFlush(),!0}if(this.fanout.isEmpty()&&this.exceedsStdioCapacity(line.text))return this.closeSession(sessionId,{type:"response",command:"close_session",success:!1,error:"session_output_overflow, resync required"},"error"),!1;this.openTurns.note(sessionId,record.type,record.reason);let attached=this.fanout.targets(sessionId,targetId,isTargeted,record.type),mirrors=isTargeted?[]:this.status.mirrorTargets(sessionId,String(record.type)),targets=mirrors.length===0?attached:[...new Set([...attached,...mirrors])];this.deliver(sessionId,record,tagged,line,targets,mirrors,isTargeted,current);let cause=isTargeted?void 0:causeOfRecord(record);return cause!==void 0&&this.status.publish(sessionId,cause,this.changeActor("agent")),this.afterRecord?.(sessionId),this.requestFlush(),!0}publishLoadedSurfacesChanged(sessionId,previous,digest2){if(this.fanout.isEmpty()){this.enqueue(sessionId,{type:"loaded_surfaces_changed"});return}if(this.sealedSessions.has(sessionId))return;let line=serializeJsonLine({type:"loaded_surfaces_changed",sessionId});for(let id of this.fanout.attachedConnections(sessionId)){if(!this.surfaceDedupe.announce(id,sessionId,previous,digest2))continue;let held=this.fanout.attachmentOf(id,sessionId,!1,"loaded_surfaces_changed");this.fanout.get(id)?.actor.enqueue(line,void 0,void 0,void 0,!1,held)}this.requestFlush()}enqueueControl(value,targetOverride){let peer=targetOverride??this.currentConnection(),reply=declarationReply(value,peer===void 0?void 0:this.compactSelection(peer));if(reply===void 0)return Promise.resolve();if(value=reply,this.failure!==void 0)return Promise.reject(this.failure);let targetId=targetOverride??this.connectionContext.getStore(),registered=targetId===void 0?void 0:this.fanout.get(targetId);if(registered)return registered.actor.enqueue(serializeJsonLine(value),void 0,void 0,void 0,isCorrelatedReply(value)),this.requestFlush(),Promise.resolve();if(this.exceedsStdioCapacity(serializeJsonLine(value)))return this.controlOverflowReported||(this.controlOverflowReported=!0,this.records.append(this.controlQueue,{type:"overflow",error:"rpc_control_output_overflow, resync required"}),this.markReady(this.controlQueue),this.requestFlush()),Promise.reject(new Error("rpc_control_output_overflow, resync required"));let queue=targetId===void 0?this.controlQueue:this.connectionQueue(targetId),completion=new Promise((resolve2,reject)=>{this.records.append(queue,{...value},void 0,resolve2,reject)});return this.markReady(queue),this.requestFlush(),completion}sendOpenQueued(connection,record){let wire={type:"queued",for_request:record.for_request,position:record.position,in_flight:record.in_flight},target=this.fanout.get(connection);target!==void 0&&(target.actor.enqueue(serializeJsonLine(wire)),this.requestFlush())}broadcastHostRecord(record){let wire;switch(record.type){case"host_superseded":wire={type:"host_superseded",instanceId:record.instanceId,generation:record.generation,successor:record.successor};break;case"host_stalled":wire={type:"host_stalled",driftMs:record.driftMs,...record.sessionId!==void 0?{sessionId:record.sessionId}:{},...record.tool!==void 0?{tool:record.tool}:{}};break;case"host_memory_pressure":wire={type:"host_memory_pressure",rssMb:record.rssMb,...record.footprintMb!==void 0?{footprintMb:record.footprintMb}:{},...record.measure!==void 0?{measure:record.measure}:{},sessions:record.sessions,...record.main!==void 0?{main:record.main}:{},...record.kernels!==void 0?{kernels:record.kernels}:{}};break;case"host_trimmed":wire={type:"host_trimmed",footprintBeforeMb:record.footprintBeforeMb,footprintAfterMb:record.footprintAfterMb,measure:record.measure,collected:record.collected,sessions:record.sessions,pauseMs:record.pauseMs};break;case"subscription_limits":wire={type:"subscription_limits",provider:record.provider,account:record.account,windows:record.windows,reportedAt:record.reportedAt,...record.plan===void 0?{}:{plan:record.plan},...record.error===void 0?{}:{error:record.error}};break;default:{let exhaustive=record;throw new Error(`unexpected host record ${exhaustive}`)}}this.fanout.isEmpty()?(this.records.append(this.controlQueue,wire),this.markReady(this.controlQueue)):this.fanout.broadcast(serializeJsonLine(wire)),this.requestFlush()}parkSession(sessionId,sessionPath,reason){this.sealLifecycle(sessionId,{type:"session_parked",sessionId,sessionPath,reason})}releaseSession(sessionId,sessionPath){this.sealLifecycle(sessionId,{type:"session_closed",sessionId,reason:"released",sessionPath})}settleBeforeSeal(sessionId){if(this.sealedSessions.has(sessionId))return!1;for(let owed=this.openTurns.take(sessionId);owed>0;owed-=1)this.enqueue(sessionId,{type:"agent_settled",reason:"session_closed"});return!this.sealedSessions.has(sessionId)}};function socketSink(socket){let needsDrain=!1,cut=!1;return{writeRaw(chunk){!cut&&!socket.destroyed&&(needsDrain=!socket.write(chunk))},close(){if(cut||(cut=!0,socket.destroyed))return;socket.end();let grace=setTimeout(()=>socket.destroy(),5e3);grace.unref(),socket.once("close",()=>clearTimeout(grace))},waitForBackpressure(){return socket.destroyed||!needsDrain?Promise.resolve():(needsDrain=!1,new Promise(resolve2=>{let done=()=>{socket.off("drain",done),socket.off("close",done),resolve2()};socket.once("drain",done),socket.once("close",done)}))}}}var SESSION_CONTEXT_PATCH_LIMITS={keyPattern:/^[a-z][a-z0-9_]{0,63}$/,valueChars:256,overlayBytes:4096},RESERVED_SESSION_CONTEXT_KEYS=new Set(["host_socket","host_instance","shard_key","tree_key","parent_session_id","root_session_id"]);function refuse(reason,action){return{refusal:{reason,action}}}function applyContextPatch(overlay,patch){let shape='send patch as an object of lowercase keys to string, number, boolean or null values, e.g. { "task_status": "running" }';if(typeof patch!="object"||patch===null||Array.isArray(patch))return refuse("patch must be an object",shape);let entries=Object.entries(patch);if(entries.length===0)return refuse("patch has no keys",shape);let merged={...overlay};for(let[key,value]of entries){if(!SESSION_CONTEXT_PATCH_LIMITS.keyPattern.test(key))return refuse(`key "${key}" must match ${SESSION_CONTEXT_PATCH_LIMITS.keyPattern.source}`,"rename the key to lowercase letters, digits and underscores");if(RESERVED_SESSION_CONTEXT_KEYS.has(key))return refuse(`key "${key}" is set by the host and cannot be patched`,"drop that key from the patch; the host keeps it current");if(typeof value=="string"&&value.length>SESSION_CONTEXT_PATCH_LIMITS.valueChars)return refuse(`value for "${key}" is ${value.length} characters, at most ${SESSION_CONTEXT_PATCH_LIMITS.valueChars} are accepted`,"shorten the value or store it elsewhere and publish a reference");if(typeof value=="number"&&!Number.isFinite(value))return refuse(`value for "${key}" must be a finite number`,shape);if(value!==null&&typeof value!="string"&&typeof value!="number"&&typeof value!="boolean")return refuse(`value for "${key}" must be a string, number, boolean or null`,shape);merged[key]=value}let bytes=Buffer.byteLength(JSON.stringify(merged));return bytes>SESSION_CONTEXT_PATCH_LIMITS.overlayBytes?refuse(`patched context would be ${bytes} bytes, at most ${SESSION_CONTEXT_PATCH_LIMITS.overlayBytes} are accepted`,"remove keys with null or shorten values before adding more"):{overlay:merged}}function publishedSessionContext(base,overlay){if(overlay===void 0)return base;let published={...base};for(let[key,value]of Object.entries(overlay))value===null?delete published[key]:published[key]=value;return published}function modelOf(model){return model===void 0?void 0:{provider:model.provider,id:model.id}}function sessionRuntimeView(session,pendingQuestions){let model=modelOf(session.model);return{isStreaming:session.isStreaming===!0,isCompacting:session.isCompacting===!0,...model!==void 0?{model}:{},...session.thinkingLevel!==void 0?{thinkingLevel:session.thinkingLevel}:{},steering:typeof session.getSteeringMessages=="function"?session.getSteeringMessages().length:0,followUp:typeof session.getFollowUpMessages=="function"?session.getFollowUpMessages().length:0,pendingQuestions:pendingQuestions??sessionQuestionBridges.get(session)?.pendingQuestions()?.length??0}}function runtimeView(entry){let session=entry.runtime?.session;if(session!==void 0)return sessionRuntimeView(session);let state=entry.worker?.snapshot?.state;if(state===void 0)return;let model=modelOf(state.model??void 0);return{isStreaming:state.isStreaming,isCompacting:state.isCompacting,...model!==void 0?{model}:{},...state.thinkingLevel!==void 0?{thinkingLevel:state.thinkingLevel}:{},steering:state.steering.length,followUp:state.followUp.length,pendingQuestions:state.pendingQuestions?.length??0}}function entryView(entry){let session=entry.runtime?.session,state=entry.worker?.snapshot?.state,durableSessionId=session?.sessionId??state?.sessionId??entry.durableSessionId,sessionPath=session?.sessionFile??state?.sessionFile??entry.sessionPath,name=session?.sessionManager.getSessionName()??state?.sessionName;return{state:entry.state,kind:entry.kind,cwd:entry.cwd,attachments:entry.attachments,...durableSessionId!==void 0?{durableSessionId}:{},...sessionPath!==void 0?{sessionPath}:{},...name!==void 0?{name}:{},context:publishedSessionContext(entry.context,entry.contextOverlay),openContext:entry.context}}function registryStatusSource(registry){return{sessionIds:()=>registry.list().map(row=>row.sessionId),entryView:sessionId=>{let entry=registry.peek(sessionId);return entry===void 0?void 0:entryView(entry)},view:sessionId=>{let entry=registry.peek(sessionId);if(entry===void 0)return;let runtime=runtimeView(entry);return runtime===void 0?{entry:entryView(entry)}:{entry:entryView(entry),runtime}}}}function refusal2(id,command,code,detail){return{id,type:"response",command,success:!1,error:`${code}: ${detail.reason}`,errorCode:code,errorData:{reason:detail.reason,action:detail.action}}}function answerSubscribeSessions(command,connectionId,stream,snapshotSink){if(connectionId===void 0)return{answer:refusal2(command.id,command.type,RPC_ERROR_UNSUPPORTED_TRANSPORT,{reason:"stdio has no per-connection identity to deliver a subscription to",action:"connect to the host socket (senpi --mode rpc --listen) and subscribe there"})};if(stream.connectionSize(connectionId)>=MAX_SUBSCRIPTIONS_PER_CONNECTION)return{answer:refusal2(command.id,command.type,RPC_ERROR_SUBSCRIPTION_LIMIT,{reason:`this connection already holds ${MAX_SUBSCRIPTIONS_PER_CONNECTION} subscriptions`,action:"unsubscribe_sessions the ones you no longer read, then subscribe again"})};let parsed=parseSubscription(command);if("refusal"in parsed)return{answer:refusal2(command.id,command.type,RPC_ERROR_INVALID_SUBSCRIPTION,parsed.refusal)};let options=snapshotSink?{...parsed.options,admissionId:command.admissionId}:parsed.options,subscribed=stream.subscribe(connectionId,options,snapshotSink);return{answer:{id:command.id,type:"response",command:"subscribe_sessions",success:!0,data:{subscriptionId:subscribed.subscriptionId,snapshot:subscribed.snapshot,seq:subscribed.seq,hostGeneration:String(hostGeneration(process.env)),hostInstanceId:hostInstanceId()}},activate:subscribed.subscriptionId}}function answerUnsubscribeSessions(command,connectionId,stream){return connectionId===void 0?refusal2(command.id,command.type,RPC_ERROR_UNSUPPORTED_TRANSPORT,{reason:"stdio has no per-connection identity holding any subscription",action:"connect to the host socket (senpi --mode rpc --listen) and manage subscriptions there"}):typeof command.subscriptionId=="string"&&stream.unsubscribe(connectionId,command.subscriptionId)?{id:command.id,type:"response",command:"unsubscribe_sessions",success:!0}:refusal2(command.id,command.type,RPC_ERROR_UNKNOWN_SUBSCRIPTION,{reason:"this connection holds no subscription with that id",action:"send the subscriptionId your subscribe_sessions answer returned, on the same connection"})}function notAttachedRefusal(command){return refusal2(command.id,command.type,RPC_ERROR_SESSION_NOT_ATTACHED,{reason:"this connection is not attached to that session",action:"attach first with open_session { sessionPath }, then patch its context"})}function answerSetSessionContext(command,entry,stream){let applied=applyContextPatch(entry.contextOverlay,command.patch);return"refusal"in applied?refusal2(command.id,command.type,RPC_ERROR_INVALID_SESSION_CONTEXT,applied.refusal):(entry.contextOverlay=applied.overlay,stream.publish(command.sessionId,"context","client",!0),{id:command.id,type:"response",command:"set_session_context",success:!0,data:{context:publishedSessionContext(entry.context,entry.contextOverlay)}})}export{applyContextPatch,publishedSessionContext,parseBoundedId,protocolId,CompactReadError,CompactReadLease,privateRootStat,recoveryAgentDir,RecoveryStorageHealth,CompactStorageReadError,CompactCommitDependencies,COMPACT_LEAF_CODE_UNITS,CompactWriteError,CompactContentStore,FRAGMENT_MAX_BYTES,FRAGMENT_ENVELOPE_MAX_BYTES,TRANSFER_STAGING_MAX_BYTES,TransferStagingError,TransferStaging,AcceptedTranscript,CompactIndexTree,CompactValues,TERMINAL_PHASE,CALL_RECORDS,runtimeItemKey,CALL_UNKNOWN,callIdentity,callOrder,callLeaves,terminal,CompactComponentRoots,COMPONENT_RECORDS,CompactCurrentComponents,SEQUENCED,field3 as field,admitRecord,correlationChange,CALL_NAMED_RECORDS,toolcallIndex,recordLoopBlockedMs,enqueueLegacyRecord,sessionRuntimeView,registryStatusSource,GeneratedFramesCursor,jsonChunks,refusal2 as refusal,answerSubscribeSessions,answerUnsubscribeSessions,notAttachedRefusal,answerSetSessionContext,captureAdmissionReply,withAdmissionReply,withAdmissionRequest,storageUnavailable,SessionEventWriter,socketSink};
|