@unieai/rabi-api-session-controller 0.0.0-stage → 0.2.2-rc.5

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.
Files changed (137) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +7 -2
  3. package/lib/client.js +4 -0
  4. package/lib/index.js +4300 -0
  5. package/lib/typert.host.d.ts +3 -0
  6. package/lib/typert.host.js +5013 -0
  7. package/lib/typert.remote-client.d.ts +115 -0
  8. package/lib/typert.remote-client.js +2714 -0
  9. package/lib/types/agent.d.ts +164 -0
  10. package/lib/types/agent.js +484 -0
  11. package/lib/types/archived-session-gate.d.ts +33 -0
  12. package/lib/types/archived-session-gate.js +54 -0
  13. package/lib/types/assistant-stream.d.ts +26 -0
  14. package/lib/types/assistant-stream.js +82 -0
  15. package/lib/types/catalog.d.ts +24 -0
  16. package/lib/types/catalog.js +107 -0
  17. package/lib/types/client/contract/events.d.ts +102 -0
  18. package/lib/types/client/contract/events.js +111 -0
  19. package/lib/types/client/contract/session.d.ts +178 -0
  20. package/lib/types/client/contract/session.js +1 -0
  21. package/lib/types/client/contract/sessions.d.ts +162 -0
  22. package/lib/types/client/contract/sessions.js +1 -0
  23. package/lib/types/client/contract/snapshot.d.ts +84 -0
  24. package/lib/types/client/contract/snapshot.js +1 -0
  25. package/lib/types/client/index.d.ts +39 -0
  26. package/lib/types/client/index.js +60 -0
  27. package/lib/types/client/ordered-baseline.d.ts +12 -0
  28. package/lib/types/client/ordered-baseline.js +40 -0
  29. package/lib/types/client/scope.d.ts +46 -0
  30. package/lib/types/client/scope.js +46 -0
  31. package/lib/types/client/session-wire-event.d.ts +11 -0
  32. package/lib/types/client/session-wire-event.js +42 -0
  33. package/lib/types/client/sessions/assistant-stream.d.ts +56 -0
  34. package/lib/types/client/sessions/assistant-stream.js +182 -0
  35. package/lib/types/client/sessions/history-records.d.ts +22 -0
  36. package/lib/types/client/sessions/history-records.js +25 -0
  37. package/lib/types/client/sessions/lineage.d.ts +48 -0
  38. package/lib/types/client/sessions/lineage.js +55 -0
  39. package/lib/types/client/sessions/manager.d.ts +272 -0
  40. package/lib/types/client/sessions/manager.js +774 -0
  41. package/lib/types/client/sessions/notifier.d.ts +39 -0
  42. package/lib/types/client/sessions/notifier.js +97 -0
  43. package/lib/types/client/sessions/projection-store.d.ts +128 -0
  44. package/lib/types/client/sessions/projection-store.js +161 -0
  45. package/lib/types/client/sessions/remotes.d.ts +29 -0
  46. package/lib/types/client/sessions/remotes.js +7 -0
  47. package/lib/types/client/sessions/service.d.ts +263 -0
  48. package/lib/types/client/sessions/service.js +597 -0
  49. package/lib/types/client/sessions/session.d.ts +303 -0
  50. package/lib/types/client/sessions/session.js +991 -0
  51. package/lib/types/client/time-zone.d.ts +8 -0
  52. package/lib/types/client/time-zone.js +13 -0
  53. package/lib/types/client/transport.d.ts +77 -0
  54. package/lib/types/client/transport.js +130 -0
  55. package/lib/types/commands.d.ts +92 -0
  56. package/lib/types/commands.js +575 -0
  57. package/lib/types/continuation.d.ts +35 -0
  58. package/lib/types/continuation.js +47 -0
  59. package/lib/types/control.d.ts +20 -0
  60. package/lib/types/control.js +106 -0
  61. package/lib/types/file-references.d.ts +27 -0
  62. package/lib/types/file-references.js +68 -0
  63. package/lib/types/history/assistant-stream.d.ts +43 -0
  64. package/lib/types/history/assistant-stream.js +79 -0
  65. package/lib/types/history/controller.d.ts +104 -0
  66. package/lib/types/history/controller.js +293 -0
  67. package/lib/types/history/listener.d.ts +105 -0
  68. package/lib/types/history/listener.js +296 -0
  69. package/lib/types/history.d.ts +58 -0
  70. package/lib/types/history.js +152 -0
  71. package/lib/types/index.d.ts +262 -0
  72. package/lib/types/index.js +693 -0
  73. package/lib/types/list.d.ts +62 -0
  74. package/lib/types/list.js +343 -0
  75. package/lib/types/media-references.d.ts +18 -0
  76. package/lib/types/media-references.js +84 -0
  77. package/lib/types/remote-events.d.ts +8 -0
  78. package/lib/types/remote-events.js +1 -0
  79. package/lib/types/skill-catalog.d.ts +28 -0
  80. package/lib/types/skill-catalog.js +203 -0
  81. package/lib/types/state/controller.d.ts +45 -0
  82. package/lib/types/state/controller.js +288 -0
  83. package/lib/types/state/listener.d.ts +40 -0
  84. package/lib/types/state/listener.js +111 -0
  85. package/lib/types/types.d.ts +687 -0
  86. package/lib/types/types.js +5 -0
  87. package/lib/types/web/controller.d.ts +25 -0
  88. package/lib/types/web/controller.js +138 -0
  89. package/locale/de.json +6 -0
  90. package/locale/en.json +5 -0
  91. package/locale/es.json +6 -0
  92. package/locale/fr.json +6 -0
  93. package/locale/ja.json +6 -0
  94. package/locale/pt.json +6 -0
  95. package/locale/ru.json +6 -0
  96. package/locale/zh.json +6 -0
  97. package/package.json +119 -4
  98. package/src/agent.ts +474 -0
  99. package/src/archived-session-gate.ts +59 -0
  100. package/src/assistant-stream.ts +102 -0
  101. package/src/catalog.ts +117 -0
  102. package/src/client/contract/events.ts +205 -0
  103. package/src/client/contract/session.ts +174 -0
  104. package/src/client/contract/sessions.ts +169 -0
  105. package/src/client/contract/snapshot.ts +94 -0
  106. package/src/client/index.ts +149 -0
  107. package/src/client/ordered-baseline.ts +43 -0
  108. package/src/client/scope.ts +76 -0
  109. package/src/client/session-wire-event.ts +46 -0
  110. package/src/client/sessions/assistant-stream.ts +229 -0
  111. package/src/client/sessions/history-records.ts +35 -0
  112. package/src/client/sessions/lineage.ts +96 -0
  113. package/src/client/sessions/manager.ts +857 -0
  114. package/src/client/sessions/notifier.ts +97 -0
  115. package/src/client/sessions/projection-store.ts +244 -0
  116. package/src/client/sessions/remotes.ts +44 -0
  117. package/src/client/sessions/service.ts +741 -0
  118. package/src/client/sessions/session.ts +1055 -0
  119. package/src/client/time-zone.ts +14 -0
  120. package/src/client/transport.ts +247 -0
  121. package/src/commands.ts +602 -0
  122. package/src/continuation.ts +58 -0
  123. package/src/control.ts +121 -0
  124. package/src/file-references.ts +42 -0
  125. package/src/history/assistant-stream.ts +102 -0
  126. package/src/history/controller.ts +256 -0
  127. package/src/history/listener.ts +302 -0
  128. package/src/history.ts +189 -0
  129. package/src/index.ts +651 -0
  130. package/src/list.ts +382 -0
  131. package/src/media-references.ts +84 -0
  132. package/src/remote-events.ts +14 -0
  133. package/src/skill-catalog.ts +108 -0
  134. package/src/state/controller.ts +221 -0
  135. package/src/state/listener.ts +116 -0
  136. package/src/types.ts +720 -0
  137. package/src/web/controller.ts +78 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 DeepSeek
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,8 @@
1
- # Temporary Holding Version
1
+ # @unieai/rabi-api-session-controller
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Session Remote commands, cold reads, and live control transport
4
+
5
+ Part of Rabi, the agent harness UnieAI Code runs on. Installed as a dependency of `@unieai/rabi`;
6
+ not meant to be used on its own.
7
+
8
+ See LICENSE for the license and copyright of this package.
package/lib/client.js ADDED
@@ -0,0 +1,4 @@
1
+
2
+ window.__ModuleLoader__.load({id:`@unieai/rabi-api-session-controller`,factory:require=>{var module={exports:{}};var exports=module.exports;Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let _unieai_cordis=require("@unieai/cordis");let _unieai_rabi_api_gateway_client=require("@unieai/rabi-api-gateway/client");let _unieai_rabi_client_store=require("@unieai/rabi-client-store");var RemoteError=class extends Error{code;details;isRABIRemoteError=true;constructor(code,message,details,options){super(message,options);this.code=code;this.details=details;this.name=`RemoteError`}};const TYPERT_OWNED_VALUE=Symbol.for(`rabi.typert.owned-value`);function typertOwnedValue(value,release){let active=true;return{[TYPERT_OWNED_VALUE]:true,value,[Symbol.dispose](){if(!active)return;active=false;release()}}}function historyEntries(records){return records}function historyRecordFirstSeq(record){return record.event.seq}function historyRecordLastSeq(record){return record.event.seq}function brandNumber(value){return value}function SessionSeq(value){if(!Number.isSafeInteger(value)||value<0||Object.is(value,-0))throw new TypeError(`SessionSeq must be a non-negative safe integer, got ${String(value)}`);return brandNumber(value)}function SessionLogOffset(value){if(!Number.isSafeInteger(value)||value<0||Object.is(value,-0))throw new TypeError(`SessionLogOffset must be a non-negative safe integer, got ${String(value)}`);return brandNumber(value)}const KNOWN_SESSION_EVENT_TYPES=new Set([`agent-preset/selected`,`agent/inbox/spliced`,`approval/asked`,`approval/decided`,`approval/policy`,`assistant/attempt`,`assistant/message`,`command/done`,`command/run`,`compaction/end`,`compaction/prune`,`compaction/start`,`compaction/summary`,`deliverables/presented`,`developer/message`,`feedback/message-delete`,`feedback/message-put`,`feedback/record`,`goal/change`,`hook/invoked`,`hook/result`,`image/offload`,`job/registered`,`job/settled`,`llm/retry`,`llm/retry-started`,`model/selection`,`permission/preset`,`plan/mode`,`request/context`,`request/header`,`sandbox/mode`,`schedule/change`,`session-log-deepseek/delivery-accepted`,`session/end-seed`,`session/title`,`session/title-llm-request`,`step/end`,`step/start`,`subagent/catalog`,`subagent/descriptor`,`subagent/model-selection-policy`,`system/message`,`team/member`,`team/message/delivered`,`team/message/queued`,`team/mode`,`team/task`,`todo/write`,`tool-workflow/agent-end`,`tool-workflow/agent-start`,`tool-workflow/run-end`,`tool-workflow/run-start`,`tool/call`,`tool/ptc-dispatch`,`tool/ptc-dispatch-start`,`tool/result`,`turn/end`,`turn/start`,`user/message`,`web/deepseek-search-llm-request`,`working-directory/change`,`workspace/changes`]);const SURFACE_EVENT_TYPES=new Set([`system/message`,`developer/message`,`user/message`,`assistant/message`,`tool/result`]);function isSurfaceEligibleType(type){return SURFACE_EVENT_TYPES.has(type)}function isRecord(value){return typeof value===`object`&&value!==null&&!Array.isArray(value)}function validateSessionEventData(event,subject){const data=event.data;if(SURFACE_EVENT_TYPES.has(event.type)&&isRecord(data)){const message=event.type===`user/message`?data:data[`message`];if(isRecord(message)){if(event.type===`developer/message`!==(message[`role`]===`developer`))throw new Error(`${subject} developer/message and developer role must occur together`);if(message[`role`]!==`developer`&&Array.isArray(message[`content`])&&message[`content`].some(block=>isRecord(block)&&(block[`type`]===`tool-addition`||block[`type`]===`tool-removal`)))throw new Error(`${subject} tool-change blocks require developer role`);if(event.type===`developer/message`&&Array.isArray(message[`content`])){let hasAdditions=false;for(const block of message[`content`]){if(!isRecord(block)||block[`type`]!==`tool-addition`&&block[`type`]!==`tool-removal`)continue;if(typeof block[`toolName`]!==`string`||block[`toolName`].length===0)throw new Error(`${subject} ${block[`type`]} requires a nonempty toolName`);if(block[`type`]===`tool-addition`){hasAdditions=true;if(Object.hasOwn(block,`tool`))throw new Error(`${subject} tool-addition must omit inline tool definitions`)}}if(hasAdditions?!isEventSeq(data[`headerSeq`]):Object.hasOwn(data,`headerSeq`))throw new Error(`${subject} requires headerSeq exactly when tool additions are present`)}}}if(event.type===`request/header`){if(!isRecord(data))throw new Error(`${subject} data must be an object`);const header=data[`header`];if(!isRecord(header))throw new Error(`${subject} header must be an object`);if(Object.hasOwn(header,`system`))throw new Error(`${subject} must omit header.system; use system/message`);if(Array.isArray(header[`tools`])&&header[`tools`].length===0)throw new Error(`${subject} must omit empty tools`);const defaults=header[`adapterDefaults`];if(isRecord(defaults)&&Object.keys(defaults).length===0)throw new Error(`${subject} must omit empty adapterDefaults`)}else if(event.type===`tool/result`){if(!isRecord(data))throw new Error(`${subject} data must be an object`);if(data[`error`]===void 0)return;const message=data[`message`];if(!isRecord(message)||message[`isError`]!==true)throw new Error(`${subject} error requires message.isError === true`)}}function isEventSeq(value){return typeof value===`number`&&Number.isSafeInteger(value)&&value>=0&&!Object.is(value,-0)}function isReplaceOp(value){const op=value;return Object.keys(op).length===3&&Object.hasOwn(op,`op`)&&Object.hasOwn(op,`startSeq`)&&Object.hasOwn(op,`endSeq`)&&op[`op`]===`replace`&&isEventSeq(op[`startSeq`])&&isEventSeq(op[`endSeq`])}function surfaceOpOf(event){const raw=event;if(!isSurfaceEligibleType(event.type)){if(!KNOWN_SESSION_EVENT_TYPES.has(event.type)&&event.ignorable===true)return;if(raw.surfaceOp!==void 0)throw new Error(`session event "${event.type}" is not surface-eligible and cannot carry surfaceOp`);if(raw.sourceEventSeqs!==void 0)throw new Error(`session event "${event.type}" is not surface-eligible and cannot carry sourceEventSeqs`);return}const op=raw.surfaceOp;if(op===void 0)throw new Error(`session event "${event.type}" is surface-eligible and requires a surfaceOp marker`);if(op===`append`)return op;if(op===null||typeof op!==`object`||Array.isArray(op))throw new Error(`session event "${event.type}" carries an invalid surfaceOp`);if(!isReplaceOp(op))throw new Error(`session event "${event.type}" carries an invalid replace surfaceOp`);return op}function assertSourceEventReferences(event,shadowedSeqs){const raw=event.sourceEventSeqs;if(event.type===`assistant/message`&&raw!==void 0)throw new Error(`assistant/message embeds its source stream and cannot carry sourceEventSeqs`);const sources=new Set;if(raw!==void 0){if(!Array.isArray(raw))throw new Error(`sourceEventSeqs on event at seq ${event.seq} must be an array when present`);if(raw.length===0)throw new Error(`sourceEventSeqs must not be empty`);let nonEarlierSource;for(const source of raw){if(!isEventSeq(source))throw new Error(`session event "${event.type}" sourceEventSeqs must densely contain non-negative safe integers`);sources.add(source);if(nonEarlierSource===void 0&&source>=event.seq)nonEarlierSource=source}if(sources.size!==raw.length)throw new Error(`sourceEventSeqs must not contain duplicates`);if(nonEarlierSource!==void 0)throw new Error(`sourceEventSeqs must reference earlier events: ${nonEarlierSource} >= current seq ${event.seq}`)}const missing=shadowedSeqs.filter(seq=>!sources.has(seq));if(missing.length>0)throw new Error(`surface replace: sourceEventSeqs must include every shadowed surface node; missing ${missing.join(`, `)}`)}function validateSurfaceMetadata(event){const op=surfaceOpOf(event);if(op!==void 0&&op!==`append`&&(op.startSeq>=event.seq||op.endSeq>=event.seq))throw new Error(`surface replace at seq ${event.seq}: startSeq and endSeq must reference earlier events`);if(op!==void 0)assertSourceEventReferences(event,[]);return op}function assertSessionWireEvent(value){const subject=`session wire event`;if(typeof value!==`object`||value===null||Array.isArray(value))throw new Error(`${subject} must be an object`);const event=value;for(const key of Object.keys(event))switch(key){case`type`:case`seq`:case`time`:case`data`:case`ignorable`:case`surfaceOp`:case`sourceEventSeqs`:break;default:throw new Error(`${subject} has unexpected field ${key}`)}const seq=event[`seq`];if(typeof event[`type`]!==`string`||typeof seq!==`number`||!Number.isSafeInteger(seq)||seq<0||Object.is(seq,-0)||typeof event[`time`]!==`number`||!Number.isSafeInteger(event[`time`])||!Object.hasOwn(event,`data`)||event[`data`]===void 0||Object.hasOwn(event,`ignorable`)&&event[`ignorable`]!==true)throw new Error(`${subject} has an invalid envelope`);const current=event;validateSurfaceMetadata(current);validateSessionEventData(current,subject)}const SESSION_SEARCH_RESULT_LIMIT=20;const SESSION_SEARCH_SNIPPET_MAX_CODE_POINTS=240;function toSessionJournalChange(change){switch(change.type){case`replace`:case`prepend`:return{...change,entries:historyEntries(change.entries)};case`append`:return{type:`append`,entry:change.entry};case`notification`:return{type:`assistant-stream`,frame:change.notification}}}function createSessionControlStream(remote,options){return new _unieai_rabi_api_gateway_client.RemoteSnapshotStream(remote.$stream({name:`session control stream`,open:signal=>remote.session.control(signal),ended:accepted=>accepted?new _unieai_rabi_api_gateway_client.RemoteStreamCarrierError(`session control stream ended without a terminal result`):new Error(`session control stream ended before its opening snapshot`),...options.carrierFailed===void 0?{}:{carrierFailed:options.carrierFailed}}),{name:`session control stream`,isSnapshot:frame=>frame.type===`baseline`,replace:options.accept,update:options.accept,failed:options.failed})}var SessionEventStream=class extends _unieai_rabi_api_gateway_client.RemoteJournalStream{remote;address;constructor(remote,address,options){super(remote,{name:`session event stream`,emptyCursor:-1,entries:page=>page.records,hasMore:page=>page.hasMore,first:historyRecordFirstSeq,last:historyRecordLastSeq,compare:(left,right)=>left-right,follows:(left,right)=>right===left+1,publish:change=>{options.publish(toSessionJournalChange(change))},...options.carrierFailed===void 0?{}:{carrierFailed:options.carrierFailed},failed:options.failed});this.remote=remote;this.address=address}async*follow(request,signal){let assistantRevision;for await(const frame of this.remote.session.follow({address:this.address,activate:true,assistantStream:true,...this.repairRequest(request)},signal)){if(frame.type===`snapshot`){for(const record of frame.records)assertSessionWireEvent(record.event);if(frame.assistantStream===void 0)throw new RemoteError(`gateway/internal`,`session assistant stream omitted its opted-in opening baseline`,{});assistantRevision=frame.assistantStream.revision;yield{type:`opened`,cursor:frame.cursor,page:{records:frame.records,hasMore:frame.hasMore,projections:frame.projections,assistantStream:frame.assistantStream}};continue}if(frame.type===`assistant-stream`){const expected=(assistantRevision??0)+1;if(frame.frame.revision!==expected)throw new _unieai_rabi_api_gateway_client.RemoteStreamCarrierError(`session assistant stream skipped revision ${String(expected)}`);assistantRevision=frame.frame.revision;yield{type:`notification`,notification:frame.frame};continue}assertSessionWireEvent(frame.event);yield{type:`entry`,entry:frame}}}async readPage(request,throughSeq,signal){const result=await this.remote.session.page({address:this.address,throughSeq,...request},signal);if(!result.ok)throw result.error;for(const record of result.value.records)assertSessionWireEvent(record.event);return result.value}repairRequest(request){return{...request.maxMessages===void 0?{}:{maxMessages:request.maxMessages},...request.turnWindow===void 0?{}:{turnWindow:request.turnWindow}}}};function workspaceTitleOf(path){const trimmed=path.replace(/[/\\]+$/,``);const separator=Math.max(trimmed.lastIndexOf(`/`),trimmed.lastIndexOf(`\\`));return trimmed.slice(separator+1)}const kScope=Symbol(`rabi.client.scope`);function agentScope(){}function createScope(ctx,key){const fiber=ctx.plugin(agentScope);const identity={sessionId:key};return{fiber,ctx:fiber.ctx.extend({[kScope]:identity,[_unieai_cordis.Context.filter](listenerCtx){const tag=scopeIdentityOf(listenerCtx);return tag===void 0||tag===identity}})}}function scopeOf(ctx){return scopeIdentityOf(ctx)?.sessionId}function scopeIdentityOf(ctx){return ctx[kScope]}function mergeOrderedBaseline(current,baseline,keyOf){const baselineByKey=new Map;for(const value of baseline)baselineByKey.set(keyOf(value),value);const merged=current.map(value=>baselineByKey.get(keyOf(value))).filter(value=>value!==void 0);const mergedKeys=new Set(merged.map(keyOf));for(let index=0;index<baseline.length;index++){const value=baseline[index];if(value===void 0||mergedKeys.has(keyOf(value)))continue;let insertion=merged.length;for(let following=index+1;following<baseline.length;following++){const candidate=baseline[following];if(candidate===void 0)continue;const known=merged.findIndex(item=>keyOf(item)===keyOf(candidate));if(known!==-1){insertion=known;break}}merged.splice(insertion,0,value);mergedKeys.add(keyOf(value))}return merged}const SIMPLE_ESCAPES={'"':`"`,"\\":`\\`,"/":`/`,b:`\b`,f:`\f`,n:`
3
+ `,r:`\r`,t:` `};const CONTENT_ESCAPE=/[\\\u0000-\u001f]/u;function isWhitespace(c){return c===` `||c===`
4
+ `||c===`\r`||c===` `}function isHex(c){return c>=`0`&&c<=`9`||c>=`a`&&c<=`f`||c>=`A`&&c<=`F`}var PartialArguments=class PartialArguments{static EMPTY=PartialArguments.fromObject({});static fromText(text){const view=new PartialArguments;view.append(text);view.sealed=true;return view}static fromObject(value){const view=new PartialArguments;view.object=typeof value===`object`&&value!==null&&!Array.isArray(value)?value:{};view.sealed=true;return view}chunks=[];object;sealed=false;#ends=[];#size=0;#consumed=0;#mode=`root`;#escape=false;#keyStart=0;#keyEscaped=false;#key=``;#current=null;#nestedEnds=[];#nestedInString=false;#invalidAt;#invalidValue=false;#entries=new Map;#order=[];#reads=new Map;get isSealed(){return this.sealed}get invalid(){this.scan();return this.#mode===`invalid`||this.#invalidValue}append(fragment){if(this.sealed)throw new Error(`PartialArguments: cannot append to a sealed view`);if(fragment.length===0)return;this.chunks.push(fragment);this.#size+=fragment.length;this.#ends.push(this.#size)}settle(text){if(this.object!==void 0||text.length!==this.#size)return PartialArguments.fromText(text);let offset=0;for(const chunk of this.chunks){if(!text.startsWith(chunk,offset))return PartialArguments.fromText(text);offset+=chunk.length}this.chunks=text.length===0?[]:[text];this.#ends=text.length===0?[]:[text.length];this.sealed=true;return this}refresh(){if(this.#reads.size===0)return false;this.scan();let changed=false;let completions=false;for(const read of this.#reads.values()){if(read.completion){completions=true;continue}changed=this.refreshRead(read)||changed}if(completions){for(const read of this.#reads.values())if(read.completion)changed=this.refreshRead(read)||changed}if(this.sealed)this.#reads.clear();return changed}refreshRead(read){const now=read.answer();if(Object.is(now,read.last))return false;read.last=now;return true}closed(){return this.remember(`closed`,``,()=>this.closedNow())}keys(){return this.remember(`keys`,``,()=>this.keysNow(),keys=>keys.length)}has(key){return this.remember(`has`,key,()=>this.hasNow(key))}complete(key){return this.remember(`complete`,key,()=>this.completeNow(key))}stringLength(key,options){const step=Math.max(1,Math.floor(options?.step??1));const offset=options?.offset??0;return this.remember(`length:${step}:${offset}`,key,()=>this.lengthNow(key),length=>length===void 0?void 0:Math.ceil((length+offset)/step))}stringExceeds(key,maxLength){const limit=Math.max(0,Math.floor(maxLength));return this.remember(`exceeds:${limit}`,key,()=>(this.lengthNow(key,limit+1)??0)>limit)}text(key){return this.remember(`text`,key,()=>this.textNow(key))}textPrefix(key,maxLength){const limit=Math.max(1,Math.floor(maxLength));return this.remember(`prefix:${limit}`,key,()=>this.textPrefixNow(key,limit))}value(key){return this.remember(`value`,key,()=>this.valueNow(key))}remember(kind,key,read,comparison){this.scan();const result=read();if(!this.sealed){const id=`${kind}/${key}`;if(!this.#reads.has(id))this.#reads.set(id,{completion:kind===`complete`,answer:comparison===void 0?read:()=>comparison(read()),last:comparison===void 0?result:comparison(result)})}return result}closedNow(){return this.sealed||this.#mode===`closed`||this.#mode===`invalid`}keysNow(){return this.object===void 0?this.#order:Object.keys(this.object)}hasNow(key){return this.object===void 0?this.#entries.has(key):Object.hasOwn(this.object,key)}completeNow(key){if(this.object!==void 0)return Object.hasOwn(this.object,key);const entry=this.#entries.get(key);return entry!==void 0&&entry.end>=0&&(entry.kind===`string`?entry.invalidAt===void 0:!entry.invalid)}lengthNow(key,limit=Number.POSITIVE_INFINITY){if(this.object!==void 0){const field=Object.hasOwn(this.object,key)?this.object[key]:void 0;return typeof field===`string`?field.length:void 0}const entry=this.#entries.get(key);if(entry?.kind!==`string`)return void 0;if(entry.text!==void 0&&entry.text.at===entry.end)return entry.text.length;const read=entry.length??={at:entry.start,length:0,text:``};this.readString(entry,read,limit,false);return read.length}textNow(key){if(this.object!==void 0){const field=Object.hasOwn(this.object,key)?this.object[key]:void 0;return typeof field===`string`?field:void 0}const entry=this.#entries.get(key);if(entry?.kind!==`string`)return void 0;if(entry.text===void 0&&entry.end>=0&&entry.needsDecoding&&entry.invalidAt===void 0){let text;try{text=JSON.parse(`"${this.slice(entry.start,entry.end)}"`)}catch(_error){}if(text!==void 0)entry.text={at:entry.end,length:text.length,text}}const read=entry.text??={at:entry.start,length:0,text:``};this.readString(entry,read,Number.POSITIVE_INFINITY,true);return read.text}textPrefixNow(key,maxLength){if(this.object!==void 0){const field=Object.hasOwn(this.object,key)?this.object[key]:void 0;return typeof field===`string`?field.slice(0,maxLength):void 0}const entry=this.#entries.get(key);if(entry?.kind!==`string`)return void 0;const prefixes=entry.prefixes??=new Map;let read=prefixes.get(maxLength);if(read===void 0){read={at:entry.start,length:0,text:``};prefixes.set(maxLength,read)}this.readString(entry,read,maxLength,true);return read.text}valueNow(key){if(this.object!==void 0){if(!Object.hasOwn(this.object,key))return void 0;const field=this.object[key];return typeof field===`string`?void 0:field}const entry=this.#entries.get(key);if(entry?.kind!==`value`||entry.end<0||entry.invalid)return void 0;if(entry.parsed===void 0)try{entry.parsed=JSON.parse(this.slice(entry.start,entry.end))}catch(_error){entry.invalid=true;this.#invalidValue=true}return entry.parsed}chunkAt(at){let low=0;let high=this.#ends.length;while(low<high){const mid=low+high>>>1;if(this.#ends[mid]<=at)low=mid+1;else high=mid}return low}slice(start,end){if(start>=end)return``;const first=this.chunkAt(start);const last=this.chunkAt(end-1);const base=first===0?0:this.#ends[first-1];if(first===last)return this.chunks[first].slice(start-base,end-base);const parts=[this.chunks[first].slice(start-base)];for(let i=first+1;i<last;i++)parts.push(this.chunks[i]);parts.push(this.chunks[last].slice(0,end-this.#ends[last-1]));return parts.join(``)}readString(entry,read,limit,materialize){const end=Math.min(entry.end<0?this.#consumed:entry.end,entry.invalidAt??Number.POSITIVE_INFINITY,this.#invalidAt??Number.POSITIVE_INFINITY);if(!entry.needsDecoding){const length=Math.min(end-read.at,limit-read.length);if(length<=0)return;if(materialize)read.text+=this.slice(read.at,read.at+length);read.at+=length;read.length+=length;return}let chunkIndex=this.chunkAt(read.at);while(read.at<end&&read.length<limit){const base=chunkIndex===0?0:this.#ends[chunkIndex-1];const chunk=this.chunks[chunkIndex];const remaining=chunk.slice(read.at-base,Math.min(chunk.length,end-base));const boundary=remaining.search(CONTENT_ESCAPE);const length=Math.min(boundary<0?remaining.length:boundary,limit-read.length);if(length>0){if(materialize)read.text+=remaining.slice(0,length);read.at+=length;read.length+=length;if(read.at===base+chunk.length)chunkIndex++;continue}const type=remaining.length>1?remaining[1]:read.at+1<end?this.chunks[chunkIndex+1][0]:void 0;let decoded;let width=2;if(remaining[0]===`\\`&&type===void 0&&entry.end<0)return;if(remaining[0]===`\\`&&type===`u`){const hex=this.slice(read.at+2,Math.min(end,read.at+6));let valid=true;for(let i=0;i<hex.length;i++)if(!isHex(hex[i]))valid=false;if(valid){if(hex.length<4&&entry.end<0)return;if(hex.length===4)decoded=String.fromCharCode(Number.parseInt(hex,16))}width=6}else if(remaining[0]===`\\`&&type!==void 0)decoded=SIMPLE_ESCAPES[type];if(decoded===void 0){entry.invalidAt=read.at;this.#invalidValue=true;return}if(materialize)read.text+=decoded;read.length++;read.at+=width;while(chunkIndex<this.chunks.length&&read.at>=this.#ends[chunkIndex])chunkIndex++}}scan(){if(this.object!==void 0||this.#consumed===this.#size)return;for(let i=this.chunkAt(this.#consumed);i<this.chunks.length&&this.#invalidAt===void 0;i++){const pending=this.chunks[i];const base=i===0?0:this.#ends[i-1];for(let index=this.#consumed-base;index<pending.length&&this.#mode!==`invalid`;index++){if(this.#mode===`string`||this.#mode===`nested`&&this.#nestedInString){const end=this.stringBoundary(pending,index);this.#consumed+=end-index;index=end;if(index===pending.length)break}this.step(pending[index],this.#consumed);this.#consumed++}}}stringBoundary(fragment,start){let at=start;while(true){const quote=fragment.indexOf(`"`,at);const end=quote<0?fragment.length:quote;if(this.#mode===`string`){const entry=this.#current;if(!entry.needsDecoding&&CONTENT_ESCAPE.test(fragment.slice(at,end)))entry.needsDecoding=true}let slashStart=end;while(slashStart>at&&fragment[slashStart-1]===`\\`)slashStart--;const escaped=(end-slashStart)%2===1!==(slashStart===at&&this.#escape);this.#escape=quote<0&&escaped;if(quote<0||!escaped)return end;at=quote+1}}step(c,at){switch(this.#mode){case`root`:if(isWhitespace(c))return;if(c===`{`){this.#mode=`key-or-end`;return}this.fail();return;case`key-or-end`:if(isWhitespace(c))return;if(c===`}`){this.#mode=`closed`;return}if(c===`"`){this.beginKey(at);return}this.fail();return;case`key-only`:if(isWhitespace(c))return;if(c===`"`){this.beginKey(at);return}this.fail();return;case`key`:this.stepKey(c,at);return;case`colon`:if(isWhitespace(c))return;if(c===`:`){this.#mode=`value`;return}this.fail();return;case`value`:this.beginValue(c,at);return;case`string`:{const entry=this.#current;entry.end=at;this.#current=null;this.#mode=`comma-or-end`;return}case`scalar`:this.stepScalar(c,at);return;case`nested`:this.stepNested(c,at);return;case`comma-or-end`:if(isWhitespace(c))return;if(c===`,`){this.#mode=`key-only`;return}if(c===`}`){this.#mode=`closed`;return}this.fail();return;case`closed`:if(isWhitespace(c))return;this.fail();return;case`invalid`:return;default:assertNever(this.#mode)}}fail(){this.#invalidAt=this.#consumed;this.#mode=`invalid`;this.#current=null}beginKey(at){this.#mode=`key`;this.#keyStart=at+1;this.#keyEscaped=false;this.#escape=false}stepKey(c,at){if(c<` `){this.fail();return}if(this.#escape){this.#escape=false;return}if(c===`\\`){this.#escape=true;this.#keyEscaped=true;return}if(c!==`"`)return;const raw=this.slice(this.#keyStart,at);if(this.#keyEscaped)try{this.#key=JSON.parse(`"${raw}"`)}catch(_error){this.fail();return}else this.#key=raw;this.#mode=`colon`}open(entry){if(!this.#entries.has(this.#key))this.#order.push(this.#key);this.#entries.set(this.#key,entry);this.#current=entry}beginValue(c,at){if(isWhitespace(c))return;if(c===`"`){this.open({kind:`string`,start:at+1,end:-1,needsDecoding:false,invalidAt:void 0,length:void 0,text:void 0,prefixes:void 0});this.#escape=false;this.#mode=`string`;return}if(c===`}`||c===`,`||c===`:`||c===`]`){this.fail();return}this.open({kind:`value`,start:at,end:-1,parsed:void 0,invalid:false});if(c===`{`||c===`[`){this.#mode=`nested`;this.#nestedEnds=[c===`{`?`}`:`]`];this.#nestedInString=false;this.#escape=false;return}this.#mode=`scalar`}stepScalar(c,at){if(c!==`,`&&c!==`}`&&!isWhitespace(c))return;this.closeValue(at);this.#mode=c===`,`?`key-only`:c===`}`?`closed`:`comma-or-end`}stepNested(c,at){if(this.#nestedInString){this.#nestedInString=false;return}if(c===`"`){this.#nestedInString=true;return}if(c===`{`||c===`[`){this.#nestedEnds.push(c===`{`?`}`:`]`);return}if(c===`}`||c===`]`){if(this.#nestedEnds.pop()!==c){this.fail();return}if(this.#nestedEnds.length===0){this.closeValue(at+1);this.#mode=`comma-or-end`}}}closeValue(end){const entry=this.#current;entry.end=end;this.#current=null}};function assertNever(value,context){const rendered=JSON.stringify(value)??String(value);throw new Error(`unreachable variant${context?` in ${context}`:``}: ${rendered}`)}function hasIntrinsicConstructor(prototype,name){const constructor=Object.getOwnPropertyDescriptor(prototype,`constructor`)?.value;if(typeof constructor!==`function`)return false;try{return constructor.name===name&&constructor.prototype===prototype&&Function.prototype.toString.call(constructor)===Function.prototype.toString.call(name===`Array`?Array:Object)}catch{return false}}function isIntrinsicObjectPrototype(value){return Object.getPrototypeOf(value)===null&&hasIntrinsicConstructor(value,`Object`)}function hasPlainArrayPrototype(value){const prototype=Object.getPrototypeOf(value);if(!Array.isArray(prototype)||!hasIntrinsicConstructor(prototype,`Array`))return false;const objectPrototype=Object.getPrototypeOf(prototype);return typeof objectPrototype===`object`&&objectPrototype!==null&&isIntrinsicObjectPrototype(objectPrototype)}function hasPlainObjectPrototype(value){const prototype=Object.getPrototypeOf(value);return prototype===null||typeof prototype===`object`&&isIntrinsicObjectPrototype(prototype)}function enumerableStringKeys(value){const keys=Reflect.ownKeys(value);if(keys.some(key=>typeof key!==`string`||!Object.prototype.propertyIsEnumerable.call(value,key)))return void 0;return keys}function walkJsonValue(value,detach){const ancestors=new Set;let root;let parent;const assign=item=>{if(parent===void 0){if(detach)root=item}else if(parent.kind===`array`){if(parent.target!==void 0)parent.target[parent.key]=item}else if(parent.target!==void 0)Object.defineProperty(parent.target,parent.key,{value:item,enumerable:true,configurable:true,writable:true})};const frames=[];let current=value;for(;;){if(current===null)assign(null);else if(typeof current===`boolean`||typeof current===`string`)assign(current);else if(typeof current===`number`){if(!Number.isFinite(current)||Object.is(current,-0))return void 0;assign(current)}else{if(typeof current!==`object`)return void 0;if(ancestors.has(current))return void 0;if(Array.isArray(current)){if(!hasPlainArrayPrototype(current))return void 0;const length=current.length;if(Reflect.ownKeys(current).length!==length+1)return void 0;const target=detach?[]:void 0;if(target!==void 0)assign(target);let indices;if(!Number.isInteger(length)){indices=[];for(let index=length-1;index>=0;index--)indices.push(index)}frames.push({kind:`array`,source:current,length:indices?.length??length,index:0,key:0,indices,target})}else{if(!hasPlainObjectPrototype(current))return void 0;const keys=enumerableStringKeys(current);if(keys===void 0)return void 0;const target=detach?{}:void 0;if(target!==void 0)assign(target);frames.push({kind:`object`,source:current,keys,index:0,key:``,target})}ancestors.add(current)}for(;;){const frame=frames.at(-1);if(frame===void 0)return detach?root:true;const length=frame.kind===`array`?frame.length:frame.keys.length;if(frame.index>=length){ancestors.delete(frame.source);frames.pop();continue}const index=frame.index++;parent=frame;if(frame.kind===`array`){const key=frame.indices===void 0?index:frame.indices[frame.indices.length-index-1];if(key===void 0)return void 0;if(!Object.prototype.hasOwnProperty.call(frame.source,key))return void 0;frame.key=key;current=frame.source[key]}else{const key=frame.keys[index];if(key===void 0)return void 0;frame.key=key;current=frame.source[key]}break}}}function snapshotJsonValue(value){return walkJsonValue(value,true)}function deepFreeze(value){const seen=new WeakSet;const pending=[{kind:`visit`,node:value}];while(pending.length>0){const task=pending.pop();if(task===void 0)continue;if(task.kind===`property`){pending.push({kind:`visit`,node:task.source[task.key]});continue}const node=task.node;if(node===null||typeof node!==`object`)continue;if(node instanceof AbortSignal)continue;if(seen.has(node))continue;seen.add(node);Object.freeze(node);const keys=Object.keys(node);for(let index=keys.length-1;index>=0;index--){const key=keys[index];if(key===void 0)continue;pending.push({kind:`property`,source:node,key})}}return value}function flattenLineage(summaries){const byId=new Map;for(const s of summaries)byId.set(s.sessionId,s);const children=new Map;const roots=[];for(const s of summaries)if(s.origin===`subagent`&&s.parentSessionId!==void 0&&byId.has(s.parentSessionId)){const list=children.get(s.parentSessionId)??[];list.push(s);children.set(s.parentSessionId,list)}else roots.push(s);const out=[];const visited=new Set;const walk=(s,depth)=>{if(visited.has(s.sessionId)){console.warn(`[session-controller] lineage cycle at ${s.sessionId}; emitting as root`);return}visited.add(s.sessionId);const{agentAvailable:_agentAvailable,...row}=s;out.push({...row,depth});const kids=children.get(s.sessionId);if(kids===void 0)return;for(const kid of kids)walk(kid,depth+1)};for(const root of roots)walk(root,0);for(const s of summaries)if(!visited.has(s.sessionId))walk(s,0);return out}var Notifier=class{rebuild;listeners=new Set;dirty=false;notifyPending=false;scheduled=`none`;scheduleGeneration=0;constructor(rebuild){this.rebuild=rebuild}subscribe(listener){this.listeners.add(listener);return()=>{this.listeners.delete(listener)}}markDirty(){this.dirty=true;this.notifyPending=true;if(this.scheduled===`microtask`)return;this.schedule(`microtask`)}markFrameDirty(){this.dirty=true;this.notifyPending=true;if(this.scheduled!==`none`)return;this.schedule(typeof globalThis.requestAnimationFrame===`function`?`frame`:`microtask`)}notifyNow(){this.dirty=true;this.notifyPending=true;this.invalidateSchedule();this.flush()}ensureFresh(){if(!this.dirty)return;this.dirty=false;this.rebuild()}schedule(kind){const generation=++this.scheduleGeneration;this.scheduled=kind;const publish=()=>{if(generation!==this.scheduleGeneration)return;this.scheduled=`none`;this.flush()};if(kind===`frame`)globalThis.requestAnimationFrame(publish);else queueMicrotask(publish)}invalidateSchedule(){this.scheduleGeneration++;this.scheduled=`none`}flush(){if(!this.notifyPending)return;if(this.listeners.size===0)return;this.notifyPending=false;if(this.dirty){this.dirty=false;this.rebuild()}(0,_unieai_rabi_client_store.notifySubscribers)(this.listeners,`[session-controller]`)}};var ProjectionValueStore=class{rows=new Map;channels=new Map;valuesCache;anyNotifier=new Notifier(()=>{});faceOf(key){return this.channel(key).face}get(key){return this.rows.get(key)?.value}seqOf(key){const row=this.rows.get(key);return row?.kind===`sequenced`?row.seq:void 0}values(){if(this.valuesCache===void 0)this.valuesCache=Object.freeze(Object.fromEntries([...this.rows].map(([key,row])=>[key,row.value])));return this.valuesCache}subscribeAny(listener){return this.anyNotifier.subscribe(listener)}apply(key,value,seq){const row=this.rows.get(key);if(row?.kind===`sequenced`&&seq<=row.seq)return;this.rows.set(key,{kind:`sequenced`,value,seq});this.changed(key)}applyCached(values){for(const key of Object.keys(values)){if(this.rows.get(key)?.kind===`sequenced`)continue;this.rows.set(key,{kind:`cached`,value:values[key]});this.changed(key)}}seed(baseline){for(const[key,row]of this.rows){if(row.kind!==`cached`)continue;this.rows.delete(key);this.changed(key)}const values=baseline.values;for(const key of Object.keys(values))this.apply(key,values[key],baseline.asOfSeq);for(const[key,row]of this.rows){if(Object.hasOwn(values,key))continue;if(row.kind===`sequenced`&&row.seq>baseline.asOfSeq)continue;this.rows.delete(key);this.changed(key)}}clear(){for(const key of this.rows.keys()){this.rows.delete(key);this.changed(key)}}changed(key){this.valuesCache=void 0;this.channels.get(key)?.notifier.markDirty();this.anyNotifier.markDirty()}channel(key){let channel=this.channels.get(key);if(channel===void 0){const notifier=new Notifier(()=>{});channel={notifier,face:{getSnapshot:()=>this.rows.get(key)?.value,subscribe:listener=>notifier.subscribe(listener)}};this.channels.set(key,channel)}return channel}};function randomUUID(){const bytes=globalThis.crypto.getRandomValues(new Uint8Array(16));const hex=Array.from(bytes,(byte,index)=>{return(index===6?byte&15|64:index===8?byte&63|128:byte).toString(16).padStart(2,`0`)}).join(``);return`${hex.slice(0,8)}-${hex.slice(8,12)}-${hex.slice(12,16)}-${hex.slice(16,20)}-${hex.slice(20)}`}function leaf(entries){return{kind:`leaf`,entries,length:entries.length}}function concat(left,right){return{kind:`concat`,left,right,length:left.length+right.length}}function materialize(node){if(node.kind===`leaf`)return node.entries;const entries=new Array(node.length);const pending=[node];let index=0;while(pending.length>0){const current=pending.pop();if(current.kind===`concat`){pending.push(current.right,current.left);continue}for(const entry of current.entries){entries[index]=entry;index+=1}}return entries}function windowSnapshot(node,hasMore,revision,change){let entries;return{get entries(){entries??=materialize(node);return entries},hasMore,revision,change}}var MutableSessionEventSource=class{listeners=new Set;window=leaf([]);snapshot=windowSnapshot(this.window,false,0,{kind:`replace`,entries:[]});getSnapshot(){return this.snapshot}subscribe(listener){this.listeners.add(listener);return()=>{this.listeners.delete(listener)}}replace(entries,hasMore){this.window=leaf(entries);this.publish(hasMore,{kind:`replace`,entries})}prepend(entries,hasMore){this.window=concat(leaf(entries),this.window);this.publish(hasMore,{kind:`prepend`,entries})}append(entry){const entries=[entry];this.window=concat(this.window,leaf(entries));this.publish(this.snapshot.hasMore,{kind:`append`,entries})}settleAssistant(attemptId,entry){const entries=materialize(this.window).filter(candidate=>candidate.type!==`transient`||candidate.event.data.attemptId!==attemptId);if(entry!==void 0){const index=entries.findIndex(candidate=>candidate.event.seq>entry.event.seq);if(index<0)entries.push(entry);else entries.splice(index,0,entry)}this.window=leaf(entries);this.publish(this.snapshot.hasMore,{kind:`settle-assistant`,attemptId,...entry===void 0?{}:{entry}})}publish(hasMore,change){this.snapshot=windowSnapshot(this.window,hasMore,this.snapshot.revision+1,change);(0,_unieai_rabi_client_store.notifySubscribers)(this.listeners,`[session-controller] event feed`)}};function resolvedClientTimeZone(){const timeZone=new Intl.DateTimeFormat().resolvedOptions().timeZone;if(typeof timeZone!==`string`||timeZone.length===0)throw new Error(`browser time zone is unavailable`);return timeZone}function safeTime(value){if(!Number.isSafeInteger(value))throw new TypeError(`Assistant stream time must be a safe integer, got ${String(value)}`);return value}function safeIndex(value,label){if(!Number.isSafeInteger(value)||value<0||Object.is(value,-0))throw new TypeError(`${label} index must be a non-negative safe integer`);return value}function snapshotChunk(chunk){const snapshot=snapshotJsonValue(chunk);if(snapshot===void 0)throw new TypeError(`Assistant stream chunk must be losslessly JSON-serializable`);return snapshot}function expandAssistantStream(stream){const chunks=[];for(const candidate of stream){const record=validateRecord(candidate);if(record.type===`chunk`){chunks.push({time:record.time,chunk:record.chunk});continue}const members=record.type===`tool-call-chunks`?record.args:record.texts;let time=record.time0;for(let index=0;index<members.length;index+=1){if(index>0)time+=record.dt[index-1];let chunk;if(record.type===`text-chunks`)chunk={type:`text-delta`,index:record.index,text:members[index]};else if(record.type===`reasoning-chunks`)chunk={type:`reasoning-delta`,index:record.index,text:members[index]};else chunk={type:`tool-call-delta`,index:record.index,id:record.id,...Object.hasOwn(record,`name`)?{name:record.name}:{},argumentsDelta:members[index]};chunks.push({time,chunk})}}return chunks}function validateRecord(value){if(typeof value!==`object`||value===null||Array.isArray(value))throw new TypeError(`Assistant stream record must be an object`);const record=value;switch(record.type){case`text-chunks`:case`reasoning-chunks`:{exactKeys(record,[`type`,`time0`,`index`,`dt`,`texts`],record.type);const texts=stringArray(record.texts,`${record.type} texts`);if(texts.length===0)throw new TypeError(`${record.type} texts must be non-empty`);validateRun(record,texts.length,record.type);return record}case`tool-call-chunks`:{exactKeys(record,Object.hasOwn(record,`name`)?[`type`,`time0`,`index`,`dt`,`id`,`name`,`args`]:[`type`,`time0`,`index`,`dt`,`id`,`args`],record.type);const args=stringArray(record.args,`tool-call-chunks args`);if(args.length===0)throw new TypeError(`tool-call-chunks args must be non-empty`);if(typeof record.id!==`string`||record.id.length===0)throw new TypeError(`tool-call-chunks id must be a non-empty string`);if(record.name!==void 0&&(typeof record.name!==`string`||record.name.length===0))throw new TypeError(`tool-call-chunks name must be a non-empty string`);validateRun(record,args.length,record.type);return record}case`chunk`:{exactKeys(record,[`type`,`time`,`chunk`],`chunk`);const time=safeTime(record.time);if(typeof record.chunk!==`object`||record.chunk===null||Array.isArray(record.chunk))throw new TypeError(`Assistant stream raw chunk must be a lossless JSON object`);let chunk;try{chunk=snapshotChunk(record.chunk)}catch(error){throw new TypeError(`Assistant stream raw chunk must be a lossless JSON object`,{cause:error})}return deepFreeze({type:`chunk`,time,chunk})}default:throw new TypeError(`Unsupported Assistant stream record ${JSON.stringify(record.type)}`)}}function validateRun(record,members,label){safeTime(record.time0);safeIndex(record.index,label);if(!Array.isArray(record.dt)||record.dt.some(value=>!Number.isSafeInteger(value)))throw new TypeError(`${label} dt must contain safe integers`);if(record.dt.length!==members-1)throw new TypeError(`${label} dt length must be one less than its members`);let time=record.time0;for(const gap of record.dt){time+=gap;if(!Number.isSafeInteger(time))throw new TypeError(`${label} member times must stay safe integers`)}}function stringArray(value,label){if(!Array.isArray(value)||value.some(member=>typeof member!==`string`))throw new TypeError(`${label} must be a string array`);return value}function exactKeys(record,keys,label){if(Object.keys(record).length!==keys.length||!keys.every(key=>Object.hasOwn(record,key)))throw new TypeError(`${label} Assistant stream record must contain exactly ${keys.join(`, `)}`)}var ClientAssistantStream=class{activeAttempt;retainedAttempt;pending=new Map;publishedSeqs=new Set;durableCursor=-1;transientInGap=0;replace(entries,baseline){this.pending.clear();this.transientInGap=0;this.activeAttempt=void 0;this.retainedAttempt=void 0;const opening=baseline?.activeAttempt;if(opening!==void 0)this.activeAttempt={attemptId:opening.attemptId,startedAfterSeq:opening.startedAfterSeq,turn:opening.turn,step:opening.step,nextIndex:opening.nextIndex};const visible=[...entries];this.publishedSeqs=new Set(visible.map(entry=>entry.event.seq));this.durableCursor=visible.reduce((cursor,entry)=>Math.max(cursor,entry.event.seq),-1);if(opening!==void 0)for(const[index,member]of expandAssistantStream(opening.stream).entries()){this.transientInGap+=1;visible.push({type:`transient`,event:{type:`assistant/live-chunk`,seq:this.durableCursor+1-1/(this.transientInGap+1),time:member.time,data:{attemptId:opening.attemptId,turn:opening.turn,step:opening.step,chunk:member.chunk}}});if(index+1>=opening.nextIndex)break}return visible}acceptDurable(entry){const event=entry.event;this.durableCursor=Math.max(this.durableCursor,event.seq);this.transientInGap=0;const settlement=assistantSettlementEntry(entry);if(settlement!==void 0&&this.attemptForSettlement(settlement.event)!==void 0){if(this.pending.has(event.seq))return{type:`rebaseline`};this.pending.set(event.seq,settlement);return}return this.publish(entry)}acceptFrame(frame){switch(frame.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:frame.attemptId,startedAfterSeq:frame.startedAfterSeq,turn:frame.turn,step:frame.step,nextIndex:0};return;case`chunk`:{const attempt=this.activeAttempt;if(attempt===void 0||attempt.attemptId!==frame.attemptId)return void 0;if(frame.index!==attempt.nextIndex)return{type:`rebaseline`};attempt.nextIndex+=1;this.transientInGap+=1;return{type:`transient`,entry:{type:`transient`,event:{type:`assistant/live-chunk`,seq:this.durableCursor+1-1/(this.transientInGap+1),time:frame.time,data:{attemptId:frame.attemptId,turn:attempt.turn,step:attempt.step,chunk:frame.chunk}}}}}case`end`:{const attempt=this.activeAttempt;if(attempt===void 0||attempt.attemptId!==frame.attemptId)return;this.activeAttempt=void 0;if(frame.index!==attempt.nextIndex)return{type:`rebaseline`};if(frame.outcome.kind===`abandoned`)return this.pending.size===0?{type:`abandonment`,attemptId:attempt.attemptId}:{type:`rebaseline`};if(this.publishedSeqs.has(frame.outcome.seq))return void 0;const entry=this.pending.get(frame.outcome.seq);if(entry===void 0||entry.event.type!==frame.outcome.eventType)return{type:`rebaseline`};this.pending.delete(frame.outcome.seq);if(entry.event.type===`assistant/message`&&entry.event.data.interrupted!==true){this.retainedAttempt={attemptId:attempt.attemptId,turn:attempt.turn,step:attempt.step};return this.publish(entry)}this.publishedSeqs.add(entry.event.seq);return{type:`settlement`,attemptId:attempt.attemptId,entry}}}}attemptForSettlement(event){const attempt=this.activeAttempt;if(attempt===void 0||event.type===`assistant/message`&&event.surfaceOp!==`append`||event.seq<=attempt.startedAfterSeq||attempt.turn!==event.data.turn||attempt.step!==event.data.step)return void 0;return attempt}publish(entry){this.publishedSeqs.add(entry.event.seq);const retained=this.retainedAttempt;if(retained!==void 0&&entry.event.type===`step/end`&&entry.event.data.turn===retained.turn&&entry.event.data.step===retained.step){this.retainedAttempt=void 0;return{type:`publish`,entry,retireAttemptId:retained.attemptId}}return{type:`publish`,entry}}};function assistantSettlementEntry(entry){return entry.event.type===`assistant/message`||entry.event.type===`assistant/attempt`?entry:void 0}function projectionsBaseline(value){return{...value,asOfSeq:value.asOfSeq===-1?-1:SessionSeq(value.asOfSeq)}}const PAGE_MESSAGES=50;const HISTORY_PAGE_OPTIONS={maxMessages:500,turnWindow:{minMessages:50,minTurns:2}};const JUMP_PAGE_MESSAGES=200;const JUMP_PAGE_OPTIONS={...HISTORY_PAGE_OPTIONS,turnWindow:{...HISTORY_PAGE_OPTIONS.turnWindow,minMessages:200}};var Session=class{sessionId;remote;options;baseSeq=SessionLogOffset(0);hasMore=false;historyWasPartial=false;openState=`cold`;openError=null;openPromise=null;openGeneration=0;get loadingOlder(){return this.historyLoadStatus===`loading`}historyLoadStatus=`idle`;olderRequest=null;jumpTargetSeq=null;jumpPromise=null;pendingHistory=null;stopObservingInbox;assistantStream=new ClientAssistantStream;running=false;address;promptAttempted=false;firstPromptPendingTurn=false;blankBit=true;removed=false;promptError=null;lastAgentError=null;pendingSubmissions=[];acceptedSubmissions=[];submissionSettlements=new Map;events;projections;eventSource=new MutableSessionEventSource;snapshotCache;notifier;actx;constructor(sessionId,remote,options={}){this.sessionId=sessionId;this.remote=remote;this.options=options;this.projections=options.projections??new ProjectionValueStore;this.address=options.address;this.notifier=new Notifier(()=>{this.snapshotCache=this.buildSnapshot()});this.snapshotCache=this.buildSnapshot();this.stopObservingInbox=this.projections.faceOf(`inbox`).subscribe(()=>{this.observeSubmissionInbox()})}bindScope(actx){if(this.actx!==void 0)throw new Error(`session ${this.sessionId} already has a bound scope`);this.actx=actx}unbindScope(){this.actx=void 0}beginSubmission(input){const requestId=randomUUID();const placement=this.running?input.mode===`steer`?`steering`:`queued`:`transcript`;this.pendingSubmissions=[...this.pendingSubmissions,{requestId,placement,time:Date.now(),text:input.text,attachments:input.attachments}];this.submissionSettlements.set(requestId,{placement,accepted:false,onAccept:input.onAccept,onRetire:input.onRetire,retiring:false});return{requestId,abandon:()=>{this.retireFailedSubmission(requestId)}}}async prompt(content,mode,signal,requestId){this.promptError=null;this.lastAgentError=null;const firstPrompt=this.blankBit&&!this.firstPromptPendingTurn;if(firstPrompt)this.firstPromptPendingTurn=true;let result;if(this.address===void 0){const clientTimeZone=resolvedClientTimeZone();result=await this.remote.session.prompt({requestId:requestId??randomUUID(),sessionId:this.sessionId,mode,content,clientTimeZone},signal)}else if(content.some(part=>part.type===`file`))result={ok:false,error:new RemoteError(`subagent/attachment-invalid`,`subagent continuation does not accept files`,{reason:`SUBAGENT_FILE_UNSUPPORTED`})};else{const routedContent=content;const routed=await this.remote.subagents.prompt({requestId:requestId??randomUUID(),childSessionId:this.address.childSessionId,delivery:mode,content:routedContent,clientTimeZone:resolvedClientTimeZone()},signal);result=routed.ok?{ok:true,value:{accepted:true}}:routed}if(!result.ok){if(firstPrompt)this.firstPromptPendingTurn=false;if(requestId!==void 0)this.retireFailedSubmission(requestId);this.promptError={op:`send`,error:result.error};this.notifier.markDirty();return result}this.acceptPrompt(requestId);return result}acceptPrompt(requestId){const settlement=requestId===void 0?void 0:this.submissionSettlements.get(requestId);if(settlement?.accepted===true)return;if(settlement!==void 0){settlement.accepted=true;this.refreshAcceptedSubmissions()}this.promptAttempted=true;this.blankBit=false;this.notifier.markDirty();this.options.onEngaged?.(this);settlement?.onAccept?.()}async readAttachment(attachment){const result=await this.remote.session.attachment({sessionId:this.sessionId,attachment});if(!result.ok)return result;const binary=atob(result.value.data);const data=Uint8Array.from(binary,char=>char.charCodeAt(0));return{ok:true,value:{attachment:result.value.attachment,data}}}async updateQueue(itemId,action){return this.remote.session.updateQueue({sessionId:this.sessionId,itemId,action})}async cancel(){const address=this.address;const result=address!==void 0?await this.remote.subagents.interruptByUser(address.childSessionId):await this.remote.session.cancel({sessionId:this.sessionId});if(!result.ok){this.promptError={op:`stop`,error:result.error};this.notifier.markDirty()}return result}async rename(title){const result=await this.remote.session.rename({sessionId:this.sessionId,title});if(!result.ok)return result;const seq=SessionSeq(result.value.seq);this.projections.apply(`title`,result.value.title,seq);return{ok:true,value:{title:result.value.title,seq}}}async command(line){const result=await this.remote.commands.execute(this.sessionId,line,[]);if(!result.ok)return result;return{ok:true,value:{matched:result.value!==void 0}}}open(){if(this.openState===`open`)return Promise.resolve();if(this.openPromise!==null)return this.openPromise;const promise=this.doOpen(this.openGeneration).finally(()=>{if(this.openPromise===promise)this.openPromise=null});this.openPromise=promise;return promise}async loadOlder(options){const request=this.prepareOlder();await request?.promise;if(request!==null&&this.olderRequest===request&&(!options?.deferConsumption||request.page?.entries.length===0))this.consumeOlder()}prepareOlder(){if(this.olderRequest!==null)return this.olderRequest;const events=this.events;if(this.openState!==`open`||!this.hasMore||this.loadingOlder||events===void 0)return null;const request={generation:this.openGeneration,beforeSeq:this.baseSeq,page:null,invalidated:false,recovering:false,consuming:false};this.olderRequest=request;this.historyLoadStatus=`loading`;this.notifier.markDirty();request.promise=(async()=>{try{await events.prepend({beforeSeq:request.beforeSeq,...HISTORY_PAGE_OPTIONS});if(this.olderRequest!==request)return;if(request.invalidated||request.generation!==this.openGeneration||request.beforeSeq!==this.baseSeq)return;const page=request.page;const first=page?.entries[0];this.historyLoadStatus=page===null||(first===void 0?page.hasMore:first.event.seq>=request.beforeSeq)?`error`:`pendingConsumption`}catch(error){if(this.olderRequest!==request)return;request.page=null;this.historyLoadStatus=`error`;if(!(0,_unieai_rabi_api_gateway_client.isRemoteFailure)(error))console.error(`[session-controller] loadOlder failed:`,error)}finally{if(this.olderRequest===request){if(request.invalidated&&this.events===events){request.recovering=true;this.historyLoadStatus=`loading`;events.restart()}else if(this.historyLoadStatus===`error`)this.olderRequest=null;this.notifier.markDirty()}}})();return request}consumeOlder(){const request=this.olderRequest;if(request===null||request.consuming||this.historyLoadStatus!==`pendingConsumption`||request.page===null)return false;if(this.openState!==`open`||request.invalidated||request.generation!==this.openGeneration||request.beforeSeq!==this.baseSeq){this.clearOlderHistory();return false}const page=request.page;request.consuming=true;try{this.prependWindow(page.entries,page.hasMore);return true}catch(error){if(this.olderRequest===request)this.historyLoadStatus=`error`;throw error}finally{if(this.olderRequest===request){this.olderRequest=null;if(this.historyLoadStatus!==`error`)this.historyLoadStatus=`idle`}this.notifier.markDirty()}}clearOlderHistory(){this.olderRequest=null;this.historyLoadStatus=this.pendingHistory===null?`idle`:`loading`;this.notifier.markDirty()}loadThrough(seq){this.consumeOlder();if(this.olderRequest!==null)return Promise.resolve();if(this.openState!==`open`||!this.hasMore||this.baseSeq<=seq)return Promise.resolve();if(this.jumpPromise!==null){this.jumpTargetSeq=SessionSeq(Math.min(this.jumpTargetSeq??seq,seq));return this.jumpPromise}if(this.loadingOlder)return Promise.resolve();const events=this.events;if(events===void 0)return Promise.resolve();const pending={beforeSeq:this.baseSeq,hasMore:this.hasMore,pages:[]};this.pendingHistory=pending;this.jumpTargetSeq=seq;this.historyLoadStatus=`loading`;this.notifier.markDirty();const generation=this.openGeneration;this.jumpPromise=(async()=>{try{while(this.jumpTargetSeq!==null&&pending.beforeSeq>this.jumpTargetSeq){if(generation!==this.openGeneration)return;const before=pending.beforeSeq;await events.prepend({beforeSeq:before,...JUMP_PAGE_OPTIONS});if(generation!==this.openGeneration||this.pendingHistory!==pending)return;if(pending.beforeSeq>=before){if(pending.hasMore)this.historyLoadStatus=`error`;return}if(!pending.hasMore)return}}catch(error){if(generation===this.openGeneration&&this.pendingHistory===pending)this.historyLoadStatus=`error`;if(!(0,_unieai_rabi_api_gateway_client.isRemoteFailure)(error))console.error(`[session-controller] loadThrough failed:`,error)}finally{if(this.pendingHistory===pending){this.jumpTargetSeq=null;this.jumpPromise=null;this.pendingHistory=null;if(this.historyLoadStatus===`loading`)this.historyLoadStatus=`idle`;if(generation===this.openGeneration&&pending.pages.length>0)this.prependWindow(pending.pages.reverse().flat(),pending.hasMore);this.notifier.markDirty()}}})();return this.jumpPromise}async resync(){if(this.openState===`cold`)return;this.openGeneration++;this.clearOlderHistory();const events=this.events;this.events=void 0;await events?.dispose();this.openPromise=null;this.openState=`cold`;this.openError=null;this.baseSeq=SessionLogOffset(0);this.notifier.markDirty();await this.open()}subscribe(listener){return this.notifier.subscribe(listener)}getSnapshot(){this.notifier.ensureFresh();return this.snapshotCache}handleRunning(running){if(running&&this.blankBit){this.blankBit=false;this.notifier.markDirty()}if(running)this.firstPromptPendingTurn=false;if(this.running===running)return;this.running=running;this.notifier.markDirty()}configureSubagent(address){const same=this.address?.parentSessionId===address?.parentSessionId&&this.address?.childSessionId===address?.childSessionId&&this.address?.mode===address?.mode;this.address=address;if(!same&&this.openState!==`cold`)this.resync();else this.notifier.markDirty()}handleBlank(blank){blank=blank&&this.projections.values().sessionListMetadata?.blank!==false;if(blank===this.blankBit)return;if(blank&&(this.promptAttempted||this.running))return;this.blankBit=blank;this.notifier.markDirty()}handleRemoved(){this.removed=true;this.notifier.markDirty()}handleAgentError(message){this.lastAgentError=message;this.notifier.markDirty()}async dispose(){this.stopObservingInbox();for(const[requestId,settlement]of[...this.submissionSettlements])if(settlement.admitted!==void 0)this.scheduleObservedRetirement(requestId,settlement.admitted);else this.retireFailedSubmission(requestId);this.openGeneration++;this.clearOlderHistory();const events=this.events;this.events=void 0;await events?.dispose()}async doOpen(generation){this.openState=`loading`;this.openError=null;this.notifier.markDirty();const events=new SessionEventStream(this.remote,this.sessionAddress(),{publish:change=>{if(generation!==this.openGeneration||this.events!==events)return;this.acceptEventChange(change)},failed:error=>{this.failEventStream(events,generation,error)}});this.events=events;try{await events.open(HISTORY_PAGE_OPTIONS);if(generation!==this.openGeneration||this.events!==events)return;this.openState=`open`}catch(error){if(generation!==this.openGeneration||this.events!==events)return;if(!(0,_unieai_rabi_api_gateway_client.isRemoteFailure)(error))throw error;this.events=void 0;this.openState=`error`;this.openError=error}finally{if(generation===this.openGeneration)this.notifier.markDirty()}}acceptEventChange(change){switch(change.type){case`replace`:this.installWindow(change.entries,change.hasMore,change.page.projections===void 0?void 0:projectionsBaseline(change.page.projections),change.page.assistantStream);return;case`prepend`:if(this.olderRequest!==null)this.olderRequest.page={entries:change.entries,hasMore:change.hasMore};else this.prependWindow(change.entries,change.hasMore);return;case`append`:this.publishAssistantEntry(this.assistantStream.acceptDurable(change.entry));return;case`assistant-stream`:this.publishAssistantEntry(this.assistantStream.acceptFrame(change.frame))}}installWindow(entries,hasMore,projections,assistantStream){const visible=this.assistantStream.replace(entries,assistantStream);if(this.olderRequest!==null&&this.loadingOlder&&!this.olderRequest.recovering){this.olderRequest.invalidated=true;this.olderRequest.page=null}else this.clearOlderHistory();this.baseSeq=SessionLogOffset(entries[0]?.event.seq??0);this.hasMore=hasMore;this.historyWasPartial||=hasMore;if(this.pendingHistory!==null){this.pendingHistory.beforeSeq=this.baseSeq;this.pendingHistory.hasMore=hasMore;this.pendingHistory.pages.length=0}if(visible.some(entry=>entry.event.type===`turn/start`))this.firstPromptPendingTurn=false;if(projections!==void 0)this.projections.seed(projections);this.eventSource.replace(visible,hasMore);if(projections!==void 0){for(const[requestId,{receipt}]of this.submissionSettlements)if(receipt!==void 0&&receipt.seq<=projections.asOfSeq)this.scheduleObservedRetirement(requestId,receipt.attachments)}for(const entry of visible)this.observeSubmissionEvent(entry.event);if(projections!==void 0){const inbox=projections.values.inbox;for(const target of[`next-turn`,`next-step`])this.observeSubmissionInsertions(target,inbox?.[target]??[],0,projections.asOfSeq)}this.notifier.markDirty()}publishAssistantEntry(result){if(result?.type===`rebaseline`){const events=this.events;queueMicrotask(()=>{if(events!==void 0&&this.events===events)events.restart()});return}if(result?.type===`settlement`){this.eventSource.settleAssistant(result.attemptId,result.entry);this.observeSubmissionEvent(result.entry.event);this.notifier.markDirty();return}if(result?.type===`abandonment`){this.eventSource.settleAssistant(result.attemptId);this.notifier.markDirty();return}if(result?.type===`publish`){const changed=this.appendLive(result.entry);if(result.retireAttemptId!==void 0)this.eventSource.settleAssistant(result.retireAttemptId);if(changed||result.retireAttemptId!==void 0)this.notifier.markDirty()}else if(result?.type===`transient`){this.eventSource.append(result.entry);this.notifier.markDirty()}}prependWindow(entries,hasMore){if(this.pendingHistory!==null){const pending=this.pendingHistory;pending.beforeSeq=entries[0]===void 0?pending.beforeSeq:SessionLogOffset(entries[0].event.seq);pending.hasMore=hasMore;pending.pages.push(entries);return}this.baseSeq=entries[0]===void 0?this.baseSeq:SessionLogOffset(entries[0].event.seq);this.hasMore=hasMore;this.historyWasPartial||=hasMore;this.eventSource.prepend(entries,hasMore)}appendLive(entry){const event=entry.event;const awaitingFirstTurn=this.firstPromptPendingTurn;if(event.type===`turn/start`)this.firstPromptPendingTurn=false;this.eventSource.append(entry);this.observeSubmissionEvent(event);return awaitingFirstTurn!==this.firstPromptPendingTurn}observeSubmissionEvent(event){if(this.submissionSettlements.size===0)return;if(event.type===`agent/inbox/spliced`){const{target,start,removedCount=0,inserted,outcome}=event.data;for(const[requestId,settlement]of this.submissionSettlements){const receipt=settlement.receipt;if(receipt?.target!==target||receipt.index===null||receipt.seq>=event.seq)continue;const removed=receipt.index>=start&&receipt.index<start+removedCount;if(removed&&outcome===`canceled`)this.retireFailedSubmission(requestId);else settlement.receipt={...receipt,seq:event.seq,index:removed?null:receipt.index<start?receipt.index:receipt.index+inserted.length-removedCount}}this.observeSubmissionInsertions(target,inserted,start,event.seq);for(const message of inserted)this.observeSubmissionMessage(message,false,false);return}if(event.type===`request/context`||event.type===`turn/end`){for(const[requestId,settlement]of this.submissionSettlements)if(settlement.admitted===void 0&&settlement.receipt?.index===null&&settlement.receipt.seq<event.seq)this.retireFailedSubmission(requestId);return}if(event.type===`user/message`)this.observeSubmissionMessage(event.data,true)}observeSubmissionInsertions(target,messages,start,seq){for(const[index,message]of messages.entries()){const source=message.source;if(source.kind!==`user`||!(`rpcId`in source))continue;const settlement=this.submissionSettlements.get(source.rpcId);if(settlement===void 0||settlement.retiring||(settlement.receipt?.seq??-1)>seq)continue;settlement.receipt={target,seq,index:start+index,attachments:attachmentRefsIn(message.content)};this.acceptPrompt(source.rpcId)}}observeSubmissionMessage(message,admitted,retireQueued=true){const source=message.source;if(source.kind!==`user`||!(`rpcId`in source))return;const settlement=this.submissionSettlements.get(source.rpcId);if(settlement===void 0||settlement.retiring)return;if(!admitted){if(settlement.placement===`queued`&&retireQueued)this.scheduleObservedRetirement(source.rpcId,attachmentRefsIn(message.content));return}settlement.admitted=attachmentRefsIn(message.content);this.retireAdmittedSubmission(source.rpcId)}retireAdmittedSubmission(requestId){const settlement=this.submissionSettlements.get(requestId);if(settlement?.admitted===void 0)return;const receipt=settlement.receipt;if(receipt?.index===null&&(this.projections.seqOf(`inbox`)??-1)<receipt.seq)return;this.scheduleObservedRetirement(requestId,settlement.admitted)}observeSubmissionInbox(){if(this.submissionSettlements.size===0)return;const inbox=this.projections.get(`inbox`);if(inbox===void 0)return;const seq=this.projections.seqOf(`inbox`);for(const target of[`next-turn`,`next-step`]){if(seq!==void 0)this.observeSubmissionInsertions(target,inbox[target],0,seq);for(const message of inbox[target])this.observeSubmissionMessage(message,false)}for(const requestId of this.submissionSettlements.keys())this.retireAdmittedSubmission(requestId)}scheduleObservedRetirement(requestId,attachments){const settlement=this.submissionSettlements.get(requestId);if(settlement===void 0||settlement.retiring)return;settlement.retiring=true;scheduleFrame(()=>{this.finishSubmission(requestId,{reason:`observed`,attachments})})}retireFailedSubmission(requestId){const settlement=this.submissionSettlements.get(requestId);if(settlement===void 0||settlement.retiring||settlement.admitted!==void 0)return;settlement.retiring=true;this.finishSubmission(requestId,{reason:`failed`})}refreshAcceptedSubmissions(){this.acceptedSubmissions=this.pendingSubmissions.filter(echo=>this.submissionSettlements.get(echo.requestId)?.accepted===true)}finishSubmission(requestId,retirement){const settlement=this.submissionSettlements.get(requestId);if(settlement===void 0)return;this.submissionSettlements.delete(requestId);this.pendingSubmissions=this.pendingSubmissions.filter(echo=>echo.requestId!==requestId);if(settlement.accepted)this.refreshAcceptedSubmissions();this.notifier.markDirty();settlement.onRetire?.(retirement)}failEventStream(events,generation,error){if(generation!==this.openGeneration||this.events!==events)return;if(!(0,_unieai_rabi_api_gateway_client.isRemoteFailure)(error))throw error;this.openGeneration++;this.clearOlderHistory();this.events=void 0;this.openPromise=null;this.openState=`error`;this.openError=error;events.dispose();this.notifier.markDirty()}buildSnapshot(){const identity=this.projections.values().subagent;return{sessionId:this.sessionId,pendingSubmissions:this.acceptedSubmissions,running:this.running,subagent:this.address===void 0?null:{address:this.address.mode===`unknown`&&identity!=null?{...this.address,mode:identity.mode}:this.address},removed:this.removed,openState:this.openState,openError:this.openError,hasMore:this.hasMore,historyWasPartial:this.historyWasPartial,loadingOlder:this.loadingOlder,historyLoadStatus:this.historyLoadStatus,promptError:this.promptError,blank:this.blankBit,lastAgentError:this.lastAgentError,promptAttempted:this.promptAttempted,awaitingFirstTurn:this.firstPromptPendingTurn&&!this.blankBit}}sessionAddress(){return this.address===void 0?{kind:`session`,sessionId:this.sessionId}:{kind:`subagent`,...this.address}}};function scheduleFrame(fn){if(typeof requestAnimationFrame===`function`)requestAnimationFrame(()=>{fn()});else setTimeout(fn,0)}function attachmentRefsIn(content){if(!Array.isArray(content))return[];const refs=[];for(const block of content){if(typeof block!==`object`||block===null)continue;const candidate=block;if((candidate.type===`image`||candidate.type===`file`)&&typeof candidate.attachment===`object`&&candidate.attachment!==null)refs.push(candidate.attachment)}return refs}function sessionSeqCursor(value){return value===-1?-1:SessionSeq(value)}var SessionManager=class{remote;sessions=new Map;sessionDisposals=new Set;engagedSessions=new Set;disposed=false;projectionStores=new Map;summaries=[];listState=`idle`;listPhase=`pending`;listError=null;listInflight=null;listMutations=null;addresses=new Map;projectionLoads=new Map;projectionInflight=new Map;listSnapshotCache;entryCache=new Map;itemsCache=[];notifier=new Notifier(()=>{this.listSnapshotCache=this.buildListSnapshot()});constructor(remote){this.remote=remote;this.listSnapshotCache=this.buildListSnapshot()}resolveTarget(target){const id=typeof target===`string`?target:target.childSessionId;const address=typeof target===`string`?this.subagentAddress(id):target;if(typeof target===`string`&&!this.sessions.has(id)&&!this.summaries.some(summary=>summary.sessionId===id)&&address===void 0)throw new Error(`sessions.retain: unknown session ${id}`);if(address!==void 0)this.addresses.set(id,address);this.sessions.get(id)?.configureSubagent(address);return id}subagentAddress(sessionId){const retained=this.addresses.get(sessionId);if(retained!==void 0)return retained;for(const parentSessionId of this.projectionStores.keys()){const child=this.projectionStores.get(parentSessionId)?.values().subagentCatalog?.find(entry=>entry.id===sessionId);if(child!==void 0&&child.mode!==`external`)return{parentSessionId,childSessionId:sessionId,mode:child.mode}}const summary=this.summaries.find(summary=>summary.sessionId===sessionId);if(summary?.origin!==`subagent`||summary.parentSessionId===void 0)return void 0;return{parentSessionId:summary.parentSessionId,childSessionId:sessionId,mode:`unknown`}}drop(sessionId,expected){const session=this.sessions.get(sessionId);if(session!==expected)return Promise.resolve();this.sessions.delete(sessionId);this.addresses.delete(sessionId);this.pruneEngagement(sessionId,this.retainedIds(this.summaries));return this.startSessionDisposal(session)}async dispose(){this.disposed=true;this.listMutations=null;this.listInflight=null;this.engagedSessions.clear();const reads=[...this.projectionInflight.values()];for(const{controller}of reads)controller.abort();this.projectionInflight.clear();await Promise.all(reads.map(read=>read.promise));const sessions=[...this.sessions.values()];this.sessions.clear();this.addresses.clear();for(const session of sessions)this.startSessionDisposal(session);await this.drainSessionDisposals()}startSessionDisposal(session){const disposal=session.dispose();this.sessionDisposals.add(disposal);disposal.then(()=>{this.sessionDisposals.delete(disposal)},()=>{this.sessionDisposals.delete(disposal)});return disposal}async drainSessionDisposals(){while(this.sessionDisposals.size>0)await Promise.allSettled([...this.sessionDisposals])}get(sessionId){let session=this.sessions.get(sessionId);if(session===void 0){session=this.createSession(sessionId);this.sessions.set(sessionId,session);const summary=this.summaries.find(s=>s.sessionId===sessionId);if(summary!==void 0){session.handleBlank(this.effectiveBlank(summary));session.handleRunning(summary.running)}else{const address=this.addresses.get(sessionId);const child=address===void 0?void 0:this.projectionStores.get(address.parentSessionId)?.values().subagentCatalog?.find(entry=>entry.id===sessionId);if(child!==void 0&&child.mode!==`external`){session.handleBlank(false);session.handleRunning(false)}else session.handleBlank(true)}}return session}createSession(sessionId){const address=this.addresses.get(sessionId);return new Session(sessionId,this.remote,{...address===void 0?{}:{address},onEngaged:engaged=>{if(this.disposed||!this.retainedIds(this.summaries).has(engaged.sessionId))return;if(!this.engagedSessions.has(engaged.sessionId)){this.engagedSessions.add(engaged.sessionId);this.recordMutation({kind:`engaged`,sessionId:engaged.sessionId})}this.sessions.get(engaged.sessionId)?.handleBlank(false)},projections:this.projectionStore(sessionId)})}effectiveBlank(summary){return summary.blank&&!this.engagedSessions.has(summary.sessionId)}retainedIds(summaries){const retained=new Set(summaries.map(summary=>summary.sessionId));for(const sessionId of this.sessions.keys())retained.add(sessionId);for(const sessionId of this.addresses.keys())retained.add(sessionId);return retained}pruneEngagement(sessionId,retained){if(!retained.has(sessionId))this.engagedSessions.delete(sessionId)}projectionStore(sessionId){let store=this.projectionStores.get(sessionId);if(store===void 0){store=new ProjectionValueStore;const projections=store;store.subscribeAny(()=>{if(projections.values().sessionListMetadata?.blank===false)this.sessions.get(sessionId)?.handleBlank(false);this.notifier.markDirty()});this.projectionStores.set(sessionId,store)}return store}refreshProjections(sessionId){const existing=this.projectionInflight.get(sessionId);if(existing!==void 0)return existing.promise;if(this.projectionLoads.get(sessionId)?.state===`ready`)return Promise.resolve();const controller=new AbortController;const store=this.projectionStore(sessionId);const initialValues=store.values();this.projectionLoads.set(sessionId,{state:`loading`,error:null});this.notifier.markDirty();const operation=(async()=>{try{const result=await this.remote.session.projections({sessionId},controller.signal);if(controller.signal.aborted)return;if(result.ok){const value=result.value;if(value!==null)switch(value.kind){case`sequenced`:store.seed({values:value.values,asOfSeq:sessionSeqCursor(value.asOfSeq)});break;case`migration-required`:store.applyCached(value.values);break;default:assertNever(value,`session projections result`)}else if(store.values()===initialValues)store.clear();this.projectionLoads.set(sessionId,{state:value?.kind===`migration-required`?`migration-required`:`ready`,error:null})}else this.projectionLoads.set(sessionId,{state:`error`,error:result.error})}catch(error){if(controller.signal.aborted)return;if(!(0,_unieai_rabi_api_gateway_client.isRemoteFailure)(error))throw error;this.projectionLoads.set(sessionId,{state:`error`,error})}finally{if(!controller.signal.aborted){this.projectionInflight.delete(sessionId);this.notifier.markDirty()}}})();this.projectionInflight.set(sessionId,{promise:operation,controller});return operation}refreshList(){if(this.listInflight!==null)return this.listInflight;this.listState=`loading`;this.listError=null;const established=this.summaries;const mutations=[];this.listMutations=mutations;this.notifier.markDirty();this.listInflight=(async()=>{try{const result=await this.remote.session.list({});if(this.listMutations!==mutations)return;if(result.ok){const baseline=this.listPhase===`pending`?[...result.value.items]:mergeOrderedBaseline(established,result.value.items,summary=>summary.sessionId);const removedSincePull=new Set;for(const mutation of mutations)if(mutation.kind===`remove`)removedSincePull.add(mutation.sessionId);for(const s of baseline)if(s.running&&!removedSincePull.has(s.sessionId))this.engagedSessions.add(s.sessionId);const summaries=mutations.reduce(applyMutation,baseline);this.summaries=summaries;const retained=this.retainedIds(summaries);for(const sessionId of this.engagedSessions)this.pruneEngagement(sessionId,retained);this.listState=`idle`;this.listPhase=`ready`;for(const s of this.summaries){const session=this.sessions.get(s.sessionId);if(session===void 0)continue;session.handleBlank(this.effectiveBlank(s));session.handleRunning(s.running)}for(const s of result.value.items)if(s.projections!==void 0)this.applyListBlock(s.sessionId,s.projections)}else{this.listState=`error`;this.listError=result.error}}catch(error){if(!(0,_unieai_rabi_api_gateway_client.isRemoteFailure)(error))throw error;if(this.listMutations!==mutations)return;this.listState=`error`;this.listError=error}finally{if(this.listMutations===mutations){this.listMutations=null;this.listInflight=null;this.notifier.markDirty()}}})();return this.listInflight}async search(query,signal){const result=await this.remote.session.search({query},signal);if(!result.ok)return result;return{ok:true,value:{items:[...result.value.items],hasMore:result.value.hasMore}}}async create(opts={}){const shared={...opts.sessionId===void 0?{}:{sessionId:opts.sessionId},...opts.agentPreset===void 0?{}:{agentPreset:opts.agentPreset}};const payload=opts.workspaceId!==void 0?{workspaceId:opts.workspaceId,...shared}:{...opts.cwd===void 0?{}:{cwd:opts.cwd},...shared};const result=await this.remote.session.create(payload);if(result.ok)this.recordMutation({kind:`placeholder`,summary:{agentAvailable:true,sessionId:result.value.sessionId,updatedAt:Date.now(),running:false,blank:true,...opts.cwd!==void 0?{cwd:opts.cwd}:{}}});else{const publishedSessionId=workspaceAttachSessionId(result.error);if(publishedSessionId!==void 0)this.recordMutation({kind:`placeholder`,summary:{agentAvailable:true,sessionId:publishedSessionId,updatedAt:Date.now(),running:false,blank:true}})}return result}async fork(opts){const source=this.summaries.find(s=>s.sessionId===opts.sessionId);const result=await this.remote.session.fork({sessionId:opts.sessionId,...opts.atSeq===void 0?{}:{atSeq:opts.atSeq},...opts.allowMigration===void 0?{}:{allowMigration:opts.allowMigration}});const childId=result.ok?result.value.sessionId:workspaceAttachSessionId(result.error);if(childId!==void 0)this.recordMutation({kind:`placeholder`,summary:{agentAvailable:true,sessionId:childId,updatedAt:Date.now(),running:false,blank:true,...source?.cwd!==void 0?{cwd:source.cwd}:{}}});return result}async rename(sessionId,title){const result=await this.remote.session.rename({sessionId,title});if(result.ok)this.projectionStore(sessionId).apply(`title`,result.value.title,SessionSeq(result.value.seq));return result}mergeSummary(summary){this.recordMutation({kind:`upsert`,summary})}recordMutation(mutation){if(this.disposed)return;this.listMutations?.push(mutation);this.summaries=applyMutation(this.summaries,mutation);this.notifier.markDirty()}subscribe(listener){return this.notifier.subscribe(listener)}getListSnapshot(){this.notifier.ensureFresh();return this.listSnapshotCache}projectionValues(sessionId){return this.projectionStores.get(sessionId)?.values()}handleControlFrame(frame){if(frame.type===`baseline`){this.replaceControlBaseline(frame.value);return}const store=this.projectionStore(frame.sessionId);const seq=SessionSeq(frame.seq);for(const change of frame.changes)store.apply(change.key,change.val,seq);this.notifier.markDirty()}replaceControlBaseline(baseline){for(const[sessionId,block]of Object.entries(baseline.projections)){const store=this.projectionStore(sessionId);const asOfSeq=sessionSeqCursor(block.asOfSeq);store.seed({...block,asOfSeq})}this.notifier.markDirty()}handleSessionAdded(summary){this.mergeSummary(summary);if(!this.disposed&&summary.running)this.engagedSessions.add(summary.sessionId);this.sessions.get(summary.sessionId)?.handleBlank(this.effectiveBlank(summary));if(summary.projections!==void 0)this.applyListBlock(summary.sessionId,summary.projections)}applyListBlock(sessionId,block){const store=this.projectionStore(sessionId);switch(block.kind){case`sequenced`:{const seq=sessionSeqCursor(block.asOfSeq);for(const[key,value]of Object.entries(block.values))store.apply(key,value,seq);return}case`cached`:store.applyCached(block.values);return;default:assertNever(block.kind,`session list projection block kind`)}}handleSessionRemoved(sessionId){const durableSubagent=this.subagentAddress(sessionId)!==void 0||this.summaries.some(summary=>summary.sessionId===sessionId&&summary.origin===`subagent`);this.recordMutation(durableSubagent?{kind:`status`,sessionId,running:false,agentAvailable:false}:{kind:`remove`,sessionId});if(durableSubagent)this.sessions.get(sessionId)?.handleRunning(false);else this.sessions.get(sessionId)?.handleRemoved();const catalog=this.projectionStores.get(sessionId)?.values().subagentCatalog;if(!durableSubagent&&(catalog===void 0||catalog.length===0))this.projectionStores.delete(sessionId);this.pruneEngagement(sessionId,this.retainedIds(this.summaries));this.projectionInflight.get(sessionId)?.controller.abort();this.projectionInflight.delete(sessionId);this.projectionLoads.delete(sessionId)}handleSessionStatus(sessionId,running){if(!this.disposed&&running)this.engagedSessions.add(sessionId);this.recordMutation({kind:`status`,sessionId,running,agentAvailable:true});this.sessions.get(sessionId)?.handleRunning(running)}handleSessionActivity(sessionId,updatedAt){this.recordMutation({kind:`activity`,sessionId,updatedAt})}handleSessionError(sessionId,message){this.sessions.get(sessionId)?.handleAgentError(message)}handleConnected(){for(const store of this.projectionStores.values())store.clear();this.listMutations=null;this.listInflight=null;this.refreshList();const parents=new Set(this.projectionLoads.keys());for(const id of this.sessions.keys()){const address=this.addresses.get(id);if(address!==void 0)parents.add(address.parentSessionId)}for(const{controller}of this.projectionInflight.values())controller.abort();this.projectionInflight.clear();this.projectionLoads.clear();for(const parentSessionId of parents)this.refreshProjections(parentSessionId)}buildListSnapshot(){const items=flattenLineage(this.summaries.map(summary=>{const projectionStore=this.projectionStores.get(summary.sessionId);const title=projectionStore?.get(`title`);const projectionValues=projectionStore?.values();const metadata=projectionValues?.sessionListMetadata;return{...summary,blank:this.effectiveBlank(summary)&&metadata?.blank!==false,updatedAt:Math.max(summary.updatedAt,metadata?.lastPromptAt??0),...typeof title===`string`&&title!==``?{title}:{},...projectionValues===void 0?{}:{projectionValues}}})).map(entry=>{const prev=this.entryCache.get(entry.sessionId);if(prev!==void 0&&prev.updatedAt===entry.updatedAt&&prev.running===entry.running&&prev.blank===entry.blank&&prev.parentSessionId===entry.parentSessionId&&prev.cwd===entry.cwd&&prev.origin===entry.origin&&prev.title===entry.title&&prev.depth===entry.depth&&prev.formatStatus===entry.formatStatus&&prev.projectionValues===entry.projectionValues)return prev;this.entryCache.set(entry.sessionId,entry);return entry});const itemIds=new Set(items.map(entry=>entry.sessionId));for(const id of this.entryCache.keys())if(!itemIds.has(id))this.entryCache.delete(id);if(!(items.length===this.itemsCache.length&&items.every((e,i)=>e===this.itemsCache[i])))this.itemsCache=items;return{items:this.itemsCache,state:this.listState,phase:this.listPhase,error:this.listError,projectionsBySession:Object.fromEntries([...this.projectionStores].map(([sessionId,store])=>[sessionId,{values:store.values(),state:`idle`,error:null,...this.projectionLoads.get(sessionId)}]))}}};function applyMutation(summaries,mutation){switch(mutation.kind){case`upsert`:case`placeholder`:{const existing=summaries.find(summary=>summary.sessionId===mutation.summary.sessionId);if(existing===void 0)return[mutation.summary,...summaries];const filled={...existing,blank:existing.blank&&mutation.summary.blank,...mutation.kind===`upsert`?{agentAvailable:mutation.summary.agentAvailable,running:mutation.summary.running,...mutation.summary.formatStatus===void 0?{}:{formatStatus:mutation.summary.formatStatus}}:{},...existing.cwd===void 0&&mutation.summary.cwd!==void 0?{cwd:mutation.summary.cwd}:{},...existing.parentSessionId===void 0&&mutation.summary.parentSessionId!==void 0?{parentSessionId:mutation.summary.parentSessionId}:{},...existing.origin===void 0&&mutation.summary.origin!==void 0?{origin:mutation.summary.origin}:{}};if(filled.cwd===existing.cwd&&filled.parentSessionId===existing.parentSessionId&&filled.origin===existing.origin&&filled.blank===existing.blank&&filled.agentAvailable===existing.agentAvailable&&filled.running===existing.running&&filled.formatStatus===existing.formatStatus)return[...summaries];return summaries.map(summary=>summary.sessionId===mutation.summary.sessionId?filled:summary)}case`remove`:return summaries.filter(summary=>summary.sessionId!==mutation.sessionId);case`status`:return summaries.map(summary=>summary.sessionId===mutation.sessionId&&(summary.running!==mutation.running||summary.agentAvailable!==mutation.agentAvailable||mutation.running&&summary.blank)?{...summary,running:mutation.running,agentAvailable:mutation.agentAvailable,blank:summary.blank&&!mutation.running}:summary);case`activity`:return summaries.map(summary=>summary.sessionId===mutation.sessionId&&mutation.updatedAt>summary.updatedAt?{...summary,updatedAt:mutation.updatedAt}:summary);case`engaged`:return summaries.map(summary=>summary.sessionId===mutation.sessionId&&summary.blank?{...summary,blank:false}:summary)}}function workspaceAttachSessionId(error){return error.code===`session/workspace-attach-failed`?error.details.sessionId:void 0}var SessionCreateError=class extends Error{rpcError;requestedSessionId;name=`SessionCreateError`;constructor(rpcError,requestedSessionId){super(`session create failed: ${rpcError.code}: ${rpcError.message}`);this.rpcError=rpcError;this.requestedSessionId=requestedSessionId}};var SessionForkError=class extends Error{rpcError;sourceSessionId;name=`SessionForkError`;constructor(rpcError,sourceSessionId){super(`session fork failed: ${rpcError.code}: ${rpcError.message}`);this.rpcError=rpcError;this.sourceSessionId=sourceSessionId}};function displayTitleOf(title,cwd,id){if(title!==void 0)return title;if(cwd!==void 0&&cwd!==``){const base=workspaceTitleOf(cwd);if(base!==``)return base}return id}function increasedForkTitle(title,taken){let next=incrementedTitle(title);while(taken.has(next))next=incrementedTitle(next);return next}function incrementedTitle(title){const ascii=/^(.*?)\((\d+)\)$/u.exec(title);if(ascii?.[1]!==void 0&&ascii[2]!==void 0)return`${ascii[1]}(${BigInt(ascii[2])+1n})`;const fullWidth=/^(.*?)((\d+))$/u.exec(title);if(fullWidth?.[1]!==void 0&&fullWidth[2]!==void 0)return`${fullWidth[1]}(${BigInt(fullWidth[2])+1n})`;return`${title} (1)`}function freezeRetainedBy(counts){Object.setPrototypeOf(counts,null);return Object.freeze(counts)}const EMPTY_RETAIN_INFO=Object.freeze({referenceCount:0,retainedBy:freezeRetainedBy({})});async function waitForOpen(opening,signal){if(signal===void 0)return opening;const aborted=Promise.withResolvers();const onAbort=()=>{aborted.reject(signal.reason)};signal.addEventListener(`abort`,onAbort,{once:true});try{if(signal.aborted)onAbort();await Promise.race([opening,aborted.promise])}finally{signal.removeEventListener(`abort`,onAbort)}}var ClientSessionReference=class{sessionId;record;releaseReference;released=new AbortController;readiness=Promise.withResolvers();ready=this.readiness.promise;constructor(sessionId,record,releaseReference){this.sessionId=sessionId;this.record=record;this.releaseReference=releaseReference;this.ready.catch(()=>{})}get binding(){if(this.record===void 0||!this.record.live)throw new Error(`Session reference "${this.sessionId}" is released`);return this.record.binding}attachOpening(opening,signal){const waitSignal=signal===void 0?this.released.signal:AbortSignal.any([this.released.signal,signal]);waitForOpen(opening,waitSignal).then(()=>{try{waitSignal.throwIfAborted();this.readiness.resolve(this.binding)}catch(error){this.readiness.reject(error)}},error=>{this.readiness.reject(error)})}release(){const reason=new Error(`Session reference "${this.sessionId}" is released`);const release=this.releaseReference;this.released.abort(reason);this.readiness.reject(reason);this.record=void 0;this.releaseReference=void 0;release?.()}[Symbol.dispose](){this.release()}};var ClientSessions=class{rootCtx;searchResultLimit=20;list;manager;scopes=new Map;retainObservers=new Map;scopeDrops=new Set;closed=false;constructor(rootCtx,remote){this.rootCtx=rootCtx;this.manager=new SessionManager(remote);this.list=(0,_unieai_rabi_client_store.createSnapshotStore)({ids:[],byId:{},phase:`pending`,projectionsBySession:{}});const disposeManagerProjection=this.manager.subscribe(()=>{this.projectList()});rootCtx.effect(()=>async()=>{this.closed=true;disposeManagerProjection();const scopes=[...this.scopes];this.scopes.clear();for(const[,record]of scopes){record.live=false;record.session.unbindScope()}const managerDisposal=this.manager.dispose();for(const[id,record]of scopes){this.startScopeDrop(id,record);this.publishRetention(id)}await this.drainScopeDrops();await managerDisposal},`session-controller.client.sessions`);rootCtx.reflect.provide(`sessions`,this,void 0)}retain(target,options){const{source,signal}=options;signal?.throwIfAborted();if(this.closed)throw new Error(`Session Controller is disposed`);const id=this.manager.resolveTarget(target);const reference=this.retainScope(id,source);try{reference.attachOpening(this.manager.get(id).open(),signal);return reference}catch(error){reference.release();throw error}}async using(target,options,operation){const reference=this.retain(target,options);try{await reference.ready;return await operation(reference)}finally{reference.release()}}retainInfo(id){let observer=this.retainObservers.get(id);if(observer===void 0){const listeners=new Set;observer={listeners,published:this.retentionSnapshot(id),source:{getSnapshot:()=>this.retentionSnapshot(id),subscribe:listener=>{listeners.add(listener);return()=>{listeners.delete(listener)}}}};this.retainObservers.set(id,observer)}return observer.source}subagentAddress(id){return this.manager.subagentAddress(id)}refreshProjections(sessionId){return this.manager.refreshProjections(sessionId)}refresh(){return this.manager.refreshList()}search(query,signal){return this.manager.search(query,signal)}handleControlFrame(frame){this.manager.handleControlFrame(frame)}handleSessionAdded(summary){this.manager.handleSessionAdded(summary)}handleSessionRemoved(sessionId){this.manager.handleSessionRemoved(sessionId)}handleSessionStatus(...args){this.manager.handleSessionStatus(...args)}handleSessionActivity(...args){this.manager.handleSessionActivity(...args)}handleSessionError(...args){this.manager.handleSessionError(...args)}handleConnected(){this.manager.handleConnected()}async create(opts={}){const result=await this.manager.create(opts);if(!result.ok)throw new SessionCreateError(result.error,opts.sessionId);this.projectList();return result.value.sessionId}async fork(opts){const sourceTitle=opts.increaseTitle?this.list.getSnapshot().byId[opts.sessionId]?.title:void 0;const result=await this.manager.fork({sessionId:opts.sessionId,...opts.atSeq===void 0?{}:{atSeq:SessionSeq(opts.atSeq)},...opts.allowMigration===void 0?{}:{allowMigration:opts.allowMigration}});if(!result.ok)throw new SessionForkError(result.error,opts.sessionId);this.projectList();const childId=result.value.sessionId;opts.onCreated?.(childId);if(sourceTitle!==void 0){const list=this.list.getSnapshot();const taken=new Set(list.ids.flatMap(id=>list.byId[id]?.title??[]));const renamed=await this.manager.rename(childId,increasedForkTitle(sourceTitle,taken));if(!renamed.ok)throw new Error(`fork child rename failed: ${renamed.error.code}: ${renamed.error.message}`)}return childId}scope(id){return this.scopes.get(id)?.ctx}retainAgentScope(id){if(this.closed)throw new Error(`Session Controller is disposed`);return this.retainScope(id,`gateway`)}scopeOf(ctx){return scopeOf(ctx)}sessionOf(ctx){const id=scopeOf(ctx);if(id===void 0)return void 0;const record=this.scopes.get(id);return record!==void 0&&scopeIdentityOf(record.ctx)===scopeIdentityOf(ctx)?record.binding.session:void 0}binding(id){return this.scopes.get(id)?.binding}retainScope(id,source){const record=this.scopes.get(id)??this.materializeScope(id);const previous=record.retention;record.retention=Object.freeze({referenceCount:previous.referenceCount+1,retainedBy:freezeRetainedBy({...previous.retainedBy,[source]:(previous.retainedBy[source]??0)+1})});const reference=new ClientSessionReference(id,record,()=>{if(!record.live)return;const count=record.retention.referenceCount-1;const{[source]:sourceCount=0,...otherSources}=record.retention.retainedBy;const retainedBy=sourceCount>1?{...otherSources,[source]:sourceCount-1}:otherSources;record.retention=count===0?EMPTY_RETAIN_INFO:Object.freeze({referenceCount:count,retainedBy:freezeRetainedBy(retainedBy)});if(count===0)this.retireScope(id,record);else this.publishRetention(id)});if(this.list.getSnapshot().byId[id]===void 0&&this.manager.subagentAddress(id)!==void 0)this.projectList();this.publishRetention(id);return reference}retentionSnapshot(id){return this.scopes.get(id)?.retention??EMPTY_RETAIN_INFO}publishRetention(id){const state=this.list.getSnapshot();const row=state.byId[id];const retainedBy=this.retentionSnapshot(id).retainedBy;if(row!==void 0&&row.retainedBy!==retainedBy)this.list.set({...state,byId:{...state.byId,[id]:{...row,retainedBy}}});const observer=this.retainObservers.get(id);const snapshot=this.retentionSnapshot(id);if(observer===void 0||observer.published===snapshot)return;observer.published=snapshot;(0,_unieai_rabi_client_store.notifySubscribers)(observer.listeners,`[session-controller] reference sources`)}retireScope(id,record,disposeFiber=true){if(!record.live)return;record.live=false;if(this.scopes.get(id)===record)this.scopes.delete(id);record.session.unbindScope();const sessionDisposal=this.manager.drop(id,record.session);this.projectList();this.publishRetention(id);this.startScopeDrop(id,record,disposeFiber,sessionDisposal)}materializeScope(id){const{fiber,ctx}=createScope(this.rootCtx,id);const session=this.manager.get(id);session.bindScope(ctx);const record={fiber,ctx,binding:{sessionId:id,session,eventSource:session.eventSource,ctx},session,retention:EMPTY_RETAIN_INFO,live:true};this.scopes.set(id,record);ctx.effect(()=>()=>{this.retireScope(id,record,false)},`session-controller: exact generation`);return record}projectList(){const previousById=this.list.getSnapshot().byId;const{items,phase,projectionsBySession}=this.manager.getListSnapshot();const ids=[];const byId={};for(const entry of items){ids.push(entry.sessionId);byId[entry.sessionId]={id:entry.sessionId,displayTitle:displayTitleOf(entry.title,entry.cwd,entry.sessionId),running:entry.running,retainedBy:this.retentionSnapshot(entry.sessionId).retainedBy,blank:entry.blank,updatedAt:entry.updatedAt,formatStatus:entry.formatStatus,...entry.projectionValues===void 0?{}:{projectionValues:entry.projectionValues},...entry.title!==void 0?{title:entry.title}:{},...entry.cwd!==void 0?{cwd:entry.cwd}:{},...entry.parentSessionId!==void 0?{parentId:entry.parentSessionId}:{},...entry.origin!==void 0?{origin:entry.origin}:{}}}for(const[parentId,projection]of Object.entries(projectionsBySession))for(const child of projection.values.subagentCatalog??[]){if(child.mode===`external`)continue;const childId=child.id;const summary=byId[childId];const projectionValues=summary?.projectionValues??this.manager.projectionValues(childId);const projectedTitle=projectionValues?.title;const title=typeof projectedTitle===`string`&&projectedTitle!==``?projectedTitle:void 0;const displayTitle=title??child.label??childId;if(summary===void 0)byId[childId]={id:childId,displayTitle,parentId,origin:`subagent`,running:this.scopes.get(childId)?.session.getSnapshot().running??false,blank:false,updatedAt:0,retainedBy:this.retentionSnapshot(childId).retainedBy,...projectionValues===void 0?{}:{projectionValues},...title===void 0?{}:{title}};else if(summary.displayTitle!==displayTitle||summary.projectionValues!==projectionValues)byId[childId]={...summary,displayTitle,...projectionValues===void 0?{}:{projectionValues}}}for(const[id,record]of this.scopes){if(byId[id]!==void 0)continue;const address=this.manager.subagentAddress(id);if(address===void 0)continue;const previous=previousById[id];const snapshot=record.session.getSnapshot();const projectionValues=this.manager.projectionValues(id);const projectedTitle=projectionValues?.title;const title=typeof projectedTitle===`string`&&projectedTitle!==``?projectedTitle:previous?.title;byId[id]={...previous??{id,displayTitle:id,updatedAt:0},running:snapshot.running,retainedBy:record.retention.retainedBy,blank:snapshot.blank,parentId:address.parentSessionId,origin:`subagent`,...projectionValues===void 0?{}:{projectionValues},...title===void 0?{}:{title,displayTitle:title}}}this.list.set({ids,byId,phase,projectionsBySession})}startScopeDrop(id,record,disposeFiber=true,sessionDisposal=this.manager.drop(id,record.session)){const drop=this.dropScope(record,disposeFiber,sessionDisposal);this.scopeDrops.add(drop);drop.then(()=>{this.scopeDrops.delete(drop)},()=>{this.scopeDrops.delete(drop)})}async drainScopeDrops(){while(this.scopeDrops.size>0)await Promise.allSettled([...this.scopeDrops])}async dropScope(record,disposeFiber,sessionDisposal){await Promise.allSettled([sessionDisposal,...disposeFiber?[record.fiber.dispose()]:[]])}};const inject=[`connection`,`fileUpload`,`typert`,`remote`,`remote.commands`,`remote.session`,`remote.subagents`];function apply(ctx){const remotes=ctx.remote;const connection=ctx.get(`connection`);const sessions=new ClientSessions(ctx,remotes);ctx.remote.$on(`api-session/added`,summary=>{sessions.handleSessionAdded(summary)});ctx.remote.$on(`api-session/removed`,sessionId=>{sessions.handleSessionRemoved(sessionId)});ctx.remote.$on(`api-session/status`,(sessionId,running)=>{sessions.handleSessionStatus(sessionId,running)});ctx.remote.$on(`api-session/activity`,(sessionId,updatedAt)=>{sessions.handleSessionActivity(sessionId,updatedAt)});ctx.remote.$on(`api-session/error`,(sessionId,message)=>{sessions.handleSessionError(sessionId,message)});const control=createSessionControlStream(remotes,{accept:frame=>{sessions.handleControlFrame(frame)},failed:error=>{console.error(`[session-controller] control stream failed:`,error)}});const connected=()=>{if(connection.generation.getSnapshot()===void 0)return;sessions.handleConnected();control.restart();control.start()};ctx.effect(()=>connection.generation.subscribe(connected),`session-controller.client.generation`);connected();ctx.typert.contexts.registerClient(`agent`,{identity:candidate=>sessions.sessionOf(candidate)?.sessionId,resolve:sessionId=>{const reference=sessions.retainAgentScope(sessionId);return typertOwnedValue(reference.binding.ctx,()=>{reference.release()})}});ctx.effect(()=>async()=>{await control.dispose()},`session-controller.client.control`)}exports.MutableSessionEventSource=MutableSessionEventSource;exports.SESSION_SEARCH_RESULT_LIMIT=SESSION_SEARCH_RESULT_LIMIT;exports.SESSION_SEARCH_SNIPPET_MAX_CODE_POINTS=SESSION_SEARCH_SNIPPET_MAX_CODE_POINTS;exports.SessionCreateError=SessionCreateError;exports.SessionEventStream=SessionEventStream;exports.SessionForkError=SessionForkError;exports.apply=apply;exports.createScope=createScope;exports.createSessionControlStream=createSessionControlStream;exports.inject=inject;exports.scopeOf=scopeOf;return module.exports}});