@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
@@ -0,0 +1,1055 @@
1
+ // Sessions remain resident after creation so their open Remote sources keep running off-screen.
2
+
3
+ import type { Context } from '@unieai/cordis'
4
+ import type { InboxState, InboxTarget } from '@unieai/rabi-agent/types'
5
+ import { randomUUID } from '@unieai/rabi-util-crypto'
6
+ import type { FileAttachmentRef, ImageAttachmentRef } from '@unieai/rabi-attachment'
7
+ import type { SubagentAddress } from '@unieai/rabi-subagent/client'
8
+ import type { MessageId } from '@unieai/rabi-llm/brand'
9
+ import type { UserMessage } from '@unieai/rabi-llm/types'
10
+ import { SessionLogOffset, SessionSeq, type SessionId } from '@unieai/rabi-session/types'
11
+ import { SessionEventStream } from '../transport.ts'
12
+ import type { SessionJournalChange } from '../transport.ts'
13
+ import type {
14
+ PromptContentPart,
15
+ QueueAction,
16
+ SessionAddress,
17
+ SessionAssistantStreamBaseline,
18
+ SessionProjectionBaseline,
19
+ SessionRequestId,
20
+ } from '../../types.ts'
21
+ import type {
22
+ BeginSubmissionInput, PendingSubmissionRetirement, SessionFace, SubmissionHandle,
23
+ } from '../contract/session.ts'
24
+ import type {
25
+ OpenState, PendingSubmission, PromptError, SessionSnapshot,
26
+ } from '../contract/snapshot.ts'
27
+ import { MutableSessionEventSource } from '../contract/events.ts'
28
+ import type {
29
+ SessionEventLike, SessionEventLikeEntry, SessionLiveEventEntry,
30
+ } from '../contract/events.ts'
31
+ import { Notifier } from './notifier.ts'
32
+ import { isRemoteFailure } from '@unieai/rabi-api-gateway/client'
33
+ import { RemoteError } from '@unieai/rabi-typert-protocol'
34
+ import type { RemoteFailure, RemoteResult } from '@unieai/rabi-typert-protocol'
35
+ import type { SessionRemotes } from './remotes.ts'
36
+ import { ProjectionValueStore } from './projection-store.ts'
37
+ import type { ProjectionsBaseline } from './projection-store.ts'
38
+ import { resolvedClientTimeZone } from '../time-zone.ts'
39
+ import {
40
+ ClientAssistantStream,
41
+ type ClientAssistantStreamResult,
42
+ } from './assistant-stream.ts'
43
+
44
+ function projectionsBaseline(value: SessionProjectionBaseline): ProjectionsBaseline {
45
+ return {
46
+ ...value,
47
+ asOfSeq: value.asOfSeq === -1 ? -1 : SessionSeq(value.asOfSeq),
48
+ }
49
+ }
50
+
51
+ /** Minimum message count for ordinary history windows. */
52
+ export const PAGE_MESSAGES = 50
53
+
54
+ const HISTORY_PAGE_OPTIONS = { maxMessages: 500, turnWindow: { minMessages: PAGE_MESSAGES, minTurns: 2 } }
55
+
56
+ /** Minimum messages per page while a turn jump loops backwards. */
57
+ export const JUMP_PAGE_MESSAGES = 200
58
+
59
+ const JUMP_PAGE_OPTIONS = {
60
+ ...HISTORY_PAGE_OPTIONS,
61
+ turnWindow: { ...HISTORY_PAGE_OPTIONS.turnWindow, minMessages: JUMP_PAGE_MESSAGES },
62
+ }
63
+
64
+ interface PendingHistory {
65
+ beforeSeq: SessionLogOffset
66
+ hasMore: boolean
67
+ readonly pages: (readonly SessionEventLikeEntry[])[]
68
+ }
69
+
70
+ interface OlderHistoryRequest {
71
+ readonly generation: number
72
+ readonly beforeSeq: SessionLogOffset
73
+ page: { readonly entries: readonly SessionEventLikeEntry[]; readonly hasMore: boolean } | null
74
+ invalidated: boolean
75
+ recovering: boolean
76
+ consuming: boolean
77
+ promise?: Promise<void>
78
+ }
79
+
80
+ /** Manager-owned observers of a Session object's local state edges. */
81
+ export interface SessionOptions {
82
+ /** Catalog-discovered address selecting non-activating subagent transport. */
83
+ address?: SubagentAddress
84
+ /**
85
+ * Publish each accepted prompt to the Manager, including after this Session
86
+ * object is replaced. Acceptance converts display state, but does not
87
+ * establish that a turn started or reached durable history.
88
+ */
89
+ onEngaged?(session: Session): void
90
+ /**
91
+ * Manager-owned projection value store to adopt (frames route through the
92
+ * manager and values outlive instantiation); omitted, the Session owns a
93
+ * private store (bare object-layer construction).
94
+ */
95
+ projections?: ProjectionValueStore
96
+ }
97
+
98
+ /**
99
+ * Owns a session's event window, lifecycle state, and observable
100
+ * snapshot. React bindings remain outside this data layer. Features see only
101
+ * the {@link SessionFace} slice (ISession verbs + the snapshot source); the
102
+ * remaining public members are Session Controller internals.
103
+ */
104
+ export class Session implements SessionFace {
105
+ // ---- Window and derived state (all private; the snapshot is the only read API) ----
106
+ private baseSeq = SessionLogOffset(0)
107
+ private hasMore = false
108
+ private historyWasPartial = false
109
+ private openState: OpenState = 'cold'
110
+ private openError: RemoteFailure | null = null
111
+ private openPromise: Promise<void> | null = null
112
+ /** Bumped by stream replacement to invalidate an in-flight doOpen. Stale
113
+ * passes drop all writes once the generation moves on. */
114
+ private openGeneration = 0
115
+ private get loadingOlder(): boolean { return this.historyLoadStatus === 'loading' }
116
+ private historyLoadStatus: SessionSnapshot['historyLoadStatus'] = 'idle'
117
+ private olderRequest: OlderHistoryRequest | null = null
118
+ /** Shared low-water target of the running jump loop; null when no jump is paging. */
119
+ private jumpTargetSeq: SessionSeq | null = null
120
+ /** The running jump loop's completion, shared by retargeting callers. */
121
+ private jumpPromise: Promise<void> | null = null
122
+ private pendingHistory: PendingHistory | null = null
123
+ private readonly stopObservingInbox: () => void
124
+ private readonly assistantStream = new ClientAssistantStream()
125
+ private running = false
126
+ private address: SubagentAddress | undefined
127
+ /**
128
+ * Sticky send marker, private input of the composerPhase derivation: set
129
+ * when the Host accepts a prompt, never reset — the blank → engaging edge of
130
+ * the phase machine (see ComposerPhase).
131
+ */
132
+ private promptAttempted = false
133
+ /** A first accepted prompt stays in the engaging phase until its turn is observable. */
134
+ private firstPromptPendingTurn = false
135
+ /** New Session display state; unknown bare sessions begin conservatively blank. */
136
+ private blankBit = true
137
+ private removed = false
138
+ private promptError: PromptError | null = null
139
+ private lastAgentError: string | null = null
140
+ /** Local submission echoes, insertion-ordered, including those the Host has not accepted yet. */
141
+ private pendingSubmissions: readonly PendingSubmission[] = []
142
+ /** The accepted echoes, published as SessionSnapshot.pendingSubmissions; rebuilt when one is accepted or removed. */
143
+ private acceptedSubmissions: readonly PendingSubmission[] = []
144
+ /** Per-echo settlement state; `retiring` latches the first observation so a
145
+ * Inbox projection and its durable event cannot both retire one echo. */
146
+ private readonly submissionSettlements = new Map<SessionRequestId, {
147
+ readonly placement: PendingSubmission['placement']
148
+ /** Latest received Inbox position; null means removed from that queue. */
149
+ receipt?: {
150
+ readonly target: InboxTarget
151
+ readonly seq: number
152
+ readonly index: number | null
153
+ readonly attachments: readonly (ImageAttachmentRef | FileAttachmentRef)[]
154
+ }
155
+ /** Durable admission may precede the Inbox projection acknowledging its claim. */
156
+ admitted?: readonly (ImageAttachmentRef | FileAttachmentRef)[]
157
+ /** Whether the Host accepted the prompt; the echo is published only from then on. */
158
+ accepted: boolean
159
+ readonly onAccept?: (() => void) | undefined
160
+ readonly onRetire?: ((retirement: PendingSubmissionRetirement) => void) | undefined
161
+ retiring: boolean
162
+ }>()
163
+ /** Owns the addressed page/follow lifecycle while this Session is open. */
164
+ private events: SessionEventStream | undefined
165
+
166
+ /**
167
+ * Per-session projection value store (push model; see the session-projection
168
+ * subsystem page, docs/subsystems/session-projection.md): finished whole
169
+ * values computed on the Host, seeded by the tail page's
170
+ * projections block and updated by Session Controller control frames;
171
+ * Host-sequenced writes merge under higher-seq-wins and cached list blocks
172
+ * yield to them (projection-store.ts). Keys are read via `projections.faceOf(key)`
173
+ * (the useProjection resolution face); the conversation snapshot never
174
+ * carries projection values, and no client-side domain folding exists.
175
+ * Manager-owned when constructed through SessionManager (frames route and
176
+ * the store outlives instantiation, the title-snapshot precedent); a bare
177
+ * construction gets a private store.
178
+ */
179
+ readonly projections: ProjectionValueStore
180
+
181
+ /** Contiguous history and live tail consumed by Conversation assembly. */
182
+ readonly eventSource = new MutableSessionEventSource()
183
+ private snapshotCache: SessionSnapshot
184
+ private readonly notifier: Notifier
185
+ /**
186
+ * Agent-scoped cordis context, bound once by ClientSessions when it
187
+ * mints the scope (the client mirror of the host Agent's loopCtx). The
188
+ * Session dispatches its own scoped events through it; undefined means
189
+ * unbound (bare object-layer construction) or already pruned — both skip
190
+ * dispatch-dependent behavior rather than fail.
191
+ */
192
+ private actx: Context | undefined
193
+
194
+ /**
195
+ * @param sessionId - Host session identity (client sessions are always Host-born).
196
+ * @param remote - generated Remote namespaces this session calls.
197
+ * @param options - optional manager-owned state observers.
198
+ */
199
+ constructor(
200
+ readonly sessionId: SessionId,
201
+ private readonly remote: SessionRemotes,
202
+ private readonly options: SessionOptions = {},
203
+ ) {
204
+ this.projections = options.projections ?? new ProjectionValueStore()
205
+ this.address = options.address
206
+ this.notifier = new Notifier(() => {
207
+ this.snapshotCache = this.buildSnapshot()
208
+ })
209
+ this.snapshotCache = this.buildSnapshot()
210
+ this.stopObservingInbox = this.projections.faceOf('inbox').subscribe(() => {
211
+ this.observeSubmissionInbox()
212
+ })
213
+ }
214
+
215
+ /**
216
+ * Bind the Agent-scoped context minted by ClientSessions (single write;
217
+ * a second bind is a wiring error and throws). Direction stays one-way at
218
+ * this binding boundary: consumers still reach the Session via `sessions.sessionOf`,
219
+ * while the Session holds its own dispatch point (host Agent.loopCtx
220
+ * mirror).
221
+ * @param actx - the agent's scoped context.
222
+ */
223
+ bindScope(actx: Context): void {
224
+ if (this.actx !== undefined) throw new Error(`session ${this.sessionId} already has a bound scope`)
225
+ this.actx = actx
226
+ }
227
+
228
+ /** Release the bound scope at prune time (a later rebind accompanies a freshly minted scope). */
229
+ unbindScope(): void {
230
+ this.actx = undefined
231
+ }
232
+
233
+ // ---- Operations ----
234
+
235
+ /**
236
+ * Register one local submission echo (see the ISession declaration). The
237
+ * echo reconciles against Host events from now on, but it enters the
238
+ * snapshot only once the prompt receipt or an Inbox row carrying its
239
+ * request id shows that the Host accepted it.
240
+ * @param input - echo content and the optional settlement callback.
241
+ * @returns the minted identity for {@link prompt} plus the pre-prompt abandon path.
242
+ */
243
+ beginSubmission(input: BeginSubmissionInput): SubmissionHandle {
244
+ const requestId = randomUUID() as SessionRequestId
245
+ const placement = this.running ? input.mode === 'steer' ? 'steering' : 'queued' : 'transcript'
246
+ this.pendingSubmissions = [...this.pendingSubmissions, {
247
+ requestId,
248
+ placement,
249
+ time: Date.now(),
250
+ text: input.text,
251
+ attachments: input.attachments,
252
+ }]
253
+ this.submissionSettlements.set(requestId, {
254
+ placement, accepted: false, onAccept: input.onAccept, onRetire: input.onRetire, retiring: false,
255
+ })
256
+ return { requestId, abandon: () => { this.retireFailedSubmission(requestId) } }
257
+ }
258
+
259
+ /**
260
+ * Send (queue/steer passed through 1:1); failures land in the snapshot's
261
+ * promptError. The Host can hold the prompt at its admission stage, so the
262
+ * call can stay open; the echo appears and the blank → engaging edge flips
263
+ * only once the Host accepts the prompt.
264
+ * @param content - text, browser-owned temporary image uploads, and staged-file receipts.
265
+ * @param mode - queue appends after the current turn; steer interrupts it.
266
+ * @param signal - optional caller cancellation for the complete admission round-trip.
267
+ * @param requestId - identity from {@link beginSubmission}; a failed identified prompt retires its echo.
268
+ * @returns the prompt result (also mirrored into promptError on failure).
269
+ */
270
+ async prompt(
271
+ content: PromptContentPart[],
272
+ mode: 'queue' | 'steer',
273
+ signal?: AbortSignal,
274
+ requestId?: SessionRequestId,
275
+ ): Promise<RemoteResult<{ accepted: true }>> {
276
+ this.promptError = null
277
+ this.lastAgentError = null
278
+ // Before the first await, so a turn observed ahead of the receipt clears it.
279
+ const firstPrompt = this.blankBit && !this.firstPromptPendingTurn
280
+ if (firstPrompt) this.firstPromptPendingTurn = true
281
+ let result: RemoteResult<{ accepted: true }>
282
+ if (this.address === undefined) {
283
+ const clientTimeZone = resolvedClientTimeZone()
284
+ result = await this.remote.session.prompt({
285
+ requestId: requestId ?? randomUUID() as SessionRequestId,
286
+ sessionId: this.sessionId,
287
+ mode,
288
+ content,
289
+ clientTimeZone,
290
+ }, signal)
291
+ } else if (content.some(part => part.type === 'file')) {
292
+ result = {
293
+ ok: false,
294
+ error: new RemoteError(
295
+ 'subagent/attachment-invalid',
296
+ 'subagent continuation does not accept files',
297
+ { reason: 'SUBAGENT_FILE_UNSUPPORTED' },
298
+ ),
299
+ }
300
+ } else {
301
+ // The preceding branch rejects file parts before the narrower subagent
302
+ // wire type is used; this array is not filtered or reordered.
303
+ const routedContent = content as Exclude<PromptContentPart, { readonly type: 'file' }>[]
304
+ const routed = await this.remote.subagents.prompt({
305
+ requestId: requestId ?? randomUUID() as SessionRequestId,
306
+ childSessionId: this.address.childSessionId,
307
+ delivery: mode,
308
+ content: routedContent,
309
+ clientTimeZone: resolvedClientTimeZone(),
310
+ }, signal)
311
+ result = routed.ok ? { ok: true, value: { accepted: true } } : routed
312
+ }
313
+ if (!result.ok) {
314
+ // Rejection must leave a first prompt blank and eligible for workspace reuse.
315
+ if (firstPrompt) this.firstPromptPendingTurn = false
316
+ if (requestId !== undefined) this.retireFailedSubmission(requestId)
317
+ this.promptError = { op: 'send', error: result.error }
318
+ this.notifier.markDirty()
319
+ return result
320
+ }
321
+ this.acceptPrompt(requestId)
322
+ return result
323
+ }
324
+
325
+ /**
326
+ * Apply the Host's acceptance of one prompt: publish its echo, move a blank
327
+ * Session to engaging, and tell the submitter. The prompt receipt and an
328
+ * Inbox row carrying the prompt's request id both prove acceptance.
329
+ * Whichever arrives first publishes the echo; a later proof for an echo
330
+ * still pending changes nothing.
331
+ * @param requestId - identity from {@link beginSubmission}; absent for a prompt sent without an echo.
332
+ */
333
+ private acceptPrompt(requestId: SessionRequestId | undefined): void {
334
+ const settlement = requestId === undefined ? undefined : this.submissionSettlements.get(requestId)
335
+ if (settlement?.accepted === true) return
336
+ if (settlement !== undefined) {
337
+ settlement.accepted = true
338
+ this.refreshAcceptedSubmissions()
339
+ }
340
+ this.promptAttempted = true
341
+ this.blankBit = false
342
+ this.notifier.markDirty()
343
+ this.options.onEngaged?.(this)
344
+ settlement?.onAccept?.()
345
+ }
346
+
347
+ /**
348
+ * Resolve one stored image into browser-consumable bytes using this Session's gateway permission scope.
349
+ * @param attachment - complete image reference from the folded session log.
350
+ * @returns the supplied reference after storage verification, and decoded bytes.
351
+ */
352
+ async readAttachment(
353
+ attachment: ImageAttachmentRef,
354
+ ): Promise<RemoteResult<{ attachment: ImageAttachmentRef; data: Uint8Array }>> {
355
+ const result = await this.remote.session.attachment({
356
+ sessionId: this.sessionId,
357
+ attachment,
358
+ })
359
+ if (!result.ok) return result
360
+ const binary = atob(result.value.data)
361
+ const data = Uint8Array.from(binary, char => char.charCodeAt(0))
362
+ return { ok: true, value: { attachment: result.value.attachment, data } }
363
+ }
364
+
365
+ /** Apply one operation to a still-pending queue occurrence. */
366
+ async updateQueue(itemId: MessageId, action: QueueAction): Promise<RemoteResult<{ accepted: true }>> {
367
+ return this.remote.session.updateQueue({ sessionId: this.sessionId, itemId, action })
368
+ }
369
+
370
+ /**
371
+ * Stop the active turn while the Host preserves pending inbox work; failures
372
+ * land in promptError (same error-strip display slot). A subagent address
373
+ * routes through `subagents.interruptByUser`, authorized on the target Session
374
+ * without requiring a live parent Agent.
375
+ * @returns the cancel result.
376
+ */
377
+ async cancel(): Promise<RemoteResult<{ accepted: true }>> {
378
+ const address = this.address
379
+ const result = address !== undefined
380
+ ? await this.remote.subagents.interruptByUser(address.childSessionId)
381
+ : await this.remote.session.cancel({ sessionId: this.sessionId })
382
+ if (!result.ok) {
383
+ this.promptError = { op: 'stop', error: result.error }
384
+ this.notifier.markDirty()
385
+ }
386
+ return result
387
+ }
388
+
389
+ /**
390
+ * Rename: contract session.rename 1:1. On success settle the 'title'
391
+ * projection cell from the response's `{title, seq}` under the store's
392
+ * higher-seq-wins rule (the push frame arriving later is a no-op replay),
393
+ * so the list row and any useProjection('title') reader update without
394
+ * waiting for the control-stream projection update.
395
+ * @param title - raw title text (the host normalizes acceptance).
396
+ * @returns the rename result (normalized accepted title + title event seq).
397
+ */
398
+ async rename(title: string): Promise<RemoteResult<{ title: string; seq: SessionSeq }>> {
399
+ const result = await this.remote.session.rename({ sessionId: this.sessionId, title })
400
+ if (!result.ok) return result
401
+ const seq = SessionSeq(result.value.seq)
402
+ this.projections.apply('title', result.value.title, seq)
403
+ return { ok: true, value: { title: result.value.title, seq } }
404
+ }
405
+
406
+ /**
407
+ * Execute one slash-command line against this session's agent — pure
408
+ * admission semantics (the host executor durably logs the lifecycle;
409
+ * outcomes render as flow nodes, never as a response echo).
410
+ * @param line - the full command line, leading slash included.
411
+ * @returns the admission result.
412
+ */
413
+ async command(line: string): Promise<RemoteResult<{ matched: boolean }>> {
414
+ const result = await this.remote.commands.execute(this.sessionId, line, [])
415
+ if (!result.ok) return result
416
+ return { ok: true, value: { matched: result.value !== undefined } }
417
+ }
418
+
419
+ /** First open: pull the tail page (idempotent — in-flight/already-open returns the existing promise). */
420
+ open(): Promise<void> {
421
+ if (this.openState === 'open') return Promise.resolve()
422
+ if (this.openPromise !== null) return this.openPromise
423
+ const promise = this.doOpen(this.openGeneration).finally(() => {
424
+ // Identity-guarded: a superseded open must not null out the promise resync just started.
425
+ if (this.openPromise === promise) this.openPromise = null
426
+ })
427
+ this.openPromise = promise
428
+ return promise
429
+ }
430
+
431
+ /** @inheritdoc */
432
+ async loadOlder(options?: { deferConsumption?: boolean }): Promise<void> {
433
+ const request = this.prepareOlder()
434
+ await request?.promise
435
+ if (request !== null && this.olderRequest === request
436
+ && (!options?.deferConsumption || request.page?.entries.length === 0)) this.consumeOlder()
437
+ }
438
+
439
+ private prepareOlder(): OlderHistoryRequest | null {
440
+ if (this.olderRequest !== null) return this.olderRequest
441
+ const events = this.events
442
+ if (this.openState !== 'open' || !this.hasMore || this.loadingOlder || events === undefined) return null
443
+ const request: OlderHistoryRequest = {
444
+ generation: this.openGeneration,
445
+ beforeSeq: this.baseSeq,
446
+ page: null,
447
+ invalidated: false,
448
+ recovering: false,
449
+ consuming: false,
450
+ }
451
+ this.olderRequest = request
452
+ this.historyLoadStatus = 'loading'
453
+ this.notifier.markDirty()
454
+ request.promise = (async () => {
455
+ try {
456
+ await events.prepend({ beforeSeq: request.beforeSeq, ...HISTORY_PAGE_OPTIONS })
457
+ if (this.olderRequest !== request) return
458
+ if (request.invalidated || request.generation !== this.openGeneration || request.beforeSeq !== this.baseSeq) return
459
+ const page = request.page
460
+ const first = page?.entries[0]
461
+ this.historyLoadStatus = page === null || (first === undefined ? page.hasMore : first.event.seq >= request.beforeSeq)
462
+ ? 'error' : 'pendingConsumption'
463
+ } catch (error) {
464
+ if (this.olderRequest !== request) return
465
+ request.page = null
466
+ this.historyLoadStatus = 'error'
467
+ if (!isRemoteFailure(error)) console.error('[session-controller] loadOlder failed:', error)
468
+ } finally {
469
+ if (this.olderRequest === request) {
470
+ if (request.invalidated && this.events === events) {
471
+ // A replacement restores the transport cursor before another page uses the visible window.
472
+ request.recovering = true
473
+ this.historyLoadStatus = 'loading'
474
+ events.restart()
475
+ } else if (this.historyLoadStatus === 'error') this.olderRequest = null
476
+ this.notifier.markDirty()
477
+ }
478
+ }
479
+ })()
480
+ return request
481
+ }
482
+
483
+ /** @inheritdoc */
484
+ consumeOlder(): boolean {
485
+ const request = this.olderRequest
486
+ if (request === null || request.consuming || this.historyLoadStatus !== 'pendingConsumption' || request.page === null) return false
487
+ if (this.openState !== 'open' || request.invalidated || request.generation !== this.openGeneration
488
+ || request.beforeSeq !== this.baseSeq) {
489
+ this.clearOlderHistory()
490
+ return false
491
+ }
492
+ const page = request.page
493
+ // Retain the request through synchronous feed notification so subscribers cannot reenter consumption.
494
+ request.consuming = true
495
+ try {
496
+ this.prependWindow(page.entries, page.hasMore)
497
+ return true
498
+ } catch (error) {
499
+ if (this.olderRequest === request) this.historyLoadStatus = 'error'
500
+ throw error
501
+ } finally {
502
+ if (this.olderRequest === request) {
503
+ this.olderRequest = null
504
+ if (this.historyLoadStatus !== 'error') this.historyLoadStatus = 'idle'
505
+ }
506
+ this.notifier.markDirty()
507
+ }
508
+ }
509
+
510
+ private clearOlderHistory(): void {
511
+ this.olderRequest = null
512
+ this.historyLoadStatus = this.pendingHistory === null ? 'idle' : 'loading'
513
+ this.notifier.markDirty()
514
+ }
515
+
516
+ /** Jump loader: page backwards until the window covers seq (see ISession.loadThrough). */
517
+ loadThrough(seq: SessionSeq): Promise<void> {
518
+ this.consumeOlder()
519
+ if (this.olderRequest !== null) return Promise.resolve()
520
+ if (this.openState !== 'open' || !this.hasMore || this.baseSeq <= seq) return Promise.resolve()
521
+ if (this.jumpPromise !== null) {
522
+ // Retarget the running loop to the lowest requested seq.
523
+ this.jumpTargetSeq = SessionSeq(Math.min(this.jumpTargetSeq ?? seq, seq))
524
+ return this.jumpPromise
525
+ }
526
+ // A plain single-page pull owns the busy flag; the jump does not queue
527
+ // behind it (the caller retries once it settles) and must leave no
528
+ // target behind — only the loop's finally clears that field, and no
529
+ // loop starts here.
530
+ if (this.loadingOlder) return Promise.resolve()
531
+ const events = this.events
532
+ if (events === undefined) return Promise.resolve()
533
+ const pending: PendingHistory = {
534
+ beforeSeq: this.baseSeq,
535
+ hasMore: this.hasMore,
536
+ pages: [],
537
+ }
538
+ this.pendingHistory = pending
539
+ this.jumpTargetSeq = seq
540
+ this.historyLoadStatus = 'loading'
541
+ this.notifier.markDirty()
542
+ // Stale-pass guard (the doOpen pattern): a resync mid-loop replaces the
543
+ // stream generation; this pass then stops instead of paging the new
544
+ // generation toward its old target.
545
+ const generation = this.openGeneration
546
+ this.jumpPromise = (async () => {
547
+ try {
548
+ while (this.jumpTargetSeq !== null && pending.beforeSeq > this.jumpTargetSeq) {
549
+ if (generation !== this.openGeneration) return
550
+ const before = pending.beforeSeq
551
+ await events.prepend({ beforeSeq: before, ...JUMP_PAGE_OPTIONS })
552
+ if (generation !== this.openGeneration || this.pendingHistory !== pending) return
553
+ // No-progress guard: an empty or dropped page that still claims more
554
+ // history must end the loop, not spin it.
555
+ if (pending.beforeSeq >= before) {
556
+ if (pending.hasMore) this.historyLoadStatus = 'error'
557
+ return
558
+ }
559
+ if (!pending.hasMore) return
560
+ }
561
+ } catch (error) {
562
+ if (generation === this.openGeneration && this.pendingHistory === pending) this.historyLoadStatus = 'error'
563
+ if (!isRemoteFailure(error)) {
564
+ console.error('[session-controller] loadThrough failed:', error)
565
+ }
566
+ } finally {
567
+ if (this.pendingHistory === pending) {
568
+ this.jumpTargetSeq = null
569
+ this.jumpPromise = null
570
+ this.pendingHistory = null
571
+ if (this.historyLoadStatus === 'loading') this.historyLoadStatus = 'idle'
572
+ if (generation === this.openGeneration && pending.pages.length > 0) {
573
+ this.prependWindow(pending.pages.reverse().flat(), pending.hasMore)
574
+ }
575
+ this.notifier.markDirty()
576
+ }
577
+ }
578
+ })()
579
+ return this.jumpPromise
580
+ }
581
+
582
+ /** Rebuild an opened history source after address replacement.
583
+ * Invalidates any in-flight open first; projection state belongs to the independently
584
+ * reconnecting control stream and remains untouched. */
585
+ async resync(): Promise<void> {
586
+ if (this.openState === 'cold') return // never opened: no window to rebuild (doOpen flips to 'loading' synchronously, so cold implies no in-flight open)
587
+ this.openGeneration++
588
+ this.clearOlderHistory()
589
+ const events = this.events
590
+ this.events = undefined
591
+ await events?.dispose()
592
+ this.openPromise = null
593
+ this.openState = 'cold'
594
+ this.openError = null
595
+ this.baseSeq = SessionLogOffset(0)
596
+ this.notifier.markDirty()
597
+ await this.open()
598
+ }
599
+
600
+ // ---- Subscription API (useSyncExternalStore direct wiring) ----
601
+
602
+ /**
603
+ * uSES subscription entry.
604
+ * @param listener - change callback.
605
+ * @returns the unsubscribe function.
606
+ */
607
+ subscribe(listener: () => void): () => void {
608
+ return this.notifier.subscribe(listener)
609
+ }
610
+
611
+ /**
612
+ * Cached Session snapshot (rebuilt lazily when dirty with no listeners).
613
+ * @returns the cached reference (stable until the next flush).
614
+ */
615
+ getSnapshot(): SessionSnapshot {
616
+ this.notifier.ensureFresh()
617
+ return this.snapshotCache
618
+ }
619
+
620
+ // ---- Manager-only entry points (@internal; never called by the UI) ----
621
+
622
+ /**
623
+ * Running-bit relay from the host stream (list entry and snapshot stay consistent).
624
+ * @param running - the new running state.
625
+ */
626
+ handleRunning(running: boolean): void {
627
+ // Running converts display state without establishing durable turn history.
628
+ if (running && this.blankBit) {
629
+ this.blankBit = false
630
+ this.notifier.markDirty()
631
+ }
632
+ if (running) this.firstPromptPendingTurn = false
633
+ if (this.running === running) return
634
+ this.running = running
635
+ this.notifier.markDirty()
636
+ }
637
+
638
+ /**
639
+ * Install or clear the catalog-discovered transport address. A changed
640
+ * address rebuilds an already-open window through its new history route.
641
+ * @param address - direct parent/child address, or undefined for ordinary transport.
642
+ */
643
+ configureSubagent(address: SubagentAddress | undefined): void {
644
+ const same = this.address?.parentSessionId === address?.parentSessionId
645
+ && this.address?.childSessionId === address?.childSessionId
646
+ && this.address?.mode === address?.mode
647
+ this.address = address
648
+ if (!same && this.openState !== 'cold') void this.resync()
649
+ else this.notifier.markDirty()
650
+ }
651
+
652
+ /**
653
+ * Apply the Manager's effective display blank, further reconciled with the
654
+ * current `sessionListMetadata` projection. Local send attempts and current
655
+ * running state prevent re-blanking; an earlier false summary alone does not.
656
+ * The Manager retains acceptance and earlier running observations across
657
+ * Session-object replacement.
658
+ * @param blank - New Session display state after Manager reconciliation.
659
+ */
660
+ handleBlank(blank: boolean): void {
661
+ blank = blank && this.projections.values().sessionListMetadata?.blank !== false
662
+ if (blank === this.blankBit) return
663
+ if (blank && (this.promptAttempted || this.running)) return
664
+ this.blankBit = blank
665
+ this.notifier.markDirty()
666
+ }
667
+
668
+ /** `api-session/removed` relay: flag the snapshot while retaining the resident instance. */
669
+ handleRemoved(): void {
670
+ this.removed = true
671
+ this.notifier.markDirty()
672
+ }
673
+
674
+ /**
675
+ * `api-session/error` relay: the outlet for live failures with no turn position.
676
+ * @param message - the stringified error.
677
+ */
678
+ handleAgentError(message: string): void {
679
+ this.lastAgentError = message
680
+ this.notifier.markDirty()
681
+ }
682
+
683
+ /**
684
+ * Stop the Session's live Remote source.
685
+ * @returns when the Remote iterator has completed teardown.
686
+ */
687
+ async dispose(): Promise<void> {
688
+ this.stopObservingInbox()
689
+ // Unsettled echoes retire as failed so their owners can restore or
690
+ // release browser resources; admitted echoes keep their observed outcome.
691
+ for (const [requestId, settlement] of [...this.submissionSettlements]) {
692
+ if (settlement.admitted !== undefined) this.scheduleObservedRetirement(requestId, settlement.admitted)
693
+ else this.retireFailedSubmission(requestId)
694
+ }
695
+ this.openGeneration++
696
+ this.clearOlderHistory()
697
+ const events = this.events
698
+ this.events = undefined
699
+ await events?.dispose()
700
+ }
701
+
702
+ // ---- Private ----
703
+
704
+ /** @param generation - openGeneration at launch; stale passes cannot publish after replacement. */
705
+ private async doOpen(generation: number): Promise<void> {
706
+ this.openState = 'loading'
707
+ this.openError = null
708
+ this.notifier.markDirty()
709
+ const events = new SessionEventStream(this.remote, this.sessionAddress(), {
710
+ publish: (change) => {
711
+ if (generation !== this.openGeneration || this.events !== events) return
712
+ this.acceptEventChange(change)
713
+ },
714
+ failed: (error) => {
715
+ this.failEventStream(events, generation, error)
716
+ },
717
+ })
718
+ this.events = events
719
+ try {
720
+ await events.open(HISTORY_PAGE_OPTIONS)
721
+ if (generation !== this.openGeneration || this.events !== events) return
722
+ this.openState = 'open'
723
+ } catch (error) {
724
+ if (generation !== this.openGeneration || this.events !== events) return
725
+ if (!isRemoteFailure(error)) throw error
726
+ this.events = undefined
727
+ this.openState = 'error'
728
+ this.openError = error
729
+ } finally {
730
+ if (generation === this.openGeneration) this.notifier.markDirty()
731
+ }
732
+ }
733
+
734
+ /** Apply one contiguous journal update already reconciled by the Remote stream. */
735
+ private acceptEventChange(change: SessionJournalChange): void {
736
+ switch (change.type) {
737
+ case 'replace':
738
+ this.installWindow(
739
+ change.entries,
740
+ change.hasMore,
741
+ change.page.projections === undefined ? undefined : projectionsBaseline(change.page.projections),
742
+ change.page.assistantStream,
743
+ )
744
+ return
745
+ case 'prepend':
746
+ if (this.olderRequest !== null) {
747
+ this.olderRequest.page = { entries: change.entries, hasMore: change.hasMore }
748
+ } else this.prependWindow(change.entries, change.hasMore)
749
+ return
750
+ case 'append':
751
+ this.publishAssistantEntry(this.assistantStream.acceptDurable(change.entry))
752
+ return
753
+ case 'assistant-stream':
754
+ this.publishAssistantEntry(this.assistantStream.acceptFrame(change.frame))
755
+ }
756
+ }
757
+
758
+ /** Replace the complete contiguous window and apply page-owned projection metadata. */
759
+ private installWindow(
760
+ entries: readonly SessionEventLikeEntry[],
761
+ hasMore: boolean,
762
+ projections?: ProjectionsBaseline,
763
+ assistantStream?: SessionAssistantStreamBaseline,
764
+ ): void {
765
+ // A durable gap-repair page has no assistant baseline. Clearing transient
766
+ // attempts makes a held notification reopen follow once for an atomic
767
+ // page/baseline pair instead of applying it to an unrelated repair cut.
768
+ const visible = this.assistantStream.replace(entries, assistantStream)
769
+ if (this.olderRequest !== null && this.loadingOlder && !this.olderRequest.recovering) {
770
+ this.olderRequest.invalidated = true
771
+ this.olderRequest.page = null
772
+ } else this.clearOlderHistory()
773
+ this.baseSeq = SessionLogOffset(entries[0]?.event.seq ?? 0)
774
+ this.hasMore = hasMore
775
+ this.historyWasPartial ||= hasMore
776
+ if (this.pendingHistory !== null) {
777
+ this.pendingHistory.beforeSeq = this.baseSeq
778
+ this.pendingHistory.hasMore = hasMore
779
+ this.pendingHistory.pages.length = 0
780
+ }
781
+ if (visible.some(entry => entry.event.type === 'turn/start')) this.firstPromptPendingTurn = false
782
+ if (projections !== undefined) this.projections.seed(projections)
783
+ this.eventSource.replace(visible, hasMore)
784
+ // A new follow baseline replaces confirmed optimistic inputs with Host-owned rows.
785
+ // Receipt-backed inputs are accepted, not failed, even if their history is outside this window.
786
+ if (projections !== undefined) {
787
+ for (const [requestId, { receipt }] of this.submissionSettlements) {
788
+ if (receipt !== undefined && receipt.seq <= projections.asOfSeq) {
789
+ this.scheduleObservedRetirement(requestId, receipt.attachments)
790
+ }
791
+ }
792
+ }
793
+ for (const entry of visible) this.observeSubmissionEvent(entry.event)
794
+ if (projections !== undefined) {
795
+ const inbox = projections.values.inbox as InboxState | undefined
796
+ for (const target of ['next-turn', 'next-step'] as const) {
797
+ this.observeSubmissionInsertions(target, inbox?.[target] ?? [], 0, projections.asOfSeq)
798
+ }
799
+ }
800
+ this.notifier.markDirty()
801
+ }
802
+
803
+ private publishAssistantEntry(result: ClientAssistantStreamResult): void {
804
+ if (result?.type === 'rebaseline') {
805
+ const events = this.events
806
+ queueMicrotask(() => {
807
+ if (events !== undefined && this.events === events) events.restart()
808
+ })
809
+ return
810
+ }
811
+ if (result?.type === 'settlement') {
812
+ this.eventSource.settleAssistant(result.attemptId, result.entry)
813
+ this.observeSubmissionEvent(result.entry.event)
814
+ this.notifier.markDirty()
815
+ return
816
+ }
817
+ if (result?.type === 'abandonment') {
818
+ this.eventSource.settleAssistant(result.attemptId)
819
+ this.notifier.markDirty()
820
+ return
821
+ }
822
+ if (result?.type === 'publish') {
823
+ const changed = this.appendLive(result.entry)
824
+ if (result.retireAttemptId !== undefined) this.eventSource.settleAssistant(result.retireAttemptId)
825
+ if (changed || result.retireAttemptId !== undefined) this.notifier.markDirty()
826
+ } else if (result?.type === 'transient') {
827
+ this.eventSource.append(result.entry)
828
+ this.notifier.markDirty()
829
+ }
830
+ }
831
+
832
+ /** Prepend one stream-validated history page. */
833
+ private prependWindow(entries: readonly SessionEventLikeEntry[], hasMore: boolean): void {
834
+ if (this.pendingHistory !== null) {
835
+ const pending = this.pendingHistory
836
+ pending.beforeSeq = entries[0] === undefined ? pending.beforeSeq : SessionLogOffset(entries[0].event.seq)
837
+ pending.hasMore = hasMore
838
+ pending.pages.push(entries)
839
+ return
840
+ }
841
+ this.baseSeq = entries[0] === undefined ? this.baseSeq : SessionLogOffset(entries[0].event.seq)
842
+ this.hasMore = hasMore
843
+ this.historyWasPartial ||= hasMore
844
+ this.eventSource.prepend(entries, hasMore)
845
+ }
846
+
847
+ /** Append one stream-validated live event. */
848
+ private appendLive(entry: SessionLiveEventEntry): boolean {
849
+ const event = entry.event
850
+ const awaitingFirstTurn = this.firstPromptPendingTurn
851
+ if (event.type === 'turn/start') this.firstPromptPendingTurn = false
852
+ this.eventSource.append(entry)
853
+ // After the feed append: the conversation assembly's animation frame is
854
+ // registered by the feed subscribers above, so the echo-retirement frame
855
+ // scheduled here always runs after the durable node became renderable.
856
+ this.observeSubmissionEvent(event)
857
+ return awaitingFirstTurn !== this.firstPromptPendingTurn
858
+ }
859
+
860
+ /** Observe durable acceptance even when insertion and claim share one projection notification. */
861
+ private observeSubmissionEvent(event: SessionEventLike): void {
862
+ if (this.submissionSettlements.size === 0) return
863
+ if (event.type === 'agent/inbox/spliced') {
864
+ const { target, start, removedCount = 0, inserted, outcome } = event.data
865
+ for (const [requestId, settlement] of this.submissionSettlements) {
866
+ const receipt = settlement.receipt
867
+ if (receipt?.target !== target || receipt.index === null || receipt.seq >= event.seq) continue
868
+ const removed = receipt.index >= start && receipt.index < start + removedCount
869
+ if (removed && outcome === 'canceled') this.retireFailedSubmission(requestId)
870
+ else settlement.receipt = {
871
+ ...receipt,
872
+ seq: event.seq,
873
+ index: removed ? null : receipt.index < start ? receipt.index : receipt.index + inserted.length - removedCount,
874
+ }
875
+ }
876
+ this.observeSubmissionInsertions(target, inserted, start, event.seq)
877
+ // A queued echo waits for the inbox projection the queue dock renders, which can arrive after this
878
+ // event; retiring it here would empty the dock for a frame. A claim in the same projection notification
879
+ // still retires it through the durable user message.
880
+ for (const message of inserted) this.observeSubmissionMessage(message, false, false)
881
+ return
882
+ }
883
+ if (event.type === 'request/context' || event.type === 'turn/end') {
884
+ for (const [requestId, settlement] of this.submissionSettlements) {
885
+ if (settlement.admitted === undefined && settlement.receipt?.index === null
886
+ && settlement.receipt.seq < event.seq) this.retireFailedSubmission(requestId)
887
+ }
888
+ return
889
+ }
890
+ if (event.type === 'user/message') this.observeSubmissionMessage(event.data, true)
891
+ }
892
+
893
+ private observeSubmissionInsertions(target: InboxTarget, messages: readonly UserMessage[], start: number, seq: number): void {
894
+ for (const [index, message] of messages.entries()) {
895
+ const source = message.source
896
+ if (source.kind !== 'user' || !('rpcId' in source)) continue
897
+ const settlement = this.submissionSettlements.get(source.rpcId)
898
+ if (settlement === undefined || settlement.retiring || (settlement.receipt?.seq ?? -1) > seq) continue
899
+ // Either proof accepts a prompt; an Inbox row can reach the Client before the prompt receipt. Later splices
900
+ // move the recorded position, so a canceled splice that removes the row retires its echo, queued ones
901
+ // included; a queued echo otherwise leaves once the queue dock renders its row or its message is admitted.
902
+ settlement.receipt = { target, seq, index: start + index, attachments: attachmentRefsIn(message.content) }
903
+ this.acceptPrompt(source.rpcId)
904
+ }
905
+ }
906
+
907
+ private observeSubmissionMessage(message: UserMessage, admitted: boolean, retireQueued = true): void {
908
+ const source = message.source
909
+ if (source.kind !== 'user' || !('rpcId' in source)) return
910
+ const settlement = this.submissionSettlements.get(source.rpcId)
911
+ if (settlement === undefined || settlement.retiring) return
912
+ if (!admitted) {
913
+ if (settlement.placement === 'queued' && retireQueued) {
914
+ this.scheduleObservedRetirement(source.rpcId, attachmentRefsIn(message.content))
915
+ }
916
+ return
917
+ }
918
+ settlement.admitted = attachmentRefsIn(message.content)
919
+ this.retireAdmittedSubmission(source.rpcId)
920
+ }
921
+
922
+ /** Retire admitted Chat identities only after stale Inbox rows can no longer reappear. */
923
+ private retireAdmittedSubmission(requestId: SessionRequestId): void {
924
+ const settlement = this.submissionSettlements.get(requestId)
925
+ if (settlement?.admitted === undefined) return
926
+ const receipt = settlement.receipt
927
+ if (receipt?.index === null
928
+ && (this.projections.seqOf('inbox') ?? -1) < receipt.seq) return
929
+ this.scheduleObservedRetirement(requestId, settlement.admitted)
930
+ }
931
+
932
+ /** Inbox acceptance retires queued echoes; its watermark completes admitted Chat handoffs. */
933
+ private observeSubmissionInbox(): void {
934
+ if (this.submissionSettlements.size === 0) return
935
+ const inbox = this.projections.get('inbox') as InboxState | undefined
936
+ if (inbox === undefined) return
937
+ const seq = this.projections.seqOf('inbox')
938
+ for (const target of ['next-turn', 'next-step'] as const) {
939
+ if (seq !== undefined) this.observeSubmissionInsertions(target, inbox[target], 0, seq)
940
+ for (const message of inbox[target]) this.observeSubmissionMessage(message, false)
941
+ }
942
+ for (const requestId of this.submissionSettlements.keys()) this.retireAdmittedSubmission(requestId)
943
+ }
944
+
945
+ /**
946
+ * Latch one observed settlement and remove the echo an animation frame
947
+ * later. The delay keeps the echo in the snapshot until the frame in which
948
+ * the durable node (whose assembly frame was registered first) is
949
+ * renderable; the render-time rpcId dedupe hides the one-frame overlap.
950
+ */
951
+ private scheduleObservedRetirement(
952
+ requestId: SessionRequestId,
953
+ attachments: readonly (ImageAttachmentRef | FileAttachmentRef)[],
954
+ ): void {
955
+ const settlement = this.submissionSettlements.get(requestId)
956
+ if (settlement === undefined || settlement.retiring) return
957
+ settlement.retiring = true
958
+ scheduleFrame(() => { this.finishSubmission(requestId, { reason: 'observed', attachments }) })
959
+ }
960
+
961
+ /** Remove one unsettled echo immediately (prompt rejection, abort, or disposal). */
962
+ private retireFailedSubmission(requestId: SessionRequestId): void {
963
+ const settlement = this.submissionSettlements.get(requestId)
964
+ if (settlement === undefined || settlement.retiring || settlement.admitted !== undefined) return
965
+ settlement.retiring = true
966
+ this.finishSubmission(requestId, { reason: 'failed' })
967
+ }
968
+
969
+ private refreshAcceptedSubmissions(): void {
970
+ this.acceptedSubmissions = this.pendingSubmissions
971
+ .filter(echo => this.submissionSettlements.get(echo.requestId)?.accepted === true)
972
+ }
973
+
974
+ /** Single removal point: drop the echo, publish, then notify the owner. */
975
+ private finishSubmission(requestId: SessionRequestId, retirement: PendingSubmissionRetirement): void {
976
+ const settlement = this.submissionSettlements.get(requestId)
977
+ /* v8 ignore next -- retiring latches before every schedule, so one settlement never finishes twice. */
978
+ if (settlement === undefined) return
979
+ this.submissionSettlements.delete(requestId)
980
+ this.pendingSubmissions = this.pendingSubmissions.filter(echo => echo.requestId !== requestId)
981
+ if (settlement.accepted) this.refreshAcceptedSubmissions()
982
+ this.notifier.markDirty()
983
+ settlement.onRetire?.(retirement)
984
+ }
985
+
986
+ /** Publish a terminal background failure only while this stream still owns the Session. */
987
+ private failEventStream(events: SessionEventStream, generation: number, error: unknown): void {
988
+ if (generation !== this.openGeneration || this.events !== events) return
989
+ if (!isRemoteFailure(error)) throw error
990
+ this.openGeneration++
991
+ this.clearOlderHistory()
992
+ this.events = undefined
993
+ this.openPromise = null
994
+ this.openState = 'error'
995
+ this.openError = error
996
+ void events.dispose()
997
+ this.notifier.markDirty()
998
+ }
999
+
1000
+ private buildSnapshot(): SessionSnapshot {
1001
+ const identity = this.projections.values().subagent
1002
+ return {
1003
+ sessionId: this.sessionId,
1004
+ pendingSubmissions: this.acceptedSubmissions,
1005
+ running: this.running,
1006
+ subagent: this.address === undefined
1007
+ ? null
1008
+ : {
1009
+ address: this.address.mode === 'unknown' && identity != null
1010
+ ? { ...this.address, mode: identity.mode }
1011
+ : this.address,
1012
+ },
1013
+ removed: this.removed,
1014
+ openState: this.openState,
1015
+ openError: this.openError,
1016
+ hasMore: this.hasMore,
1017
+ historyWasPartial: this.historyWasPartial,
1018
+ loadingOlder: this.loadingOlder,
1019
+ historyLoadStatus: this.historyLoadStatus,
1020
+ promptError: this.promptError,
1021
+ blank: this.blankBit,
1022
+ lastAgentError: this.lastAgentError,
1023
+ promptAttempted: this.promptAttempted,
1024
+ // The flag is set before the receipt; the Session leaves blank only once the Host accepted the prompt.
1025
+ awaitingFirstTurn: this.firstPromptPendingTurn && !this.blankBit,
1026
+ }
1027
+ }
1028
+
1029
+ private sessionAddress(): SessionAddress {
1030
+ return this.address === undefined
1031
+ ? { kind: 'session', sessionId: this.sessionId }
1032
+ : { kind: 'subagent', ...this.address }
1033
+ }
1034
+ }
1035
+
1036
+ /** Run one callback on the next animation frame, or a macrotask where no frame clock exists. */
1037
+ function scheduleFrame(fn: () => void): void {
1038
+ if (typeof requestAnimationFrame === 'function') requestAnimationFrame(() => { fn() })
1039
+ else setTimeout(fn, 0)
1040
+ }
1041
+
1042
+ /** Attachment references in one structurally-read content block list, in block order. */
1043
+ function attachmentRefsIn(content: unknown): readonly (ImageAttachmentRef | FileAttachmentRef)[] {
1044
+ if (!Array.isArray(content)) return []
1045
+ const refs: Array<ImageAttachmentRef | FileAttachmentRef> = []
1046
+ for (const block of content) {
1047
+ if (typeof block !== 'object' || block === null) continue
1048
+ const candidate = block as { readonly type?: unknown; readonly attachment?: unknown }
1049
+ if ((candidate.type === 'image' || candidate.type === 'file')
1050
+ && typeof candidate.attachment === 'object' && candidate.attachment !== null) {
1051
+ refs.push(candidate.attachment as ImageAttachmentRef | FileAttachmentRef)
1052
+ }
1053
+ }
1054
+ return refs
1055
+ }