@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
23 lines • 219 kB
JavaScript
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 = () => {}; } }
import{COMPACT_LEAF_CODE_UNITS,CatalogNodeWriter,CompactComponentRoots,CompactContentStore,CompactReadError,CompactReadLease,CompactSelection,CompactValues,CompactWriteError,DEFAULT_TRANSCRIPT_ANCESTRY_BYTES,EVENT_RESYNC_CAPABILITY,ExtensionTransportOwner,FRAGMENT_MAX_BYTES,McpPresenterAuthority,SECRET_INPUT_FEATURE,SEQUENCED,SocketPeerRecovery,StagedReadError,TransferStaging,TransferStagingError,answerSealedFrame,applyContextPatch,assertRange,attachMcpGrantPresentation,baseRef,catalogDigest,catalogDigester,catalogRootRef,checkSealedAnswer,childRef,createAuthority,declarationReply,decodeCatalogNode,effectStatusRecord,features,isCorrelatedReply,isMachineOpCommand,machineOpRefusal,maskOfRoles,nextIncarnation,observeLifecycleDelivery,openFrozenBytes,parseBoundedId,parseContentDigest,parseContentRef,parseDeclaration,parsePageRef,privateRootStat,producePage,protocolId,publishedSessionContext,readAuthority,readRootMarker,refSteps,refused,remoteOriginField,requestId,rolesOfMask,rootOwnerState,samePrincipal,secretBinding,secretRequestHash,secretRequestTranscript,startAtOrBefore,storeNarrowed,storeRetired,storedBytes,unvouchedCall,withReceipt}from"./chunk-VHOAN5G5.js";import{RPC_ERROR_INVALID_SESSION_CONTEXT,RPC_ERROR_INVALID_SUBSCRIPTION,RPC_ERROR_RESPONSE_UNWRITABLE,RPC_ERROR_SESSION_NOT_ATTACHED,RPC_ERROR_SUBSCRIPTION_LIMIT,RPC_ERROR_UNKNOWN_SUBSCRIPTION,RPC_ERROR_UNSUPPORTED_TRANSPORT}from"./chunk-ARIPHUYY.js";import{carriesMedia,normalizeJsonValue,omitNormalInlineMedia}from"./chunk-XI6THO4F.js";import{BaseContentHash,compactUpdatesEnabled,fingerprintLine,parseSessionEntryLine}from"./chunk-4R7JSL3B.js";import{bindPrivateMcpForms,isRecord}from"./chunk-MOVB6H22.js";import{COMPACT_EVENTS_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,RAISER_NOTICE_CAPABILITY,RPC_METHOD_CLASS,RPC_METHOD_CLASSES_DIGEST,RPC_METHOD_CLASSES_VERSION,classifyRpcMethod,hostGeneration,hostInstanceId}from"./chunk-OPUPPWQY.js";import{PRESENTER_EXCHANGE_MS,PRESENTER_PARKING_MS}from"./chunk-7WYJAYHH.js";import{RPC_LAUNCH_PROOF_RECORD}from"./chunk-YQHLIPNR.js";import{LegacyRecordDepthError,attachJsonlLineReader,isStackOverflow,serializeJsonLine}from"./chunk-SF4MQDKZ.js";import{external_exports}from"./chunk-36BLGKRO.js";import{randomUUID}from"node:crypto";import{tmpdir}from"node:os";import{join}from"node:path";var SKIPPED=new Set(["undefined","function","symbol"]),isRecord2=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(isRecord2(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 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:join(tmpdir(),`senpi-event-leases-${randomUUID()}`)}));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})
`);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"})}
`)}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"})}
`)}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),terminal=record.type==="session_closed"||record.type==="session_parked",routes=[...new Set([...(stream?.routes??[]).filter(id=>this.admissions.has(id)||terminal&&[...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;let frozen=this.fanout.checkpoints.freeze({...caller,peer,admissionId,routeKind:"mirror"},lane,!0);if(!frozen.ok){registered.close("checkpoint_unavailable",frozen.failure.reason);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.close("checkpoint_unavailable",frozen.failure.reason);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)}}};function causeLine(cause){let text=cause instanceof Error?`${cause.name}: ${cause.message}`:String(cause);return text.split(`
`,1)[0]??text}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})
`)}reportReply(sessionId,command,cause){this.count+=1,process.stderr.write(`senpi rpc host: ${command} response unwritable (${causeLine(cause)}); answered ${RPC_ERROR_RESPONSE_UNWRITABLE} (session ${sessionId})
`)}};function isReply(record){return Reflect.get(record,"type")==="response"}function unwritableReply(record,cause){let command=typeof record.command=="string"?record.command:"unknown";return{...typeof record.id=="string"||typeof record.id=="number"?{id:record.id}:{},type:"response",command,success:!1,error:`${command} response could not be written: ${causeLine(cause)}`,errorCode:RPC_ERROR_RESPONSE_UNWRITABLE}}function enqueueLegacyRecord(writer,sessionId,record){try{return writer.enqueue(sessionId,record)}catch(cause){if(isReply(record)){let answer=unwritableReply(record,cause);return writer.legacyRefusals.reportReply(sessionId,Reflect.get(answer,"command"),cause),writer.enqueue(sessionId,answer)}let refusal3=isStackOverflow(cause)?new LegacyRecordDepthError(record,cause):cause;if(!(refusal3 instanceof LegacyRecordDepthError))throw cause;return writer.legacyRefusals.report(sessionId,refusal3),!0}}var RaiserNotices=class{#pending=new Map;constructor(fanout,flush){this.fanout=fanout,this.flush=flush}raised(sessionId,uiRequestId,excluded,notice){let session=this.#pending.get(sessionId)??new Map;if(session.has(uiRequestId))return;let recipients=this.fanout.attachedConnections(sessionId).filter(id=>!excluded.includes(id)&&this.fanout.connectionHas(id,RAISER_NOTICE_CAPABILITY));recipients.length!==0&&(session.set(uiRequestId,recipients),this.#pending.set(sessionId,session),this.#send(recipients,{...notice,sessionId,uiRequestId}))}settled(sessionId,uiRequestId,record){let session=this.#pending.get(sessionId),recipients=session?.get(uiRequestId);session===void 0||recipients===void 0||(session.delete(uiRequestId),session.size===0&&this.#pending.delete(sessionId),this.#send(recipients,{...record,sessionId,uiRequestId}))}dropSession(sessionId){this.#pending.delete(sessionId)}#send(recipients,record){let line=serializeJsonLine(record);for(let id of recipients)this.fanout.get(id)?.actor.enqueue(line);this.flush()}};var NO_RAISING_CONNECTION="agent",SecretInputPresentations=class{constructor(fanout,current,writeSole,flush,locality){this.owners=new Map,this.soleCapabilities=[],this.latches=new Map,this.fanout=fanout,this.current=current,this.writeSole=writeSole,this.flush=flush,this.locality=locality,this.notices=new RaiserNotices(fanout,flush)}handshake(capabilities){this.soleCapabilities=[...capabilities],this.recheck()}useSealed(source){return this.unsubscribeSealed?.(),this.sealedSource=source,this.unsubscribeSealed=source?.onChange(()=>this.recheck()),this.recheck(),()=>{this.sealedSource===source&&this.useSealed(void 0)}}route(session,sealed=!1){let capable=connection=>this.capable(connection),bound;return{presenter:id=>this.owners.get(id)?.connection,select:(id,cancel)=>{let preferred=this.current(),attached=this.fanout.attachedConnections(session),refused2,connection=preferred??attached.find(candidate=>capable(candidate)&&this.local(candidate));preferred!==void 0&&(!attached.includes(preferred)||!capable(preferred))?refused2="client_unsupported":connection===void 0&&!(this.fanout.isEmpty()&&capable(void 0))&&(refused2=this.fanout.isEmpty()?"client_unsupported":"no_presenter");let holders=sealed?this.sealedSource?.holders(session):void 0;if(refused2!==void 0&&!holders?.size)return refused2;let origin=preferred===void 0?void 0:this.locality.originOf(preferred);this.owners.set(id,{session,...refused2===void 0?{connection}:{},cancel,raiser:refused2===void 0,sealed:holders??new Set,background:preferred===void 0,raisedBy:preferred??NO_RAISING_CONNECTION,...origin===void 0?{}:{origin}})},accepts:id=>{let owner=this.owners.get(id);return owner?.session===session&&owner.raiser&&owner.connection===this.current()&&this.live(owner)},available:id=>{let owner=this.owners.get(id);return owner?.session===session&&this.available(owner)},sealed:id=>(this.owners.get(id)?.sealed.size??0)>0,raiser:id=>this.owners.get(id)?.raiser===!0,sealedOutcome:(id,outcome,winner)=>{let owner=this.owners.get(id);owner?.session===session&&owner.sealed.size>0&&this.sealedSource?.settle(owner.sealed,id,outcome,winner)},bindSealedResponder:latch=>{latch?sealed&&(bound=latch,this.latches.set(session,latch)):(bound!==void 0&&this.latches.get(session)===bound&&this.latches.delete(session),bound=void 0)},offerSealed:(id,offer)=>{let owner=this.owners.get(id);owner?.session===session&&owner.sealed.size>0&&this.sealedSource?.offer(session,owner.sealed,{uiRequestId:id,...offer})},send:(id,record)=>{let owner=this.owners.get(id);if(owner?.session===session&&this.notify(id,owner,record),!owner||owner.session!==session||!this.available(owner)){owner?.cancel?.();return}if(!owner.raiser||!this.live(owner))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),this.sealedSource?.retire(id)},forget:id=>{this.owners.delete(id),this.sealedSource?.withdraw(id)},handshake:capabilities=>{this.current()===void 0&&this.handshake(capabilities)}}}answerSealed(connection,value){return answerSealedFrame(connection,value,this.sealedSource,id=>{let owner=this.owners.get(id);return owner&&{sealed:owner.sealed,latch:this.latches.get(owner.session)}})}recheck(){for(let owner of this.owners.values())this.available(owner)||owner.cancel?.()}detach(connection){for(let[id,owner]of this.owners)if(owner.connection===connection){if(owner.raiser=!1,owner.connection=void 0,this.available(owner))continue;owner.cancel?.(),this.owners.delete(id)}}notify(id,owner,record){let type=Reflect.get(record,"type");type==="extension_ui_request"&&this.available(owner)?this.notices.raised(owner.session,id,[owner.connection,this.raisingConnection(owner),...this.holderConnections(owner)],{type:"secret_input_notice",title:Reflect.get(record,"title"),deadlineAtMs:Reflect.get(record,"deadlineAtMs"),raisedBy:owner.raisedBy,...remoteOriginField(owner.origin)}):type==="secret_input_settled"&&this.notices.settled(owner.session,id,{type:"secret_input_notice_settled",outcome:Reflect.get(record,"outcome")})}raisingConnection(owner){return owner.raisedBy===NO_RAISING_CONNECTION?void 0:owner.raisedBy}available(owner){return owner.raiser&&this.live(owner)||[...owner.sealed].some(holder=>this.sealedSource?.current(holder)===!0)}holderConnections(owner){let source=this.sealedSource;return source?[...owner.sealed].map(holder=>source.connectionOf(holder)):[]}local(connection){return!this.locality.isRemote(connection)}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)&&(!owner.background||this.local(owner.connection)))}};var RpcSecurityPresentations=class{#sessions=new Map;#attachments=new Map;constructor(fanout,inConnection,flush,locality){this.fanout=fanout,this.inConnection=inConnection,this.flush=flush,this.locality=locality,this.notices=new RaiserNotices(fanout,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.locality.isRemote(id)&&this.#cancelFor(state,id,!0):this.#cancelFor(state,id))}}routeWorkerGrant(sessionId,requestId2,preferred,fallbackCapabilities,cancel,title){let attached=this.fanout.attachedConnections(sessionId),raiser=preferred!==void 0&&attached.includes(preferred)&&this.#localPresenter(preferred),connection=raiser?preferred:attached.find(id=>this.#localPresenter(id));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(requestId2,{connection,cancel,background:!raiser}),title!==void 0&&this.noticeGrant(sessionId,requestId2,title,connection),{accepted:!0,connection}}noticeGrant(sessionId,requestId2,title,presenter){this.notices.raised(sessionId,requestId2,[presenter],{type:"grant_select_notice",title})}acceptWorkerResponse(sessionId,requestId2,connection){let pending=this.#sessions.get(sessionId)?.grants.get(requestId2);if(pending!==void 0)return!(pending.connection!==connection||connection!==void 0&&!this.fanout.connectionHas(connection,"grant_select"))}settleGrant(sessionId,requestId2){this.#sessions.get(sessionId)?.grants.delete(requestId2),this.notices.settled(sessionId,requestId2,{type:"grant_select_notice_settled"})}dropSession(sessionId){this.#stop(this.#sessions.get(sessionId)),this.#sessions.delete(sessionId),this.notices.dropSession(sessionId);for(let[id,sessions]of this.#attachments)sessions.delete(sessionId),sessions.size===0&&this.#attachments.delete(id)}#localPresenter(id){return this.fanout.connectionHas(id,"grant_select")&&!this.locality.isRemote(id)}#register(id,state){if(!this.#localPresenter(id)){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,backgroundOnly=!1){for(let[requestId2,pending]of state.grants)pending.connection===id&&(!backgroundOnly||pending.background)&&(state.grants.delete(requestId2),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,readdir,rm}from"node:fs/promises";import{dirname,join as join2,resolve}from"node:path";var ROOT_NAME=/^senpi-(?:transcript|settled|current|event-leases)-/;async function rootBytes(path){try{let stat=await lstat(path);if(!stat.isDirectory()||stat.isSymbolicLink())return stat.size;let bytes=0;for(let name of await readdir(path)){let child=await rootBytes(join2(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=join2(ownedBase,name);if(dirname(path)===ownedBase)try{let stat=await lstat(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 lstat(path);if(current.dev!==stat.dev||current.ino!==stat.ino||!privateRootStat(current))throw new Error("root identity changed during classification");await rm(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)}
`),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}
`)}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(field2=>`${Buffer.byteLength(field2)}:${field2}`).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(field2=>typeof field2!="string"||!parseBoundedId(field2).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(root){let{transcript,refusedCorrelations}=root,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),requiredKinds=families.filter(({producer})=>producer==="complete").map(({family})=>family).sort((a,b)=>a<b?-1:a>b?1:0),base={format:"senpi-recovery-families",version:1,families,requiredKinds};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 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,identity2={sessionEpoch,sequence,activeMessageId,turnId,correlation,refusedCorrelations};yield*textComponent(reader.store,IDENTITY,IDENTITY,JSON.stringify(identity2));for await(let member of settled.members(reader.valid)){if(member.kind!=="owner")continue;let join4=JSON.stringify({messageId:member.messageId,entryId:member.entryId});yield*textComponent(reader.store,IDENTITY,joinMember(member.ordinal),join4)}}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),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;return assertCoverage(registry,emitted),registry}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}from"node:crypto";import{open}from"node:fs/promises";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 open(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)})}
`)}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=createHash("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 open2=this.level(height),units=open2.units+token.length+ +(open2.tokens.length>0);if(units>COMPACT_LEAF_CODE_UNITS)return this.push(height+1,headToken(this.seal(height))),this.push(height,token);open2.tokens.push(token),open2.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 open2=at(level);level===0&&owner!==0&&(store.adjust(owner,1,0),held.add(owner)),open2.owners.push(owner),"leaves"in child?open2.pointers.component(child.leaves):open2.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 field2 of TEXT_FIELDS){let value=strings[field2];if(value===null){texts.set(field2,null);continue}let bounded=parseBoundedId(value);if(bounded.ok){texts.set(field2,{id:bounded.value});continue}let leaves=chunks(value).map(chunk=>store.createLeaf(chunk));owned.push(...leaves);let component={kind:MANIFEST,id:protocolId(field2),leaves,owner:store.text.own(leaves)};oversized.push({field:field2,component})}try{let check=()=>{cutValid(),valid()},cut={store,values:new CompactValues(store),root,settled:lane.settledOf(root)},emitted={},components=async function*(){yield*oversized.map(({component})=>component),emitted.registry=yield*checkpointComponents(cut,check)},built=await this.catalogs.build(store,ref,components(),check),requiredKinds=emitted.registry?.requiredKinds;if(!requiredKinds)throw this.catalogs.release(store,built),new CompactReadError("ownership");return await this.assemble(store,token,ref,built,oversized,texts,requiredKinds)}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,requiredKinds){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:field2,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(field2,{ref:childRef(leftmost,index),length:entry.length,digest:entry.digest})}let text=field2=>{let value=texts.get(field2);if(value===void 0)throw new CompactReadError("ownership");return value},required=field2=>text(field2)??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,requiredKinds},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,join4=!1){if(lane.retired)return this.refuse(repairNeeded("lane_retired"));let current=join4?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}};function transportOf(connection){return{writeRaw:chunk=>connection.writeRaw(chunk),waitForBackpressure:()=>connection.waitForBackpressure()}}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 SOCKET_CLOSING_CODES={checkpoint_unavailable:{retryable:!0},event_queue_failed:{retryable:!0},event_lease_refused:{retryable:!0},compact_endpoint_unsupported:{retryable:!1},host_shutdown:{retryable:!0},host_handoff:{retryable:!0}},SOCKET_CLOSING_FLUSH_MS=1e3,closing=new WeakSet;function closeSocket(transport,queue,compact,code,detail){if(!compact)return transport.close?.(),Promise.resolve();if(closing.has(transport))return Promise.resolve();closing.add(transport),queue.close();let{retryable}=SOCKET_CLOSING_CODES[code],record={type:"socket_closing",code,retryable,...detail===void 0?{}:{detail}},drained;try{transport.writeRaw(serializeJsonLine(record)),drained=transport.waitForBackpressure()}catch(cause){drained=Promise.reject(cause)}return settledWithin(drained,SOCKET_CLOSING_FLUSH_MS).then(failure=>{failure!==void 0&&process.stderr.write(`senpi rpc socket_closing (${code}) not delivered: ${failure}; closing
`),transport.close?.()})}function settledWithin(drained,ms){let timer,bound=new Promise(resolve2=>{timer=setTimeout(resolve2,ms,void 0),timer.unref?.()}),settled=drained.then(()=>{},cause=>cause instanceof Error?cause.message:String(cause));return Promise.race([settled,bound]).finally(()=>clearTimeout(timer))}function queueFailureDetail(cause){return cause instanceof SocketEventQueueOverflowError?"overflow":cause instanceof SocketEventQueueStallError?"stall":"transport_error"}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=>{let current=this.connections.get(id)?.actor===actor,compact=current&&this.connectionHas(id,COMPACT_EVENTS_CAPABILITY);current&&(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)}
`),closeSocket(connection,actor,compact,"event_queue_failed",queueFailureDetail(cause))},options.maxQueueBytes,options.stallMs,this.shedMode);actor instanceof AdmissionRoutingActor&&actor.bind(this.checkpoints,socketEpoch,id);let close=(code,detail)=>{closeSocket(connection,actor,this.connectionHas(id,COMPACT_EVENTS_CAPABILITY),code,detail)},selection=new CompactSelection;this.connections.set(id,{connection:transportOf(connection),actor,socketEpoch,owner,selection,close}),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,delegationOf=()=>{}){this.storage=new AsyncLocalStorage2,this.ownerOf=ownerOf,this.delegationOf=delegationOf}run(id,task){let delegation=this.delegationOf(id);return this.storage.run({id,owner:this.ownerOf(id),...delegation===void 0?{}:{delegation}},task)}outside(task){return this.storage.exit(task)}get delegation(){return this.storage.getStore()?.delegation}runCaptured(id,identity2,task){let owner=this.ownerOf(id),binding=owner?.ownerId===identity2.ownerId?owner.peek(identity2.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,terminal){if(terminal!==void 0)return terminal.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,terminal,cause){let status=statusOf(entry,runtime,fanout,terminal),reason=terminal?.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}:{},archived:entry.archived===!0,...entry.settled??{settled:!1},...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},...runtime?.waiting!==void 0&&status==="running"?{waiting:runtime.waiting}:{},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":reason==="host_shutdown"?"host_shutdown":"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_info_changed":return"rename";case"session_parked":return"park";case"session_closed":return"close";case"session_archived_changed":return"archive";case"session_settled_changed":return"settle";case"question_resolved":return"question";case"auto_retry_start":case"auto_retry_end":return"retry";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,entryView,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=entryView();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 isRecord3(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(!isRecord3(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,field2){return value===void 0||typeof value=="boolean"?value:{reason:`${field2} must be a boolean`,action:`send ${field2}: 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,view.entry.lastActivityAt,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,terminal,cause,by){this.terminals.set(sessionId,terminal),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,lastActivityAt,at){return this.lastChanges.get(sessionId)??{at:lastActivityAt===void 0?at??(this.delivery.now?.()??new Date).toISOString():new Date(lastActivityAt).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,id=>this.delegationDescriptorOf(id)),this.locality={isRemote:connection=>this.isRemoteConnection(connection),originOf:connection=>this.originOf?.(connection)},this.securityPresentations=new RpcSecurityPresentations(this.fanout,(id,task)=>this.withConnection(id,task),()=>this.requestFlush(),this.locality),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.locality),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}};function presenterContextReply(authority,sender,request,advertised){let sessionId="sessionId"in request&&typeof request.sessionId=="string"?request.sessionId:void 0,context=sender&&sessionId!==void 0?authority?.connectionContext(sender,sessionId):void 0;if(!context)return{error:"presenter_not_authorized"};let controlEndpoint="discover"in request&&request.discover===!0?advertised:void 0;return{ok:!0,context:controlEndpoint===void 0?context:{...context,controlEndpoint}}}var CLASSIFY_RECORD_COMMAND="classify_record";function classifyRecord(record){let id=requestId(record),target=Reflect.get(record,"record"),methodClass=classifyRpcMethod(target),type=typeof target=="object"&&target!==null?Reflect.get(target,"type"):void 0,entry=methodClass!==void 0&&typeof type=="string"?RPC_METHOD_CLASS[type]:void 0;return{...id===void 0?{}:{id},type:"response",command:CLASSIFY_RECORD_COMMAND,success:!0,data:{class:methodClass??null,version:RPC_METHOD_CLASSES_VERSION,digest:RPC_METHOD_CLASSES_DIGEST,...entry===void 0?{}:typeof entry=="string"?{static:!0}:{static:!1,rule:entry.version}}}}function createRecord(principal,granted,roles){return roles===void 0?{principal,mode:"legacy",granted,current:void 0,lastIncarnation:0,closed:!1}:{principal,mode:"host",granted,current:{incarnation:1,authority:createAuthority(1,maskOfRoles(roles))},lastIncarnation:1,closed:!1}}function narrowRecord(record,parsed){if(!samePrincipal(record.principal,parsed.principal)||[...parsed.granted].some(c=>!record.granted.has(c)))return!1;if(parsed.roles!==void 0){if(record.current===void 0)return!1;let mask=readAuthority(record.current.authority).roles;if([...parsed.roles].some(role=>!mask.includes(role)))return!1;storeNarrowed(record.current.authority,parsed.roles)}return record.granted=parsed.granted,!0}function echoedRoles(record){let current=record.current;return current===void 0?{}:{roles:rolesOfMask(readAuthority(current.authority).mask)}}function descriptorOf(record){let current=record.current;return current===void 0?{principal:record.principal,mode:record.mode}:{principal:record.principal,mode:record.mode,...current}}function rotateIncarnation(record,max=2147483647){let current=record.current;if(record.mode!=="host"||current===void 0||record.closed)return!0;storeRetired(current.authority);let next=nextIncarnation(record.lastIncarnation,max);return next===void 0?(record.closed=!0,!1):(record.lastIncarnation=next,record.current={incarnation:next,authority:createAuthority(next,readAuthority(current.authority).mask)},!0)}function closeRecord(record){record.current!==void 0&&storeRetired(record.current.authority),record.closed=!0}var PRESENTER_CONTROL_INFO_COMMAND="mcp_presenter_control_info",PRESENTER_CLIENT_RECORDS=new Set(["mcp_presenter_context","mcp_form_presented","mcp_form_response","mcp_form_sync"]);function isPrivatePresenterType(type){return typeof type=="string"&&(type.startsWith("mcp_form_")||type.startsWith("mcp_presenter_"))}function privatePresenterVerdict(type,id,granted){return type===PRESENTER_CONTROL_INFO_COMMAND?{kind:"private",id,error:"presenter_not_authorized"}:PRESENTER_CLIENT_RECORDS.has(type)?granted.has("answer")?{kind:"presenter",id}:{kind:"private",id,error:"delegation_not_granted"}:{kind:"private",id,error:"delegation_unclassified"}}var DECLARE_DELEGATION_COMMAND="declare_delegation",CONNECTION_LOCAL_REQUIREMENT={set_client_info:"self",subscribe_sessions:"observe",unsubscribe_sessions:"self",record_user_activity:"drive",detach_connection:"self",release_session:"device_admin",warm:"device_admin",host_response:"self",release_attachment:"self",reclaim_session:"device_admin",move_session:"device_admin",get_recovery_page:"self",release_recovery:"self",cancel_attempt:"self",reset_stream:"self"},PRE_DECLARATION=new Set(["get_protocol_info","authenticate",RPC_LAUNCH_PROOF_RECORD]),PASS={kind:"pass"},CONSUMED={kind:"consumed"},ConnectionDelegations=class{constructor(options={}){this.connections=new Map,this.incarnationMax=options.incarnationMax??2147483647,this.endConnection=options.endConnection}admit(id,proofSource){this.connections.has(id)||this.connections.set(id,{proofSource,proven:proofSource==="proven",spoken:!1,delegation:void 0})}close(id){let delegation=this.connections.get(id)?.delegation;delegation===void 0?this.connections.delete(id):closeRecord(delegation)}forget(id){this.connections.delete(id)}recordOf(id){return this.connections.get(id)?.delegation}descriptorOf(id){let record=this.recordOf(id);return record===void 0?void 0:descriptorOf(record)}viewOf(id){let record=this.recordOf(id);return record===void 0?void 0:{descriptor:descriptorOf(record),closed:record.closed}}lineAnswered(id){let state=id===void 0?void 0:this.connections.get(id);id===void 0||state?.endAfterAnswer!==!0||(delete state.endAfterAnswer,this.endConnection?.(id))}isDelegated(id){return id!==void 0&&this.connections.get(id)?.delegation!==void 0}unparsable(id,error){return{type:"response",command:"parse",success:!1,error,...this.isDelegated(id)?{errorCode:"delegation_malformed"}:{}}}inspect(id,record){let state=id===void 0?void 0:this.state(id),type=typeof record=="object"&&record!==null?Reflect.get(record,"type"):void 0;if(type===RPC_LAUNCH_PROOF_RECORD&&state?.proofSource!==void 0)return state.proven=!0,CONSUMED;if(type===DECLARE_DELEGATION_COMMAND)return{kind:"reply",response:this.declaration(state,record)};if(type===CLASSIFY_RECORD_COMMAND)return state&&(state.spoken=!0),{kind:"reply",response:classifyRecord(record)};if(isMachineOpCommand(type)){state&&(state.spoken=!0);let id2=requestId(record);return state?.proven===!0&&state.delegation===void 0?{kind:"machine_op",id:id2,command:type}:{kind:"reply",response:machineOpRefusal(id2,type)}}if(type===PRESENTER_CONTROL_INFO_COMMAND&&state?.delegation===void 0)return state&&(state.spoken=!0),state?.proven===!0?{kind:"control_info",id:requestId(record)}:{kind:"reply",response:refused(requestId(record),PRESENTER_CONTROL_INFO_COMMAND,"presenter_not_authorized","mcp_presenter_control_info needs a connection that proved the endpoint's launch key")};if(state===void 0)return PASS;PRE_DECLARATION.has(type)||(state.spoken=!0);let delegation=state.delegation;if(delegation===void 0)return PASS;if(isPrivatePresenterType(type))return privatePresenterVerdict(type,requestId(record),delegation.granted);let refusal3=refuseOnDelegation(record,delegation.granted);return refusal3!==void 0?{kind:"reply",response:refusal3}:(type==="detach_connection"&&!rotateIncarnation(delegation,this.incarnationMax)&&(state.endAfterAnswer=!0),PASS)}state(id){let state=this.connections.get(id);return state===void 0&&(state={proofSource:void 0,proven:!1,spoken:!1,delegation:void 0},this.connections.set(id,state)),state}declaration(state,record){let id=requestId(record),parsed=parseDeclaration(record);if(typeof parsed=="string")return refused(id,DECLARE_DELEGATION_COMMAND,"delegation_malformed",parsed);if(state===void 0||!state.proven)return refused(id,DECLARE_DELEGATION_COMMAND,"delegation_unauthenticated","declare_delegation needs a connection that proved the endpoint's launch key");let current=state.delegation;if(current!==void 0){if(!narrowRecord(current,parsed))return refused(id,DECLARE_DELEGATION_COMMAND,"delegation_fixed","a delegated connection keeps its principal and mode and can only narrow its grant and roles")}else{if(state.spoken)return refused(id,DECLARE_DELEGATION_COMMAND,"delegation_late","declare_delegation must come before any record other than get_protocol_info or authenticate");current=createRecord(parsed.principal,parsed.granted,parsed.roles),state.delegation=current}return{...id===void 0?{}:{id},type:"response",command:DECLARE_DELEGATION_COMMAND,success:!0,data:{granted:[...parsed.granted],digest:RPC_METHOD_CLASSES_DIGEST,...echoedRoles(current)}}}};function refuseOnDelegation(record,granted){let object=typeof record=="object"&&record!==null&&!Array.isArray(record)?record:void 0,id=object===void 0?void 0:requestId(object),type=object===void 0?void 0:Reflect.get(object,"type");if(typeof type!="string")return refused(id,"parse","delegation_malformed","a record is a JSON object with a string type");let command=type,methodClass=classifyRpcMethod(record);if(methodClass===void 0)return refused(id,command,"delegation_unclassified",`the engine does not classify ${command}`);if(methodClass!=="connection_local")return granted.has(methodClass)?void 0:refused(id,command,"delegation_not_granted",`${command} needs the ${methodClass} grant`,{class:methodClass});let required=CONNECTION_LOCAL_REQUIREMENT[command];if(!(required==="self"||granted.has(required)))return refused(id,command,"delegation_local_only",`${command} on a delegated connection needs the ${required} grant`,{class:required})}var SessionEventWriterConnections=class extends SessionEventWriterLanes{constructor(){super(...arguments),this.delegations=new ConnectionDelegations}delegationDescriptorOf(id){return this.delegations.descriptorOf(id)}isRemoteConnection(connection){return this.delegations.isDelegated(connection)||this.originOf?.(connection)!==void 0}isTargetedRecord(record){return record.type==="response"||record.type==="bash_execution_update"||record.type==="host_request"||record.type==="relocation_due"||record.type==="extension_ui_request"&&record.audience!=="session"&&["select","confirm","input","editor"].includes(String(record.method))}isSessionSealed(sessionId){return this.sealedSessions.has(sessionId)}registerConnection(id,connection,options={}){this.delegations.admit(id,options.launchProof);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.delegations.close(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,requestId2,preferred,capabilities,cancel,title){return this.securityPresentations.routeWorkerGrant(sessionId,requestId2,preferred,capabilities,cancel,title)}noticeGrantDialog(sessionId,id,title){this.securityPresentations.noticeGrant(sessionId,id,title,this.currentConnection())}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)}closeConnection(id,code,close){let registered=this.fanout.get(id),compact=registered!==void 0&&this.fanout.connectionHas(id,COMPACT_EVENTS_CAPABILITY);return registered===void 0?(close(!1),Promise.resolve()):closeSocket({...registered.connection,close:()=>close(compact)},registered.actor,compact,code)}async flushConnection(id){let target=this.fanout.get(id);target&&await settleActors([target.actor])}endExhaustedConnections(sinkOf){this.delegations.endConnection=id=>{let sink=sinkOf(id);sink&&this.flushConnection(id).finally(()=>sink.close?.())}}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 authority(){return this.enableMcpPresenters()}get mcpPresenters(){return this.presenterAuthority}advertiseMcpPresenterControl(path){this.presenterControlEndpoint=path}withdrawMcpPresenterControl(path){this.presenterControlEndpoint===path&&(this.presenterControlEndpoint=void 0)}get mcpPresenterControlEndpoint(){return this.presenterControlEndpoint}writeMcpFormReply(requestId2,reply){let id=this.currentConnection(),connection=id===void 0?void 0:this.fanout.get(id)?.connection;if(connection)try{connection.writeRaw(serializeJsonLine({type:"mcp_form_reply",...requestId2===void 0?{}:{id:requestId2},...reply}))}catch{let sender=id===void 0?void 0:this.presenterConnections.get(id);sender&&this.presenterAuthority?.detach(sender)}}attachSealedSecrets(source){return this.secretPresentations.useSealed(source)}mcpPresenterContextReply(sender,request){return presenterContextReply(this.presenterAuthority,sender,request,this.presenterControlEndpoint)}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"&&value.type!=="mcp_presenter_secret_answer")return!1;let id=this.currentConnection(),connection=id===void 0?void 0:this.fanout.get(id)?.connection;if(value.type==="mcp_presenter_secret_answer"){let lineId="id"in value&&typeof value.id=="string"?{id:value.id}:{};return id!==void 0&&connection&&this.secretPresentations.answerSealed(id,value).catch(()=>({error:"secret_answer_refused"})).then(reply2=>{try{connection.writeRaw(serializeJsonLine({...reply2,type:"mcp_presenter_secret_reply",...lineId}))}catch{}}),!0}let sender=id===void 0?void 0:this.presenterConnections.get(id),reply=value.type==="mcp_presenter_context"?this.mcpPresenterContextReply(sender,value):sender&&this.presenterAuthority?this.presenterAuthority.receive(sender,value):{error:"presenter_not_authorized"};return this.writeMcpFormReply("id"in value&&typeof value.id=="string"?value.id:void 0,reply),!0}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,...plain}=record;return{plain:serializeJsonLine(plain),withContext:serializeJsonLine(context===void 0?plain:{...plain,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 terminal=terminalOfLifecycle(lifecycle),cause=causeOfRecord(lifecycle);terminal!==void 0&&cause!==void 0&&this.status.seal(sessionId,terminal,cause,this.changeActor("host"))}reserveCloseResponse(sessionId,response,records=2){let bytes=Buffer.byteLength(serializeJsonLine({...withReceipt(response,this.currentConnection()),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:(terminal,reason)=>{if(!active)return;release();let reply=withReceipt(response,this.currentConnection());terminal&&!this.sealedSessions.has(sessionId)?this.closeSession(sessionId,reply,reason):this.appendClosedResponse(sessionId,reply)}}}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=>{if(!lane||lane.retired)return actor.remember(sessionId,this.recoveryCheckpoints,socketEpoch??"")?.routes.includes(id)===!0;if(socketEpoch&&this.recoveryCheckpoints.stream({socketEpoch,sessionId})?.routes.includes(id))return!0;let frozen=socketEpoch&&lane?this.recoveryCheckpoints.freeze({socketEpoch,sessionId,peer,admissionId:id,routeKind:"mirror"},lane,!0):void 0;return frozen?.ok||(actor.pendingMirrors.get(id)?.retire("storage_unavailable"),process.stderr.write(`senpi rpc mirror checkpoint unavailable (${type}); closing connection
`),this.fanout.get(peer)?.close("checkpoint_unavailable",frozen?.failure.reason)),!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}};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,minted=fanout.events.mint({...caller,admissionId:owner},at,record,{chunks:()=>payload(content)});if(!minted.ok){let{reason}=minted;return{line:serializeJsonLine({type:"event_lease_refused",sessionId,reason}),atomic:!0,undelivered:()=>registered.close("event_lease_refused",reason)}}let held=fanout.events.claim(caller,minted.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:minted.value,materializer:{...at,generation:stream.generation,payload:minted.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,minted.value.id),new RangeError("materializer envelope exceeded H");return{line,atomic:!0,undelivered:written=>{written||fanout.events?.abandon(caller.socketEpoch,minted.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);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)?.close("compact_endpoint_unsupported")};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 identity3=lane.identities.of(record.type,lane.acceptedSequence)??unvouchedCall(record),stamped2=identity3?{...record,...identity3}:record;copy={stamped:stamped2,line:identity3?new RecordLine(stamped2):line},copies.set(record,copy)}let{stamped,line:stampedLine}=copy,identity2=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,...identity2?{record:stamped}:{}};let at={sessionEpoch:lane.sessionEpoch,sequence:lane.acceptedSequence},routes=this.ordinaryRoute(target,sessionId)?.routes??[],owner=routes[0]??admissionId,minted=events.mint({socketEpoch,sessionId,admissionId:owner},at,stamped,built??size);if(minted.ok){let{id}=minted.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:minted.value}),...identity2?{record:stamped}:{},undelivered:written=>{written||events.abandon(socketEpoch,id)}}}process.stderr.write(`senpi rpc connection ${target} event lease refused (${minted.reason}); closing
`);let{reason}=minted;return{line:serializeJsonLine({type:"event_lease_refused",sessionId,reason}),undelivered:()=>this.fanout.get(target)?.close("event_lease_refused",reason)}}};var SessionEventWriter=class extends SessionEventWriterDestinations{secretInputRoute(sessionId,sealed=!1){return this.secretPresentations.route(sessionId,sealed)}setSoleSecretCapabilities(capabilities){this.secretPresentations.handshake(capabilities)}enqueue(sessionId,value){if(value=withReceipt(value,this.connectionContext.getStore()),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();value=withReceipt(value,peer);let 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)}))}}}import{randomUUID as randomUUID6}from"node:crypto";import{mkdtemp,rm as rm2}from"node:fs/promises";import{tmpdir as tmpdir3}from"node:os";import{join as join3}from"node:path";import{createServer}from"node:net";import{randomBytes as randomBytes4,randomUUID as randomUUID4}from"node:crypto";import{createHash as createHash2,createPublicKey,randomBytes as randomBytes3,randomUUID as randomUUID3}from"node:crypto";import{randomBytes as randomBytes2,randomUUID as randomUUID2,verify}from"node:crypto";function signed(value,transcript,key){return!isRecord(value)||Object.keys(value).length!==2||value.type!=="proof"||typeof value.signature!="string"||!/^[a-f0-9]{128}$/.test(value.signature)?!1:verify(null,Buffer.from(transcript),key,Buffer.from(value.signature,"hex"))}function challengeTranscript(hostInstance,backendGeneration,command){return JSON.stringify(["mcp-presenter-control-v1",hostInstance,backendGeneration,randomUUID2(),randomBytes2(32).toString("hex"),command])}function send(stream,value){stream.write(`${JSON.stringify(value)}
`)||stream.destroy()}function privateFrames(stream,receive,deadline=!0){let parked=deadline==="parked",timer=deadline===!1?void 0:setTimeout(()=>stream.destroy(),parked?PRESENTER_PARKING_MS:PRESENTER_EXCHANGE_MS),detach=attachJsonlLineReader(stream,line=>{parked&&(parked=!1,clearTimeout(timer),timer=setTimeout(()=>stream.destroy(),PRESENTER_EXCHANGE_MS));try{receive(JSON.parse(line))}catch{stream.destroy()}},{maxLineLength:16*1024,onOversizedLine:()=>stream.destroy()});return stream.on("error",()=>stream.destroy()),stream.once("close",()=>{clearTimeout(timer),detach()}),()=>{clearTimeout(timer),detach()}}function identity(value){return typeof value=="string"&&value.length>0&&value.length<=256}function installationKey(publicKey,installationKeyId){if(!(typeof publicKey!="string"||publicKey.length>1024)&&!(typeof installationKeyId!="string"||!/^[a-f0-9]{64}$/.test(installationKeyId)))try{let key=createPublicKey(publicKey),spki=key.export({type:"spki",format:"der"});return key.asymmetricKeyType!=="ed25519"?void 0:createHash2("sha256").update(spki).digest("hex")===installationKeyId?key:void 0}catch{return}}function parseAccountEnrollment(value){if(!isRecord(value)||Object.keys(value).length!==6||value.type!=="account_enroll"||value.version!==1||value.purpose!=="mcp_form"||typeof value.installationKeyId!="string"||typeof value.attestation!="string"||value.attestation.length>8192)return;let key=installationKey(value.publicKey,value.installationKeyId);return key&&{key,installationKeyId:value.installationKeyId,attestation:value.attestation}}function accountEnrollmentTranscript(hostInstance,hostAccount,claims,installationKeyId,nonce){return JSON.stringify(["mcp-presenter-account-enroll-v1","mcp_form",hostInstance,hostAccount,claims.acc,claims.dev,installationKeyId,claims.jti,nonce,3e4])}function parsePresenterEnrollment(value){if(!isRecord(value)||Object.keys(value).length!==11||value.type!=="enroll"||value.version!==2||value.purpose!=="mcp_form"||typeof value.publicKey!="string"||value.publicKey.length>1024||typeof value.installationKeyId!="string"||!/^[a-f0-9]{64}$/.test(value.installationKeyId)||!identity(value.backendGeneration)||typeof value.launchRequestNonce!="string"||!/^[a-f0-9]{64}$/.test(value.launchRequestNonce)||value.launchKind!=="initial"&&value.launchKind!=="replacement"||!identity(value.environmentId))return;let predecessor=value.predecessorHostInstance;if((value.launchKind==="initial"?predecessor!==null:!identity(predecessor))||predecessor!==null&&typeof predecessor!="string")return;let realm=value.executionRealm;if(!Array.isArray(realm))return;let executionRealm;if(realm.length===1&&realm[0]==="native")executionRealm=["native"];else if(realm.length===3&&realm[0]==="wsl"&&identity(realm[1])&&identity(realm[2]))executionRealm=["wsl",realm[1],realm[2]];else return;if(installationKey(value.publicKey,value.installationKeyId))return{type:"enroll",version:2,purpose:"mcp_form",publicKey:value.publicKey,installationKeyId:value.installationKeyId,backendGeneration:value.backendGeneration,launchRequestNonce:value.launchRequestNonce,launchKind:value.launchKind,predecessorHostInstance:predecessor,executionRealm,environmentId:value.environmentId}}function presenterEnrollmentTranscript(request,hostInstance,nonce){return JSON.stringify(["mcp-presenter-enroll-v2",request.purpose,request.installationKeyId,request.backendGeneration,request.launchRequestNonce,request.launchKind,request.predecessorHostInstance,request.executionRealm,request.environmentId,hostInstance,nonce,3e4])}var McpPresenterEnrollment=class{constructor(hostInstance,endpoint){this.started=!1,this.nonces=new Set,this.hostInstance=hostInstance,this.endpoint=endpoint}bootstrap(stream,enrolled){if(this.started){stream.destroy();return}this.started=!0,this.stream=stream;let pending,consumed=!1,stop=privateFrames(stream,value=>{if(consumed)return;if(!pending){if(isRecord(value)&&value.type==="enroll"&&value.version!==2){consumed=!0,stop(),stream.end(`${JSON.stringify({type:"unavailable",versions:[2]})}
`);return}let request=parsePresenterEnrollment(value);if(!request||request.predecessorHostInstance===this.hostInstance){stream.destroy();return}this.nonces.add(request.launchRequestNonce),pending={request,key:createPublicKey(request.publicKey),transcript:presenterEnrollmentTranscript(request,this.hostInstance,randomBytes3(32).toString("hex")),deadline:performance.now()+3e4},send(stream,{type:"challenge",version:2,transcript:pending.transcript,hostInstance:this.hostInstance});return}let attempt=pending;if(consumed=!0,pending=void 0,stop(),performance.now()>=attempt.deadline||!signed(value,attempt.transcript,attempt.key)){stream.destroy();return}let principal={id:randomUUID3(),key:attempt.key,enrollment:attempt.request};enrolled(principal),stream.end(`${JSON.stringify({type:"enrolled",version:2,principalId:principal.id,hostInstance:this.hostInstance,backendGeneration:attempt.request.backendGeneration,launchRequestNonce:attempt.request.launchRequestNonce,endpoint:this.endpoint})}
`)},"parked")}dispose(){this.stream?.destroy(),this.nonces.clear()}};function accountLapse(principal,authority){let hostAccount=authority?.hostAccount();return hostAccount===void 0?"presenter_account_unavailable":hostAccount!==principal.acc?"presenter_account_mismatch":Date.now()/1e3<principal.attestedUntil?void 0:"attestation_expired"}var AttestationExpiry=class{constructor(){this.timers=new Map}arm(principal,expire){this.clear(principal);let delay=Math.max(0,principal.attestedUntil*1e3-Date.now()),timer=setTimeout(expire,delay);timer.unref(),this.timers.set(principal,timer)}clear(principal){clearTimeout(this.timers.get(principal)),this.timers.delete(principal)}dispose(){for(let timer of this.timers.values())clearTimeout(timer);this.timers.clear()}};import{createHash as createHash3}from"node:crypto";var ED25519_SPKI_PREFIX=Buffer.from("302a300506032b6570032100","hex");function presenterKeyThumbprint(spkiDer){let der=Buffer.from(spkiDer);if(der.length!==44||!der.subarray(0,12).equals(ED25519_SPKI_PREFIX))return;let x=der.subarray(12).toString("base64url");return createHash3("sha256").update(JSON.stringify({crv:"Ed25519",kty:"OKP",x})).digest("base64url")}var PresenterJtiCache=class{constructor(cap=4096){this.seen=new Map,this.cap=cap}admit(jti,exp,nowS){for(let[id,until]of this.seen)until<=nowS&&this.seen.delete(id);return this.seen.has(jti)?"attestation_replayed":this.seen.size>=this.cap?"presenter_busy":(this.seen.set(jti,exp+60),"ok")}clear(){this.seen.clear()}};function boundedClaim(value){return value.length>0&&value.length<=256&&!new RegExp("\\p{Cc}","u").test(value)}function accountIdentity(principal){return{principalKind:"account",dev:principal.dev,dname:principal.dname}}function refuse(stream,reason){stream.end(`${JSON.stringify({type:"account_refused",version:1,reason})}
`,()=>stream.destroy())}var McpPresenterAccounts=class{constructor(hostInstance,principals,authority,revokeStream){this.jtis=new PresenterJtiCache,this.attempts=new WeakMap,this.started=new WeakSet,this.verifying=new WeakSet,this.closing=new WeakSet,this.expiry=new AttestationExpiry,this.hostInstance=hostInstance,this.principals=principals,this.authority=authority,this.revokeStream=revokeStream,this.unsubscribe=authority?.onAccountChange(()=>{for(let principal of[...this.principals.values()])principal.kind==="account"&&this.revoke(principal,accountLapse(principal,this.authority)??"presenter_account_mismatch")})}receive(stream,value,fresh,authenticated){if(this.closing.has(stream))return!0;if(this.verifying.has(stream))return stream.destroy(),!0;let attempt=this.attempts.get(stream);if(attempt)return this.attempts.delete(stream),this.prove(stream,value,attempt,authenticated),!0;if(value.type==="account_enroll")return!fresh||this.started.has(stream)?stream.destroy():this.enroll(stream,value),!0;if(value.type!=="account_reattest")return!1;let principal=this.principalOn(stream);return!principal||Object.keys(value).length!==2||typeof value.attestation!="string"?stream.destroy():this.reattest(stream,principal,value.attestation),!0}lapsed(principal){if(principal.kind!=="account")return!1;let reason=accountLapse(principal,this.authority);return reason!==void 0&&this.revoke(principal,reason),reason!==void 0}dispose(){this.unsubscribe?.(),this.expiry.dispose(),this.jtis.clear()}async enroll(stream,value){this.started.add(stream);let request=parseAccountEnrollment(value);if(!request)return void stream.destroy();this.verifying.add(stream);let attested=await this.attest(stream,request.attestation,request.key);if(this.verifying.delete(stream),attested===void 0)return;if(typeof attested=="string")return this.refuse(stream,attested);let transcript=accountEnrollmentTranscript(this.hostInstance,attested.acc,attested,request.installationKeyId,randomBytes4(32).toString("hex"));this.attempts.set(stream,{request,attestation:attested,transcript}),send(stream,{type:"challenge",version:1,transcript,hostInstance:this.hostInstance})}prove(stream,value,attempt,authenticated){let{request,attestation}=attempt;if(!signed(value,attempt.transcript,request.key))return this.refuse(stream,"presenter_proof_invalid");if(this.authority?.hostAccount()!==attestation.acc)return this.refuse(stream,"presenter_account_mismatch");for(let old of this.principals.values())old.kind==="account"&&old.acc===attestation.acc&&old.dev===attestation.dev&&old.installationKeyId===request.installationKeyId&&this.revoke(old);let principal={kind:"account",id:randomUUID4(),key:request.key,acc:attestation.acc,dev:attestation.dev,dname:attestation.dname,installationKeyId:request.installationKeyId,attestedUntil:attestation.exp,stream,sessions:new WeakSet};this.principals.set(principal.id,principal),this.expireAt(principal),stream.once("close",()=>{this.expiry.clear(principal),this.principals.get(principal.id)===principal&&this.principals.delete(principal.id)}),authenticated(),send(stream,{type:"account_enrolled",version:1,principalId:principal.id,hostInstance:this.hostInstance,attestedUntil:principal.attestedUntil})}async reattest(stream,principal,token){let attested=await this.attest(stream,token,principal.key);if(!(attested===void 0||this.principals.get(principal.id)!==principal)){if(typeof attested!="string"&&attested.acc!==principal.acc&&(attested="presenter_account_mismatch"),typeof attested!="string")return principal.attestedUntil=attested.exp,this.expireAt(principal),send(stream,{type:"account_reattested",version:1,attestedUntil:attested.exp});if(attested==="attestation_key_mismatch"||attested==="presenter_account_mismatch"||attested==="presenter_account_unavailable")return this.revoke(principal,attested);send(stream,{type:"account_refused",version:1,reason:attested})}}async attest(stream,token,key){let authority=this.authority;if(!authority||authority.hostAccount()===void 0)return"presenter_account_unavailable";let nowS=Math.floor(Date.now()/1e3),result;try{result=await authority.verify(token,key.export({type:"spki",format:"der"}),nowS)}catch{stream.destroy();return}if(stream.destroyed)return;if(!result.ok)return result.reason;let{attestation}=result;if(![attestation.dev,attestation.dname,attestation.jti].every(boundedClaim)||!Number.isSafeInteger(attestation.exp)||attestation.exp>nowS+960)return"attestation_malformed";let hostAccount=authority.hostAccount();if(hostAccount===void 0)return"presenter_account_unavailable";if(attestation.acc!==hostAccount)return"presenter_account_mismatch";let admitted=this.jtis.admit(attestation.jti,attestation.exp,nowS);return admitted==="ok"?attestation:admitted}expireAt(principal){this.expiry.arm(principal,()=>{this.principals.get(principal.id)===principal&&this.revoke(principal,"attestation_expired")})}principalOn(stream){for(let principal of this.principals.values())if(principal.kind==="account"&&principal.stream===stream)return principal}revoke(principal,reason){this.expiry.clear(principal),this.principals.delete(principal.id),this.revokeStream(principal.stream),reason?this.refuse(principal.stream,reason):principal.stream.destroy()}refuse(stream,reason){this.closing.add(stream),refuse(stream,reason)}};function runPresenterCommand(command,control){let{host,authority,stream,id,principal,owner,registrations,sealed}=control;switch(command.type){case"mcp_presenter_assign":{let binding=typeof command.sessionId=="string"?host.getMcpFormBinding(command.sessionId):void 0;if(!binding||binding.epoch!==command.bindingEpoch||command.purpose!=="mcp_form")throw new Error("presenter_not_authorized");principal.sessions.add(binding),send(stream,{type:"mcp_presenter_assigned",id,sessionId:command.sessionId});return}case"mcp_presenter_acquire":{if(command.hostInstance!==authority.instance||typeof command.sessionId!="string"||typeof command.bindingEpoch!="string"||typeof command.connectionNonce!="string"||command.kind!=="desktop"&&command.kind!=="gateway"||command.features!==void 0&&!features(command.features))throw new Error("presenter_not_authorized");let binding=host.getMcpFormBinding(command.sessionId),connection=host.findMcpPresenterConnection(command.connectionNonce);if(!binding||!principal.sessions.has(binding)||binding.epoch!==command.bindingEpoch||!connection)throw new Error("presenter_not_authorized");let capabilities=host.getConnectionCapabilities(connection.id);if(!capabilities?.includes("interactive_user")||!capabilities.includes("mcp_form_presenter_v1"))throw new Error("presenter_not_authorized");let context=authority.connectionContext(connection,command.sessionId);if(!context||command.purpose!=="mcp_form"||command.attachmentId!==context.attachmentId||command.attachmentEpoch!==context.attachmentEpoch)throw new Error("presenter_not_authorized");let registration=owner.register(binding,connection,{kind:command.kind,features:command.features}),grant=owner.acquire(registration);registrations.set(registration.id,registration),features(command.features)&&command.features.includes(SECRET_INPUT_FEATURE)&&sealed?.tokens.want(grant.scope.durableSessionId,binding,()=>authority.secretInputHeld(binding)),send(stream,{type:"mcp_presenter_acquired",id,registrationId:registration.id,...grant});return}case"mcp_presenter_revoke":{let registration=typeof command.registrationId=="string"?registrations.get(command.registrationId):void 0;if(!registration)throw new Error("presenter_not_authorized");owner.revoke(registration),registrations.delete(registration.id),send(stream,{type:"mcp_presenter_revoked",id});return}default:throw new Error("presenter_not_authorized")}}import{generateKeyPairSync,sign}from"node:crypto";var HOST_TOKEN_AUDIENCE="omo-secret-host",HOST_TOKEN_TYPE="secret_host",MAX_LIFETIME_S=900,SKEW_S=60,MAX_TOKEN_CHARS=8192,MINT_TIMEOUT_MS=3e4,RETRY_MAX_MS=6e4,RETRY_MIN_MS=5e3,RETRY_BEFORE_EXP_MS=1e3,RETRY_MIN_WAIT_MS=250;function sealedRouteAuthority(authority){return typeof authority?.mintSecretHostToken=="function"&&typeof authority.verifySecretAnswer=="function"}function claimsOf(token){let parts=token.split(".");if(parts.length===3)try{let claims=JSON.parse(Buffer.from(parts[1]??"","base64url").toString("utf8"));return isRecord(claims)?claims:void 0}catch{return}}var SecretHostTokens=class _SecretHostTokens{static create(hostInstance,authority){return sealedRouteAuthority(authority)?new _SecretHostTokens(hostInstance,authority):void 0}constructor(hostInstance,authority){this.entries=new Map,this.listeners=new Set,this.disposed=!1,this.hostInstance=hostInstance,this.authority=authority;let{publicKey,privateKey}=generateKeyPairSync("ed25519");this.privateKey=privateKey,this.spki=publicKey.export({type:"spki",format:"der"});let jkt=presenterKeyThumbprint(this.spki);if(jkt===void 0)throw new Error("secret_host_key_unavailable");this.hostJkt=jkt,this.hostPk=this.spki.subarray(12).toString("base64url")}want(durableSessionId,binding,held){if(this.disposed||!binding.subscribe||!held())return;let entry=this.entries.get(durableSessionId);if(entry&&entry.binding!==binding&&(this.drop(durableSessionId,entry),entry=void 0),!entry){let created={binding,held,minting:!1};created.unsubscribe=binding.subscribe(()=>{held()||this.drop(durableSessionId,created)}),this.entries.set(durableSessionId,created),entry=created}!entry.minting&&(entry.refresh===void 0||!this.valid(entry.token))&&this.mint(durableSessionId,entry)}current(durableSessionId){let token=this.entries.get(durableSessionId)?.token;return this.valid(token)?token:void 0}valid(token){return token!==void 0&&Date.now()<token.exp*1e3&&token.acc===this.authority.hostAccount()}signRequest(binding){if(binding[1]!==this.hostInstance||binding[2]!==this.hostJkt)throw new Error("secret_request_foreign");return sign(null,Buffer.from(secretRequestTranscript(binding)),this.privateKey).toString("hex")}onToken(listener){return this.listeners.add(listener),()=>this.listeners.delete(listener)}dispose(){this.listeners.clear(),this.disposed=!0;for(let[durableSessionId,entry]of[...this.entries])this.drop(durableSessionId,entry)}async mint(durableSessionId,entry){clearTimeout(entry.refresh),entry.refresh=void 0,entry.minting=!0;let open2=!0,proof=input=>{let{issuer,nonce}=input;if(!open2||typeof issuer!="string"||typeof nonce!="string"||!boundedClaim(issuer)||!boundedClaim(nonce))throw new Error("secret_host_proof_refused");let transcript=["omo-secret-host-proof/v1",issuer,HOST_TOKEN_AUDIENCE,this.hostJkt,nonce,this.hostInstance,durableSessionId].join(`
`);return sign(null,Buffer.from(transcript),this.privateKey).toString("base64url")},minted,deadline;try{if(this.authority.hostAccount()!==void 0){let call=(async()=>this.authority.mintSecretHostToken({hostInstance:this.hostInstance,durableSessionId,hostKeySpki:new Uint8Array(this.spki),sign:proof}))(),timedOut=new Promise(resolve2=>{deadline=setTimeout(()=>resolve2(void 0),MINT_TIMEOUT_MS),deadline.unref()});minted=await Promise.race([call.catch(()=>{}),timedOut])}}finally{clearTimeout(deadline),open2=!1,entry.minting=!1}if(this.disposed||this.entries.get(durableSessionId)!==entry)return;let token=typeof minted=="string"?this.accept(minted,durableSessionId):void 0;if(token){entry.token=token;for(let listener of[...this.listeners])listener(durableSessionId,token);this.arm(durableSessionId,entry,(token.exp*1e3-Date.now())*2/3);return}if(!entry.held())return;let remainingMs2=this.valid(entry.token)?entry.token.exp*1e3-Date.now():void 0,left=remainingMs2===void 0?RETRY_MAX_MS:remainingMs2/3,delay=Math.min(RETRY_MAX_MS,Math.max(RETRY_MIN_MS,left));remainingMs2!==void 0&&(delay=Math.min(delay,Math.max(RETRY_MIN_WAIT_MS,remainingMs2-RETRY_BEFORE_EXP_MS))),this.arm(durableSessionId,entry,delay)}accept(token,durableSessionId){if(token.length===0||token.length>MAX_TOKEN_CHARS)return;let claims=claimsOf(token);if(!claims||!isRecord(claims.cnf))return;let{aud,typ,acc,dev,iat,exp,hin,sid}=claims,nowS=Math.floor(Date.now()/1e3);if(!(aud!==HOST_TOKEN_AUDIENCE||typ!==HOST_TOKEN_TYPE||hin!==this.hostInstance||sid!==durableSessionId||claims.cnf.jkt!==this.hostJkt||typeof acc!="string"||acc!==this.authority.hostAccount()||typeof dev!="string"||!boundedClaim(dev)||typeof iat!="number"||typeof exp!="number"||!Number.isSafeInteger(iat)||!Number.isSafeInteger(exp)||exp<=iat||exp-iat>MAX_LIFETIME_S||iat>nowS+SKEW_S||nowS>=exp))return Object.freeze({token,acc,dev,iat,exp})}arm(durableSessionId,entry,delayMs){clearTimeout(entry.refresh),entry.refresh=setTimeout(()=>{entry.refresh=void 0,!this.disposed&&this.entries.get(durableSessionId)===entry&&!entry.minting&&this.mint(durableSessionId,entry)},Math.max(0,delayMs)),entry.refresh.unref()}drop(durableSessionId,entry){clearTimeout(entry.refresh),entry.refresh=void 0,entry.token=void 0,entry.unsubscribe?.(),this.entries.get(durableSessionId)===entry&&this.entries.delete(durableSessionId)}};var SealedSecretHolders=class _SealedSecretHolders{static create(host,account,principals){let tokens2=SecretHostTokens.create(host.authority.instance,account);return tokens2&&account?new _SealedSecretHolders(host,account,tokens2,principals):void 0}constructor(host,account,tokens2,principals){this.offered=new Map,this.listeners=new Set,this.jtis=new PresenterJtiCache,this.watched=new WeakSet,this.host=host,this.authority=host.authority,this.account=account,this.tokens=tokens2,this.principals=principals,this.unsubscribe=tokens2.onToken((durableSessionId,token)=>{for(let offered of this.offered.values())if(offered.durableSessionId===durableSessionId&&!offered.settled)for(let holder of offered.holders)this.current(holder)&&holder.registration.connection.send({type:"mcp_presenter_secret_token",v:1,hostInstance:this.authority.instance,durableSessionId,hostToken:token.token})}),this.detach=host.attachSealedSecrets?.(this)}holders(sessionId){let binding=this.host.getMcpFormBinding(sessionId);return binding?(binding.subscribe&&!this.watched.has(binding)&&(this.watched.add(binding),binding.subscribe(()=>{for(let listener of[...this.listeners])listener()})),new Set(this.authority.secretCandidates(binding).filter(grant=>this.eligible(grant)))):new Set}eligible(holder){let binding=holder.registration.binding;return this.authority.secretCandidates(binding).includes(holder)&&this.unlapsed(holder)!==void 0&&this.tokens.current(holder.scope.durableSessionId)!==void 0}principalOf(holder){return this.unlapsed(holder)?.id}async answer(holder,frame){let offered=this.offered.get(frame.uiRequestId),principal=this.unlapsed(holder);if(!offered||!offered.holders.has(holder)||!principal)return{error:"secret_answer_refused"};let{req}=offered,checked=await checkSealedAnswer({frame,principal,req,deadlineAtMs:offered.deadlineAtMs,hostToken:this.tokens.current(offered.durableSessionId),account:this.account});if(!checked.ok)return{error:checked.error};let{jti,exp}=checked,value=frame.value;return{uiRequestId:frame.uiRequestId,principal:principal.id,grantId:frame.grantId,answerId:frame.answerId,req,...value===void 0||jti===void 0||exp===void 0?{}:{value:{jti,exp,enc:value.enc.toString("base64url"),ct:value.ct.toString("base64url")}}}}admitJti(jti,exp){return this.jtis.admit(jti,exp,Math.floor(Date.now()/1e3))==="ok"}settle(holders,uiRequestId,outcome,winnerGrant){let offered=this.offered.get(uiRequestId);if(offered)for(let holder of holders)offered.holders.has(holder)&&holder.registration.connection.send({type:"mcp_presenter_secret_settled",v:1,uiRequestId,outcome,elsewhere:holder.id!==winnerGrant})}current(holder){return this.authority.isCurrent(holder)}connectionOf(holder){return holder.registration.connection.id}offer(sessionId,holders,offer){let first=[...holders][0];if(!first)return;let durableSessionId=first.scope.durableSessionId,token=this.tokens.current(durableSessionId);if(!token)return;let binding=secretBinding({hostInstance:this.authority.instance,hostJkt:this.tokens.hostJkt,durableSessionId,...offer}),sig=this.tokens.signRequest(binding);this.offered.set(offer.uiRequestId,{durableSessionId,holders,req:secretRequestHash(binding),deadlineAtMs:offer.deadlineAtMs});for(let holder of holders)holder.registration.connection.send({type:"mcp_presenter_secret_request",v:1,sessionId,durableSessionId,uiRequestId:offer.uiRequestId,title:offer.title,...offer.placeholder===void 0?{}:{placeholder:offer.placeholder},deadlineAtMs:offer.deadlineAtMs,hostInstance:this.authority.instance,hpkePk:offer.hpkePk,hostPk:this.tokens.hostPk,hostToken:token.token,sig})}withdraw(uiRequestId){this.offered.delete(uiRequestId)}retire(uiRequestId){let offered=this.offered.get(uiRequestId);offered&&(offered.settled=!0)}onChange(listener){return this.listeners.add(listener),()=>this.listeners.delete(listener)}dispose(){this.detach?.(),this.unsubscribe(),this.listeners.clear(),this.offered.clear(),this.jtis.clear(),this.tokens.dispose()}unlapsed(grant){let principal=this.principals.get(grant.registration.principal);return principal?.kind==="account"&&accountLapse(principal,this.account)===void 0?principal:void 0}};import{randomUUID as randomUUID5}from"node:crypto";import{Duplex,PassThrough,Readable,Writable}from"node:stream";var McpPresenterSuccessors=class{constructor(predecessor,nonces){this.pending=new Map,this.predecessor=predecessor,this.nonces=nonces}prepare(owner){return owner.stream.destroyed||this.pending.size?Promise.resolve(void 0):new Promise(resolve2=>{let id=randomUUID5(),deadline=performance.now()+3e4,timer=setTimeout(()=>close(),3e4),endpoint,proof,stop=()=>{},close=()=>{clearTimeout(timer),stop(),this.pending.delete(id),endpoint?.destroy(),resolve2(void 0)};this.pending.set(id,{owner,close,receive:value=>{if(performance.now()>=deadline)return close();if(value.type==="mcp_presenter_successor_proof"&&proof&&typeof value.signature=="string"){let forward=proof;proof=void 0,forward(value.signature);return}if(value.type!=="mcp_presenter_successor_authorize"||endpoint)return close();let request=parsePresenterEnrollment(value.enrollment),previous=owner.principal.enrollment;if(!request||request.launchKind!=="replacement"||request.predecessorHostInstance!==this.predecessor||request.backendGeneration!==owner.backendGeneration||request.installationKeyId!==previous.installationKeyId||request.environmentId!==previous.environmentId||JSON.stringify(request.executionRealm)!==JSON.stringify(previous.executionRealm)||this.nonces.has(request.launchRequestNonce))return close();this.nonces.add(request.launchRequestNonce);let toChild=new PassThrough,fromChild=new PassThrough;endpoint=Duplex.from({readable:Readable.toWeb(toChild),writable:Writable.toWeb(fromChild)}),endpoint.once("close",()=>{toChild.destroy(),fromChild.destroy(),close()});let incarnation;stop=privateFrames(fromChild,frame=>{if(performance.now()>=deadline||!isRecord(frame))return close();if(frame.type==="challenge"&&!incarnation&&frame.version===2){if(typeof frame.hostInstance!="string"||frame.hostInstance===this.predecessor||typeof frame.transcript!="string")return close();let tuple=JSON.parse(frame.transcript);if(!Array.isArray(tuple)||typeof tuple[10]!="string"||!/^[a-f0-9]{64}$/.test(tuple[10])||frame.transcript!==presenterEnrollmentTranscript(request,frame.hostInstance,tuple[10]))return close();incarnation=frame.hostInstance,proof=signature=>toChild.write(`${JSON.stringify({type:"proof",signature})}
`),send(owner.stream,{type:"mcp_presenter_successor_challenge",id,challenge:frame})}else frame.type==="enrolled"&&incarnation&&!proof&&frame.version===2&&frame.hostInstance===incarnation&&frame.launchRequestNonce===request.launchRequestNonce&&frame.backendGeneration===request.backendGeneration&&send(owner.stream,{type:"mcp_presenter_successor_enrolled",id,enrollment:frame}),close()}),toChild.write(`${JSON.stringify(request)}
`),resolve2(endpoint)}}),send(owner.stream,{type:"mcp_presenter_successor_prepare",id,version:2,launchKind:"replacement",predecessorHostInstance:this.predecessor,backendGeneration:owner.backendGeneration})})}receive(stream,value){if(value.type!=="mcp_presenter_successor_authorize"&&value.type!=="mcp_presenter_successor_proof")return!1;let pending=typeof value.id=="string"?this.pending.get(value.id):void 0;return!pending||pending.owner.stream!==stream?stream.destroy():pending.receive(value),!0}revoke(stream){for(let pending of this.pending.values())pending.owner.stream===stream&&pending.close()}dispose(){for(let pending of this.pending.values())pending.close()}};var McpPresenterControl=class{constructor(host,path,account){this.principals=new Map,this.controls=new Set,this.revokeControls=new Map,this.backendGenerations=new Map,this.host=host,this.authority=host.authority,this.path=path,this.account=account,this.enrollment=new McpPresenterEnrollment(this.authority.instance,path),this.successors=new McpPresenterSuccessors(this.authority.instance,this.enrollment.nonces),this.accounts=new McpPresenterAccounts(this.authority.instance,this.principals,account,stream=>this.revokeControls.get(stream)?.()),this.sealed=SealedSecretHolders.create(host,account,this.principals),this.server=createServer(stream=>this.manage(stream))}listen(){return new Promise((resolve2,reject)=>{this.server.once("error",reject),this.server.listen(this.path,()=>{this.server.off("error",reject),this.account&&this.host.advertiseMcpPresenterControl(this.path),resolve2()})})}successorBootstrap(){let owner=this.launchOwner;return owner?this.successors.prepare(owner):Promise.resolve(void 0)}successorBootstrapProvider(){return this.launchOwner?()=>this.successorBootstrap():void 0}bootstrap(stream){this.enrollment.bootstrap(stream,principal=>{this.principals.set(principal.id,{...principal,kind:"inherited",sessions:new WeakSet})})}dispose(){this.sealed?.dispose(),this.host.withdrawMcpPresenterControl(this.path);let streams=[...this.controls];for(let revoke of[...this.revokeControls.values()])revoke();this.host.sharedAuthority||this.authority.dispose();for(let stream of streams)stream.destroy();this.controls.clear(),this.successors.dispose(),this.accounts.dispose(),this.enrollment.dispose(),this.principals.clear(),this.server.close()}manage(stream){if(this.controls.size>=64){stream.destroy();return}this.controls.add(stream);let principal,owner,transcript,pending,backendGeneration,deadline=performance.now()+3e4,challengeTimer=setTimeout(()=>stream.destroy(),3e4),registrations=new Map,revoke=()=>{clearTimeout(challengeTimer);for(let registration of registrations.values())owner?.revoke(registration);registrations.clear(),this.controls.delete(stream),this.revokeControls.delete(stream),this.backendGenerations.delete(stream),this.launchOwner?.stream===stream&&(this.launchOwner=void 0),this.successors.revoke(stream)};this.revokeControls.set(stream,revoke),stream.once("close",revoke);let stop=privateFrames(stream,value=>{if(!isRecord(value)){stream.destroy();return}if(this.successors.receive(stream,value)||this.accounts.receive(stream,value,!principal&&!pending,()=>clearTimeout(challengeTimer)))return;if(value.type==="challenge"){if(pending||typeof value.principalId!="string"||typeof value.backendGeneration!="string"||!isRecord(value.command)){stream.destroy();return}let requested=this.principals.get(value.principalId),foreign=requested?.kind==="account"&&requested.stream!==stream;if(!requested||foreign||principal&&principal!==requested){stream.destroy();return}principal=requested,backendGeneration=value.backendGeneration,pending=value.command,deadline=performance.now()+3e4,clearTimeout(challengeTimer),challengeTimer=setTimeout(()=>stream.destroy(),3e4),transcript=challengeTranscript(this.authority.instance,value.backendGeneration,pending),send(stream,{type:"challenge",transcript,hostInstance:this.authority.instance});return}if(!principal||!pending||!transcript||performance.now()>=deadline||!signed(value,transcript,principal.key)){stream.destroy();return}let command=pending;if(clearTimeout(challengeTimer),pending=void 0,transcript=void 0,this.accounts.lapsed(principal))return;if(owner??=this.authority.enroll(principal.id,principal.kind==="account"?accountIdentity(principal):void 0),backendGeneration===void 0){stream.destroy();return}for(let[oldStream,old]of this.backendGenerations)old.principal===principal&&old.generation!==backendGeneration&&(this.revokeControls.get(oldStream)?.(),oldStream.destroy());this.backendGenerations.set(stream,{principal,generation:backendGeneration}),principal.kind==="inherited"&&(this.launchOwner={stream,principal,backendGeneration});let id=typeof command.id=="string"?command.id:void 0;try{runPresenterCommand(command,{host:this.host,authority:this.authority,stream,id,principal,owner,registrations,sealed:this.sealed})}catch{send(stream,{type:"mcp_presenter_error",id,error:"presenter_not_authorized"})}},!1);stream.once("close",stop)}};function presenterPipePath(){return`\\\\.\\pipe\\senpi-presenter-${randomUUID6()}`}async function startMcpPresenterControl(host,options){let{bootstrap,account}=options;if(options.enforcement!==!0||!bootstrap&&!account){bootstrap?.destroy();return}let dir,control;try{return process.platform!=="win32"&&(dir=await mkdtemp(join3(tmpdir3(),"senpi-presenter-"))),control=new McpPresenterControl(host,dir?join3(dir,"control.sock"):presenterPipePath(),account),await control.listen(),bootstrap&&control.bootstrap(bootstrap),{control,...dir&&{dir}}}catch{bootstrap?.destroy(),control?.dispose(),dir&&await rm2(dir,{recursive:!0,force:!0});return}}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)}})}var NOTHING_DROPPED={deliveries:[],user_messages:[]};function takeQueuedInput(session,abortWillFollow=!0){let admittedBefore=session.externalAdmission.list().pending,cleared=session.clearQueue({abortWillFollow}),stillAdmitted=new Set(session.externalAdmission.list().pending);return{deliveries:admittedBefore.filter(deliveryId=>!stillAdmitted.has(deliveryId)),user_messages:cleared.ordered.map(queued=>queued.text)}}async function abortAndSettle(port,sessionId,session){session.abortBash();let stopStarts=session.subscribe(event=>{event.type==="agent_start"&&session.abort()}),deadline,expired=new Promise(resolve2=>{deadline=setTimeout(resolve2,1e4)});try{await Promise.race([Promise.allSettled([session.abort().then(()=>session.waitForIdle()),port.otherRequestsSettled(sessionId),...port.pendingPrompts(sessionId)]),expired])}finally{clearTimeout(deadline),stopStarts()}return session.isIdle?handBackUnwrittenDeliveries(session):[]}function handBackUnwrittenDeliveries(session){let admittedBefore=session.externalAdmission.list().pending;session.takeQueuedDeliveries();let stillAdmitted=new Set(session.externalAdmission.list().pending);return admittedBefore.filter(deliveryId=>!stillAdmitted.has(deliveryId))}var GRACEFUL_CLOSE_DEFAULT_WAIT_MS=6e4,GRACEFUL_CLOSE_MAX_WAIT_MS=6e5,GRACEFUL_ADMISSION_CLOSED="session_closing: the session is closing on request and takes no new deliveries";function gracefulWaitMs(requested){return Math.min(requested??GRACEFUL_CLOSE_DEFAULT_WAIT_MS,GRACEFUL_CLOSE_MAX_WAIT_MS)}function fenceForClose(session){return session.holdForClose(),session.externalAdmission.close(GRACEFUL_ADMISSION_CLOSED),{dropped:takeQueuedInput(session,!1),startedAt:Date.now()}}function reopenAfterDrain(session){session.releaseCloseHold(),session.externalAdmission.reopen()}async function drainUntilQuiet(session,port,waitMs){let deadline=Date.now()+waitMs,settlingPending=!0,changed=Promise.withResolvers(),unsubscribe=session.subscribe(()=>changed.resolve());try{for(;port.busy().length>0;){let left=deadline-Date.now();if(left<=0)return!1;changed=Promise.withResolvers();let timer,expired=new Promise(resolve2=>{timer=setTimeout(resolve2,left)}),waits=[changed.promise.then(()=>settlingPending=!0),expired];settlingPending&&waits.push(Promise.allSettled([session.waitForIdle(),...port.settling()]).then(()=>settlingPending=!1));try{await Promise.race(waits)}finally{clearTimeout(timer)}}return!0}finally{unsubscribe()}}function drainFacts(session,drain){return{turn:session.externalAdmission.turnEpoch,waited_ms:Date.now()-drain.startedAt}}function recordGracefulClose(session,drain){let record={graceful:!0,...drainFacts(session,drain),returned:{deliveries:[...drain.dropped.deliveries],user_messages:[...drain.dropped.user_messages]},stopped:{wake_sources:[...session.activeWakeSources]},at:new Date().toISOString()};return session.releaseCloseHold(),session.recordClosedOnRequest(record),record}export{PRESENTER_CONTROL_INFO_COMMAND,recordLoopBlockedMs,enqueueLegacyRecord,echoedRoles,GeneratedFramesCursor,jsonChunks,refusal2 as refusal,answerSubscribeSessions,answerUnsubscribeSessions,notAttachedRefusal,answerSetSessionContext,captureAdmissionReply,withAdmissionReply,withAdmissionRequest,storageUnavailable,NOTHING_DROPPED,takeQueuedInput,abortAndSettle,gracefulWaitMs,fenceForClose,reopenAfterDrain,drainUntilQuiet,drainFacts,recordGracefulClose,presenterContextReply,SessionEventWriter,socketSink,presenterPipePath,startMcpPresenterControl};