@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,741 @@
1
+ /** Client catalog and source-labelled ownership of exact Session generations. */
2
+ import type { Context, Fiber } from '@unieai/cordis'
3
+ import type { SubagentAddress } from '@unieai/rabi-subagent/client'
4
+ import { SessionSeq, type SessionId } from '@unieai/rabi-session/types'
5
+ import { workspaceTitleOf } from '@unieai/rabi-util-workspace-path'
6
+ import type { WorkspaceId } from '@unieai/rabi-workspace/types'
7
+ import { SESSION_SEARCH_RESULT_LIMIT } from '../../types.ts'
8
+ import type { SessionProjectionSummaryValues } from '@unieai/rabi-session-projection/types'
9
+ import {
10
+ createSnapshotStore, notifySubscribers, type ObservableSnapshot, type SnapshotStore,
11
+ } from '@unieai/rabi-client-store'
12
+ import type { RemoteFailure, RemoteResult } from '@unieai/rabi-typert-protocol'
13
+ import type { SessionEventSource } from '../contract/events.ts'
14
+ import type { SessionFace } from '../contract/session.ts'
15
+ import type {
16
+ AgentContext, ISessions, SessionReference, SessionRetainInfo, SessionRetainOptions, SessionTarget,
17
+ } from '../contract/sessions.ts'
18
+ import type { SessionReferenceSource } from '../index.ts'
19
+ import { createScope, scopeIdentityOf, scopeOf as scopeTagOf } from '../scope.ts'
20
+ import { SessionManager } from './manager.ts'
21
+ import type { SessionRemotes } from './remotes.ts'
22
+ import type { SessionListPhase, SessionSearchResultItem, SessionProjectionSnapshot } from './manager.ts'
23
+ import type { Session } from './session.ts'
24
+ import type { SessionListEntry } from './lineage.ts'
25
+
26
+ /** Session list row projected from the host list RPC plus live stream increments. */
27
+ export interface SessionSummary {
28
+ id: SessionId
29
+ /** Latest durable log-backed title, absent until the host projects one. */
30
+ title?: string
31
+ /** Human-facing label: durable title, project basename, then session id. */
32
+ displayTitle: string
33
+ cwd?: string
34
+ parentId?: SessionId
35
+ /** Coarse durable origin for navigation filtering; not a continuation capability. */
36
+ origin?: 'subagent'
37
+ /** Format classification supplied by the Host list, when available. */
38
+ formatStatus?: SessionListEntry['formatStatus']
39
+ /** Host running state for `ids` members; a display fallback for other rows. */
40
+ running: boolean
41
+ /** Local ownership counts; Host metadata refreshes cannot overwrite them. */
42
+ readonly retainedBy: SessionRetainInfo['retainedBy']
43
+ /**
44
+ * New Session presentation and reuse eligibility, derived from the Host
45
+ * summary, `sessionListMetadata`, and client acceptance/running observations.
46
+ * New Session and Workspace reconnection may reuse a blank in the same workspace. Filtering
47
+ * stays with the consumer: the store carries every row, while the Workspace
48
+ * browser shows only the selected blank entry.
49
+ */
50
+ blank: boolean
51
+ updatedAt: number
52
+ /**
53
+ * The row's summary projection values retained by the object layer, never the
54
+ * full projection set. A connected Session's store may hold more values from
55
+ * its control/follow baseline; those are outside the list contract.
56
+ */
57
+ projectionValues?: Readonly<Partial<SessionProjectionSummaryValues>>
58
+ }
59
+
60
+ /** Catalog metadata and local source counts; catalog membership owns no Client generation. */
61
+ export interface SessionListState {
62
+ /** Host list order; every id has a matching byId row in the same snapshot. */
63
+ ids: SessionId[]
64
+ /** Host/catalog rows plus retained subagent fallbacks; only `ids` expresses Host-list membership. */
65
+ byId: Record<SessionId, SessionSummary>
66
+ /** Arrival lifecycle projected 1:1 from the manager snapshot (see SessionListPhase): empty-with-ready means "truly no sessions". */
67
+ phase: SessionListPhase
68
+ /** Shared projection values and explicit-read state, including unopened Sessions. */
69
+ projectionsBySession: Readonly<Record<SessionId, SessionProjectionSnapshot>>
70
+ }
71
+
72
+ /** Structured session-create failure. */
73
+ export class SessionCreateError extends Error {
74
+ override readonly name = 'SessionCreateError'
75
+
76
+ /**
77
+ * @param rpcError - Host business or folded transport error.
78
+ * @param requestedSessionId - caller-preallocated id used for later stream/list reconciliation.
79
+ */
80
+ constructor(
81
+ readonly rpcError: RemoteFailure,
82
+ readonly requestedSessionId: SessionId | undefined,
83
+ ) {
84
+ super(`session create failed: ${rpcError.code}: ${rpcError.message}`)
85
+ }
86
+ }
87
+
88
+ /** Structured session-fork failure. */
89
+ export class SessionForkError extends Error {
90
+ override readonly name = 'SessionForkError'
91
+
92
+ /**
93
+ * @param rpcError - Host business or folded transport error.
94
+ * @param sourceSessionId - the session the fork was cut from.
95
+ */
96
+ constructor(
97
+ readonly rpcError: RemoteFailure,
98
+ readonly sourceSessionId: SessionId,
99
+ ) {
100
+ super(`session fork failed: ${rpcError.code}: ${rpcError.message}`)
101
+ }
102
+ }
103
+
104
+ /** Identity-stable logical binding for one materialized Client Session. */
105
+ export interface SessionBinding {
106
+ readonly sessionId: SessionId
107
+ /** The outward session face only — feature code never sees the concrete class. */
108
+ readonly session: SessionFace
109
+ /** Contiguous event window reserved for Conversation assembly. */
110
+ readonly eventSource: SessionEventSource
111
+ readonly ctx: AgentContext
112
+ }
113
+
114
+ // Scope primitives live in ../scope.ts (the client mirror of host
115
+ // rabi-scope, keyed by Agent identity); re-exported here so existing
116
+ // consumers keep their import site.
117
+ export { scopeOf } from '../scope.ts'
118
+
119
+ /**
120
+ * Display title projection: durable title, project directory basename, then
121
+ * the raw id.
122
+ */
123
+ function displayTitleOf(title: string | undefined, cwd: string | undefined, id: SessionId): string {
124
+ if (title !== undefined) return title
125
+ if (cwd !== undefined && cwd !== '') {
126
+ const base = workspaceTitleOf(cwd)
127
+ if (base !== '') return base
128
+ }
129
+ return id
130
+ }
131
+
132
+ /**
133
+ * Increment the fork number until the candidate is not taken.
134
+ * @param title - source session's durable title.
135
+ * @param taken - durable titles of Host-listed sessions.
136
+ * @returns the title assigned to the fork child.
137
+ */
138
+ function increasedForkTitle(title: string, taken: ReadonlySet<string>): string {
139
+ let next = incrementedTitle(title)
140
+ while (taken.has(next)) next = incrementedTitle(next)
141
+ return next
142
+ }
143
+
144
+ /**
145
+ * Increment a trailing fork number while preserving its half-width or
146
+ * full-width parentheses; an unnumbered title starts with ` (1)`.
147
+ * @param title - title to increment.
148
+ * @returns the title with the next fork number.
149
+ */
150
+ function incrementedTitle(title: string): string {
151
+ const ascii = /^(.*?)\((\d+)\)$/u.exec(title)
152
+ if (ascii?.[1] !== undefined && ascii[2] !== undefined) {
153
+ return `${ascii[1]}(${BigInt(ascii[2]) + 1n})`
154
+ }
155
+ const fullWidth = /^(.*?)((\d+))$/u.exec(title)
156
+ if (fullWidth?.[1] !== undefined && fullWidth[2] !== undefined) {
157
+ return `${fullWidth[1]}(${BigInt(fullWidth[2]) + 1n})`
158
+ }
159
+ return `${title} (1)`
160
+ }
161
+
162
+ /** Source labels are dictionary keys, including names also present on Object.prototype. */
163
+ function freezeRetainedBy(counts: Partial<Record<SessionReferenceSource, number>>): SessionRetainInfo['retainedBy'] {
164
+ Object.setPrototypeOf(counts, null)
165
+ return Object.freeze(counts)
166
+ }
167
+
168
+ const EMPTY_RETAIN_INFO: SessionRetainInfo = Object.freeze({ referenceCount: 0, retainedBy: freezeRetainedBy({}) })
169
+
170
+ interface ScopeRecord {
171
+ fiber: Fiber
172
+ ctx: AgentContext
173
+ binding: SessionBinding
174
+ session: Session
175
+ retention: SessionRetainInfo
176
+ live: boolean
177
+ }
178
+
179
+ interface RetentionObserver {
180
+ readonly source: ObservableSnapshot<SessionRetainInfo>
181
+ readonly listeners: Set<() => void>
182
+ published: SessionRetainInfo
183
+ }
184
+
185
+ /** A cancelled waiter releases only its own reference, not the shared opening. */
186
+ async function waitForOpen(opening: Promise<void>, signal?: AbortSignal): Promise<void> {
187
+ if (signal === undefined) return opening
188
+ const aborted = Promise.withResolvers<never>()
189
+ const onAbort = (): void => { aborted.reject(signal.reason) }
190
+ signal.addEventListener('abort', onAbort, { once: true })
191
+ try {
192
+ if (signal.aborted) onAbort()
193
+ await Promise.race([opening, aborted.promise])
194
+ } finally {
195
+ signal.removeEventListener('abort', onAbort)
196
+ }
197
+ }
198
+
199
+ class ClientSessionReference implements SessionReference {
200
+ private readonly released = new AbortController()
201
+ private readonly readiness = Promise.withResolvers<SessionBinding>()
202
+ readonly ready = this.readiness.promise
203
+
204
+ constructor(
205
+ readonly sessionId: SessionId,
206
+ private record: ScopeRecord | undefined,
207
+ private releaseReference: (() => void) | undefined,
208
+ ) {
209
+ void this.ready.catch(() => {})
210
+ }
211
+
212
+ get binding(): SessionBinding {
213
+ if (this.record === undefined || !this.record.live) throw new Error(`Session reference "${this.sessionId}" is released`)
214
+ return this.record.binding
215
+ }
216
+
217
+ attachOpening(opening: Promise<void>, signal?: AbortSignal): void {
218
+ const waitSignal = signal === undefined
219
+ ? this.released.signal
220
+ : AbortSignal.any([this.released.signal, signal])
221
+ void waitForOpen(opening, waitSignal).then(
222
+ () => {
223
+ try {
224
+ waitSignal.throwIfAborted()
225
+ this.readiness.resolve(this.binding)
226
+ } catch (error: unknown) {
227
+ this.readiness.reject(error)
228
+ }
229
+ },
230
+ (error: unknown) => { this.readiness.reject(error) },
231
+ )
232
+ }
233
+
234
+ release(): void {
235
+ const reason = new Error(`Session reference "${this.sessionId}" is released`)
236
+ const release = this.releaseReference
237
+ this.released.abort(reason)
238
+ this.readiness.reject(reason)
239
+ this.record = undefined
240
+ this.releaseReference = undefined
241
+ release?.()
242
+ }
243
+
244
+ [Symbol.dispose](): void {
245
+ this.release()
246
+ }
247
+ }
248
+
249
+ /** Host catalog and local reference allocator; view selection remains outside the Controller. */
250
+ export class ClientSessions implements ISessions {
251
+ /**
252
+ * The wire schema's own result bound, re-exposed for presentation plugins as
253
+ * injected data. Not per-connection state: the `session.search` response
254
+ * schema caps `items` at this constant, so every transport (fixture included)
255
+ * reports the same number.
256
+ */
257
+ readonly searchResultLimit = SESSION_SEARCH_RESULT_LIMIT
258
+ /** Catalog metadata and local reference-source projection. */
259
+ readonly list: SnapshotStore<SessionListState>
260
+ /** The object-layer instance cluster and frame dispatch entry. */
261
+ private readonly manager: SessionManager
262
+ private readonly scopes = new Map<SessionId, ScopeRecord>()
263
+ /** Stable per-id sources retained for the Client root lifetime, including across generation replacement. */
264
+ private readonly retainObservers = new Map<SessionId, RetentionObserver>()
265
+ private readonly scopeDrops = new Set<Promise<void>>()
266
+ private closed = false
267
+
268
+ /**
269
+ * @param ctx - client root context (scope fibers mount under it).
270
+ * @param remote - generated Remote namespaces shared with every Session.
271
+ */
272
+ constructor(
273
+ private readonly rootCtx: Context,
274
+ remote: SessionRemotes,
275
+ ) {
276
+ this.manager = new SessionManager(remote)
277
+ this.list = createSnapshotStore<SessionListState>({
278
+ ids: [], byId: {}, phase: 'pending', projectionsBySession: {},
279
+ })
280
+ const disposeManagerProjection = this.manager.subscribe(() => { this.projectList() })
281
+ rootCtx.effect(() => async () => {
282
+ this.closed = true
283
+ disposeManagerProjection()
284
+ const scopes = [...this.scopes]
285
+ this.scopes.clear()
286
+ for (const [, record] of scopes) {
287
+ record.live = false
288
+ record.session.unbindScope()
289
+ }
290
+ const managerDisposal = this.manager.dispose()
291
+ for (const [id, record] of scopes) {
292
+ this.startScopeDrop(id, record)
293
+ this.publishRetention(id)
294
+ }
295
+ await this.drainScopeDrops()
296
+ await managerDisposal
297
+ }, 'session-controller.client.sessions')
298
+ rootCtx.reflect.provide('sessions', this, undefined)
299
+ }
300
+
301
+ retain(target: SessionTarget, options: SessionRetainOptions): SessionReference {
302
+ const { source, signal } = options
303
+ signal?.throwIfAborted()
304
+ if (this.closed) throw new Error('Session Controller is disposed')
305
+ const id = this.manager.resolveTarget(target)
306
+ const reference = this.retainScope(id, source)
307
+ try {
308
+ reference.attachOpening(this.manager.get(id).open(), signal)
309
+ return reference
310
+ } catch (error) {
311
+ reference.release()
312
+ throw error
313
+ }
314
+ }
315
+
316
+ async using<T>(
317
+ target: SessionTarget,
318
+ options: SessionRetainOptions,
319
+ operation: (reference: SessionReference) => T | Promise<T>,
320
+ ): Promise<T> {
321
+ const reference = this.retain(target, options)
322
+ try {
323
+ await reference.ready
324
+ return await operation(reference)
325
+ } finally {
326
+ reference.release()
327
+ }
328
+ }
329
+
330
+ retainInfo(id: SessionId): ObservableSnapshot<SessionRetainInfo> {
331
+ let observer = this.retainObservers.get(id)
332
+ if (observer === undefined) {
333
+ const listeners = new Set<() => void>()
334
+ observer = {
335
+ listeners,
336
+ published: this.retentionSnapshot(id),
337
+ source: {
338
+ getSnapshot: () => this.retentionSnapshot(id),
339
+ subscribe: (listener) => {
340
+ listeners.add(listener)
341
+ return () => { listeners.delete(listener) }
342
+ },
343
+ },
344
+ }
345
+ this.retainObservers.set(id, observer)
346
+ }
347
+ return observer.source
348
+ }
349
+
350
+ /**
351
+ * Resolve an already discovered direct-parent address without opening it.
352
+ * Feature plugins use this to avoid Agent-bound RPCs in persisted child views.
353
+ * @param id - possible addressed child id.
354
+ * @returns A retained, catalog-derived, or unknown-mode listed address, without retaining a new selection or scope.
355
+ */
356
+ subagentAddress(id: SessionId): SubagentAddress | undefined {
357
+ return this.manager.subagentAddress(id)
358
+ }
359
+
360
+ /**
361
+ * Read projections without starting migration; retry failed or migration-deferred reads.
362
+ * @param sessionId - Session to inspect without opening its conversation.
363
+ */
364
+ refreshProjections(sessionId: SessionId): Promise<void> {
365
+ return this.manager.refreshProjections(sessionId)
366
+ }
367
+
368
+ /**
369
+ * Refresh the real Session baseline, reusing an in-flight pull.
370
+ * @returns completion of the current or newly started baseline pull.
371
+ */
372
+ refresh(): Promise<void> {
373
+ return this.manager.refreshList()
374
+ }
375
+
376
+ /**
377
+ * Search the Host's visible message-content index. Results stay
378
+ * request-local; the list snapshot remains the metadata authority.
379
+ * @param query - non-blank literal phrase.
380
+ * @param signal - cancellation for a superseded search.
381
+ * @returns bounded results or a business/transport error.
382
+ */
383
+ search(
384
+ query: string,
385
+ signal: AbortSignal,
386
+ ): Promise<RemoteResult<{ items: SessionSearchResultItem[]; hasMore: boolean }>> {
387
+ return this.manager.search(query, signal)
388
+ }
389
+
390
+ /**
391
+ * Apply one Session Controller live-control frame.
392
+ * @param frame - baseline or live control replacement.
393
+ */
394
+ handleControlFrame(frame: Parameters<SessionManager['handleControlFrame']>[0]): void {
395
+ this.manager.handleControlFrame(frame)
396
+ }
397
+
398
+ /**
399
+ * Apply one remotely forwarded Session-list addition.
400
+ * @param summary - current Host summary for the added Session.
401
+ */
402
+ handleSessionAdded(summary: Parameters<SessionManager['handleSessionAdded']>[0]): void {
403
+ this.manager.handleSessionAdded(summary)
404
+ }
405
+
406
+ /**
407
+ * Apply one remotely forwarded Session removal.
408
+ * @param sessionId - removed Session identity.
409
+ */
410
+ handleSessionRemoved(sessionId: Parameters<SessionManager['handleSessionRemoved']>[0]): void {
411
+ this.manager.handleSessionRemoved(sessionId)
412
+ }
413
+
414
+ /**
415
+ * Apply one remotely forwarded running-state change.
416
+ * @param args - Session identity and current Agent running state.
417
+ */
418
+ handleSessionStatus(...args: Parameters<SessionManager['handleSessionStatus']>): void {
419
+ this.manager.handleSessionStatus(...args)
420
+ }
421
+
422
+ /**
423
+ * Apply one remotely forwarded list-activity change.
424
+ * @param args - Session identity and durable activity timestamp.
425
+ */
426
+ handleSessionActivity(...args: Parameters<SessionManager['handleSessionActivity']>): void {
427
+ this.manager.handleSessionActivity(...args)
428
+ }
429
+
430
+ /**
431
+ * Apply one remotely forwarded Agent failure.
432
+ * @param args - Session identity and caller-visible failure description.
433
+ */
434
+ handleSessionError(...args: Parameters<SessionManager['handleSessionError']>): void {
435
+ this.manager.handleSessionError(...args)
436
+ }
437
+
438
+ /** Rebuild the Session baseline and every opened window after connection. */
439
+ handleConnected(): void {
440
+ this.manager.handleConnected()
441
+ }
442
+
443
+ /**
444
+ * Create a Host Session and publish its catalog row before resolving.
445
+ * Callers retain the returned identity before borrowing its binding.
446
+ * @param opts - target workspace or directory, an optional blank Session to reuse, and an optional Agent preset.
447
+ * @returns the created or reused session id.
448
+ * @throws {SessionCreateError} with the requested id.
449
+ */
450
+ async create(opts: {
451
+ workspaceId?: WorkspaceId
452
+ cwd?: string
453
+ sessionId?: SessionId
454
+ agentPreset?: string
455
+ } = {}): Promise<SessionId> {
456
+ const result = await this.manager.create(opts)
457
+ if (!result.ok) throw new SessionCreateError(result.error, opts.sessionId)
458
+ this.projectList()
459
+ return result.value.sessionId
460
+ }
461
+
462
+ /**
463
+ * Fork a session from an exact inclusive prefix of the source (same
464
+ * synchronous-addressability guarantee as {@link ClientSessions.create}:
465
+ * on resolution the child is catalogued and may be explicitly retained).
466
+ * @param opts - source session id, the optional exact inclusive boundary
467
+ * seq (a real event seq the caller already knows; a cut inside an open
468
+ * turn is balanced Host-side with synthetic closers, and omission selects
469
+ * the latest completed-turn prefix), and whether to increment an
470
+ * inherited durable title, skipping numbers Host-listed titles already use,
471
+ * before resolving, plus permission to start source migration.
472
+ * @returns the child session id.
473
+ * @throws {SessionForkError} with the source id.
474
+ * @throws {Error} when a requested child-title rename fails after creation.
475
+ */
476
+ async fork(opts: {
477
+ sessionId: SessionId
478
+ atSeq?: number
479
+ increaseTitle?: boolean
480
+ onCreated?: (childId: SessionId) => void
481
+ allowMigration?: boolean
482
+ }): Promise<SessionId> {
483
+ const sourceTitle = opts.increaseTitle
484
+ ? this.list.getSnapshot().byId[opts.sessionId]?.title
485
+ : undefined
486
+ const result = await this.manager.fork({
487
+ sessionId: opts.sessionId,
488
+ ...(opts.atSeq === undefined ? {} : { atSeq: SessionSeq(opts.atSeq) }),
489
+ ...(opts.allowMigration === undefined ? {} : { allowMigration: opts.allowMigration }),
490
+ })
491
+ if (!result.ok) throw new SessionForkError(result.error, opts.sessionId)
492
+ this.projectList()
493
+ const childId = result.value.sessionId
494
+ opts.onCreated?.(childId)
495
+ if (sourceTitle !== undefined) {
496
+ const list = this.list.getSnapshot()
497
+ const taken = new Set(list.ids.flatMap(id => list.byId[id]?.title ?? []))
498
+ const renamed = await this.manager.rename(childId, increasedForkTitle(sourceTitle, taken))
499
+ if (!renamed.ok) throw new Error(`fork child rename failed: ${renamed.error.code}: ${renamed.error.message}`)
500
+ }
501
+ return childId
502
+ }
503
+
504
+ /**
505
+ * Borrow an already-retained Agent-scoped Context.
506
+ * @param id - session id (the agent identity — 1:1 same axis).
507
+ * @returns the scoped Context, or undefined without a retained generation.
508
+ */
509
+ scope(id: SessionId): AgentContext | undefined {
510
+ return this.scopes.get(id)?.ctx
511
+ }
512
+
513
+ /**
514
+ * Retain a validated Gateway identity synchronously, without history or catalog I/O.
515
+ * @param id - Host-projected Session identity, possibly not yet catalogued.
516
+ * @returns a Gateway-source reference owned by the invocation.
517
+ */
518
+ retainAgentScope(id: SessionId): SessionReference {
519
+ if (this.closed) throw new Error('Session Controller is disposed')
520
+ return this.retainScope(id, 'gateway')
521
+ }
522
+
523
+ /**
524
+ * Read the Agent scope tag off a context. Service-method boundary: fetch
525
+ * bundles must reach scope resolution through ctx.sessions — a cross-bundle
526
+ * value import of the standalone helper would inline a second module
527
+ * instance whose private tag Symbol never matches.
528
+ * @param ctx - any client context.
529
+ * @returns the session id, or undefined on root contexts.
530
+ */
531
+ scopeOf(ctx: Context): SessionId | undefined {
532
+ return scopeTagOf(ctx)
533
+ }
534
+
535
+ /**
536
+ * Resolve the business Session behind an Agent-scoped context — the one
537
+ * hop every scoped consumer (event listeners, per-session controllers)
538
+ * takes from ctx-space into object-space (the client mirror of host
539
+ * `agent.session`). Same service-method boundary as
540
+ * {@link ClientSessions.scopeOf}.
541
+ * @param ctx - an Agent-scoped context.
542
+ * @returns the matching live Session, or undefined for an untagged or ended generation.
543
+ */
544
+ sessionOf(ctx: Context): SessionFace | undefined {
545
+ const id = scopeTagOf(ctx)
546
+ if (id === undefined) return undefined
547
+ const record = this.scopes.get(id)
548
+ return record !== undefined && scopeIdentityOf(record.ctx) === scopeIdentityOf(ctx)
549
+ ? record.binding.session
550
+ : undefined
551
+ }
552
+
553
+ /**
554
+ * Borrow an already-retained binding without extending its lifetime.
555
+ * @param id - Session identity.
556
+ * @returns the live binding, or undefined without a retained generation.
557
+ */
558
+ binding(id: SessionId): SessionBinding | undefined {
559
+ return this.scopes.get(id)?.binding
560
+ }
561
+
562
+ private retainScope(id: SessionId, source: SessionReferenceSource): ClientSessionReference {
563
+ const record = this.scopes.get(id) ?? this.materializeScope(id)
564
+ const previous = record.retention
565
+ record.retention = Object.freeze({
566
+ referenceCount: previous.referenceCount + 1,
567
+ retainedBy: freezeRetainedBy({ ...previous.retainedBy, [source]: (previous.retainedBy[source] ?? 0) + 1 }),
568
+ })
569
+ const reference = new ClientSessionReference(id, record, () => {
570
+ if (!record.live) return
571
+ const count = record.retention.referenceCount - 1
572
+ const { [source]: sourceCount = 0, ...otherSources } = record.retention.retainedBy
573
+ const retainedBy = sourceCount > 1 ? { ...otherSources, [source]: sourceCount - 1 } : otherSources
574
+ record.retention = count === 0
575
+ ? EMPTY_RETAIN_INFO
576
+ : Object.freeze({ referenceCount: count, retainedBy: freezeRetainedBy(retainedBy) })
577
+ if (count === 0) this.retireScope(id, record)
578
+ else this.publishRetention(id)
579
+ })
580
+ if (this.list.getSnapshot().byId[id] === undefined && this.manager.subagentAddress(id) !== undefined) {
581
+ this.projectList()
582
+ }
583
+ this.publishRetention(id)
584
+ return reference
585
+ }
586
+
587
+ private retentionSnapshot(id: SessionId): SessionRetainInfo {
588
+ return this.scopes.get(id)?.retention ?? EMPTY_RETAIN_INFO
589
+ }
590
+
591
+ private publishRetention(id: SessionId): void {
592
+ const state = this.list.getSnapshot()
593
+ const row = state.byId[id]
594
+ const retainedBy = this.retentionSnapshot(id).retainedBy
595
+ if (row !== undefined && row.retainedBy !== retainedBy) {
596
+ this.list.set({ ...state, byId: { ...state.byId, [id]: { ...row, retainedBy } } })
597
+ }
598
+ const observer = this.retainObservers.get(id)
599
+ const snapshot = this.retentionSnapshot(id)
600
+ if (observer === undefined || observer.published === snapshot) return
601
+ observer.published = snapshot
602
+ notifySubscribers(observer.listeners, '[session-controller] reference sources')
603
+ }
604
+
605
+ private retireScope(id: SessionId, record: ScopeRecord, disposeFiber = true): void {
606
+ if (!record.live) return
607
+ record.live = false
608
+ if (this.scopes.get(id) === record) this.scopes.delete(id)
609
+ record.session.unbindScope()
610
+ const sessionDisposal = this.manager.drop(id, record.session)
611
+ this.projectList()
612
+ this.publishRetention(id)
613
+ this.startScopeDrop(id, record, disposeFiber, sessionDisposal)
614
+ }
615
+
616
+ /** Materialize one scope after its caller establishes that the id may be addressed. */
617
+ private materializeScope(id: SessionId): ScopeRecord {
618
+ const { fiber, ctx } = createScope(this.rootCtx, id)
619
+ const session = this.manager.get(id)
620
+ // The Session owns its scoped dispatch point (host Agent.loopCtx mirror);
621
+ // mint and bind are one step so a live scope record implies a bound actx.
622
+ session.bindScope(ctx)
623
+ const binding: SessionBinding = { sessionId: id, session, eventSource: session.eventSource, ctx }
624
+ const record: ScopeRecord = {
625
+ fiber,
626
+ ctx,
627
+ binding,
628
+ session,
629
+ retention: EMPTY_RETAIN_INFO,
630
+ live: true,
631
+ }
632
+ this.scopes.set(id, record)
633
+ ctx.effect(() => () => { this.retireScope(id, record, false) }, 'session-controller: exact generation')
634
+ return record
635
+ }
636
+
637
+ /** Project the manager's list snapshot into the store (title derivation is display-only). */
638
+ private projectList(): void {
639
+ const previousById = this.list.getSnapshot().byId
640
+ const {
641
+ items, phase, projectionsBySession,
642
+ } = this.manager.getListSnapshot()
643
+ const ids: SessionId[] = []
644
+ const byId: Record<SessionId, SessionSummary> = {}
645
+ for (const entry of items) {
646
+ ids.push(entry.sessionId)
647
+ byId[entry.sessionId] = {
648
+ id: entry.sessionId,
649
+ displayTitle: displayTitleOf(entry.title, entry.cwd, entry.sessionId),
650
+ running: entry.running,
651
+ retainedBy: this.retentionSnapshot(entry.sessionId).retainedBy,
652
+ blank: entry.blank,
653
+ updatedAt: entry.updatedAt,
654
+ formatStatus: entry.formatStatus,
655
+ ...(entry.projectionValues === undefined
656
+ ? {}
657
+ : { projectionValues: entry.projectionValues }),
658
+ ...(entry.title !== undefined ? { title: entry.title } : {}),
659
+ ...(entry.cwd !== undefined ? { cwd: entry.cwd } : {}),
660
+ ...(entry.parentSessionId !== undefined ? { parentId: entry.parentSessionId } : {}),
661
+ ...(entry.origin !== undefined ? { origin: entry.origin } : {}),
662
+ }
663
+ }
664
+ for (const [parentId, projection] of Object.entries(projectionsBySession)) {
665
+ for (const child of projection.values.subagentCatalog ?? []) {
666
+ if (child.mode === 'external') continue
667
+ const childId = child.id
668
+ const summary = byId[childId]
669
+ const projectionValues = summary?.projectionValues ?? this.manager.projectionValues(childId)
670
+ const projectedTitle = projectionValues?.title
671
+ const title = typeof projectedTitle === 'string' && projectedTitle !== '' ? projectedTitle : undefined
672
+ const displayTitle = title ?? child.label ?? childId
673
+ if (summary === undefined) {
674
+ byId[childId] = {
675
+ id: childId, displayTitle, parentId: parentId as SessionId,
676
+ origin: 'subagent', running: this.scopes.get(childId)?.session.getSnapshot().running ?? false, blank: false, updatedAt: 0,
677
+ retainedBy: this.retentionSnapshot(childId).retainedBy,
678
+ ...(projectionValues === undefined ? {} : { projectionValues }),
679
+ ...(title === undefined ? {} : { title }),
680
+ }
681
+ } else if (summary.displayTitle !== displayTitle || summary.projectionValues !== projectionValues) {
682
+ byId[childId] = {
683
+ ...summary,
684
+ displayTitle,
685
+ ...(projectionValues === undefined ? {} : { projectionValues }),
686
+ }
687
+ }
688
+ }
689
+ }
690
+ for (const [id, record] of this.scopes) {
691
+ if (byId[id] !== undefined) continue
692
+ const address = this.manager.subagentAddress(id)
693
+ if (address === undefined) continue
694
+ const previous = previousById[id]
695
+ const snapshot = record.session.getSnapshot()
696
+ const projectionValues = this.manager.projectionValues(id)
697
+ const projectedTitle = projectionValues?.title
698
+ const title = typeof projectedTitle === 'string' && projectedTitle !== '' ? projectedTitle : previous?.title
699
+ byId[id] = {
700
+ ...(previous ?? { id, displayTitle: id, updatedAt: 0 }),
701
+ running: snapshot.running,
702
+ retainedBy: record.retention.retainedBy,
703
+ blank: snapshot.blank,
704
+ parentId: address.parentSessionId,
705
+ origin: 'subagent',
706
+ ...(projectionValues === undefined ? {} : { projectionValues }),
707
+ ...(title === undefined ? {} : { title, displayTitle: title }),
708
+ }
709
+ }
710
+ this.list.set({ ids, byId, phase, projectionsBySession })
711
+ }
712
+
713
+ private startScopeDrop(
714
+ id: SessionId,
715
+ record: ScopeRecord,
716
+ disposeFiber = true,
717
+ sessionDisposal = this.manager.drop(id, record.session),
718
+ ): void {
719
+ const drop = this.dropScope(record, disposeFiber, sessionDisposal)
720
+ this.scopeDrops.add(drop)
721
+ void drop.then(
722
+ () => { this.scopeDrops.delete(drop) },
723
+ () => { this.scopeDrops.delete(drop) },
724
+ )
725
+ }
726
+
727
+ private async drainScopeDrops(): Promise<void> {
728
+ while (this.scopeDrops.size > 0) {
729
+ await Promise.allSettled([...this.scopeDrops])
730
+ }
731
+ }
732
+
733
+ /** Await the already-withdrawn Session and scoped cleanup to quiescence. */
734
+ private async dropScope(
735
+ record: ScopeRecord,
736
+ disposeFiber: boolean,
737
+ sessionDisposal: Promise<void>,
738
+ ): Promise<void> {
739
+ await Promise.allSettled([sessionDisposal, ...disposeFiber ? [record.fiber.dispose()] : []])
740
+ }
741
+ }