@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,857 @@
1
+ /** Host catalog, durable projection caches, and explicitly retained Client instances. */
2
+
3
+ import type { SubagentAddress } from '@unieai/rabi-subagent/client'
4
+ import { SessionSeq, type SessionId, type SessionSeqCursor } from '@unieai/rabi-session/types'
5
+ import type { SessionProjectionMap, SessionProjectionViewValues } from '@unieai/rabi-session-projection/types'
6
+ import type { WorkspaceId } from '@unieai/rabi-workspace/types'
7
+ import type {
8
+ SessionControlBaseline,
9
+ SessionControlFrame,
10
+ SessionProjectionHints,
11
+ SessionRenameValue,
12
+ SessionSummary,
13
+ } from '../../types.ts'
14
+ import { mergeOrderedBaseline } from '../ordered-baseline.ts'
15
+ import { isRemoteFailure } from '@unieai/rabi-api-gateway/client'
16
+ import { assertNever } from '@unieai/rabi-util-values'
17
+ import type { RemoteFailure, RemoteResult } from '@unieai/rabi-typert-protocol'
18
+ import type { SessionListEntry, TitledSessionSummary } from './lineage.ts'
19
+ import { flattenLineage } from './lineage.ts'
20
+ // Type-only merge edge: the title domain's client-namespace outlet declares
21
+ // the 'title' projection key this manager projects into list rows (and any
22
+ // useProjection('title') consumer reads). Zero value imports by construction.
23
+ import type {} from '@unieai/rabi-session-title/client'
24
+ import { Notifier } from './notifier.ts'
25
+ import { ProjectionValueStore } from './projection-store.ts'
26
+ import { Session } from './session.ts'
27
+ import type { SessionRemotes } from './remotes.ts'
28
+ import type { SessionTarget } from '../contract/sessions.ts'
29
+
30
+ function sessionSeqCursor(value: number): SessionSeqCursor {
31
+ return value === -1 ? -1 : SessionSeq(value)
32
+ }
33
+
34
+ /**
35
+ * List arrival lifecycle, orthogonal to the pull-activity `state` axis:
36
+ * `pending` (no successful pull yet — an empty items array means "nothing
37
+ * arrived", not "nothing exists") → `ready` (at least one pull landed).
38
+ * Monotone: `ready` never steps back — later pull failures and reconnect
39
+ * re-pulls ride the `state`/`error` axis, which is where failure is modeled
40
+ * (no `error` phase here; that would duplicate `state`).
41
+ */
42
+ export type SessionListPhase = 'pending' | 'ready'
43
+
44
+ /** Request-local content hit returned to sidebar search consumers. */
45
+ export interface SessionSearchResultItem {
46
+ sessionId: SessionId
47
+ snippet: string
48
+ }
49
+
50
+ /** Immutable session-list snapshot for useSessionList. */
51
+ export interface SessionListSnapshot {
52
+ items: readonly SessionListEntry[]
53
+ state: 'idle' | 'loading' | 'error'
54
+ /** Arrival lifecycle (see {@link SessionListPhase}); `state` stays the pull-activity axis. */
55
+ phase: SessionListPhase
56
+ error: RemoteFailure | null
57
+ projectionsBySession: Readonly<Record<SessionId, SessionProjectionSnapshot>>
58
+
59
+ }
60
+
61
+ /**
62
+ * Every projection value the store currently holds, with the summary mark
63
+ * stripped, and the lifecycle of its explicit baseline read. This is the full
64
+ * attached-Session set, not a list row's summary contract (see
65
+ * `SessionListEntry.projectionValues`).
66
+ */
67
+ export interface SessionProjectionSnapshot {
68
+ readonly values: Readonly<Partial<SessionProjectionViewValues>>
69
+ readonly state: 'idle' | 'loading' | 'ready' | 'migration-required' | 'error'
70
+ readonly error: RemoteFailure | null
71
+ }
72
+
73
+ interface ProjectionInflight {
74
+ readonly promise: Promise<void>
75
+ readonly controller: AbortController
76
+ }
77
+
78
+ type ProjectionLoad = Omit<SessionProjectionSnapshot, 'values'>
79
+
80
+ type SessionListMutation =
81
+ | { kind: 'upsert' | 'placeholder'; summary: SessionSummary }
82
+ | { kind: 'remove'; sessionId: SessionId }
83
+ | { kind: 'status'; sessionId: SessionId; running: boolean; agentAvailable: boolean }
84
+ | { kind: 'activity'; sessionId: SessionId; updatedAt: number }
85
+ /** Local first-send flip: the sender clears blank without waiting for a host frame. */
86
+ | { kind: 'engaged'; sessionId: SessionId }
87
+
88
+ /** Instance cluster + frame entry + the session list. */
89
+ export class SessionManager {
90
+ private readonly sessions = new Map<SessionId, Session>()
91
+ /** In-flight Session disposals remain here after instances leave `sessions`, so manager disposal can await quiescence. */
92
+ private readonly sessionDisposals = new Set<Promise<void>>()
93
+ /**
94
+ * Accepted/running presentation must survive a later empty-history list
95
+ * response. Host-asserted running is recorded even before a row, instance, or
96
+ * address holds the identity — the listing that would hold it may not have
97
+ * landed yet — while the client-local acceptance callback requires a current
98
+ * holder, because it can arrive from a replaced or already-dropped Session.
99
+ */
100
+ private readonly engagedSessions = new Set<SessionId>()
101
+ private disposed = false
102
+ /** Per-session projection value stores, retained independently of instance arrival (the
103
+ * title-snapshot precedent, generalized): push frames land here whether or not the Session
104
+ * is instantiated (list rows read the 'title' key), and an instantiated Session adopts the
105
+ * same store so history-baseline seeding and frames converge on one row set. */
106
+ private readonly projectionStores = new Map<SessionId, ProjectionValueStore>()
107
+ private summaries: SessionSummary[] = []
108
+ private listState: 'idle' | 'loading' | 'error' = 'idle'
109
+ /** Arrival phase; the pending → ready edge fires on the first successful pull (see SessionListPhase). */
110
+ private listPhase: SessionListPhase = 'pending'
111
+ private listError: RemoteFailure | null = null
112
+ private listInflight: Promise<void> | null = null
113
+ /** Active list request's mutation log; its identity also fences completion after reconnect. */
114
+ private listMutations: SessionListMutation[] | null = null
115
+ private readonly addresses = new Map<SessionId, SubagentAddress>()
116
+ private readonly projectionLoads = new Map<SessionId, ProjectionLoad>()
117
+ private readonly projectionInflight = new Map<SessionId, ProjectionInflight>()
118
+
119
+
120
+ private listSnapshotCache: SessionListSnapshot
121
+ /** Entry-identity cache (reference stability): list rebuilds reuse the previous entry
122
+ * object when every field matches — wire refreshes mint all-new summary objects, so identity
123
+ * must be recovered by value or every SessionListItem memo misses on every refresh. */
124
+ private entryCache = new Map<SessionId, SessionListEntry>()
125
+ private itemsCache: readonly SessionListEntry[] = []
126
+ private readonly notifier = new Notifier(() => {
127
+ this.listSnapshotCache = this.buildListSnapshot()
128
+ })
129
+
130
+ /** @param remote - generated Remote namespaces used by catalog and history readers. */
131
+ constructor(private readonly remote: SessionRemotes) {
132
+ this.listSnapshotCache = this.buildListSnapshot()
133
+ }
134
+
135
+ /**
136
+ * Resolve an acquisition target without materializing a Session.
137
+ * @param target - known identity or durable direct-parent address.
138
+ * @returns the resolved identity with its explicit or catalog-derived history route installed.
139
+ */
140
+ resolveTarget(target: SessionTarget): SessionId {
141
+ const id = typeof target === 'string' ? target : target.childSessionId
142
+ const address = typeof target === 'string' ? this.subagentAddress(id) : target
143
+ if (typeof target === 'string'
144
+ && !this.sessions.has(id)
145
+ && !this.summaries.some(summary => summary.sessionId === id)
146
+ && address === undefined) {
147
+ throw new Error(`sessions.retain: unknown session ${id}`)
148
+ }
149
+ if (address !== undefined) this.addresses.set(id, address)
150
+ this.sessions.get(id)?.configureSubagent(address)
151
+ return id
152
+ }
153
+
154
+ /**
155
+ * Resolve an address for breadcrumb navigation without retaining transport authority.
156
+ * @param sessionId - possible child id in received Session metadata.
157
+ * @returns A retained address, then a catalog address, then an unknown-mode address
158
+ * from a listed subagent header; undefined without that evidence.
159
+ */
160
+ subagentAddress(sessionId: SessionId): SubagentAddress | undefined {
161
+ const retained = this.addresses.get(sessionId)
162
+ if (retained !== undefined) return retained
163
+ for (const parentSessionId of this.projectionStores.keys()) {
164
+ const child = this.projectionStores.get(parentSessionId)?.values().subagentCatalog
165
+ ?.find(entry => entry.id === sessionId)
166
+ if (child !== undefined && child.mode !== 'external') {
167
+ return {
168
+ parentSessionId,
169
+ childSessionId: sessionId,
170
+ mode: child.mode,
171
+ }
172
+ }
173
+ }
174
+ const summary = this.summaries.find(summary => summary.sessionId === sessionId)
175
+ if (summary?.origin !== 'subagent' || summary.parentSessionId === undefined) return undefined
176
+ return {
177
+ parentSessionId: summary.parentSessionId,
178
+ childSessionId: sessionId,
179
+ mode: 'unknown',
180
+ }
181
+ }
182
+
183
+ // ---- Instance management ----
184
+
185
+ /**
186
+ * Withdraw an exact Client instance before running its teardown callbacks.
187
+ * @param sessionId - identity to withdraw.
188
+ * @param expected - instance being released; a replacement is left untouched.
189
+ * @returns completion of the detached instance's stream teardown.
190
+ */
191
+ drop(sessionId: SessionId, expected: Session): Promise<void> {
192
+ const session = this.sessions.get(sessionId)
193
+ if (session !== expected) return Promise.resolve()
194
+ this.sessions.delete(sessionId)
195
+ this.addresses.delete(sessionId)
196
+ this.pruneEngagement(sessionId, this.retainedIds(this.summaries))
197
+ return this.startSessionDisposal(session)
198
+ }
199
+
200
+ /**
201
+ * Stop catalog requests and dispose every resident Session.
202
+ * @returns once catalog requests and every Session stream have stopped.
203
+ */
204
+ async dispose(): Promise<void> {
205
+ this.disposed = true
206
+ this.listMutations = null
207
+ this.listInflight = null
208
+ this.engagedSessions.clear()
209
+ const reads = [...this.projectionInflight.values()]
210
+ for (const { controller } of reads) controller.abort()
211
+ this.projectionInflight.clear()
212
+ await Promise.all(reads.map(read => read.promise))
213
+ const sessions = [...this.sessions.values()]
214
+ this.sessions.clear()
215
+ this.addresses.clear()
216
+ for (const session of sessions) void this.startSessionDisposal(session)
217
+ await this.drainSessionDisposals()
218
+ }
219
+
220
+ private startSessionDisposal(session: Session): Promise<void> {
221
+ const disposal = session.dispose()
222
+ this.sessionDisposals.add(disposal)
223
+ void disposal.then(
224
+ () => { this.sessionDisposals.delete(disposal) },
225
+ () => { this.sessionDisposals.delete(disposal) },
226
+ )
227
+ return disposal
228
+ }
229
+
230
+ private async drainSessionDisposals(): Promise<void> {
231
+ while (this.sessionDisposals.size > 0) {
232
+ await Promise.allSettled([...this.sessionDisposals])
233
+ }
234
+ }
235
+
236
+ /**
237
+ * Lazy build: return the existing instance or construct one (no auto-open —
238
+ * the reference allocator opens history after binding the scope).
239
+ * New instances reconcile retained metadata before returning.
240
+ * @param sessionId - the session to get.
241
+ * @returns the resident instance.
242
+ */
243
+ get(sessionId: SessionId): Session {
244
+ let session = this.sessions.get(sessionId)
245
+ if (session === undefined) {
246
+ session = this.createSession(sessionId)
247
+ this.sessions.set(sessionId, session)
248
+ // Sync the running and blank bits from the list snapshot into the new
249
+ // instance (consistency when the list precedes open).
250
+ const summary = this.summaries.find(s => s.sessionId === sessionId)
251
+ if (summary !== undefined) {
252
+ session.handleBlank(this.effectiveBlank(summary))
253
+ session.handleRunning(summary.running)
254
+ } else {
255
+ const address = this.addresses.get(sessionId)
256
+ const child = address === undefined ? undefined : this.projectionStores.get(address.parentSessionId)?.values().subagentCatalog
257
+ ?.find(entry => entry.id === sessionId)
258
+ if (child !== undefined && child.mode !== 'external') {
259
+ // A catalogued child exists only after its delegated session has
260
+ // durable history, even though child rows do not carry `blank`.
261
+ session.handleBlank(false)
262
+ session.handleRunning(false)
263
+ } else {
264
+ // Retained metadata may have notified before this Session existed.
265
+ session.handleBlank(true)
266
+ }
267
+ }
268
+ }
269
+ return session
270
+ }
271
+
272
+ private createSession(sessionId: SessionId): Session {
273
+ const address = this.addresses.get(sessionId)
274
+ return new Session(sessionId, this.remote, {
275
+ ...(address === undefined ? {} : { address }),
276
+ // The sender's local first-send flip mirrors into the list row so the
277
+ // session surfaces (lists filter on blank) before any host frame lands.
278
+ onEngaged: (engaged) => {
279
+ if (this.disposed || !this.retainedIds(this.summaries).has(engaged.sessionId)) return
280
+ // An identity already on the ledger needs no second row mutation.
281
+ if (!this.engagedSessions.has(engaged.sessionId)) {
282
+ this.engagedSessions.add(engaged.sessionId)
283
+ this.recordMutation({ kind: 'engaged', sessionId: engaged.sessionId })
284
+ }
285
+ this.sessions.get(engaged.sessionId)?.handleBlank(false)
286
+ },
287
+ projections: this.projectionStore(sessionId),
288
+ })
289
+ }
290
+
291
+ private effectiveBlank(summary: SessionSummary): boolean {
292
+ return summary.blank && !this.engagedSessions.has(summary.sessionId)
293
+ }
294
+
295
+ /**
296
+ * Identities an engagement may still belong to: the given list rows, resident
297
+ * Session instances, and retained child addresses.
298
+ * @param summaries - list rows of the caller's snapshot.
299
+ * @returns the retained identity set.
300
+ */
301
+ private retainedIds(summaries: readonly SessionSummary[]): Set<SessionId> {
302
+ const retained = new Set(summaries.map(summary => summary.sessionId))
303
+ for (const sessionId of this.sessions.keys()) retained.add(sessionId)
304
+ for (const sessionId of this.addresses.keys()) retained.add(sessionId)
305
+ return retained
306
+ }
307
+
308
+ /**
309
+ * Forget one engagement that no retained identity holds.
310
+ * @param sessionId - identity whose engagement may be dropped.
311
+ * @param retained - identities from {@link retainedIds} for the caller's snapshot.
312
+ */
313
+ private pruneEngagement(sessionId: SessionId, retained: ReadonlySet<SessionId>): void {
314
+ if (!retained.has(sessionId)) this.engagedSessions.delete(sessionId)
315
+ }
316
+
317
+ /** Resident per-session projection store (create-on-demand; outlives instantiation). */
318
+ private projectionStore(sessionId: SessionId): ProjectionValueStore {
319
+ let store = this.projectionStores.get(sessionId)
320
+ if (store === undefined) {
321
+ store = new ProjectionValueStore()
322
+ const projections = store
323
+ store.subscribeAny(() => {
324
+ // Newer history or control metadata corrects a resident Session's stale list hint.
325
+ if (projections.values().sessionListMetadata?.blank === false) {
326
+ this.sessions.get(sessionId)?.handleBlank(false)
327
+ }
328
+ this.notifier.markDirty()
329
+ })
330
+ this.projectionStores.set(sessionId, store)
331
+ }
332
+ return store
333
+ }
334
+
335
+ /**
336
+ * Read projections without starting migration; retry failed or migration-deferred reads.
337
+ * @param sessionId - Session to inspect without opening its conversation.
338
+ * @returns completion of the current or newly started read.
339
+ */
340
+ refreshProjections(sessionId: SessionId): Promise<void> {
341
+ const existing = this.projectionInflight.get(sessionId)
342
+ if (existing !== undefined) return existing.promise
343
+ if (this.projectionLoads.get(sessionId)?.state === 'ready') return Promise.resolve()
344
+ const controller = new AbortController()
345
+ const store = this.projectionStore(sessionId)
346
+ const initialValues = store.values()
347
+ this.projectionLoads.set(sessionId, { state: 'loading', error: null })
348
+ this.notifier.markDirty()
349
+ const operation = (async () => {
350
+ try {
351
+ const result = await this.remote.session.projections({ sessionId }, controller.signal)
352
+ if (controller.signal.aborted) return
353
+ if (result.ok) {
354
+ const value = result.value
355
+ if (value !== null) {
356
+ switch (value.kind) {
357
+ case 'sequenced':
358
+ store.seed({ values: value.values, asOfSeq: sessionSeqCursor(value.asOfSeq) })
359
+ break
360
+ case 'migration-required':
361
+ store.applyCached(value.values)
362
+ break
363
+ default:
364
+ assertNever(value, 'session projections result')
365
+ }
366
+ } else if (store.values() === initialValues) {
367
+ // A later frame proves existence independently of an earlier missing read.
368
+ store.clear()
369
+ }
370
+ this.projectionLoads.set(sessionId, {
371
+ state: value?.kind === 'migration-required' ? 'migration-required' : 'ready',
372
+ error: null,
373
+ })
374
+ } else {
375
+ this.projectionLoads.set(sessionId, { state: 'error', error: result.error })
376
+ }
377
+ } catch (error: unknown) {
378
+ if (controller.signal.aborted) return
379
+ if (!isRemoteFailure(error)) throw error
380
+ this.projectionLoads.set(sessionId, { state: 'error', error })
381
+ } finally {
382
+ if (!controller.signal.aborted) {
383
+ this.projectionInflight.delete(sessionId)
384
+ this.notifier.markDirty()
385
+ }
386
+ }
387
+ })()
388
+ this.projectionInflight.set(sessionId, { promise: operation, controller })
389
+ return operation
390
+ }
391
+
392
+ // ---- List API ----
393
+
394
+ /** Full refresh via session.list (single-flight within one Host generation). */
395
+ refreshList(): Promise<void> {
396
+ if (this.listInflight !== null) return this.listInflight
397
+ this.listState = 'loading'
398
+ this.listError = null
399
+ const established = this.summaries
400
+ const mutations: SessionListMutation[] = []
401
+ this.listMutations = mutations
402
+ this.notifier.markDirty()
403
+ this.listInflight = (async () => {
404
+ try {
405
+ const result = await this.remote.session.list({})
406
+ if (this.listMutations !== mutations) return
407
+ if (result.ok) {
408
+ const baseline: SessionSummary[] = this.listPhase === 'pending'
409
+ ? [...result.value.items]
410
+ : mergeOrderedBaseline(established, result.value.items, summary => summary.sessionId)
411
+ // A removal supersedes running observed in the pull, including after re-addition.
412
+ const removedSincePull = new Set<SessionId>()
413
+ for (const mutation of mutations) {
414
+ if (mutation.kind === 'remove') removedSincePull.add(mutation.sessionId)
415
+ }
416
+ for (const s of baseline) {
417
+ if (s.running && !removedSincePull.has(s.sessionId)) this.engagedSessions.add(s.sessionId)
418
+ }
419
+ const summaries = mutations.reduce(applyMutation, baseline)
420
+ this.summaries = summaries
421
+ // A full list can remove identities without a removal frame.
422
+ const retained = this.retainedIds(summaries)
423
+ for (const sessionId of this.engagedSessions) this.pruneEngagement(sessionId, retained)
424
+ this.listState = 'idle'
425
+ this.listPhase = 'ready'
426
+
427
+ // Resident Sessions and list rows share one display blank, reconciled with the metadata projection.
428
+ for (const s of this.summaries) {
429
+ const session = this.sessions.get(s.sessionId)
430
+ if (session === undefined) continue
431
+ session.handleBlank(this.effectiveBlank(s))
432
+ session.handleRunning(s.running)
433
+ }
434
+ // Land each row's projection block in the per-session value store
435
+ // (cold titles surface without opening the session). A list block is
436
+ // partial — only the keys its source holds — so an absent key never
437
+ // clears; how the present keys merge depends on the block's kind.
438
+ for (const s of result.value.items) {
439
+ if (s.projections !== undefined) this.applyListBlock(s.sessionId, s.projections)
440
+ }
441
+ } else {
442
+ this.listState = 'error'
443
+ this.listError = result.error
444
+ }
445
+ } catch (error) {
446
+ if (!isRemoteFailure(error)) throw error
447
+ if (this.listMutations !== mutations) return
448
+ this.listState = 'error'
449
+ this.listError = error
450
+ } finally {
451
+ if (this.listMutations === mutations) {
452
+ this.listMutations = null
453
+ this.listInflight = null
454
+ this.notifier.markDirty()
455
+ }
456
+ }
457
+ })()
458
+ return this.listInflight
459
+ }
460
+
461
+ /**
462
+ * Search visible session message content without adding transient query
463
+ * state to the list snapshot.
464
+ * @param query - non-blank literal phrase.
465
+ * @param signal - cancellation for superseded UI queries.
466
+ * @returns the Host result or a folded transport error.
467
+ */
468
+ async search(
469
+ query: string,
470
+ signal: AbortSignal,
471
+ ): Promise<RemoteResult<{ items: SessionSearchResultItem[]; hasMore: boolean }>> {
472
+ const result = await this.remote.session.search({ query }, signal)
473
+ if (!result.ok) return result
474
+ return {
475
+ ok: true,
476
+ value: {
477
+ items: [...result.value.items],
478
+ hasMore: result.value.hasMore,
479
+ },
480
+ }
481
+ }
482
+
483
+ /**
484
+ * Contract session.create; on success merge into summaries immediately (no
485
+ * wait for the next refresh). A created session is blank by definition
486
+ * (entity birth precedes the first message).
487
+ * @param opts - target workspace or working directory, an optional blank Session to reuse, and an optional Agent preset.
488
+ * @returns the create result, naming the Session the Host created or reused.
489
+ */
490
+ async create(
491
+ opts: {
492
+ workspaceId?: WorkspaceId
493
+ cwd?: string
494
+ sessionId?: SessionId
495
+ agentPreset?: string
496
+ } = {},
497
+ ): Promise<RemoteResult<{ sessionId: SessionId }>> {
498
+ const shared = {
499
+ ...(opts.sessionId === undefined ? {} : { sessionId: opts.sessionId }),
500
+ ...(opts.agentPreset === undefined ? {} : { agentPreset: opts.agentPreset }),
501
+ }
502
+ const payload = opts.workspaceId !== undefined
503
+ ? { workspaceId: opts.workspaceId, ...shared }
504
+ : { ...(opts.cwd === undefined ? {} : { cwd: opts.cwd }), ...shared }
505
+ const result = await this.remote.session.create(payload)
506
+ if (result.ok) {
507
+ this.recordMutation({ kind: 'placeholder', summary: { agentAvailable: true,
508
+ sessionId: result.value.sessionId, updatedAt: Date.now(), running: false, blank: true,
509
+ ...(opts.cwd !== undefined ? { cwd: opts.cwd } : {}),
510
+ } })
511
+ } else {
512
+ const publishedSessionId = workspaceAttachSessionId(result.error)
513
+ // Publication precedes attachment. The error's id is a real Session,
514
+ // so expose it immediately as Ungrouped while the caller keeps the
515
+ // prompt buffer and decides whether to retry attachment.
516
+ if (publishedSessionId !== undefined) {
517
+ this.recordMutation({ kind: 'placeholder', summary: { agentAvailable: true,
518
+ sessionId: publishedSessionId,
519
+ updatedAt: Date.now(),
520
+ running: false,
521
+ blank: true,
522
+ } })
523
+ }
524
+ }
525
+ return result
526
+ }
527
+
528
+ /**
529
+ * Contract session.fork; on success merge the child into summaries
530
+ * immediately (same synchronous-addressability guarantee as create).
531
+ * Blankness starts provisionally true so the authoritative Host summary can
532
+ * preserve it or lower it after an exact cut before the first `turn/start`;
533
+ * the fork has no durable source relationship. A child published before Workspace
534
+ * attachment fails is also reconciled into the list.
535
+ * @param opts - source session, optional exact inclusive boundary seq, and permission to start migration.
536
+ * @returns the fork result (the child session id).
537
+ */
538
+ async fork(
539
+ opts: { sessionId: SessionId; atSeq?: SessionSeq; allowMigration?: boolean },
540
+ ): Promise<RemoteResult<{ sessionId: SessionId }>> {
541
+ const source = this.summaries.find(s => s.sessionId === opts.sessionId)
542
+ const result = await this.remote.session.fork({
543
+ sessionId: opts.sessionId,
544
+ ...opts.atSeq === undefined ? {} : { atSeq: opts.atSeq },
545
+ ...opts.allowMigration === undefined ? {} : { allowMigration: opts.allowMigration },
546
+ })
547
+ const childId = result.ok
548
+ ? result.value.sessionId
549
+ : workspaceAttachSessionId(result.error)
550
+ if (childId !== undefined) {
551
+ this.recordMutation({ kind: 'placeholder', summary: { agentAvailable: true,
552
+ sessionId: childId, updatedAt: Date.now(), running: false, blank: true,
553
+ ...(source?.cwd !== undefined ? { cwd: source.cwd } : {}),
554
+ } })
555
+ }
556
+ return result
557
+ }
558
+
559
+ /**
560
+ * Rename a Session and update its title projection without opening its history.
561
+ * @param sessionId - Session to rename.
562
+ * @param title - raw title text for Host normalization.
563
+ * @returns the accepted title and event position, or the Remote failure.
564
+ */
565
+ async rename(sessionId: SessionId, title: string): Promise<RemoteResult<SessionRenameValue>> {
566
+ const result = await this.remote.session.rename({ sessionId, title })
567
+ if (result.ok) {
568
+ this.projectionStore(sessionId).apply('title', result.value.title, SessionSeq(result.value.seq))
569
+ }
570
+ return result
571
+ }
572
+
573
+ /**
574
+ * Merge a Host summary, replacing live state and filling missing metadata.
575
+ * Local create/fork placeholders only fill metadata on an existing row.
576
+ */
577
+ private mergeSummary(summary: SessionSummary): void {
578
+ this.recordMutation({ kind: 'upsert', summary })
579
+ }
580
+
581
+ /** Apply immediately and retain for replay when a list response is in flight. */
582
+ private recordMutation(mutation: SessionListMutation): void {
583
+ if (this.disposed) return
584
+ this.listMutations?.push(mutation)
585
+ this.summaries = applyMutation(this.summaries, mutation)
586
+ this.notifier.markDirty()
587
+ }
588
+
589
+ // ---- Subscription API (for useSessionList) ----
590
+
591
+ /**
592
+ * uSES subscription entry for useSessionList.
593
+ * @param listener - change callback.
594
+ * @returns the unsubscribe function.
595
+ */
596
+ subscribe(listener: () => void): () => void {
597
+ return this.notifier.subscribe(listener)
598
+ }
599
+
600
+ /**
601
+ * Cached list snapshot (rebuilt lazily when dirty with no listeners).
602
+ * @returns the cached reference (stable until the next flush).
603
+ */
604
+ getListSnapshot(): SessionListSnapshot {
605
+ this.notifier.ensureFresh()
606
+ return this.listSnapshotCache
607
+ }
608
+
609
+ /**
610
+ * Read cached projection values for a Session that may exist only in a loaded subagent catalog.
611
+ * @param sessionId - Session whose control or history baseline supplied projections.
612
+ * @returns current values, or undefined before any projection store exists.
613
+ */
614
+ projectionValues(sessionId: SessionId): Readonly<Partial<SessionProjectionMap>> | undefined {
615
+ return this.projectionStores.get(sessionId)?.values()
616
+ }
617
+
618
+ // ---- Live control and Host-event sinks ----
619
+
620
+ /**
621
+ * Apply a complete control baseline or one later per-event projection frame.
622
+ * @param frame - baseline or live per-event projection change from Session Controller.
623
+ */
624
+ handleControlFrame(frame: SessionControlFrame): void {
625
+ if (frame.type === 'baseline') {
626
+ this.replaceControlBaseline(frame.value)
627
+ return
628
+ }
629
+ const store = this.projectionStore(frame.sessionId)
630
+ const seq = SessionSeq(frame.seq)
631
+ for (const change of frame.changes) store.apply(change.key, change.val, seq)
632
+ this.notifier.markDirty()
633
+ }
634
+
635
+ private replaceControlBaseline(baseline: SessionControlBaseline): void {
636
+
637
+ for (const [sessionId, block] of Object.entries(baseline.projections)) {
638
+ const store = this.projectionStore(sessionId as SessionId)
639
+ const asOfSeq = sessionSeqCursor(block.asOfSeq)
640
+ store.seed({ ...block, asOfSeq })
641
+ }
642
+ this.notifier.markDirty()
643
+ }
644
+
645
+ /**
646
+ * Apply one Session-list addition forwarded through `ctx.remote.$on`.
647
+ * @param summary - current Host summary for the added Session.
648
+ */
649
+ handleSessionAdded(summary: SessionSummary): void {
650
+ this.mergeSummary(summary)
651
+ if (!this.disposed && summary.running) this.engagedSessions.add(summary.sessionId)
652
+ this.sessions.get(summary.sessionId)?.handleBlank(this.effectiveBlank(summary))
653
+ if (summary.projections !== undefined) this.applyListBlock(summary.sessionId, summary.projections)
654
+ }
655
+
656
+ /**
657
+ * Merge one list-surface projection block by the sequence space it declares.
658
+ * A `sequenced` block came from the Host's live registry for an attached
659
+ * Session, so each key lands under higher-seq-wins against that Session's
660
+ * baselines and frames. A `cached` block was viewed from the persisted
661
+ * checkpoint by a header-only listing: its watermark is not comparable with
662
+ * this connection's seqs, so it only fills keys no sequenced row holds.
663
+ */
664
+ private applyListBlock(sessionId: SessionId, block: SessionProjectionHints): void {
665
+ const store = this.projectionStore(sessionId)
666
+ switch (block.kind) {
667
+ case 'sequenced': {
668
+ const seq = sessionSeqCursor(block.asOfSeq)
669
+ for (const [key, value] of Object.entries(block.values)) store.apply(key, value, seq)
670
+ return
671
+ }
672
+ case 'cached':
673
+ store.applyCached(block.values)
674
+ return
675
+ default:
676
+ assertNever(block.kind, 'session list projection block kind')
677
+ }
678
+ }
679
+
680
+ /**
681
+ * Apply one Session removal forwarded through `ctx.remote.$on`.
682
+ * @param sessionId - removed Session identity.
683
+ */
684
+ handleSessionRemoved(sessionId: SessionId): void {
685
+ const durableSubagent = this.subagentAddress(sessionId) !== undefined
686
+ || this.summaries.some(summary => summary.sessionId === sessionId && summary.origin === 'subagent')
687
+ this.recordMutation(durableSubagent
688
+ ? { kind: 'status', sessionId, running: false, agentAvailable: false }
689
+ : { kind: 'remove', sessionId })
690
+ if (durableSubagent) this.sessions.get(sessionId)?.handleRunning(false)
691
+ else this.sessions.get(sessionId)?.handleRemoved()
692
+ const catalog = this.projectionStores.get(sessionId)?.values().subagentCatalog
693
+ if (!durableSubagent && (catalog === undefined || catalog.length === 0)) {
694
+ this.projectionStores.delete(sessionId)
695
+ }
696
+ this.pruneEngagement(sessionId, this.retainedIds(this.summaries))
697
+ this.projectionInflight.get(sessionId)?.controller.abort()
698
+ this.projectionInflight.delete(sessionId)
699
+ this.projectionLoads.delete(sessionId)
700
+ }
701
+
702
+ /**
703
+ * Apply one live Agent running-state change.
704
+ * @param sessionId - Session whose Agent state changed.
705
+ * @param running - current Agent running state.
706
+ */
707
+ handleSessionStatus(sessionId: SessionId, running: boolean): void {
708
+ if (!this.disposed && running) this.engagedSessions.add(sessionId)
709
+ this.recordMutation({ kind: 'status', sessionId, running, agentAvailable: true })
710
+ this.sessions.get(sessionId)?.handleRunning(running)
711
+ }
712
+
713
+ /**
714
+ * Advance Session-list activity from one user-authored durable message.
715
+ * @param sessionId - Session whose activity changed.
716
+ * @param updatedAt - durable message timestamp.
717
+ */
718
+ handleSessionActivity(sessionId: SessionId, updatedAt: number): void {
719
+ this.recordMutation({ kind: 'activity', sessionId, updatedAt })
720
+ }
721
+
722
+ /**
723
+ * Surface one live Agent failure on an already-materialized Session.
724
+ * @param sessionId - Session whose Agent failed.
725
+ * @param message - caller-visible failure description.
726
+ */
727
+ handleSessionError(sessionId: SessionId, message: string): void {
728
+ this.sessions.get(sessionId)?.handleAgentError(message)
729
+ }
730
+
731
+ /**
732
+ * Repair one re-established Host-event generation with queryable baselines.
733
+ * Discard old projection cuts before new queries, including cold Sessions
734
+ * absent from the process-local control baseline.
735
+ * Opened Session follow streams resume independently through API Gateway.
736
+ */
737
+ handleConnected(): void {
738
+ for (const store of this.projectionStores.values()) store.clear()
739
+ this.listMutations = null
740
+ this.listInflight = null
741
+ void this.refreshList()
742
+ const parents = new Set(this.projectionLoads.keys())
743
+ for (const id of this.sessions.keys()) {
744
+ const address = this.addresses.get(id)
745
+ if (address !== undefined) parents.add(address.parentSessionId)
746
+ }
747
+ for (const { controller } of this.projectionInflight.values()) controller.abort()
748
+ this.projectionInflight.clear()
749
+ this.projectionLoads.clear()
750
+ for (const parentSessionId of parents) void this.refreshProjections(parentSessionId)
751
+ }
752
+
753
+ private buildListSnapshot(): SessionListSnapshot {
754
+ const merged: TitledSessionSummary[] = this.summaries.map((summary) => {
755
+ // List rows read the generic 'title' projection key (host-computed unit
756
+ // value; there is no dedicated title frame).
757
+ const projectionStore = this.projectionStores.get(summary.sessionId)
758
+ const title = projectionStore?.get('title')
759
+ const projectionValues = projectionStore?.values()
760
+ const metadata = projectionValues?.sessionListMetadata
761
+ return {
762
+ ...summary,
763
+ // Cached list hints can precede a history opening or control update.
764
+ blank: this.effectiveBlank(summary) && metadata?.blank !== false,
765
+ updatedAt: Math.max(summary.updatedAt, metadata?.lastPromptAt ?? 0),
766
+ ...(typeof title === 'string' && title !== '' ? { title } : {}),
767
+ ...(projectionValues === undefined ? {} : { projectionValues }),
768
+ }
769
+ })
770
+ const fresh = flattenLineage(merged)
771
+ const items = fresh.map((entry) => {
772
+ const prev = this.entryCache.get(entry.sessionId)
773
+ if (
774
+ prev !== undefined && prev.updatedAt === entry.updatedAt && prev.running === entry.running
775
+ && prev.blank === entry.blank
776
+ && prev.parentSessionId === entry.parentSessionId && prev.cwd === entry.cwd
777
+ && prev.origin === entry.origin && prev.title === entry.title && prev.depth === entry.depth
778
+ && prev.formatStatus === entry.formatStatus
779
+ && prev.projectionValues === entry.projectionValues
780
+ ) return prev
781
+ this.entryCache.set(entry.sessionId, entry)
782
+ return entry
783
+ })
784
+ const itemIds = new Set(items.map(entry => entry.sessionId))
785
+ for (const id of this.entryCache.keys()) {
786
+ if (!itemIds.has(id)) this.entryCache.delete(id)
787
+ }
788
+ const sameOrder = items.length === this.itemsCache.length && items.every((e, i) => e === this.itemsCache[i])
789
+ if (!sameOrder) this.itemsCache = items
790
+ return {
791
+ items: this.itemsCache,
792
+ state: this.listState,
793
+ phase: this.listPhase,
794
+ error: this.listError,
795
+ projectionsBySession: Object.fromEntries([...this.projectionStores].map(([sessionId, store]) => [
796
+ sessionId,
797
+ { values: store.values(), state: 'idle', error: null, ...this.projectionLoads.get(sessionId) },
798
+ ])),
799
+ }
800
+ }
801
+ }
802
+
803
+ /** Apply one list mutation without deriving display order. */
804
+ function applyMutation(summaries: readonly SessionSummary[], mutation: SessionListMutation): SessionSummary[] {
805
+ switch (mutation.kind) {
806
+ case 'upsert':
807
+ case 'placeholder': {
808
+ const existing = summaries.find(summary => summary.sessionId === mutation.summary.sessionId)
809
+ if (existing === undefined) return [mutation.summary, ...summaries]
810
+ const filled: SessionSummary = {
811
+ ...existing,
812
+ // Blank only lowers: a stale true (session-added racing the local
813
+ // first send) never re-hides an already-surfaced session.
814
+ blank: existing.blank && mutation.summary.blank,
815
+ ...(mutation.kind === 'upsert' ? {
816
+ agentAvailable: mutation.summary.agentAvailable,
817
+ running: mutation.summary.running,
818
+ ...(mutation.summary.formatStatus === undefined ? {} : { formatStatus: mutation.summary.formatStatus }),
819
+ } : {}),
820
+ ...(existing.cwd === undefined && mutation.summary.cwd !== undefined ? { cwd: mutation.summary.cwd } : {}),
821
+ ...(existing.parentSessionId === undefined && mutation.summary.parentSessionId !== undefined
822
+ ? { parentSessionId: mutation.summary.parentSessionId } : {}),
823
+ ...(existing.origin === undefined && mutation.summary.origin !== undefined
824
+ ? { origin: mutation.summary.origin } : {}),
825
+ }
826
+ if (filled.cwd === existing.cwd && filled.parentSessionId === existing.parentSessionId
827
+ && filled.origin === existing.origin && filled.blank === existing.blank
828
+ && filled.agentAvailable === existing.agentAvailable && filled.running === existing.running
829
+ && filled.formatStatus === existing.formatStatus
830
+ ) return [...summaries]
831
+ return summaries.map(summary => summary.sessionId === mutation.summary.sessionId ? filled : summary)
832
+ }
833
+ case 'remove':
834
+ return summaries.filter(summary => summary.sessionId !== mutation.sessionId)
835
+ case 'status':
836
+ // Running converts display state; it does not establish durable history.
837
+ return summaries.map(summary => summary.sessionId === mutation.sessionId
838
+ && (summary.running !== mutation.running
839
+ || summary.agentAvailable !== mutation.agentAvailable || (mutation.running && summary.blank))
840
+ ? { ...summary, running: mutation.running, agentAvailable: mutation.agentAvailable, blank: summary.blank && !mutation.running }
841
+ : summary)
842
+ case 'activity':
843
+ return summaries.map(summary => summary.sessionId === mutation.sessionId
844
+ && mutation.updatedAt > summary.updatedAt
845
+ ? { ...summary, updatedAt: mutation.updatedAt }
846
+ : summary)
847
+ case 'engaged':
848
+ return summaries.map(summary => summary.sessionId === mutation.sessionId && summary.blank
849
+ ? { ...summary, blank: false }
850
+ : summary)
851
+ }
852
+ }
853
+
854
+ /** Temporary source-plane bridge while the Host contract and client project build independently. */
855
+ function workspaceAttachSessionId(error: RemoteFailure): SessionId | undefined {
856
+ return error.code === 'session/workspace-attach-failed' ? error.details.sessionId : undefined
857
+ }