@codexhost/cli-win32-x64 0.28.1 → 0.28.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -7,7 +7,7 @@ Run Pi and Claude Code as first-class external harnesses inside Codex Desktop.
7
7
  ## Install
8
8
 
9
9
  ```bash
10
- npm install -g @codexhost/cli@0.28.1
10
+ npm install -g @codexhost/cli@0.28.2
11
11
  ```
12
12
 
13
13
  Do not install this package directly. npm selects it through the optional dependencies of `@codexhost/cli`.
@@ -1 +1 @@
1
- {"schemaVersion":1,"version":"0.28.1","distribution":"npm","target":"windows-x64"}
1
+ {"schemaVersion":1,"version":"0.28.2","distribution":"npm","target":"windows-x64"}
@@ -124,6 +124,6 @@ if(t===void 0)return;a.push({kind:`object-property`,source:r,key:t,...s===void 0
124
124
  /* v8 ignore next -- the loop condition guarantees one pending task. */
125
125
  if(e===void 0)continue;if(e.kind===`property`){n.push({kind:`visit`,node:e.source[e.key]});continue}let r=e.node;if(typeof r!=`object`||!r||r instanceof AbortSignal||t.has(r))continue;t.add(r),Object.freeze(r);let i=Object.keys(r);for(let e=i.length-1;e>=0;e--){let t=i[e];
126
126
  /* v8 ignore next -- the loop is bounded by the captured key count. */
127
- t!==void 0&&n.push({kind:`property`,source:r,key:t})}}return e}function Gp(e){let t=/* @__PURE__ */ new Map;for(let n of e)t.set(n.sessionId,n);let n=/* @__PURE__ */ new Map,r=[];for(let i of e)if(i.parentSessionId!==void 0&&t.has(i.parentSessionId)){let e=n.get(i.parentSessionId)??[];e.push(i),n.set(i.parentSessionId,e)}else r.push(i);let i=[],a=/* @__PURE__ */ new Set,o=(e,t)=>{if(a.has(e.sessionId)){console.warn(`[session-controller] lineage cycle at ${e.sessionId}; emitting as root`);return}a.add(e.sessionId);let{agentAvailable:r,...s}=e;i.push({...s,depth:t});let c=n.get(e.sessionId);if(c!==void 0)for(let e of c)o(e,t+1)};for(let e of r)o(e,0);for(let t of e)a.has(t.sessionId)||o(t,0);return i}var Kp=class{rebuild;listeners=/* @__PURE__ */ new Set;dirty=!1;notifyPending=!1;scheduled=`none`;scheduleGeneration=0;constructor(e){this.rebuild=e}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}markDirty(){this.dirty=!0,this.notifyPending=!0,this.scheduled!==`microtask`&&this.schedule(`microtask`)}markFrameDirty(){this.dirty=!0,this.notifyPending=!0,this.scheduled===`none`&&this.schedule(typeof globalThis.requestAnimationFrame==`function`?`frame`:`microtask`)}notifyNow(){this.dirty=!0,this.notifyPending=!0,this.invalidateSchedule(),this.flush()}ensureFresh(){this.dirty&&(this.dirty=!1,this.rebuild())}schedule(e){let t=++this.scheduleGeneration;this.scheduled=e;let n=()=>{t===this.scheduleGeneration&&(this.scheduled=`none`,this.flush())};e===`frame`?globalThis.requestAnimationFrame(n):queueMicrotask(n)}invalidateSchedule(){this.scheduleGeneration++,this.scheduled=`none`}flush(){this.notifyPending&&this.listeners.size!==0&&(this.notifyPending=!1,this.dirty&&(this.dirty=!1,this.rebuild()),(0,a.notifySubscribers)(this.listeners,`[session-controller]`))}};function qp(e,t){if(Object.is(e,t))return!0;if(typeof e!=`object`||typeof t!=`object`||e===null||t===null)return!1;if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!qp(e[n],t[n]))return!1;return!0}let n=Object.getPrototypeOf(e);if(n!==Object.getPrototypeOf(t)||n!==Object.prototype&&n!==null)return!1;let r=e,i=t,a=Object.keys(r),o=Object.keys(i);if(a.length!==o.length)return!1;for(let e of a)if(!Object.hasOwn(i,e)||!qp(r[e],i[e]))return!1;return!0}var Jp=class{anyIgnoredKeys;rows=/* @__PURE__ */ new Map;channels=/* @__PURE__ */ new Map;valuesCache;writeRevision=0;anyNotifier=new Kp(()=>{});constructor(e){this.anyIgnoredKeys=e}get revision(){return this.writeRevision}faceOf(e){return this.channel(e).face}get(e){return this.rows.get(e)?.value}seqOf(e){let t=this.rows.get(e);return t?.kind===`sequenced`?t.seq:void 0}values(){return this.valuesCache===void 0&&(this.valuesCache=Object.freeze(Object.fromEntries([...this.rows].map(([e,t])=>[e,t.value])))),this.valuesCache}subscribeAny(e){return this.anyNotifier.subscribe(e)}apply(e,t,n){let r=this.rows.get(e);return r?.kind===`sequenced`&&n<=r.seq?!1:r!==void 0&&qp(r.value,t)?(this.rows.set(e,{kind:`sequenced`,value:r.value,seq:n}),this.writeRevision+=1,!1):(this.rows.set(e,{kind:`sequenced`,value:t,seq:n}),this.changed(e),!0)}applyLive(e,t,n){let r=this.rows.get(e);return r?.kind===`sequenced`&&n<r.seq?!1:r!==void 0&&qp(r.value,t)?(this.rows.set(e,{kind:`sequenced`,value:r.value,seq:n}),this.writeRevision+=1,!1):(this.rows.set(e,{kind:`sequenced`,value:t,seq:n}),this.changed(e),!0)}applyCached(e){for(let t of Object.keys(e)){let n=this.rows.get(t);n?.kind!==`sequenced`&&(n!==void 0&&qp(n.value,e[t])?this.writeRevision+=1:(this.rows.set(t,{kind:`cached`,value:e[t]}),this.changed(t)))}}seed(e,t,n){let r=e.values;for(let[e,t]of this.rows)t.kind!==`cached`||Object.hasOwn(r,e)||(this.rows.delete(e),this.changed(e));for(let n of Object.keys(r))t?.has(n)?this.applyLive(n,r[n],e.asOfSeq):this.apply(n,r[n],e.asOfSeq);for(let[t,i]of this.rows)Object.hasOwn(r,t)||n?.has(t)||i.kind===`sequenced`&&i.seq>e.asOfSeq||(this.rows.delete(t),this.changed(t))}discard(e){for(let t of e)this.rows.delete(t)&&this.changed(t)}clear(e){for(let[t,n]of[...this.rows])e?.has(t)===!0?this.rows.set(t,{kind:`cached`,value:n.value}):(this.rows.delete(t),this.changed(t))}changed(e){this.writeRevision+=1,this.valuesCache=void 0,this.channels.get(e)?.notifier.markDirty(),this.anyIgnoredKeys?.has(e)||this.anyNotifier.markDirty()}channel(e){let t=this.channels.get(e);if(t===void 0){let n=new Kp(()=>{});t={notifier:n,face:{getSnapshot:()=>this.rows.get(e)?.value,subscribe:e=>n.subscribe(e)}},this.channels.set(e,t)}return t}};let Yp=/* @__PURE__ */ new WeakMap;function Xp(e){return e.length*2}function Zp(e,t){return Xp(e)+Xp(t)+64}function Qp(e){if(e===void 0||e.size===0)return 0;let t=64;for(let[n,r]of e)t+=Zp(n,r);return t}function $p(e,t=0,n){if(e==null)return 0;switch(typeof e){case`string`:return Xp(e);case`number`:case`boolean`:case`bigint`:case`symbol`:return 8;case`function`:return 64;case`object`:{if(t>=12)return 64;if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer)return e.byteLength+64;let r=Yp.get(e);if(r!==void 0)return r;if(n?.has(e))return 8;let i=n??/* @__PURE__ */ new Set;i.add(e);let a=64;try{if(Array.isArray(e)){a+=e.length*8;for(let n=0;n<e.length;n+=1)a+=$p(e[n],t+1,i)}else if(e instanceof Map)for(let[n,r]of e)a+=64+$p(n,t+1,i)+$p(r,t+1,i);else if(e instanceof Set)for(let n of e)a+=8+$p(n,t+1,i);else{let n=e;for(let e in n)Object.hasOwn(n,e)&&(a+=Xp(e)+8+$p(n[e],t+1,i))}}finally{i.delete(e)}return t===0&&n===void 0&&Object.isFrozen(e)&&Yp.set(e,a),a}default:return 0}}function em(e){let t=Yp.get(e);if(t!==void 0)return t;let n=$p(e);return Yp.set(e,n),n}function tm(e){let t=0;for(let n=0;n<e.length;n+=1)t+=8+em(e[n]);return t}function nm(e){return e===void 0?0:64+Xp(e.epoch)+tm(e.records)}function rm(e){let t=64,n;if(e.journal!==void 0){t+=64+Xp(e.journal.epoch),n=/* @__PURE__ */ new Set;for(let r of e.journal.records)t+=8+em(r),n.add(r),typeof r.event==`object`&&r.event!==null&&n.add(r.event)}t+=64;for(let r of e.entries){if(t+=8,n!==void 0){if(n.has(r))continue;if(typeof r.event==`object`&&r.event!==null&&n.has(r.event)){t+=64;continue}}t+=em(r)}return t+=Qp(e.toolOutputs),t+=$p(e.projections),t}var im=class{readRemote;values=/* @__PURE__ */ new Map;pending=/* @__PURE__ */ new Map;maxBytes;totalBytes=0;constructor(e,t,n={}){if(this.readRemote=e,this.maxBytes=Math.max(0,n.maxBytes??8388608),t!==void 0)for(let[e,n]of t)this.remember(e,n)}get estimatedBytes(){return this.totalBytes}read(e){let t=JSON.stringify([e.sessionId,e.epoch,e.turn,e.seq,e.callId,e.part,e.version]),n=this.values.get(t);if(n!==void 0)return this.values.delete(t),this.values.set(t,n),Promise.resolve(n);let r=this.pending.get(t);if(r)return r;let i=this.readRemote(e).then(e=>{if(!e.ok)throw e.error;return this.remember(t,e.value.text),e.value.text}).finally(()=>{this.pending.delete(t)});return this.pending.set(t,i),i}remember(e,t){let n=this.values.get(e);n!==void 0&&(this.totalBytes-=Zp(e,n),this.values.delete(e));let r=Zp(e,t);if(!(r>this.maxBytes))for(this.values.set(e,t),this.totalBytes+=r;this.totalBytes>this.maxBytes&&this.values.size>0;){let t=this.values.entries().next().value;if(t[0]===e)break;this.values.delete(t[0]),this.totalBytes-=Zp(t[0],t[1])}}};function am(){let e=globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16)),t=Array.from(e,(e,t)=>(t===6?e&15|64:t===8?e&63|128:e).toString(16).padStart(2,`0`)).join(``);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function om(e){return{kind:`leaf`,entries:e,length:e.length}}function sm(e,t){return{kind:`concat`,left:e,right:t,length:e.length+t.length}}function cm(e){if(e.kind===`leaf`)return e.entries;let t=Array(e.length),n=[e],r=0;for(;n.length>0;){let e=n.pop();if(e.kind===`concat`)n.push(e.right,e.left);else for(let n of e.entries)t[r]=n,r+=1}return t}function lm(e,t,n,r){let i;return{get entries(){return i??=cm(e),i},hasMore:t,revision:n,change:r}}var um=class{listeners=/* @__PURE__ */ new Set;window=om([]);estimatedEntryBytes=0;snapshot=lm(this.window,!1,0,{kind:`replace`,entries:[]});get estimatedBytes(){return this.estimatedEntryBytes}getSnapshot(){return this.snapshot}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}replace(e,t){this.window=om(e),this.estimatedEntryBytes=tm(e),this.publish(t,{kind:`replace`,entries:e})}prepend(e,t){this.window=sm(om(e),this.window),this.estimatedEntryBytes+=tm(e),this.publish(t,{kind:`prepend`,entries:e})}append(e){let t=[e];this.window=sm(this.window,om(t)),this.estimatedEntryBytes+=8+em(e),this.publish(this.snapshot.hasMore,{kind:`append`,entries:t})}settleAssistant(e,t){let n=cm(this.window).filter(t=>t.type!==`transient`||t.event.data.attemptId!==e);if(t!==void 0){let e=n.findIndex(e=>e.event.seq>t.event.seq);e<0?n.push(t):n.splice(e,0,t)}this.window=om(n),this.estimatedEntryBytes=tm(n),this.publish(this.snapshot.hasMore,{kind:`settle-assistant`,attemptId:e,...t===void 0?{}:{entry:t}})}publish(e,t){this.snapshot=lm(this.window,e,this.snapshot.revision+1,t),(0,a.notifySubscribers)(this.listeners,`[session-controller] event feed`)}};function dm(){let e=new Intl.DateTimeFormat().resolvedOptions().timeZone;if(typeof e!=`string`||e.length===0)throw Error(`browser time zone is unavailable`);return e}function fm(e){if(!Number.isSafeInteger(e))throw TypeError(`Assistant stream time must be a safe integer, got ${String(e)}`);return e}function pm(e,t){if(!Number.isSafeInteger(e)||e<0||Object.is(e,-0))throw TypeError(`${t} index must be a non-negative safe integer`);return e}function mm(e){let t=Up(e);if(t===void 0)throw TypeError(`Assistant stream chunk must be losslessly JSON-serializable`);return t}function hm(e){let t=[];for(let n of e){let e=gm(n);if(e.type===`chunk`){t.push({time:e.time,chunk:e.chunk});continue}let r=e.type===`tool-call-chunks`?e.args:e.texts,i=e.time0;for(let n=0;n<r.length;n+=1){n>0&&(i+=e.dt[n-1]);let a;a=e.type===`text-chunks`?{type:`text-delta`,index:e.index,text:r[n]}:e.type===`reasoning-chunks`?{type:`reasoning-delta`,index:e.index,text:r[n]}:{type:`tool-call-delta`,index:e.index,id:e.id,...Object.hasOwn(e,`name`)?{name:e.name}:{},argumentsDelta:r[n]},t.push({time:i,chunk:a})}}return t}function gm(e){if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(`Assistant stream record must be an object`);let t=e;switch(t.type){case`text-chunks`:case`reasoning-chunks`:{ym(t,[`type`,`time0`,`index`,`dt`,`texts`],t.type);let e=vm(t.texts,`${t.type} texts`);if(e.length===0)throw TypeError(`${t.type} texts must be non-empty`);return _m(t,e.length,t.type),t}case`tool-call-chunks`:{ym(t,Object.hasOwn(t,`name`)?[`type`,`time0`,`index`,`dt`,`id`,`name`,`args`]:[`type`,`time0`,`index`,`dt`,`id`,`args`],t.type);let e=vm(t.args,`tool-call-chunks args`);if(e.length===0)throw TypeError(`tool-call-chunks args must be non-empty`);if(typeof t.id!=`string`||t.id.length===0)throw TypeError(`tool-call-chunks id must be a non-empty string`);if(t.name!==void 0&&(typeof t.name!=`string`||t.name.length===0))throw TypeError(`tool-call-chunks name must be a non-empty string`);return _m(t,e.length,t.type),t}case`chunk`:{ym(t,[`type`,`time`,`chunk`],`chunk`);let e=fm(t.time);if(typeof t.chunk!=`object`||t.chunk===null||Array.isArray(t.chunk))throw TypeError(`Assistant stream raw chunk must be a lossless JSON object`);let n;try{n=mm(t.chunk)}catch(e){throw TypeError(`Assistant stream raw chunk must be a lossless JSON object`,{cause:e})}return Wp({type:`chunk`,time:e,chunk:n})}default:throw TypeError(`Unsupported Assistant stream record ${JSON.stringify(t.type)}`)}}function _m(e,t,n){if(fm(e.time0),pm(e.index,n),!Array.isArray(e.dt)||e.dt.some(e=>!Number.isSafeInteger(e)))throw TypeError(`${n} dt must contain safe integers`);if(e.dt.length!==t-1)throw TypeError(`${n} dt length must be one less than its members`);let r=e.time0;for(let t of e.dt)if(r+=t,!Number.isSafeInteger(r))throw TypeError(`${n} member times must stay safe integers`)}function vm(e,t){if(!Array.isArray(e)||e.some(e=>typeof e!=`string`))throw TypeError(`${t} must be a string array`);return e}function ym(e,t,n){if(Object.keys(e).length!==t.length||!t.every(t=>Object.hasOwn(e,t)))throw TypeError(`${n} Assistant stream record must contain exactly ${t.join(`, `)}`)}var bm=class{activeAttempt;retainedAttempt;pending=/* @__PURE__ */ new Map;publishedSeqs=/* @__PURE__ */ new Set;durableCursor=-1;transientInGap=0;transientOrder=0;replace(e,t){this.pending.clear(),this.transientInGap=0,this.transientOrder=0,this.activeAttempt=void 0,this.retainedAttempt=void 0;let n=t?.activeAttempt;n!==void 0&&(this.activeAttempt={attemptId:n.attemptId,startedAfterSeq:n.startedAfterSeq,turn:n.turn,step:n.step,nextIndex:n.nextIndex});let r=[...e];if(this.publishedSeqs=new Set(r.map(e=>e.event.seq)),this.durableCursor=r.reduce((e,t)=>Math.max(e,t.event.seq),-1),n!==void 0){for(let[e,t]of hm(n.stream).entries())if(r.push(this.transientEntry(n,t.time,t.chunk)),e+1>=n.nextIndex)break}return r}acceptDurable(e){let t=e.event;this.durableCursor=Math.max(this.durableCursor,t.seq),this.transientInGap=0;let n=xm(e);if(n!==void 0&&this.attemptForSettlement(n.event)!==void 0){if(this.pending.has(t.seq))return{type:`rebaseline`};this.pending.set(t.seq,n)}else return this.publish(e)}acceptFrame(e){switch(e.type){case`start`:if(this.activeAttempt!==void 0||this.retainedAttempt!==void 0||this.pending.size>0)return{type:`rebaseline`};this.pending.clear(),this.activeAttempt={attemptId:e.attemptId,startedAfterSeq:e.startedAfterSeq,turn:e.turn,step:e.step,nextIndex:0};return;case`chunk`:{let t=this.activeAttempt;return t===void 0||t.attemptId!==e.attemptId?void 0:e.index===t.nextIndex?(t.nextIndex+=1,{type:`transient`,entry:this.transientEntry(t,e.time,e.chunk)}):{type:`rebaseline`}}case`end`:{let t=this.activeAttempt;if(t===void 0||t.attemptId!==e.attemptId)return;if(this.activeAttempt=void 0,e.index!==t.nextIndex)return{type:`rebaseline`};if(e.outcome.kind===`abandoned`)return this.pending.size===0?{type:`abandonment`,attemptId:t.attemptId}:{type:`rebaseline`};if(this.publishedSeqs.has(e.outcome.seq))return;let n=this.pending.get(e.outcome.seq);return n===void 0||n.event.type!==e.outcome.eventType?{type:`rebaseline`}:(this.pending.delete(e.outcome.seq),n.event.type===`assistant/message`&&n.event.data.interrupted!==!0?(this.retainedAttempt={attemptId:t.attemptId,turn:t.turn,step:t.step},this.publish(n)):(this.publishedSeqs.add(n.event.seq),{type:`settlement`,attemptId:t.attemptId,entry:n}))}}}transientEntry({attemptId:e,turn:t,step:n},r,i){let a=this.durableCursor+1;this.transientInGap+=1;let o=Math.max(1/(this.transientInGap+1),a*2**-52);return{type:`transient`,event:{type:`assistant/live-chunk`,seq:Math.max(this.durableCursor,a-o),order:++this.transientOrder,time:r,data:{attemptId:e,turn:t,step:n,chunk:i}}}}attemptForSettlement(e){let t=this.activeAttempt;if(!(t===void 0||e.type===`assistant/message`&&e.surfaceOp!==`append`||e.seq<=t.startedAfterSeq||t.turn!==e.data.turn||t.step!==e.data.step))return t}publish(e){this.publishedSeqs.add(e.event.seq);let t=this.retainedAttempt;return t!==void 0&&e.event.type===`step/end`&&e.event.data.turn===t.turn&&e.event.data.step===t.step?(this.retainedAttempt=void 0,{type:`publish`,entry:e,retireAttemptId:t.attemptId}):{type:`publish`,entry:e}}};function xm(e){return e.event.type===`assistant/message`||e.event.type===`assistant/attempt`?e:void 0}function Sm(e){return{...e,asOfSeq:e.asOfSeq===-1?-1:p(e.asOfSeq)}}let Cm={maxMessages:500,turnWindow:{minMessages:50,minTurns:2}},wm={...Cm,turnWindow:{...Cm.turnWindow,minMessages:200}};var Tm=class{sessionId;remote;baseSeq=m(0);cachedJournal;toolOutputs;hasMore=!1;openState=`cold`;lastSyncedAt;openError=null;openPromise=null;openGeneration=0;loadingOlder=!1;olderError=null;jumpTargetSeq=null;jumpPromise=null;pendingHistory=null;stopObservingInbox;onEngaged;assistantStream=new bm;running=!1;address;parentAvailable;promptAttempted=!1;firstPromptPendingTurn=!1;blankBit=!0;removed=!1;promptError=null;inFlightPrompts=/* @__PURE__ */ new Map;lastAgentError=null;pendingSubmissions=[];submissionTarget;submissionSettlements=/* @__PURE__ */ new Map;events;projections;eventSource=new um;cachedProjectionBytesRevision=-1;cachedProjectionBytes=0;snapshotCache;notifier;actx;constructor(e,t,n={}){if(this.sessionId=e,this.remote=t,this.toolOutputs=new im(e=>this.remote.session.toolOutput(e),n.cachedView?.toolOutputs),this.onEngaged=n.onEngaged,this.projections=n.projections??new Jp,n.cachedView){let e=n.cachedView;this.cachedJournal=e.journal,this.baseSeq=e.baseSeq,this.hasMore=e.hasMore,this.lastSyncedAt=e.lastSyncedAt,this.projections.applyCached(e.projections),this.eventSource.replace(e.entries,e.hasMore)}this.address=n.address,this.parentAvailable=n.parentAvailable,this.notifier=new Kp(()=>{this.snapshotCache=this.buildSnapshot()}),this.snapshotCache=this.buildSnapshot(),this.stopObservingInbox=this.projections.faceOf(`inbox`).subscribe(()=>{this.observeSubmissionInbox()})}bindScope(e){if(this.actx!==void 0)throw Error(`session ${this.sessionId} already has a bound scope`);this.actx=e}unbindScope(){this.actx=void 0}beginSubmission(e){if(this.submissionTarget!==void 0)return this.submissionTarget.beginSubmission(e);let t=am(),n=this.running?e.mode===`steer`?`steering`:`queued`:`transcript`;return this.pendingSubmissions=[...this.pendingSubmissions,{requestId:t,placement:n,time:Date.now(),text:e.text,attachments:e.attachments}],this.submissionSettlements.set(t,{placement:n,expectedTurnId:e.mode===`steer`?this.activeTurnForSteering():null,onRetire:e.onRetire,retiring:!1}),this.promptAttempted=!0,this.notifier.markDirty(),{requestId:t,abandon:()=>{this.retireFailedSubmission(t)}}}handoffSubmissions(e){if(e=e.submissionOwner(),e===this||this.submissionTarget!==void 0)return[];let t=this.pendingSubmissions.map(e=>e.requestId);if(t.length===0)return t;e.pendingSubmissions=[...e.pendingSubmissions,...this.pendingSubmissions];for(let n of t){let t=this.submissionSettlements.get(n);t!==void 0&&e.submissionSettlements.set(n,t);let r=this.inFlightPrompts.get(n);r!==void 0&&e.inFlightPrompts.set(n,r)}this.submissionSettlements.clear(),this.submissionTarget=e,e.promptAttempted||=this.promptAttempted;for(let{event:t}of e.eventSource.getSnapshot().entries)e.observeSubmissionEvent(t);return e.observeSubmissionInbox(),e.notifier.markDirty(),t}submissionOwner(){return this.submissionTarget?.submissionOwner()??this}get hasInFlightPrompts(){return this.inFlightPrompts.size>0}activeTurnForSteering(){let e=this.projections.get(Nf);return typeof e==`string`?e:null}async prompt(e,t,n,r){if(this.submissionTarget!==void 0)return this.submissionTarget.prompt(e,t,n,r);let i=r??am();this.promptError=null,this.lastAgentError=null,this.promptAttempted=!0,this.blankBit&&(this.firstPromptPendingTurn=!0),this.notifier.markDirty();let a={observed:!1};this.inFlightPrompts.set(i,a);try{let a=this.submissionSettlements.get(i),s;if(t===`steer`&&r!==void 0&&a===void 0)s={ok:!1,error:new o(`remote/turn-changed`,`The selected Turn has ended or changed.`,{})};else if(this.address===void 0){let r=dm(),o=this.projections.get(`remoteHost`)!=null,c=a?a.placement===`transcript`:!this.running;s=await this.remote.session.prompt({requestId:i,sessionId:this.sessionId,mode:t,...o&&t===`queue`&&c?{sendWhenIdle:!0}:{},...t===`steer`?{expectedTurnId:a?a.expectedTurnId:this.activeTurnForSteering()}:{},content:e,clientTimeZone:r},n)}else if(e.some(e=>e.type===`file`))s={ok:!1,error:new o(`subagent/attachment-invalid`,`subagent continuation does not accept files`,{reason:`SUBAGENT_FILE_UNSUPPORTED`})};else{let r=e,a=await this.remote.subagents.prompt({requestId:i,parentSessionId:this.address.parentSessionId,childSessionId:this.address.childSessionId,mode:`continuable`,delivery:t,content:r,clientTimeZone:dm()},n);s=a.ok?{ok:!0,value:{accepted:!0}}:a}let c=this.submissionOwner();return!s.ok&&s.error.code===`remote/outcome-unknown`&&c.hasObservedPrompt(i)&&(s={ok:!0,value:{accepted:!0}}),s.ok?(c.acceptPrompt(),s):(r!==void 0&&c.retireFailedSubmission(r),c.promptError={op:`send`,error:s.error,requestId:i},c.notifier.markDirty(),s)}finally{this.inFlightPrompts.get(i)===a&&this.inFlightPrompts.delete(i);let e=this.submissionOwner();e.inFlightPrompts.get(i)===a&&e.inFlightPrompts.delete(i),this.notifier.markDirty()}}acceptPrompt(){this.blankBit&&(this.blankBit=!1,this.notifier.markDirty()),this.onEngaged?.(this)}hasObservedPrompt(e){let t=t=>t.source.kind===`user`&&`rpcId`in t.source&&t.source.rpcId===e,n=this.projections.get(`inbox`);return this.inFlightPrompts.get(e)?.observed===!0||this.eventSource.getSnapshot().entries.some(({event:e})=>e.type===`user/message`&&t(e.data))||[...n?.[`next-turn`]??[],...n?.[`next-step`]??[]].some(t)}confirmPrompt(e){let t=this.inFlightPrompts.get(e);t&&(t.observed=!0),this.promptError?.op===`send`&&this.promptError.error.code===`remote/outcome-unknown`&&this.promptError.requestId===e&&(this.promptError=null,this.notifier.markDirty(),this.acceptPrompt())}async readAttachment(e){let t=await this.remote.session.attachment({sessionId:this.sessionId,attachmentId:e});if(!t.ok)return t;let n=atob(t.value.data),r=Uint8Array.from(n,e=>e.charCodeAt(0));return{ok:!0,value:{attachment:t.value.attachment,data:r}}}readToolOutput(e){return e.sessionId===this.sessionId?this.toolOutputs.read(e):Promise.reject(new o(`session/tool-output-stale`,`Tool output belongs to another session.`,{}))}async updateQueue(e,t){return this.remote.session.updateQueue({sessionId:this.sessionId,itemId:e,action:t})}async cancel(){let e=this.address,t=e===void 0?await this.remote.session.cancel({sessionId:this.sessionId}):await this.remote.subagents.interruptByParent(e.childSessionId,e.parentSessionId,`continuable`);return t.ok||(this.promptError={op:`stop`,error:t.error},this.notifier.markDirty()),t}async rename(e){let t=await this.remote.session.rename({sessionId:this.sessionId,title:e});if(!t.ok)return t;let n=p(t.value.seq);return this.projections.apply(`title`,t.value.title,n),{ok:!0,value:{title:t.value.title,seq:n}}}async command(e){let t=await this.remote.commands.execute(this.sessionId,e,[]);return t.ok?{ok:!0,value:{matched:t.value!==void 0}}:t}open(){if(this.openState===`open`)return Promise.resolve();if(this.openPromise!==null)return this.openPromise;let e=this.doOpen(this.openGeneration).finally(()=>{this.openPromise===e&&(this.openPromise=null)});return this.openPromise=e,e}async loadOlder(){if(this.openState!==`open`||!this.hasMore||this.loadingOlder)return;let e=this.events;if(e===void 0)return;let t=this.openGeneration;this.loadingOlder=!0,this.olderError=null,this.notifier.markDirty();try{await e.prepend({beforeSeq:this.baseSeq,...Cm})}catch(e){t===this.openGeneration&&(this.olderError=(0,i.isRemoteFailure)(e)?e:new o(`gateway/internal`,`Could not load earlier history.`,{}))}finally{t===this.openGeneration&&(this.loadingOlder=!1,this.notifier.markDirty())}}loadThrough(e){if(this.openState!==`open`||!this.hasMore||this.baseSeq<=e)return Promise.resolve();if(this.jumpPromise!==null)return this.jumpTargetSeq=p(Math.min(this.jumpTargetSeq??e,e)),this.jumpPromise;if(this.loadingOlder)return Promise.resolve();let t=this.events;if(t===void 0)return Promise.resolve();let n={beforeSeq:this.baseSeq,hasMore:this.hasMore,pages:[]};this.pendingHistory=n,this.jumpTargetSeq=e,this.olderError=null,this.loadingOlder=!0,this.notifier.markDirty();let r=this.openGeneration;return this.jumpPromise=(async()=>{try{for(;n.hasMore&&this.jumpTargetSeq!==null&&n.beforeSeq>this.jumpTargetSeq;){if(r!==this.openGeneration)return;let e=n.beforeSeq;if(await t.prepend({beforeSeq:e,...wm}),n.beforeSeq>=e)return}}catch(e){(0,i.isRemoteFailure)(e)||console.error(`[session-controller] loadThrough failed:`,e)}finally{this.jumpTargetSeq=null,this.jumpPromise=null,this.pendingHistory=null,this.loadingOlder=!1,r===this.openGeneration&&n.pages.length>0&&this.prependWindow(n.pages.reverse().flat(),n.hasMore),this.notifier.markDirty()}})(),this.jumpPromise}async resync(){if(this.openState===`cold`)return;let e=++this.openGeneration,t=this.events;this.cachedJournal=t?.capture()??this.cachedJournal,this.events=void 0,await t?.dispose(),e===this.openGeneration&&(this.openPromise=null,this.openState=`cold`,this.openError=null,this.baseSeq=m(0),this.notifier.markDirty(),await this.open())}subscribe(e){return this.notifier.subscribe(e)}getSnapshot(){return this.notifier.ensureFresh(),this.snapshotCache}estimatedBytes(){let e=this.projections.revision;return this.cachedProjectionBytesRevision!==e&&(this.cachedProjectionBytes=$p(this.projections.values()),this.cachedProjectionBytesRevision=e),(this.eventSource.estimatedBytes>0?this.eventSource.estimatedBytes:nm(this.cachedJournal))+this.toolOutputs.estimatedBytes+this.cachedProjectionBytes}captureView(){if(this.lastSyncedAt===void 0||this.removed)return;let e=this.events?.capture()??this.cachedJournal;return{...e===void 0?{}:{journal:e},toolOutputs:new Map(this.toolOutputs.values),entries:this.eventSource.getSnapshot().entries,baseSeq:this.baseSeq,hasMore:this.hasMore,projections:this.projections.values(),lastSyncedAt:this.lastSyncedAt}}handleRunning(e){e&&this.blankBit&&(this.blankBit=!1,this.notifier.markDirty()),e&&(this.firstPromptPendingTurn=!1),this.running!==e&&(this.running=e,this.notifier.markDirty())}configureSubagent(e,t){let n=this.address?.parentSessionId===e?.parentSessionId&&this.address?.childSessionId===e?.childSessionId&&this.address?.mode===e?.mode;this.address=e,this.parentAvailable=t,!n&&this.openState!==`cold`?this.resync():this.notifier.markDirty()}handleSubagentParentAvailable(e){this.parentAvailable!==e&&(this.parentAvailable=e,this.notifier.markDirty())}handleBlank(e){e&&=this.projections.values().sessionListMetadata?.blank!==!1,e!==this.blankBit&&(e&&(this.promptAttempted||this.running)||(this.blankBit=e,this.notifier.markDirty()))}handleRemoved(){this.removed=!0,this.notifier.markDirty()}handleRestored(){this.removed&&(this.removed=!1,this.notifier.markDirty())}handleAgentError(e){this.lastAgentError=e,this.notifier.markDirty()}async dispose(){this.stopObservingInbox();for(let[e,t]of[...this.submissionSettlements])t.admitted===void 0?this.retireFailedSubmission(e):this.scheduleObservedRetirement(e,t.admitted);this.openGeneration++;let e=this.events;this.events=void 0,await e?.dispose()}async doOpen(e){this.openState=`loading`,this.openError=null,this.olderError=null,this.loadingOlder=!1,this.notifier.markDirty();let t=this.cachedJournal?.epoch,n=new pe(this.remote,this.sessionAddress(),{publish:r=>{e===this.openGeneration&&this.events===n&&(r.type===`replace`&&(t&&n.journalEpoch!==t&&this.projections.discard(Pf),t=n.journalEpoch),this.acceptEventChange(r))},failed:t=>{this.failEventStream(n,e,t)}},this.cachedJournal);this.events=n;try{if(await n.open(Cm),e!==this.openGeneration||this.events!==n)return;this.cachedJournal=void 0,this.openState=`open`}catch(t){if(e!==this.openGeneration||this.events!==n)return;if(!(0,i.isRemoteFailure)(t))throw t;this.events=void 0,this.openState=`error`,this.openError=t}finally{e===this.openGeneration&&this.notifier.markDirty()}}acceptEventChange(e){switch(e.type){case`replace`:this.installWindow(e.entries,e.hasMore,e.page.projections===void 0?void 0:Sm(e.page.projections),e.page.assistantStream);break;case`prepend`:this.prependWindow(e.entries,e.hasMore);break;case`append`:this.publishAssistantEntry(this.assistantStream.acceptDurable(e.entry));break;case`assistant-stream`:this.publishAssistantEntry(this.assistantStream.acceptFrame(e.frame));break;case`projection`:this.projections.applyLive(e.key,e.value,p(e.seq))}this.lastSyncedAt=Date.now(),this.notifier.markFrameDirty()}installWindow(e,t,n,r){let i=this.assistantStream.replace(e,r);if(this.baseSeq=m(e[0]?.event.seq??0),this.hasMore=t,this.pendingHistory!==null&&(this.pendingHistory.beforeSeq=this.baseSeq,this.pendingHistory.hasMore=t,this.pendingHistory.pages.length=0),i.some(e=>e.event.type===`turn/start`)&&(this.firstPromptPendingTurn=!1),n!==void 0&&this.projections.seed(n,Pf),this.eventSource.replace(i,t),n!==void 0)for(let[e,{receipt:t}]of this.submissionSettlements)t!==void 0&&t.seq<=n.asOfSeq&&this.scheduleObservedRetirement(e,t.attachments);for(let e of i)this.observeSubmissionEvent(e.event);if(n!==void 0){let e=n.values.inbox;for(let t of[`next-turn`,`next-step`])this.observeSubmissionInsertions(t,e?.[t]??[],0,n.asOfSeq)}this.notifier.markDirty()}publishAssistantEntry(e){if(e?.type===`rebaseline`){let e=this.events;queueMicrotask(()=>{e!==void 0&&this.events===e&&e.restart()})}else if(e?.type===`settlement`)this.eventSource.settleAssistant(e.attemptId,e.entry),this.observeSubmissionEvent(e.entry.event),this.notifier.markDirty();else if(e?.type===`abandonment`)this.eventSource.settleAssistant(e.attemptId),this.notifier.markDirty();else if(e?.type===`publish`){let t=this.appendLive(e.entry);e.retireAttemptId!==void 0&&this.eventSource.settleAssistant(e.retireAttemptId),(t||e.retireAttemptId!==void 0)&&this.notifier.markDirty()}else e?.type===`transient`&&(this.eventSource.append(e.entry),this.notifier.markDirty())}prependWindow(e,t){if(this.pendingHistory!==null){let n=this.pendingHistory;n.beforeSeq=e[0]===void 0?n.beforeSeq:m(e[0].event.seq),n.hasMore=t,n.pages.push(e)}else{this.baseSeq=e[0]===void 0?this.baseSeq:m(e[0].event.seq),this.hasMore=t,this.eventSource.prepend(e,t);for(let{event:t}of e)if(t.type===`user/message`)this.observeSubmissionMessage(t.data,!0);else if(t.type===`agent/inbox/spliced`)for(let{source:e}of t.data.inserted)e.kind===`user`&&`rpcId`in e&&this.confirmPrompt(e.rpcId)}}appendLive(e){let t=e.event,n=this.firstPromptPendingTurn;return t.type===`turn/start`&&(this.firstPromptPendingTurn=!1),this.eventSource.append(e),this.observeSubmissionEvent(t),n!==this.firstPromptPendingTurn}observeSubmissionEvent(e){if(e.type===`user/message`)this.observeSubmissionMessage(e.data,!0);else if(this.submissionSettlements.size!==0||this.inFlightPrompts.size!==0||this.promptError?.requestId!==void 0){if(e.type===`agent/inbox/spliced`){let{target:t,start:n,removedCount:r=0,inserted:i,outcome:a}=e.data;for(let[o,s]of this.submissionSettlements){let c=s.receipt;if(c?.target!==t||c.index===null||c.seq>=e.seq)continue;let l=c.index>=n&&c.index<n+r;l&&a===`canceled`?this.retireFailedSubmission(o):s.receipt={...c,seq:e.seq,index:l?null:c.index<n?c.index:c.index+i.length-r}}this.observeSubmissionInsertions(t,i,n,e.seq);for(let e of i)this.observeSubmissionMessage(e,!1,t)}else if(e.type===`request/context`||e.type===`turn/end`)for(let[t,n]of this.submissionSettlements)n.admitted===void 0&&n.receipt?.index===null&&n.receipt.seq<e.seq&&this.retireFailedSubmission(t)}}observeSubmissionInsertions(e,t,n,r){for(let[i,a]of t.entries()){let t=a.source;if(t.kind!==`user`||!(`rpcId`in t))continue;this.confirmPrompt(t.rpcId);let o=this.submissionSettlements.get(t.rpcId);o===void 0||o.placement===`queued`||o.retiring||(o.receipt?.seq??-1)>r||(o.receipt={target:e,seq:r,index:n+i,attachments:Dm(a.content)})}}observeSubmissionMessage(e,t,n){let r=e.source;if(r.kind!==`user`||!(`rpcId`in r))return;this.confirmPrompt(r.rpcId);let i=this.submissionSettlements.get(r.rpcId);i===void 0||i.retiring||(t?(i.admitted=Dm(e.content),this.retireAdmittedSubmission(r.rpcId)):(i.placement===`queued`||n===`next-turn`)&&this.scheduleObservedRetirement(r.rpcId,Dm(e.content)))}retireAdmittedSubmission(e){let t=this.submissionSettlements.get(e);if(t?.admitted===void 0)return;let n=t.receipt;n?.index===null&&(this.projections.seqOf(`inbox`)??-1)<n.seq||this.scheduleObservedRetirement(e,t.admitted)}observeSubmissionInbox(){if(this.submissionSettlements.size===0&&this.inFlightPrompts.size===0&&this.promptError?.requestId===void 0)return;let e=this.projections.get(`inbox`);if(e===void 0)return;let t=this.projections.seqOf(`inbox`);for(let n of[`next-turn`,`next-step`]){t!==void 0&&this.observeSubmissionInsertions(n,e[n],0,t);for(let t of e[n])this.observeSubmissionMessage(t,!1,n)}for(let e of this.submissionSettlements.keys())this.retireAdmittedSubmission(e)}scheduleObservedRetirement(e,t){let n=this.submissionSettlements.get(e);n===void 0||n.retiring||(n.retiring=!0,Em(()=>{this.finishSubmission(e,{reason:`observed`,attachments:t})}))}retireFailedSubmission(e){if(this.submissionTarget!==void 0){this.submissionTarget.retireFailedSubmission(e);return}let t=this.submissionSettlements.get(e);t===void 0||t.retiring||t.admitted!==void 0||(t.retiring=!0,this.finishSubmission(e,{reason:`failed`}))}finishSubmission(e,t){if(this.submissionTarget!==void 0){this.submissionTarget.finishSubmission(e,t);return}let n=this.submissionSettlements.get(e);
127
+ t!==void 0&&n.push({kind:`property`,source:r,key:t})}}return e}function Gp(e){let t=/* @__PURE__ */ new Map;for(let n of e)t.set(n.sessionId,n);let n=/* @__PURE__ */ new Map,r=[];for(let i of e)if(i.parentSessionId!==void 0&&t.has(i.parentSessionId)){let e=n.get(i.parentSessionId)??[];e.push(i),n.set(i.parentSessionId,e)}else r.push(i);let i=[],a=/* @__PURE__ */ new Set,o=(e,t)=>{if(a.has(e.sessionId)){console.warn(`[session-controller] lineage cycle at ${e.sessionId}; emitting as root`);return}a.add(e.sessionId);let{agentAvailable:r,...s}=e;i.push({...s,depth:t});let c=n.get(e.sessionId);if(c!==void 0)for(let e of c)o(e,t+1)};for(let e of r)o(e,0);for(let t of e)a.has(t.sessionId)||o(t,0);return i}var Kp=class{rebuild;listeners=/* @__PURE__ */ new Set;dirty=!1;notifyPending=!1;scheduled=`none`;scheduleGeneration=0;constructor(e){this.rebuild=e}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}markDirty(){this.dirty=!0,this.notifyPending=!0,this.scheduled!==`microtask`&&this.schedule(`microtask`)}markFrameDirty(){this.dirty=!0,this.notifyPending=!0,this.scheduled===`none`&&this.schedule(typeof globalThis.requestAnimationFrame==`function`?`frame`:`microtask`)}notifyNow(){this.dirty=!0,this.notifyPending=!0,this.invalidateSchedule(),this.flush()}ensureFresh(){this.dirty&&(this.dirty=!1,this.rebuild())}schedule(e){let t=++this.scheduleGeneration;this.scheduled=e;let n=()=>{t===this.scheduleGeneration&&(this.scheduled=`none`,this.flush())};e===`frame`?globalThis.requestAnimationFrame(n):queueMicrotask(n)}invalidateSchedule(){this.scheduleGeneration++,this.scheduled=`none`}flush(){this.notifyPending&&this.listeners.size!==0&&(this.notifyPending=!1,this.dirty&&(this.dirty=!1,this.rebuild()),(0,a.notifySubscribers)(this.listeners,`[session-controller]`))}};function qp(e,t){if(Object.is(e,t))return!0;if(typeof e!=`object`||typeof t!=`object`||e===null||t===null)return!1;if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!qp(e[n],t[n]))return!1;return!0}let n=Object.getPrototypeOf(e);if(n!==Object.getPrototypeOf(t)||n!==Object.prototype&&n!==null)return!1;let r=e,i=t,a=Object.keys(r),o=Object.keys(i);if(a.length!==o.length)return!1;for(let e of a)if(!Object.hasOwn(i,e)||!qp(r[e],i[e]))return!1;return!0}var Jp=class{anyIgnoredKeys;rows=/* @__PURE__ */ new Map;channels=/* @__PURE__ */ new Map;valuesCache;writeRevision=0;anyNotifier=new Kp(()=>{});constructor(e){this.anyIgnoredKeys=e}get revision(){return this.writeRevision}faceOf(e){return this.channel(e).face}get(e){return this.rows.get(e)?.value}seqOf(e){let t=this.rows.get(e);return t?.kind===`sequenced`?t.seq:void 0}values(){return this.valuesCache===void 0&&(this.valuesCache=Object.freeze(Object.fromEntries([...this.rows].map(([e,t])=>[e,t.value])))),this.valuesCache}subscribeAny(e){return this.anyNotifier.subscribe(e)}apply(e,t,n){let r=this.rows.get(e);return r?.kind===`sequenced`&&n<=r.seq?!1:r!==void 0&&qp(r.value,t)?(this.rows.set(e,{kind:`sequenced`,value:r.value,seq:n}),this.writeRevision+=1,!1):(this.rows.set(e,{kind:`sequenced`,value:t,seq:n}),this.changed(e),!0)}applyLive(e,t,n){let r=this.rows.get(e);return r?.kind===`sequenced`&&n<r.seq?!1:r!==void 0&&qp(r.value,t)?(this.rows.set(e,{kind:`sequenced`,value:r.value,seq:n}),this.writeRevision+=1,!1):(this.rows.set(e,{kind:`sequenced`,value:t,seq:n}),this.changed(e),!0)}applyCached(e){for(let t of Object.keys(e)){let n=this.rows.get(t);n?.kind!==`sequenced`&&(n!==void 0&&qp(n.value,e[t])?this.writeRevision+=1:(this.rows.set(t,{kind:`cached`,value:e[t]}),this.changed(t)))}}seed(e,t,n){let r=e.values;for(let[e,t]of this.rows)t.kind!==`cached`||Object.hasOwn(r,e)||(this.rows.delete(e),this.changed(e));for(let n of Object.keys(r))t?.has(n)?this.applyLive(n,r[n],e.asOfSeq):this.apply(n,r[n],e.asOfSeq);for(let[t,i]of this.rows)Object.hasOwn(r,t)||n?.has(t)||i.kind===`sequenced`&&i.seq>e.asOfSeq||(this.rows.delete(t),this.changed(t))}discard(e){for(let t of e)this.rows.delete(t)&&this.changed(t)}clear(e){for(let[t,n]of[...this.rows])e?.has(t)===!0?this.rows.set(t,{kind:`cached`,value:n.value}):(this.rows.delete(t),this.changed(t))}changed(e){this.writeRevision+=1,this.valuesCache=void 0,this.channels.get(e)?.notifier.markDirty(),this.anyIgnoredKeys?.has(e)||this.anyNotifier.markDirty()}channel(e){let t=this.channels.get(e);if(t===void 0){let n=new Kp(()=>{});t={notifier:n,face:{getSnapshot:()=>this.rows.get(e)?.value,subscribe:e=>n.subscribe(e)}},this.channels.set(e,t)}return t}};let Yp=/* @__PURE__ */ new WeakMap;function Xp(e){return e.length*2}function Zp(e,t){return Xp(e)+Xp(t)+64}function Qp(e){if(e===void 0||e.size===0)return 0;let t=64;for(let[n,r]of e)t+=Zp(n,r);return t}function $p(e,t=0,n){if(e==null)return 0;switch(typeof e){case`string`:return Xp(e);case`number`:case`boolean`:case`bigint`:case`symbol`:return 8;case`function`:return 64;case`object`:{if(t>=12)return 64;if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer)return e.byteLength+64;let r=Yp.get(e);if(r!==void 0)return r;if(n?.has(e))return 8;let i=n??/* @__PURE__ */ new Set;i.add(e);let a=64;try{if(Array.isArray(e)){a+=e.length*8;for(let n=0;n<e.length;n+=1)a+=$p(e[n],t+1,i)}else if(e instanceof Map)for(let[n,r]of e)a+=64+$p(n,t+1,i)+$p(r,t+1,i);else if(e instanceof Set)for(let n of e)a+=8+$p(n,t+1,i);else{let n=e;for(let e in n)Object.hasOwn(n,e)&&(a+=Xp(e)+8+$p(n[e],t+1,i))}}finally{i.delete(e)}return t===0&&n===void 0&&Object.isFrozen(e)&&Yp.set(e,a),a}default:return 0}}function em(e){let t=Yp.get(e);if(t!==void 0)return t;let n=$p(e);return Yp.set(e,n),n}function tm(e){let t=0;for(let n=0;n<e.length;n+=1)t+=8+em(e[n]);return t}function nm(e){return e===void 0?0:64+Xp(e.epoch)+tm(e.records)}function rm(e){let t=64,n;if(e.journal!==void 0){t+=64+Xp(e.journal.epoch),n=/* @__PURE__ */ new Set;for(let r of e.journal.records)t+=8+em(r),n.add(r),typeof r.event==`object`&&r.event!==null&&n.add(r.event)}t+=64;for(let r of e.entries){if(t+=8,n!==void 0){if(n.has(r))continue;if(typeof r.event==`object`&&r.event!==null&&n.has(r.event)){t+=64;continue}}t+=em(r)}return t+=Qp(e.toolOutputs),t+=$p(e.projections),t}var im=class{readRemote;values=/* @__PURE__ */ new Map;pending=/* @__PURE__ */ new Map;maxBytes;totalBytes=0;constructor(e,t,n={}){if(this.readRemote=e,this.maxBytes=Math.max(0,n.maxBytes??8388608),t!==void 0)for(let[e,n]of t)this.remember(e,n)}get estimatedBytes(){return this.totalBytes}read(e){let t=JSON.stringify([e.sessionId,e.epoch,e.turn,e.seq,e.callId,e.part,e.version]),n=this.values.get(t);if(n!==void 0)return this.values.delete(t),this.values.set(t,n),Promise.resolve(n);let r=this.pending.get(t);if(r)return r;let i=this.readRemote(e).then(e=>{if(!e.ok)throw e.error;return this.remember(t,e.value.text),e.value.text}).finally(()=>{this.pending.delete(t)});return this.pending.set(t,i),i}remember(e,t){let n=this.values.get(e);n!==void 0&&(this.totalBytes-=Zp(e,n),this.values.delete(e));let r=Zp(e,t);if(!(r>this.maxBytes))for(this.values.set(e,t),this.totalBytes+=r;this.totalBytes>this.maxBytes&&this.values.size>0;){let t=this.values.entries().next().value;if(t[0]===e)break;this.values.delete(t[0]),this.totalBytes-=Zp(t[0],t[1])}}};function am(){let e=globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16)),t=Array.from(e,(e,t)=>(t===6?e&15|64:t===8?e&63|128:e).toString(16).padStart(2,`0`)).join(``);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function om(e){return{kind:`leaf`,entries:e,length:e.length}}function sm(e,t){return{kind:`concat`,left:e,right:t,length:e.length+t.length}}function cm(e){if(e.kind===`leaf`)return e.entries;let t=Array(e.length),n=[e],r=0;for(;n.length>0;){let e=n.pop();if(e.kind===`concat`)n.push(e.right,e.left);else for(let n of e.entries)t[r]=n,r+=1}return t}function lm(e,t,n,r){let i;return{get entries(){return i??=cm(e),i},hasMore:t,revision:n,change:r}}var um=class{listeners=/* @__PURE__ */ new Set;window=om([]);estimatedEntryBytes=0;snapshot=lm(this.window,!1,0,{kind:`replace`,entries:[]});get estimatedBytes(){return this.estimatedEntryBytes}getSnapshot(){return this.snapshot}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}replace(e,t){this.window=om(e),this.estimatedEntryBytes=tm(e),this.publish(t,{kind:`replace`,entries:e})}prepend(e,t){this.window=sm(om(e),this.window),this.estimatedEntryBytes+=tm(e),this.publish(t,{kind:`prepend`,entries:e})}append(e){let t=[e];this.window=sm(this.window,om(t)),this.estimatedEntryBytes+=8+em(e),this.publish(this.snapshot.hasMore,{kind:`append`,entries:t})}settleAssistant(e,t){let n=cm(this.window).filter(t=>t.type!==`transient`||t.event.data.attemptId!==e);if(t!==void 0){let e=n.findIndex(e=>e.event.seq>t.event.seq);e<0?n.push(t):n.splice(e,0,t)}this.window=om(n),this.estimatedEntryBytes=tm(n),this.publish(this.snapshot.hasMore,{kind:`settle-assistant`,attemptId:e,...t===void 0?{}:{entry:t}})}publish(e,t){this.snapshot=lm(this.window,e,this.snapshot.revision+1,t),(0,a.notifySubscribers)(this.listeners,`[session-controller] event feed`)}};function dm(){let e=new Intl.DateTimeFormat().resolvedOptions().timeZone;if(typeof e!=`string`||e.length===0)throw Error(`browser time zone is unavailable`);return e}function fm(e){if(!Number.isSafeInteger(e))throw TypeError(`Assistant stream time must be a safe integer, got ${String(e)}`);return e}function pm(e,t){if(!Number.isSafeInteger(e)||e<0||Object.is(e,-0))throw TypeError(`${t} index must be a non-negative safe integer`);return e}function mm(e){let t=Up(e);if(t===void 0)throw TypeError(`Assistant stream chunk must be losslessly JSON-serializable`);return t}function hm(e){let t=[];for(let n of e){let e=gm(n);if(e.type===`chunk`){t.push({time:e.time,chunk:e.chunk});continue}let r=e.type===`tool-call-chunks`?e.args:e.texts,i=e.time0;for(let n=0;n<r.length;n+=1){n>0&&(i+=e.dt[n-1]);let a;a=e.type===`text-chunks`?{type:`text-delta`,index:e.index,text:r[n]}:e.type===`reasoning-chunks`?{type:`reasoning-delta`,index:e.index,text:r[n]}:{type:`tool-call-delta`,index:e.index,id:e.id,...Object.hasOwn(e,`name`)?{name:e.name}:{},argumentsDelta:r[n]},t.push({time:i,chunk:a})}}return t}function gm(e){if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(`Assistant stream record must be an object`);let t=e;switch(t.type){case`text-chunks`:case`reasoning-chunks`:{ym(t,[`type`,`time0`,`index`,`dt`,`texts`],t.type);let e=vm(t.texts,`${t.type} texts`);if(e.length===0)throw TypeError(`${t.type} texts must be non-empty`);return _m(t,e.length,t.type),t}case`tool-call-chunks`:{ym(t,Object.hasOwn(t,`name`)?[`type`,`time0`,`index`,`dt`,`id`,`name`,`args`]:[`type`,`time0`,`index`,`dt`,`id`,`args`],t.type);let e=vm(t.args,`tool-call-chunks args`);if(e.length===0)throw TypeError(`tool-call-chunks args must be non-empty`);if(typeof t.id!=`string`||t.id.length===0)throw TypeError(`tool-call-chunks id must be a non-empty string`);if(t.name!==void 0&&(typeof t.name!=`string`||t.name.length===0))throw TypeError(`tool-call-chunks name must be a non-empty string`);return _m(t,e.length,t.type),t}case`chunk`:{ym(t,[`type`,`time`,`chunk`],`chunk`);let e=fm(t.time);if(typeof t.chunk!=`object`||t.chunk===null||Array.isArray(t.chunk))throw TypeError(`Assistant stream raw chunk must be a lossless JSON object`);let n;try{n=mm(t.chunk)}catch(e){throw TypeError(`Assistant stream raw chunk must be a lossless JSON object`,{cause:e})}return Wp({type:`chunk`,time:e,chunk:n})}default:throw TypeError(`Unsupported Assistant stream record ${JSON.stringify(t.type)}`)}}function _m(e,t,n){if(fm(e.time0),pm(e.index,n),!Array.isArray(e.dt)||e.dt.some(e=>!Number.isSafeInteger(e)))throw TypeError(`${n} dt must contain safe integers`);if(e.dt.length!==t-1)throw TypeError(`${n} dt length must be one less than its members`);let r=e.time0;for(let t of e.dt)if(r+=t,!Number.isSafeInteger(r))throw TypeError(`${n} member times must stay safe integers`)}function vm(e,t){if(!Array.isArray(e)||e.some(e=>typeof e!=`string`))throw TypeError(`${t} must be a string array`);return e}function ym(e,t,n){if(Object.keys(e).length!==t.length||!t.every(t=>Object.hasOwn(e,t)))throw TypeError(`${n} Assistant stream record must contain exactly ${t.join(`, `)}`)}var bm=class{activeAttempt;retainedAttempt;pending=/* @__PURE__ */ new Map;publishedSeqs=/* @__PURE__ */ new Set;durableCursor=-1;transientInGap=0;transientOrder=0;replace(e,t){this.pending.clear(),this.transientInGap=0,this.transientOrder=0,this.activeAttempt=void 0,this.retainedAttempt=void 0;let n=t?.activeAttempt;n!==void 0&&(this.activeAttempt={attemptId:n.attemptId,startedAfterSeq:n.startedAfterSeq,turn:n.turn,step:n.step,nextIndex:n.nextIndex});let r=[...e];if(this.publishedSeqs=new Set(r.map(e=>e.event.seq)),this.durableCursor=r.reduce((e,t)=>Math.max(e,t.event.seq),-1),n!==void 0){for(let[e,t]of hm(n.stream).entries())if(r.push(this.transientEntry(n,t.time,t.chunk)),e+1>=n.nextIndex)break}return r}acceptDurable(e){let t=e.event;this.durableCursor=Math.max(this.durableCursor,t.seq),this.transientInGap=0;let n=xm(e);if(n!==void 0&&this.attemptForSettlement(n.event)!==void 0){if(this.pending.has(t.seq))return{type:`rebaseline`};this.pending.set(t.seq,n)}else return this.publish(e)}acceptFrame(e){switch(e.type){case`start`:if(this.activeAttempt!==void 0||this.retainedAttempt!==void 0||this.pending.size>0)return{type:`rebaseline`};this.pending.clear(),this.activeAttempt={attemptId:e.attemptId,startedAfterSeq:e.startedAfterSeq,turn:e.turn,step:e.step,nextIndex:0};return;case`chunk`:{let t=this.activeAttempt;return t===void 0||t.attemptId!==e.attemptId?void 0:e.index===t.nextIndex?(t.nextIndex+=1,{type:`transient`,entry:this.transientEntry(t,e.time,e.chunk)}):{type:`rebaseline`}}case`end`:{let t=this.activeAttempt;if(t===void 0||t.attemptId!==e.attemptId)return;if(this.activeAttempt=void 0,e.index!==t.nextIndex)return{type:`rebaseline`};if(e.outcome.kind===`abandoned`)return this.pending.size===0?{type:`abandonment`,attemptId:t.attemptId}:{type:`rebaseline`};if(this.publishedSeqs.has(e.outcome.seq))return;let n=this.pending.get(e.outcome.seq);return n===void 0||n.event.type!==e.outcome.eventType?{type:`rebaseline`}:(this.pending.delete(e.outcome.seq),n.event.type===`assistant/message`&&n.event.data.interrupted!==!0?(this.retainedAttempt={attemptId:t.attemptId,turn:t.turn,step:t.step},this.publish(n)):(this.publishedSeqs.add(n.event.seq),{type:`settlement`,attemptId:t.attemptId,entry:n}))}}}transientEntry({attemptId:e,turn:t,step:n},r,i){let a=this.durableCursor+1;this.transientInGap+=1;let o=Math.max(1/(this.transientInGap+1),a*2**-52);return{type:`transient`,event:{type:`assistant/live-chunk`,seq:Math.max(this.durableCursor,a-o),order:++this.transientOrder,time:r,data:{attemptId:e,turn:t,step:n,chunk:i}}}}attemptForSettlement(e){let t=this.activeAttempt;if(!(t===void 0||e.type===`assistant/message`&&e.surfaceOp!==`append`||e.seq<=t.startedAfterSeq||t.turn!==e.data.turn||t.step!==e.data.step))return t}publish(e){this.publishedSeqs.add(e.event.seq);let t=this.retainedAttempt;return t!==void 0&&e.event.type===`step/end`&&e.event.data.turn===t.turn&&e.event.data.step===t.step?(this.retainedAttempt=void 0,{type:`publish`,entry:e,retireAttemptId:t.attemptId}):{type:`publish`,entry:e}}};function xm(e){return e.event.type===`assistant/message`||e.event.type===`assistant/attempt`?e:void 0}function Sm(e){return{...e,asOfSeq:e.asOfSeq===-1?-1:p(e.asOfSeq)}}let Cm={maxMessages:500,turnWindow:{minMessages:50,minTurns:2}},wm={...Cm,turnWindow:{...Cm.turnWindow,minMessages:200}};var Tm=class{sessionId;remote;baseSeq=m(0);cachedJournal;toolOutputs;hasMore=!1;openState=`cold`;lastSyncedAt;openError=null;openPromise=null;openGeneration=0;loadingOlder=!1;olderError=null;jumpTargetSeq=null;jumpPromise=null;pendingHistory=null;stopObservingInbox;onEngaged;assistantStream=new bm;running=!1;address;parentAvailable;promptAttempted=!1;firstPromptPendingTurn=!1;blankBit=!0;removed=!1;promptError=null;inFlightPrompts=/* @__PURE__ */ new Map;lastAgentError=null;pendingSubmissions=[];submissionTarget;submissionSettlements=/* @__PURE__ */ new Map;events;projections;eventSource=new um;cachedProjectionBytesRevision=-1;cachedProjectionBytes=0;snapshotCache;notifier;actx;constructor(e,t,n={}){if(this.sessionId=e,this.remote=t,this.toolOutputs=new im(e=>this.remote.session.toolOutput(e),n.cachedView?.toolOutputs),this.onEngaged=n.onEngaged,this.projections=n.projections??new Jp,n.cachedView){let e=n.cachedView;this.cachedJournal=e.journal,this.baseSeq=e.baseSeq,this.hasMore=e.hasMore,this.lastSyncedAt=e.lastSyncedAt,this.projections.applyCached(e.projections),this.eventSource.replace(e.entries,e.hasMore)}this.address=n.address,this.parentAvailable=n.parentAvailable,this.notifier=new Kp(()=>{this.snapshotCache=this.buildSnapshot()}),this.snapshotCache=this.buildSnapshot(),this.stopObservingInbox=this.projections.faceOf(`inbox`).subscribe(()=>{this.observeSubmissionInbox()})}bindScope(e){if(this.actx!==void 0)throw Error(`session ${this.sessionId} already has a bound scope`);this.actx=e}unbindScope(){this.actx=void 0}beginSubmission(e){if(this.submissionTarget!==void 0)return this.submissionTarget.beginSubmission(e);let t=am(),n=this.running?e.mode===`steer`?`steering`:`queued`:`transcript`;return this.pendingSubmissions=[...this.pendingSubmissions,{requestId:t,placement:n,time:Date.now(),text:e.text,attachments:e.attachments}],this.submissionSettlements.set(t,{placement:n,expectedTurnId:e.mode===`steer`?this.activeTurnForSteering():null,onObserved:e.onObserved,onRetire:e.onRetire,observed:!1,retiring:!1}),this.promptAttempted=!0,this.notifier.markDirty(),{requestId:t,abandon:()=>{this.retireFailedSubmission(t)}}}handoffSubmissions(e){if(e=e.submissionOwner(),e===this||this.submissionTarget!==void 0)return[];let t=this.pendingSubmissions.map(e=>e.requestId);if(t.length===0)return t;e.pendingSubmissions=[...e.pendingSubmissions,...this.pendingSubmissions];for(let n of t){let t=this.submissionSettlements.get(n);t!==void 0&&e.submissionSettlements.set(n,t);let r=this.inFlightPrompts.get(n);r!==void 0&&e.inFlightPrompts.set(n,r)}this.submissionSettlements.clear(),this.submissionTarget=e,e.promptAttempted||=this.promptAttempted;for(let{event:t}of e.eventSource.getSnapshot().entries)e.observeSubmissionEvent(t);return e.observeSubmissionInbox(),e.notifier.markDirty(),t}submissionOwner(){return this.submissionTarget?.submissionOwner()??this}get hasInFlightPrompts(){return this.inFlightPrompts.size>0}activeTurnForSteering(){let e=this.projections.get(Nf);return typeof e==`string`?e:null}async prompt(e,t,n,r){if(this.submissionTarget!==void 0)return this.submissionTarget.prompt(e,t,n,r);let i=r??am();this.promptError=null,this.lastAgentError=null,this.promptAttempted=!0,this.blankBit&&(this.firstPromptPendingTurn=!0),this.notifier.markDirty();let a={observed:!1};this.inFlightPrompts.set(i,a);try{let a=this.submissionSettlements.get(i),s;if(t===`steer`&&r!==void 0&&a===void 0)s={ok:!1,error:new o(`remote/turn-changed`,`The selected Turn has ended or changed.`,{})};else if(this.address===void 0){let r=dm(),o=this.projections.get(`remoteHost`)!=null,c=a?a.placement===`transcript`:!this.running;s=await this.remote.session.prompt({requestId:i,sessionId:this.sessionId,mode:t,...o&&t===`queue`&&c?{sendWhenIdle:!0}:{},...t===`steer`?{expectedTurnId:a?a.expectedTurnId:this.activeTurnForSteering()}:{},content:e,clientTimeZone:r},n)}else if(e.some(e=>e.type===`file`))s={ok:!1,error:new o(`subagent/attachment-invalid`,`subagent continuation does not accept files`,{reason:`SUBAGENT_FILE_UNSUPPORTED`})};else{let r=e,a=await this.remote.subagents.prompt({requestId:i,parentSessionId:this.address.parentSessionId,childSessionId:this.address.childSessionId,mode:`continuable`,delivery:t,content:r,clientTimeZone:dm()},n);s=a.ok?{ok:!0,value:{accepted:!0}}:a}let c=this.submissionOwner();return!s.ok&&s.error.code===`remote/outcome-unknown`&&c.hasObservedPrompt(i)&&(s={ok:!0,value:{accepted:!0}}),s.ok?(c.acceptPrompt(),s):(r!==void 0&&c.retireFailedSubmission(r),c.promptError={op:`send`,error:s.error,requestId:i},c.notifier.markDirty(),s)}finally{this.inFlightPrompts.get(i)===a&&this.inFlightPrompts.delete(i);let e=this.submissionOwner();e.inFlightPrompts.get(i)===a&&e.inFlightPrompts.delete(i),this.notifier.markDirty()}}acceptPrompt(){this.blankBit&&(this.blankBit=!1,this.notifier.markDirty()),this.onEngaged?.(this)}hasObservedPrompt(e){let t=t=>t.source.kind===`user`&&`rpcId`in t.source&&t.source.rpcId===e,n=this.projections.get(`inbox`);return this.inFlightPrompts.get(e)?.observed===!0||this.eventSource.getSnapshot().entries.some(({event:e})=>e.type===`user/message`&&t(e.data))||[...n?.[`next-turn`]??[],...n?.[`next-step`]??[]].some(t)}confirmPrompt(e){let t=this.inFlightPrompts.get(e);t&&(t.observed=!0),this.promptError?.op===`send`&&this.promptError.error.code===`remote/outcome-unknown`&&this.promptError.requestId===e&&(this.promptError=null,this.notifier.markDirty(),this.acceptPrompt())}async readAttachment(e){let t=await this.remote.session.attachment({sessionId:this.sessionId,attachmentId:e});if(!t.ok)return t;let n=atob(t.value.data),r=Uint8Array.from(n,e=>e.charCodeAt(0));return{ok:!0,value:{attachment:t.value.attachment,data:r}}}readToolOutput(e){return e.sessionId===this.sessionId?this.toolOutputs.read(e):Promise.reject(new o(`session/tool-output-stale`,`Tool output belongs to another session.`,{}))}async updateQueue(e,t){return this.remote.session.updateQueue({sessionId:this.sessionId,itemId:e,action:t})}async cancel(){let e=this.address,t=e===void 0?await this.remote.session.cancel({sessionId:this.sessionId}):await this.remote.subagents.interruptByParent(e.childSessionId,e.parentSessionId,`continuable`);return t.ok||(this.promptError={op:`stop`,error:t.error},this.notifier.markDirty()),t}async rename(e){let t=await this.remote.session.rename({sessionId:this.sessionId,title:e});if(!t.ok)return t;let n=p(t.value.seq);return this.projections.apply(`title`,t.value.title,n),{ok:!0,value:{title:t.value.title,seq:n}}}async command(e){let t=await this.remote.commands.execute(this.sessionId,e,[]);return t.ok?{ok:!0,value:{matched:t.value!==void 0}}:t}open(){if(this.openState===`open`)return Promise.resolve();if(this.openPromise!==null)return this.openPromise;let e=this.doOpen(this.openGeneration).finally(()=>{this.openPromise===e&&(this.openPromise=null)});return this.openPromise=e,e}async loadOlder(){if(this.openState!==`open`||!this.hasMore||this.loadingOlder)return;let e=this.events;if(e===void 0)return;let t=this.openGeneration;this.loadingOlder=!0,this.olderError=null,this.notifier.markDirty();try{await e.prepend({beforeSeq:this.baseSeq,...Cm})}catch(e){t===this.openGeneration&&(this.olderError=(0,i.isRemoteFailure)(e)?e:new o(`gateway/internal`,`Could not load earlier history.`,{}))}finally{t===this.openGeneration&&(this.loadingOlder=!1,this.notifier.markDirty())}}loadThrough(e){if(this.openState!==`open`||!this.hasMore||this.baseSeq<=e)return Promise.resolve();if(this.jumpPromise!==null)return this.jumpTargetSeq=p(Math.min(this.jumpTargetSeq??e,e)),this.jumpPromise;if(this.loadingOlder)return Promise.resolve();let t=this.events;if(t===void 0)return Promise.resolve();let n={beforeSeq:this.baseSeq,hasMore:this.hasMore,pages:[]};this.pendingHistory=n,this.jumpTargetSeq=e,this.olderError=null,this.loadingOlder=!0,this.notifier.markDirty();let r=this.openGeneration;return this.jumpPromise=(async()=>{try{for(;n.hasMore&&this.jumpTargetSeq!==null&&n.beforeSeq>this.jumpTargetSeq;){if(r!==this.openGeneration)return;let e=n.beforeSeq;if(await t.prepend({beforeSeq:e,...wm}),n.beforeSeq>=e)return}}catch(e){(0,i.isRemoteFailure)(e)||console.error(`[session-controller] loadThrough failed:`,e)}finally{this.jumpTargetSeq=null,this.jumpPromise=null,this.pendingHistory=null,this.loadingOlder=!1,r===this.openGeneration&&n.pages.length>0&&this.prependWindow(n.pages.reverse().flat(),n.hasMore),this.notifier.markDirty()}})(),this.jumpPromise}async resync(){if(this.openState===`cold`)return;let e=++this.openGeneration,t=this.events;this.cachedJournal=t?.capture()??this.cachedJournal,this.events=void 0,await t?.dispose(),e===this.openGeneration&&(this.openPromise=null,this.openState=`cold`,this.openError=null,this.baseSeq=m(0),this.notifier.markDirty(),await this.open())}subscribe(e){return this.notifier.subscribe(e)}getSnapshot(){return this.notifier.ensureFresh(),this.snapshotCache}estimatedBytes(){let e=this.projections.revision;return this.cachedProjectionBytesRevision!==e&&(this.cachedProjectionBytes=$p(this.projections.values()),this.cachedProjectionBytesRevision=e),(this.eventSource.estimatedBytes>0?this.eventSource.estimatedBytes:nm(this.cachedJournal))+this.toolOutputs.estimatedBytes+this.cachedProjectionBytes}captureView(){if(this.lastSyncedAt===void 0||this.removed)return;let e=this.events?.capture()??this.cachedJournal;return{...e===void 0?{}:{journal:e},toolOutputs:new Map(this.toolOutputs.values),entries:this.eventSource.getSnapshot().entries,baseSeq:this.baseSeq,hasMore:this.hasMore,projections:this.projections.values(),lastSyncedAt:this.lastSyncedAt}}handleRunning(e){e&&this.blankBit&&(this.blankBit=!1,this.notifier.markDirty()),e&&(this.firstPromptPendingTurn=!1),this.running!==e&&(this.running=e,this.notifier.markDirty())}configureSubagent(e,t){let n=this.address?.parentSessionId===e?.parentSessionId&&this.address?.childSessionId===e?.childSessionId&&this.address?.mode===e?.mode;this.address=e,this.parentAvailable=t,!n&&this.openState!==`cold`?this.resync():this.notifier.markDirty()}handleSubagentParentAvailable(e){this.parentAvailable!==e&&(this.parentAvailable=e,this.notifier.markDirty())}handleBlank(e){e&&=this.projections.values().sessionListMetadata?.blank!==!1,e!==this.blankBit&&(e&&(this.promptAttempted||this.running)||(this.blankBit=e,this.notifier.markDirty()))}handleRemoved(){this.removed=!0,this.notifier.markDirty()}handleRestored(){this.removed&&(this.removed=!1,this.notifier.markDirty())}handleAgentError(e){this.lastAgentError=e,this.notifier.markDirty()}async dispose(){this.stopObservingInbox();for(let[e,t]of[...this.submissionSettlements])t.admitted===void 0?this.retireFailedSubmission(e):this.scheduleObservedRetirement(e,t.admitted);this.openGeneration++;let e=this.events;this.events=void 0,await e?.dispose()}async doOpen(e){this.openState=`loading`,this.openError=null,this.olderError=null,this.loadingOlder=!1,this.notifier.markDirty();let t=this.cachedJournal?.epoch,n=new pe(this.remote,this.sessionAddress(),{publish:r=>{e===this.openGeneration&&this.events===n&&(r.type===`replace`&&(t&&n.journalEpoch!==t&&this.projections.discard(Pf),t=n.journalEpoch),this.acceptEventChange(r))},failed:t=>{this.failEventStream(n,e,t)}},this.cachedJournal);this.events=n;try{if(await n.open(Cm),e!==this.openGeneration||this.events!==n)return;this.cachedJournal=void 0,this.openState=`open`}catch(t){if(e!==this.openGeneration||this.events!==n)return;if(!(0,i.isRemoteFailure)(t))throw t;this.events=void 0,this.openState=`error`,this.openError=t}finally{e===this.openGeneration&&this.notifier.markDirty()}}acceptEventChange(e){switch(e.type){case`replace`:this.installWindow(e.entries,e.hasMore,e.page.projections===void 0?void 0:Sm(e.page.projections),e.page.assistantStream);break;case`prepend`:this.prependWindow(e.entries,e.hasMore);break;case`append`:this.publishAssistantEntry(this.assistantStream.acceptDurable(e.entry));break;case`assistant-stream`:this.publishAssistantEntry(this.assistantStream.acceptFrame(e.frame));break;case`projection`:this.projections.applyLive(e.key,e.value,p(e.seq))}this.lastSyncedAt=Date.now(),this.notifier.markFrameDirty()}installWindow(e,t,n,r){let i=this.assistantStream.replace(e,r);if(this.baseSeq=m(e[0]?.event.seq??0),this.hasMore=t,this.pendingHistory!==null&&(this.pendingHistory.beforeSeq=this.baseSeq,this.pendingHistory.hasMore=t,this.pendingHistory.pages.length=0),i.some(e=>e.event.type===`turn/start`)&&(this.firstPromptPendingTurn=!1),n!==void 0&&this.projections.seed(n,Pf),this.eventSource.replace(i,t),n!==void 0)for(let[e,{receipt:t}]of this.submissionSettlements)t!==void 0&&t.seq<=n.asOfSeq&&this.scheduleObservedRetirement(e,t.attachments);for(let e of i)this.observeSubmissionEvent(e.event);if(n!==void 0){let e=n.values.inbox;for(let t of[`next-turn`,`next-step`])this.observeSubmissionInsertions(t,e?.[t]??[],0,n.asOfSeq)}this.notifier.markDirty()}publishAssistantEntry(e){if(e?.type===`rebaseline`){let e=this.events;queueMicrotask(()=>{e!==void 0&&this.events===e&&e.restart()})}else if(e?.type===`settlement`)this.eventSource.settleAssistant(e.attemptId,e.entry),this.observeSubmissionEvent(e.entry.event),this.notifier.markDirty();else if(e?.type===`abandonment`)this.eventSource.settleAssistant(e.attemptId),this.notifier.markDirty();else if(e?.type===`publish`){let t=this.appendLive(e.entry);e.retireAttemptId!==void 0&&this.eventSource.settleAssistant(e.retireAttemptId),(t||e.retireAttemptId!==void 0)&&this.notifier.markDirty()}else e?.type===`transient`&&(this.eventSource.append(e.entry),this.notifier.markDirty())}prependWindow(e,t){if(this.pendingHistory!==null){let n=this.pendingHistory;n.beforeSeq=e[0]===void 0?n.beforeSeq:m(e[0].event.seq),n.hasMore=t,n.pages.push(e)}else{this.baseSeq=e[0]===void 0?this.baseSeq:m(e[0].event.seq),this.hasMore=t,this.eventSource.prepend(e,t);for(let{event:t}of e)if(t.type===`user/message`)this.observeSubmissionMessage(t.data,!0);else if(t.type===`agent/inbox/spliced`)for(let{source:e}of t.data.inserted)e.kind===`user`&&`rpcId`in e&&this.confirmPrompt(e.rpcId)}}appendLive(e){let t=e.event,n=this.firstPromptPendingTurn;return t.type===`turn/start`&&(this.firstPromptPendingTurn=!1),this.eventSource.append(e),this.observeSubmissionEvent(t),n!==this.firstPromptPendingTurn}observeSubmissionEvent(e){if(e.type===`user/message`)this.observeSubmissionMessage(e.data,!0);else if(this.submissionSettlements.size!==0||this.inFlightPrompts.size!==0||this.promptError?.requestId!==void 0){if(e.type===`agent/inbox/spliced`){let{target:t,start:n,removedCount:r=0,inserted:i,outcome:a}=e.data;for(let[o,s]of this.submissionSettlements){let c=s.receipt;if(c?.target!==t||c.index===null||c.seq>=e.seq)continue;let l=c.index>=n&&c.index<n+r;l&&a===`canceled`?this.retireFailedSubmission(o):s.receipt={...c,seq:e.seq,index:l?null:c.index<n?c.index:c.index+i.length-r}}this.observeSubmissionInsertions(t,i,n,e.seq);for(let e of i)this.observeSubmissionMessage(e,!1,t)}else if(e.type===`request/context`||e.type===`turn/end`)for(let[t,n]of this.submissionSettlements)n.admitted===void 0&&n.receipt?.index===null&&n.receipt.seq<e.seq&&this.retireFailedSubmission(t)}}observeSubmissionInsertions(e,t,n,r){for(let[i,a]of t.entries()){let t=a.source;if(t.kind!==`user`||!(`rpcId`in t))continue;this.confirmPrompt(t.rpcId);let o=this.submissionSettlements.get(t.rpcId);o===void 0||o.placement===`queued`||o.retiring||(o.receipt?.seq??-1)>r||(o.receipt={target:e,seq:r,index:n+i,attachments:Dm(a.content)})}}observeSubmissionMessage(e,t,n){let r=e.source;if(r.kind!==`user`||!(`rpcId`in r))return;this.confirmPrompt(r.rpcId);let i=this.submissionSettlements.get(r.rpcId);i===void 0||i.retiring||(t?(i.admitted=Dm(e.content),this.notifySubmissionObserved(i,i.admitted),this.retireAdmittedSubmission(r.rpcId)):(i.placement===`queued`||n===`next-turn`)&&this.scheduleObservedRetirement(r.rpcId,Dm(e.content)))}retireAdmittedSubmission(e){let t=this.submissionSettlements.get(e);if(t?.admitted===void 0)return;let n=t.receipt;n?.index===null&&(this.projections.seqOf(`inbox`)??-1)<n.seq||this.scheduleObservedRetirement(e,t.admitted)}observeSubmissionInbox(){if(this.submissionSettlements.size===0&&this.inFlightPrompts.size===0&&this.promptError?.requestId===void 0)return;let e=this.projections.get(`inbox`);if(e===void 0)return;let t=this.projections.seqOf(`inbox`);for(let n of[`next-turn`,`next-step`]){t!==void 0&&this.observeSubmissionInsertions(n,e[n],0,t);for(let t of e[n])this.observeSubmissionMessage(t,!1,n)}for(let e of this.submissionSettlements.keys())this.retireAdmittedSubmission(e)}notifySubmissionObserved(e,t){e.observed||(e.observed=!0,e.onObserved?.(t))}scheduleObservedRetirement(e,t){let n=this.submissionSettlements.get(e);n===void 0||n.retiring||(n.retiring=!0,this.notifySubmissionObserved(n,t),Em(()=>{this.finishSubmission(e,{reason:`observed`,attachments:t})}))}retireFailedSubmission(e){if(this.submissionTarget!==void 0){this.submissionTarget.retireFailedSubmission(e);return}let t=this.submissionSettlements.get(e);t===void 0||t.retiring||t.admitted!==void 0||(t.retiring=!0,this.finishSubmission(e,{reason:`failed`}))}finishSubmission(e,t){if(this.submissionTarget!==void 0){this.submissionTarget.finishSubmission(e,t);return}let n=this.submissionSettlements.get(e);
128
128
  /* v8 ignore next -- retiring latches before every schedule, so one settlement never finishes twice. */
129
129
  n!==void 0&&(this.submissionSettlements.delete(e),this.pendingSubmissions=this.pendingSubmissions.filter(t=>t.requestId!==e),this.notifier.markDirty(),n.onRetire?.(t))}failEventStream(e,t,n){if(t===this.openGeneration&&this.events===e){if(!(0,i.isRemoteFailure)(n))throw n;this.openGeneration++,this.cachedJournal=e.capture(),this.events=void 0,this.openPromise=null,this.openState=`error`,this.openError=n,e.dispose(),this.notifier.markDirty()}}buildSnapshot(){let e=this.projections.values().subagent;return{sessionId:this.sessionId,pendingSubmissions:this.pendingSubmissions,running:this.running,subagent:this.address===void 0?null:{address:this.address.mode===`unknown`&&e!=null?{...this.address,mode:e.mode}:this.address,...this.parentAvailable===void 0?{}:{parentAvailable:this.parentAvailable}},removed:this.removed,openState:this.openState,...this.lastSyncedAt===void 0?{}:{lastSyncedAt:this.lastSyncedAt},openError:this.openError,hasMore:this.hasMore,loadingOlder:this.loadingOlder,olderError:this.olderError,promptError:this.promptError,blank:this.blankBit,lastAgentError:this.lastAgentError,promptAttempted:this.promptAttempted,awaitingFirstTurn:this.firstPromptPendingTurn}}sessionAddress(){return this.address===void 0?{kind:`session`,sessionId:this.sessionId}:{kind:`subagent`,...this.address}}};function Em(e){typeof requestAnimationFrame==`function`?requestAnimationFrame(()=>{e()}):setTimeout(e,0)}function Dm(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!=`object`||!n)continue;let e=n;(e.type===`image`||e.type===`file`)&&typeof e.attachment==`object`&&e.attachment!==null&&t.push(e.attachment)}return t}var Om=class{views=/* @__PURE__ */ new Map;maxEntries;maxBytes;estimateBytes;cachedBytes=0;constructor(e={}){this.maxEntries=Math.max(0,e.maxEntries??8),this.maxBytes=Math.max(0,e.maxBytes??25165824),this.estimateBytes=e.estimateBytes??rm}get size(){return this.views.size}get totalBytes(){return this.cachedBytes}take(e){let t=this.views.get(e);if(t!==void 0)return this.views.delete(e),this.cachedBytes-=t.bytes,t.view}remember(e,t){let n=this.views.get(e);n!==void 0&&(this.views.delete(e),this.cachedBytes-=n.bytes);let r=Math.max(0,this.estimateBytes(t));if(this.maxEntries===0||r>this.maxBytes)return[e];this.views.set(e,{view:t,bytes:r}),this.cachedBytes+=r;let i=[];for(;this.views.size>this.maxEntries||this.cachedBytes>this.maxBytes;){let t=this.views.entries().next().value;if(t[0]===e)break;this.views.delete(t[0]),this.cachedBytes-=t[1].bytes,i.push(t[0])}return i}delete(e){let t=this.views.get(e);t!==void 0&&(this.views.delete(e),this.cachedBytes-=t.bytes)}clear(){this.views.clear(),this.cachedBytes=0}};function km(e){return e===-1?-1:p(e)}let Am=/* @__PURE__ */ new Set([`title`,`codexhostUsage`,`contextPressure`,`contextBreakdown`]),jm=/* @__PURE__ */ new Set([...Pf,`codexhostTurnTimes`,`codexhostUsage`,`contextPressure`,`contextBreakdown`,`inbox`,`queueState`,`turnOutline`,`sessionStats`,`compacting`]);var Mm=class{remote;sessions=/* @__PURE__ */ new Map;recentViews=new Om;sessionDisposals=/* @__PURE__ */ new Set;engagedSessions=/* @__PURE__ */ new Set;disposed=!1;projectionStores=/* @__PURE__ */ new Map;summaries=[];summaryOnlyIds=/* @__PURE__ */ new Set;listState=`idle`;listPhase=`pending`;listError=null;listRequestIsMore=!1;listRequestWorkspaceId;headRefreshRevision=0;listInflight=null;includeArchived=!1;nextCursor;listMutations=null;addresses=/* @__PURE__ */ new Map;projectionLoads=/* @__PURE__ */ new Map;projectionInflight=/* @__PURE__ */ new Map;listSnapshotCache;entryCache=/* @__PURE__ */ new Map;itemsCache=[];projectionSnapshotCache=/* @__PURE__ */ new Map;projectionsBySessionCache={};notifier=new Kp(()=>{this.listSnapshotCache=this.buildListSnapshot()});constructor(e){this.remote=e,this.listSnapshotCache=this.buildListSnapshot()}resolveTarget(e){let t=typeof e==`string`?e:e.childSessionId,n=typeof e==`string`?this.subagentAddress(t):e;if(typeof e==`string`&&!this.sessions.has(t)&&!this.summaries.some(e=>e.sessionId===t)&&n===void 0)throw Error(`sessions.retain: unknown session ${t}`);return n!==void 0&&this.addresses.set(t,n),this.sessions.get(t)?.configureSubagent(n,n===void 0?void 0:this.agentAvailable(n.parentSessionId)),t}subagentAddress(e){let t=this.addresses.get(e);if(t!==void 0)return t;for(let t of this.projectionStores.keys()){let n=this.projectionStores.get(t)?.values().subagentCatalog?.find(t=>t.id===e);if(n!==void 0)return{parentSessionId:t,childSessionId:e,mode:n.mode}}}drop(e,t){let n=this.sessions.get(e);if(n!==t)return Promise.resolve();let r=n.captureView();if(r)for(let t of this.recentViews.remember(e,r))this.projectionStores.get(t)?.discard(Pf);return this.sessions.delete(e),this.addresses.delete(e),this.pruneEngagement(e,this.retainedIds(this.summaries)),this.startSessionDisposal(n)}async dispose(){this.disposed=!0,this.listMutations=null,this.listInflight=null,this.engagedSessions.clear();let e=[...this.projectionInflight.values()];for(let{controller:t}of e)t.abort();this.projectionInflight.clear(),await Promise.all(e.map(e=>e.promise));let t=[...this.sessions.values()];this.sessions.clear(),this.recentViews.clear(),this.addresses.clear();for(let e of t)this.startSessionDisposal(e);await this.drainSessionDisposals()}startSessionDisposal(e){let t=e.dispose();return this.sessionDisposals.add(t),t.then(()=>{this.sessionDisposals.delete(t)},()=>{this.sessionDisposals.delete(t)}),t}async drainSessionDisposals(){for(;this.sessionDisposals.size>0;)await Promise.allSettled([...this.sessionDisposals])}get(e){let t=this.sessions.get(e);if(t===void 0){t=this.createSession(e),this.sessions.set(e,t);let n=this.summaries.find(t=>t.sessionId===e);if(n!==void 0)t.handleBlank(this.effectiveBlank(n)),t.handleRunning(n.running);else{let n=this.addresses.get(e);(n===void 0?void 0:this.projectionStores.get(n.parentSessionId)?.values().subagentCatalog?.find(t=>t.id===e))===void 0?t.handleBlank(!0):(t.handleBlank(!1),t.handleRunning(!1))}}return t}createSession(e){let t=this.addresses.get(e),n=t===void 0?void 0:this.agentAvailable(t.parentSessionId);return new Tm(e,this.remote,{...t===void 0?{}:{address:t,...n===void 0?{}:{parentAvailable:n}},onEngaged:e=>{!this.disposed&&this.retainedIds(this.summaries).has(e.sessionId)&&(this.engagedSessions.has(e.sessionId)||(this.engagedSessions.add(e.sessionId),this.recordMutation({kind:`engaged`,sessionId:e.sessionId})),this.sessions.get(e.sessionId)?.handleBlank(!1))},projections:this.projectionStore(e),cachedView:this.recentViews.take(e)})}effectiveBlank(e){return e.blank&&!this.engagedSessions.has(e.sessionId)}retainedIds(e){let t=new Set(e.map(e=>e.sessionId));for(let e of this.sessions.keys())t.add(e);for(let e of this.addresses.keys())t.add(e);return t}pruneEngagement(e,t){t.has(e)||this.engagedSessions.delete(e)}projectionStore(e){let t=this.projectionStores.get(e);if(t===void 0){t=new Jp(jm);let n=t;t.subscribeAny(()=>{n.values().sessionListMetadata?.blank===!1&&this.sessions.get(e)?.handleBlank(!1),this.notifier.markFrameDirty()}),this.projectionStores.set(e,t)}return t}refreshProjections(e){let t=this.projectionInflight.get(e);if(t!==void 0)return t.promise;if(this.projectionLoads.get(e)?.state===`ready`)return Promise.resolve();let n=new AbortController,r=this.projectionStore(e),a=r.revision;this.projectionLoads.set(e,{state:`loading`,error:null}),this.notifier.markDirty();let o=(async()=>{try{let t=await this.remote.session.projections({sessionId:e},n.signal);if(n.signal.aborted)return;t.ok?(t.value===null?r.revision===a&&r.clear():r.seed({...t.value,asOfSeq:km(t.value.asOfSeq)}),this.projectionLoads.set(e,{state:`ready`,error:null})):this.projectionLoads.set(e,{state:`error`,error:t.error})}catch(t){if(n.signal.aborted)return;if(!(0,i.isRemoteFailure)(t))throw t;this.projectionLoads.set(e,{state:`error`,error:t})}finally{n.signal.aborted||(this.projectionInflight.delete(e),this.notifier.markDirty())}})();return this.projectionInflight.set(e,{promise:o,controller:n}),o}agentAvailable(e){return this.summaries.find(t=>t.sessionId===e)?.agentAvailable??(this.listPhase!==`ready`&&void 0)}updateParentAvailability(){for(let[e,t]of this.addresses){let n=this.agentAvailable(t.parentSessionId);n!==void 0&&this.sessions.get(e)?.handleSubagentParentAvailable(n)}}setIncludeArchived(e){return this.includeArchived===e?this.listInflight??Promise.resolve():(this.includeArchived=e,this.nextCursor=void 0,this.listMutations=null,this.listInflight=null,this.refreshList())}hasSummary(e){return this.summaries.some(t=>t.sessionId===e)}async loadSummary(e){if(this.summaries.some(t=>t.sessionId===e))return;let t=await this.remote.session.list({sessionId:e});if(!t.ok)throw t.error;if(!this.disposed)for(let e of t.value.items)this.summaries.some(t=>t.sessionId===e.sessionId)||this.summaryOnlyIds.add(e.sessionId),this.handleSessionAdded(e,!1)}loadMore(e){return this.nextCursor?this.refreshList(this.nextCursor,e):Promise.resolve()}refreshList(e,t){if(this.disposed)return Promise.resolve();if(this.listInflight!==null)return this.listInflight;let n=this.includeArchived;this.listState=`loading`,this.listError=null,this.listRequestIsMore=e!==void 0,this.listRequestWorkspaceId=e===void 0?void 0:t;let r=this.summaries,a=[];return this.listMutations=a,this.notifier.markDirty(),this.listInflight=(async()=>{try{let i=await this.remote.session.list({includeArchived:n,...e?{cursor:e,...t?{workspaceId:t}:{}}:{}});if(this.listMutations!==a)return;if(i.ok){let t=new Set(i.value.archivedSessionIds),o=new Set(i.value.items.map(e=>e.sessionId)),s=i.value.nextCursor!==void 0;(e!==void 0||this.nextCursor===void 0)&&(this.nextCursor=i.value.nextCursor??null);let c=[...i.value.items,...r.filter(e=>!o.has(e.sessionId)&&(s||!n&&t.has(e.sessionId)))],l=this.listPhase===`pending`?c:jp(r,c,e=>e.sessionId),u=/* @__PURE__ */ new Set;for(let e of a)e.kind===`remove`&&u.add(e.sessionId);for(let e of l)e.running&&!u.has(e.sessionId)&&this.engagedSessions.add(e.sessionId);let d=a.reduce(Nm,l);this.summaries=d;let f=new Set(d.map(e=>e.sessionId));for(let e of this.summaryOnlyIds)(o.has(e)||!f.has(e))&&this.summaryOnlyIds.delete(e);let p=this.retainedIds(d);for(let e of this.engagedSessions)this.pruneEngagement(e,p);this.listState=`idle`,this.listPhase=`ready`,this.updateParentAvailability();for(let e of this.summaries){let t=this.sessions.get(e.sessionId);t!==void 0&&(t.handleBlank(this.effectiveBlank(e)),t.handleRunning(e.running))}for(let e of i.value.items)e.projections!==void 0&&this.applyListBlock(e.sessionId,e.projections);e===void 0&&this.listMutations===a&&(this.headRefreshRevision+=1)}else this.listState=`error`,this.listError=i.error}catch(e){if(!(0,i.isRemoteFailure)(e))throw e;if(this.listMutations!==a)return;this.listState=`error`,this.listError=e}finally{this.listMutations===a&&(this.listMutations=null,this.listInflight=null,this.notifier.markDirty())}})(),this.listInflight}async search(e,t){let n=await this.remote.session.search({query:e},t);return n.ok?{ok:!0,value:{items:n.value.items.filter(e=>this.summaries.some(t=>t.sessionId===e.sessionId)),hasMore:n.value.hasMore}}:n}async create(e={}){let t=e.sessionId===void 0?{}:{sessionId:e.sessionId},n=e.workspaceId===void 0?{...e.cwd===void 0?{}:{cwd:e.cwd},...t}:{workspaceId:e.workspaceId,...t},r=await this.remote.session.create(n);if(r.ok)this.recordMutation({kind:`placeholder`,summary:{agentAvailable:!0,sessionId:r.value.sessionId,updatedAt:Date.now(),running:!1,blank:!0,...e.cwd===void 0?{}:{cwd:e.cwd}}});else{let e=Pm(r.error);e!==void 0&&this.recordMutation({kind:`placeholder`,summary:{agentAvailable:!0,sessionId:e,updatedAt:Date.now(),running:!1,blank:!0}})}return r}async fork(e){let t=this.sessions.get(e.sessionId);if(t&&t.getSnapshot().openState!==`open`)return{ok:!1,error:new o(`session/syncing`,`Wait for the Session history to finish synchronizing.`,{})};let n=this.summaries.find(t=>t.sessionId===e.sessionId),r=await this.remote.session.fork({sessionId:e.sessionId,...e.atSeq===void 0?{}:{atSeq:e.atSeq}}),i=r.ok?r.value.sessionId:Pm(r.error);return i!==void 0&&this.recordMutation({kind:`placeholder`,summary:{agentAvailable:!0,sessionId:i,updatedAt:Date.now(),running:!1,blank:!0,parentSessionId:e.sessionId,...n?.cwd===void 0?{}:{cwd:n.cwd}}}),r}async rename(e,t){let n=await this.remote.session.rename({sessionId:e,title:t});return n.ok&&this.projectionStore(e).apply(`title`,n.value.title,p(n.value.seq))&&this.notifier.markDirty(),n}mergeSummary(e){let t=this.recordMutation({kind:`upsert`,summary:e},`frame`);return this.updateParentAvailability(),t}recordMutation(e,t=`microtask`){if(this.disposed)return!1;this.listMutations?.push(e);let n=Nm(this.summaries,e);return n!==this.summaries&&(this.summaries=n,t===`frame`?this.notifier.markFrameDirty():this.notifier.markDirty(),!0)}subscribe(e){return this.notifier.subscribe(e)}getListSnapshot(){return this.notifier.ensureFresh(),this.listSnapshotCache}projectionValues(e){return this.projectionStores.get(e)?.values()}handleControlFrame(e){e.type===`baseline`?this.replaceControlBaseline(e.value):this.projectionStore(e.sessionId).applyLive(e.key,e.value,p(e.seq))&&!jm.has(e.key)&&this.notifier.markFrameDirty()}replaceControlBaseline(e){for(let[t,n]of Object.entries(e.projections)){let e=this.projectionStore(t),r=km(n.asOfSeq);e.seed({...n,asOfSeq:r},void 0,Pf)}this.notifier.markFrameDirty()}handleSessionAdded(e,t=!0){let n=t&&this.summaryOnlyIds.delete(e.sessionId),r=this.mergeSummary(e);n&&!r&&this.notifier.markFrameDirty(),!this.disposed&&e.running&&this.engagedSessions.add(e.sessionId);let i=this.sessions.get(e.sessionId);i?.handleRestored(),i?.handleBlank(this.effectiveBlank(e)),e.projections!==void 0&&this.applyListBlock(e.sessionId,e.projections)}applyListBlock(e,t){let n=this.projectionStore(e);switch(t.kind){case`sequenced`:{let e=km(t.asOfSeq);for(let[r,i]of Object.entries(t.values))n.apply(r,i,e);return}case`cached`:n.applyCached(t.values);return;default:Ip(t.kind,`session list projection block kind`)}}handleSessionRemoved(e){let t=this.summaryOnlyIds.delete(e),n=this.subagentAddress(e)!==void 0||this.summaries.some(t=>t.sessionId===e&&t.origin===`subagent`),r=this.recordMutation(n?{kind:`status`,sessionId:e,running:!1,agentAvailable:!1}:{kind:`remove`,sessionId:e},`frame`),i=!1;if(n){let t=this.sessions.get(e);i=t?.getSnapshot().running===!0,t?.handleRunning(!1)}else this.recentViews.delete(e),this.sessions.get(e)?.handleRemoved();let a=this.projectionStores.get(e)?.values().subagentCatalog,o=!n&&(a===void 0||a.length===0)&&this.projectionStores.delete(e);this.pruneEngagement(e,this.retainedIds(this.summaries)),this.projectionInflight.get(e)?.controller.abort(),this.projectionInflight.delete(e);let s=this.projectionLoads.delete(e);!r&&(t||o||s||i)&&this.notifier.markFrameDirty();for(let[t,n]of this.addresses)n.parentSessionId===e&&this.sessions.get(t)?.handleSubagentParentAvailable(!1)}handleSessionStatus(e,t){!this.disposed&&t&&this.engagedSessions.add(e);let n=this.recordMutation({kind:`status`,sessionId:e,running:t,agentAvailable:!0},`frame`);this.updateParentAvailability();let r=this.sessions.get(e),i=r?.getSnapshot().running;r?.handleRunning(t),!n&&r!==void 0&&i!==t&&this.notifier.markFrameDirty()}handleSessionActivity(e,t){this.recordMutation({kind:`activity`,sessionId:e,updatedAt:t},`frame`)}handleSessionError(e,t){this.sessions.get(e)?.handleAgentError(t)}handleConnected(){for(let e of this.sessions.values())e.getSnapshot().openState===`error`&&e.resync();for(let e of this.projectionStores.values())e.clear(Am);this.listMutations=null,this.listInflight=null,this.nextCursor=void 0,this.refreshList();let e=new Set(this.projectionLoads.keys());for(let t of this.sessions.keys()){let n=this.addresses.get(t);n!==void 0&&e.add(n.parentSessionId)}for(let{controller:e}of this.projectionInflight.values())e.abort();this.projectionInflight.clear(),this.projectionLoads.clear();for(let t of e)this.refreshProjections(t)}buildListSnapshot(){let e=Gp(this.summaries.map(e=>{let t=this.projectionStores.get(e.sessionId),n=t?.get(`title`),r=t?.values(),i=r?.sessionListMetadata;return{...e,blank:this.effectiveBlank(e)&&i?.blank!==!1,updatedAt:Math.max(e.updatedAt,i?.lastPromptAt??0),...typeof n==`string`&&n!==``?{title:n}:{},...r===void 0?{}:{projectionValues:r}}})).map(e=>{let t=this.entryCache.get(e.sessionId);return t!==void 0&&t.updatedAt===e.updatedAt&&t.running===e.running&&t.blank===e.blank&&t.parentSessionId===e.parentSessionId&&t.cwd===e.cwd&&t.origin===e.origin&&t.title===e.title&&t.depth===e.depth&&t.projectionValues===e.projectionValues?t:(this.entryCache.set(e.sessionId,e),e)}),t=new Set(e.map(e=>e.sessionId));for(let e of this.entryCache.keys())t.has(e)||this.entryCache.delete(e);e.length===this.itemsCache.length&&e.every((e,t)=>e===this.itemsCache[t])||(this.itemsCache=e);let n=this.projectionSnapshotCache.size!==this.projectionStores.size;for(let[e,t]of this.projectionStores){let r=t.values(),i=this.projectionLoads.get(e),a=i?.state??`idle`,o=i?.error??null,s=this.projectionSnapshotCache.get(e);(s===void 0||s.values!==r||s.state!==a||s.error!==o)&&(this.projectionSnapshotCache.set(e,{values:r,state:a,error:o}),n=!0)}if(n){for(let e of this.projectionSnapshotCache.keys())this.projectionStores.has(e)||this.projectionSnapshotCache.delete(e);this.projectionsBySessionCache=Object.fromEntries(this.projectionSnapshotCache)}return{items:this.itemsCache,hasMore:!!this.nextCursor,headRefreshRevision:this.headRefreshRevision,summaryOnlyIds:[...this.summaryOnlyIds],state:this.listState,phase:this.listPhase,error:this.listError,errorPage:this.listError?this.listRequestIsMore?`more`:`head`:null,errorWorkspaceId:this.listError&&this.listRequestIsMore?this.listRequestWorkspaceId??null:null,projectionsBySession:this.projectionsBySessionCache}}};function Nm(e,t){switch(t.kind){case`upsert`:case`placeholder`:{let n=e.findIndex(e=>e.sessionId===t.summary.sessionId);if(n===-1)return[t.summary,...e];let r=e[n],i={...r,blank:r.blank&&t.summary.blank,...t.kind===`upsert`?{agentAvailable:t.summary.agentAvailable,running:t.summary.running}:{},...r.cwd===void 0&&t.summary.cwd!==void 0?{cwd:t.summary.cwd}:{},...r.parentSessionId===void 0&&t.summary.parentSessionId!==void 0?{parentSessionId:t.summary.parentSessionId}:{},...r.origin===void 0&&t.summary.origin!==void 0?{origin:t.summary.origin}:{}};if(i.cwd===r.cwd&&i.parentSessionId===r.parentSessionId&&i.origin===r.origin&&i.blank===r.blank&&i.agentAvailable===r.agentAvailable&&i.running===r.running)return e;let a=[...e];return a[n]=i,a}case`remove`:return e.findIndex(e=>e.sessionId===t.sessionId)===-1?e:e.filter(e=>e.sessionId!==t.sessionId);case`status`:{let n=e.findIndex(e=>e.sessionId===t.sessionId);if(n===-1)return e;let r=e[n];if(r.running===t.running&&r.agentAvailable===t.agentAvailable&&(!t.running||!r.blank))return e;let i=[...e];return i[n]={...r,running:t.running,agentAvailable:t.agentAvailable,blank:r.blank&&!t.running},i}case`activity`:{let n=e.findIndex(e=>e.sessionId===t.sessionId);if(n===-1)return e;let r=e[n];if(!(t.updatedAt>r.updatedAt))return e;let i=[...e];return i[n]={...r,updatedAt:t.updatedAt},i}case`engaged`:{let n=e.findIndex(e=>e.sessionId===t.sessionId);if(n===-1)return e;let r=e[n];if(!r.blank)return e;let i=[...e];return i[n]={...r,blank:!1},i}}}function Pm(e){return e.code===`session/workspace-attach-failed`?e.details.sessionId:void 0}var Fm=class extends Error{rpcError;requestedSessionId;name=`SessionCreateError`;constructor(e,t){super(`session create failed: ${e.code}: ${e.message}`),this.rpcError=e,this.requestedSessionId=t}},Im=class extends Error{rpcError;sourceSessionId;name=`SessionForkError`;constructor(e,t){super(`session fork failed: ${e.code}: ${e.message}`),this.rpcError=e,this.sourceSessionId=t}};function Lm(e,t,n){if(e!==void 0)return e;if(t!==void 0&&t!==``){let e=me(t);if(e!==``)return e}return n}function Rm(e){let t=/^(.*?)\((\d+)\)$/u.exec(e);if(t?.[1]!==void 0&&t[2]!==void 0)return`${t[1]}(${BigInt(t[2])+1n})`;let n=/^(.*?)((\d+))$/u.exec(e);return n?.[1]!==void 0&&n[2]!==void 0?`${n[1]}(${BigInt(n[2])+1n})`:`${e} (1)`}function zm(e){return Object.setPrototypeOf(e,null),Object.freeze(e)}let Bm=Object.freeze({referenceCount:0,retainedBy:zm({})});async function Vm(e,t){if(t===void 0)return e;let n=Promise.withResolvers(),r=()=>{n.reject(t.reason)};t.addEventListener(`abort`,r,{once:!0});try{t.aborted&&r(),await Promise.race([e,n.promise])}finally{t.removeEventListener(`abort`,r)}}var Hm=class{sessionId;record;releaseReference;released=new AbortController;readiness=Promise.withResolvers();ready=this.readiness.promise;constructor(e,t,n){this.sessionId=e,this.record=t,this.releaseReference=n,this.ready.catch(()=>{})}get binding(){if(this.record===void 0||!this.record.live)throw Error(`Session reference "${this.sessionId}" is released`);return this.record.binding}attachOpening(e,t){let n=t===void 0?this.released.signal:AbortSignal.any([this.released.signal,t]);Vm(e,n).then(()=>{try{n.throwIfAborted(),this.readiness.resolve(this.binding)}catch(e){this.readiness.reject(e)}},e=>{this.readiness.reject(e)})}release(){let e=/* @__PURE__ */ Error(`Session reference "${this.sessionId}" is released`),t=this.releaseReference;this.released.abort(e),this.readiness.reject(e),this.record=void 0,this.releaseReference=void 0,t?.()}[Symbol.dispose](){this.release()}},Um=class{rootCtx;searchResultLimit=20;list;manager;scopes=/* @__PURE__ */ new Map;retainObservers=/* @__PURE__ */ new Map;scopeDrops=/* @__PURE__ */ new Set;projectedItemCache=/* @__PURE__ */ new Map;closed=!1;constructor(e,t){this.rootCtx=e,this.manager=new Mm(t),this.list=(0,a.createSnapshotStore)({ids:[],byId:{},phase:`pending`,headRefreshRevision:0,summaryOnlyIds:[],projectionsBySession:{}});let n=this.manager.subscribe(()=>{this.projectList()});e.effect(()=>async()=>{this.closed=!0,n();let e=[...this.scopes];this.scopes.clear();for(let[,t]of e)t.live=!1,t.session.unbindScope();let t=this.manager.dispose();for(let[t,n]of e)this.startScopeDrop(t,n),this.publishRetention(t);await this.drainScopeDrops(),await t},`session-controller.client.sessions`),e.reflect.provide(`sessions`,this,void 0)}retain(e,t){let{source:n,signal:r}=t;if(r?.throwIfAborted(),this.closed)throw Error(`Session Controller is disposed`);let i=this.manager.resolveTarget(e),a=this.retainScope(i,n);try{return a.attachOpening(this.manager.get(i).open(),r),a}catch(e){throw a.release(),e}}handoffSubmissions(e,t){let n=this.scopes.get(e)?.session;if(n===void 0||e===t||n.getSnapshot().pendingSubmissions.length===0&&!n.hasInFlightPrompts)return;let r=this.retain(t,{source:`controllerOperation`}),i=this.retain(e,{source:`controllerOperation`}),a=this.manager.get(t),o=new Set(n.handoffSubmissions(a)),s=[],c=!1,l=()=>{if(!c){c=!0;for(let e of s)e();r.release(),i.release()}},u=()=>{!n.hasInFlightPrompts&&!a.getSnapshot().pendingSubmissions.some(e=>o.has(e.requestId))&&l()};s.push(a.subscribe(u),n.subscribe(u)),r.ready.catch(l),i.ready.catch(l),u()}async using(e,t,n){let r=this.retain(e,t);try{return await r.ready,await n(r)}finally{r.release()}}retainInfo(e){let t=this.retainObservers.get(e);if(t===void 0){let n=/* @__PURE__ */ new Set;t={listeners:n,published:this.retentionSnapshot(e),source:{getSnapshot:()=>this.retentionSnapshot(e),subscribe:e=>(n.add(e),()=>{n.delete(e)})}},this.retainObservers.set(e,t)}return t.source}async retryHistory(e){let t=this.scopes.get(e);if(!t?.live)throw Error(`Session history is no longer retained`);await t.session.resync()}subagentAddress(e){return this.manager.subagentAddress(e)}refreshProjections(e){return this.manager.refreshProjections(e)}refresh(){return this.manager.refreshList()}async loadSummary(e){await this.manager.loadSummary(e),this.closed||this.projectList()}syncSummary(e){return this.list.getSnapshot().byId[e]===void 0?this.closed||!this.manager.hasSummary(e)?!1:(this.projectList(),this.list.getSnapshot().byId[e]!==void 0):!0}loadMore(e){return this.manager.loadMore(e)}setIncludeArchived(e){return this.manager.setIncludeArchived(e)}search(e,t){return this.manager.search(e,t)}handleControlFrame(e){this.manager.handleControlFrame(e)}handleSessionAdded(e){this.manager.handleSessionAdded(e)}handleSessionRemoved(e){this.manager.handleSessionRemoved(e)}handleSessionStatus(...e){this.manager.handleSessionStatus(...e)}handleSessionActivity(...e){this.manager.handleSessionActivity(...e)}handleSessionError(...e){this.manager.handleSessionError(...e)}handleConnected(){this.manager.handleConnected()}async create(e={}){let t=await this.manager.create(e);if(!t.ok)throw new Fm(t.error,e.sessionId);return this.projectList(),t.value.sessionId}async fork(e){let t=e.increaseTitle?this.list.getSnapshot().byId[e.sessionId]?.title:void 0,n=await this.manager.fork({sessionId:e.sessionId,...e.atSeq===void 0?{}:{atSeq:p(e.atSeq)}});if(!n.ok)throw new Im(n.error,e.sessionId);this.projectList();let r=n.value.sessionId;if(e.onCreated?.(r),t!==void 0){let e=await this.manager.rename(r,Rm(t));if(!e.ok)throw Error(`fork child rename failed: ${e.error.code}: ${e.error.message}`)}return r}scope(e){return this.scopes.get(e)?.ctx}retainAgentScope(e){if(this.closed)throw Error(`Session Controller is disposed`);return this.retainScope(e,`gateway`)}scopeOf(e){return ve(e)}sessionOf(e){let t=ve(e);if(t===void 0)return;let n=this.scopes.get(t);return n!==void 0&&ye(n.ctx)===ye(e)?n.binding.session:void 0}binding(e){return this.scopes.get(e)?.binding}estimatedBytes(e){return this.scopes.get(e)?.session.estimatedBytes()??0}retainScope(e,t){let n=this.scopes.get(e)??this.materializeScope(e),r=n.retention;n.retention=Object.freeze({referenceCount:r.referenceCount+1,retainedBy:zm({...r.retainedBy,[t]:(r.retainedBy[t]??0)+1})});let i=new Hm(e,n,()=>{if(!n.live)return;let r=n.retention.referenceCount-1,{[t]:i=0,...a}=n.retention.retainedBy,o=i>1?{...a,[t]:i-1}:a;n.retention=r===0?Bm:Object.freeze({referenceCount:r,retainedBy:zm(o)}),r===0?this.retireScope(e,n):this.publishRetention(e)});return this.list.getSnapshot().byId[e]===void 0&&this.manager.subagentAddress(e)!==void 0&&this.projectList(),this.publishRetention(e),i}retentionSnapshot(e){return this.scopes.get(e)?.retention??Bm}publishRetention(e){let t=this.list.getSnapshot(),n=t.byId[e],r=this.retentionSnapshot(e).retainedBy;n!==void 0&&n.retainedBy!==r&&this.list.set({...t,byId:{...t.byId,[e]:{...n,retainedBy:r}}});let i=this.retainObservers.get(e),o=this.retentionSnapshot(e);i!==void 0&&i.published!==o&&(i.published=o,(0,a.notifySubscribers)(i.listeners,`[session-controller] reference sources`))}retireScope(e,t,n=!0){if(!t.live)return;t.live=!1,this.scopes.get(e)===t&&this.scopes.delete(e),t.session.unbindScope();let r=this.manager.drop(e,t.session);this.projectList(),this.publishRetention(e),this.startScopeDrop(e,t,n,r)}materializeScope(e){let{fiber:t,ctx:n}=_e(this.rootCtx,e),r=this.manager.get(e);r.bindScope(n);let i={fiber:t,ctx:n,binding:{sessionId:e,session:r,eventSource:r.eventSource,ctx:n},session:r,retention:Bm,live:!0};return this.scopes.set(e,i),n.effect(()=>()=>{this.retireScope(e,i,!1)},`session-controller: exact generation`),i}projectList(){let e=this.list.getSnapshot().byId,{items:t,phase:n,projectionsBySession:r,hasMore:i,state:a,error:o,errorPage:s,errorWorkspaceId:c,headRefreshRevision:l,summaryOnlyIds:u}=this.manager.getListSnapshot(),d=[],f={};for(let e of t){d.push(e.sessionId);let t=this.retentionSnapshot(e.sessionId).retainedBy,n=this.projectedItemCache.get(e.sessionId);if(n!==void 0&&n.entry===e&&n.retainedBy===t){f[e.sessionId]=n.summary;continue}let r={id:e.sessionId,displayTitle:Lm(e.title,e.cwd,e.sessionId),running:e.running,retainedBy:t,blank:e.blank,updatedAt:e.updatedAt,...e.projectionValues===void 0?{}:{projectionValues:e.projectionValues},...e.title===void 0?{}:{title:e.title},...e.cwd===void 0?{}:{cwd:e.cwd},...e.parentSessionId===void 0?{}:{parentId:e.parentSessionId},...e.origin===void 0?{}:{origin:e.origin}};this.projectedItemCache.set(e.sessionId,{entry:e,retainedBy:t,summary:r}),f[e.sessionId]=r}if(this.projectedItemCache.size>t.length)for(let e of this.projectedItemCache.keys())f[e]===void 0&&this.projectedItemCache.delete(e);for(let[e,t]of Object.entries(r))for(let n of t.values.subagentCatalog??[]){let t=n.id,r=f[t],i=r?.projectionValues??this.manager.projectionValues(t),a=i?.title,o=typeof a==`string`&&a!==``?a:void 0,s=o??n.label??t;r===void 0?f[t]={id:t,displayTitle:s,parentId:e,origin:`subagent`,running:this.scopes.get(t)?.session.getSnapshot().running??!1,blank:!1,updatedAt:0,retainedBy:this.retentionSnapshot(t).retainedBy,...i===void 0?{}:{projectionValues:i},...o===void 0?{}:{title:o}}:(r.displayTitle!==s||r.projectionValues!==i)&&(f[t]={...r,displayTitle:s,...i===void 0?{}:{projectionValues:i}})}for(let[t,n]of this.scopes){if(f[t]!==void 0)continue;let r=this.manager.subagentAddress(t);if(r===void 0)continue;let i=e[t],a=n.session.getSnapshot(),o=this.manager.projectionValues(t),s=o?.title,c=typeof s==`string`&&s!==``?s:i?.title;f[t]={...i??{id:t,displayTitle:t,updatedAt:0},running:a.running,retainedBy:n.retention.retainedBy,blank:a.blank,parentId:r.parentSessionId,origin:`subagent`,...o===void 0?{}:{projectionValues:o},...c===void 0?{}:{title:c,displayTitle:c}}}this.list.set({ids:d,byId:f,phase:n,projectionsBySession:r,hasMore:i,loading:a===`loading`,listError:o?.message??null,listErrorPage:s,listErrorWorkspaceId:c,headRefreshRevision:l??0,summaryOnlyIds:u??[]})}startScopeDrop(e,t,n=!0,r=this.manager.drop(e,t.session)){let i=this.dropScope(t,n,r);this.scopeDrops.add(i),i.then(()=>{this.scopeDrops.delete(i)},()=>{this.scopeDrops.delete(i)})}async drainScopeDrops(){for(;this.scopeDrops.size>0;)await Promise.allSettled([...this.scopeDrops])}async dropScope(e,t,n){await Promise.allSettled([n,...t?[e.fiber.dispose()]:[]])}};let Wm=[`connection`,`fileUpload`,`typert`,`remote`,`remote.commands`,`remote.session`,`remote.subagents`];function Gm(e){let t=e.remote,n=e.get(`connection`),r=new Um(e,t);e.remote.$on(`api-session/added`,e=>{r.handleSessionAdded(e)}),e.remote.$on(`api-session/removed`,e=>{r.handleSessionRemoved(e)}),e.remote.$on(`api-session/status`,(e,t)=>{r.handleSessionStatus(e,t)}),e.remote.$on(`api-session/activity`,(e,t)=>{r.handleSessionActivity(e,t)}),e.remote.$on(`api-session/error`,(e,t)=>{r.handleSessionError(e,t)});let i,a=()=>{if(n.generation.getSnapshot()===void 0)return;let e=i;i=void 0,e?.dispose(),r.handleConnected();let a=fe(t,{accept:e=>{i===a&&r.handleControlFrame(e)},failed:e=>{i===a&&console.error(`[session-controller] control stream failed:`,e)}});i=a,a.start()};e.effect(()=>n.generation.subscribe(a),`session-controller.client.generation`),a(),e.typert.contexts.registerClient(`agent`,{identity:e=>r.sessionOf(e)?.sessionId,resolve:e=>{let t=r.retainAgentScope(e);return c(t.binding.ctx,()=>{t.release()})}}),e.effect(()=>async()=>{await i?.dispose()},`session-controller.client.control`)}return n.MutableSessionEventSource=um,n.SESSION_SEARCH_RESULT_LIMIT=20,n.SESSION_SEARCH_SNIPPET_MAX_CODE_POINTS=240,n.SessionCreateError=Fm,n.SessionEventStream=pe,n.SessionForkError=Im,n.apply=Gm,n.createScope=_e,n.createSessionControlStream=fe,n.inject=Wm,n.scopeOf=ve,t.exports}});