@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,302 @@
1
+ /** Passive per-Session streams; subscriptions never acquire Session observations. */
2
+
3
+ import type { Context } from '@unieai/cordis'
4
+ import { Deque } from '@unieai/rabi-deque'
5
+ import { SessionLogOffset } from '@unieai/rabi-session'
6
+ import type { Session, SessionEvent, SessionId } from '@unieai/rabi-session'
7
+ import { RemoteError } from '@unieai/rabi-typert-protocol'
8
+ import { entryFor } from '../history.ts'
9
+ import type { SessionProjectionChange, SessionEventEntry } from '../types.ts'
10
+
11
+ /** Raw history notifications buffered before an opening cut is known. */
12
+ export type EventItem =
13
+ | { readonly type: 'event'; readonly session: Session; readonly event: SessionEvent }
14
+ | { readonly type: 'created'; readonly session: Session; readonly end: number }
15
+
16
+ /** A single subscription buffers before either consumption mode starts. */
17
+ export class EventListener implements Disposable {
18
+ private readonly buffer: ListenerBuffer<SessionEventEntry> | undefined
19
+ private readonly disposes: (() => void)[] = []
20
+ private firstReceivedSeq: number | undefined
21
+ private nextExpectedSeq: number | undefined
22
+
23
+ /**
24
+ * @param ctx - context owning the event registrations.
25
+ * @param sessionId - Session whose notifications are emitted.
26
+ * @param signal - cancellation that wakes consumers.
27
+ * @param queue - optional caller-owned buffer; only an internally created buffer is disposed here.
28
+ */
29
+ constructor(ctx: Context, sessionId: SessionId, signal: AbortSignal,
30
+ queue?: Pick<ListenerBuffer<SessionEventEntry>, 'createInput' | 'capture'>) {
31
+ signal.throwIfAborted()
32
+ const buffer = queue ?? new ListenerBuffer(ctx, signal)
33
+ this.buffer = queue === undefined ? buffer as ListenerBuffer<SessionEventEntry> : undefined
34
+ const input = buffer.createInput<EventItem>(item => this.transform(item))
35
+ const target = sessionId
36
+ try {
37
+ this.disposes.push(ctx.on('session/event', (session, event) => {
38
+ if (session.id !== target) return
39
+ buffer.capture(() => {
40
+ this.recordFirst(event.seq)
41
+ input.append({ type: 'event', session, event })
42
+ })
43
+ }, { global: true }))
44
+ this.disposes.push(ctx.on('session/created', (session) => {
45
+ if (session.id !== target) return
46
+ buffer.capture(() => {
47
+ if (session.firstLiveSeq < session.seq) this.recordFirst(session.firstLiveSeq)
48
+ input.prepend({ type: 'created', session, end: session.seq })
49
+ })
50
+ }, { global: true }))
51
+ this.buffer?.own(() => { this[Symbol.dispose]() })
52
+ } catch (error: unknown) {
53
+ this[Symbol.dispose]()
54
+ throw error
55
+ }
56
+ }
57
+
58
+ /** Consume notifications without reading history.
59
+ * @returns event frames from the first received event, without loading a baseline. */
60
+ events(): AsyncIterable<SessionEventEntry> {
61
+ return this.iterate()
62
+ }
63
+
64
+ /** Set the inclusive opening cut for buffered history notifications.
65
+ * @param cursor - snapshot cut set before consuming the queue. */
66
+ setCursor(cursor: number): void {
67
+ this.nextExpectedSeq = cursor + 1
68
+ }
69
+
70
+ private *transform(item: EventItem): Iterable<SessionEventEntry> {
71
+ if (this.disposes.length === 0) return
72
+ this.nextExpectedSeq ??= this.firstReceivedSeq
73
+ const result = eventItem(item, this.nextExpectedSeq)
74
+ this.nextExpectedSeq = result.next
75
+ for (const event of result.events) {
76
+ if (this.disposes.length === 0) return
77
+ yield entryFor(event)
78
+ }
79
+ }
80
+
81
+ private async *iterate(): AsyncIterable<SessionEventEntry> {
82
+ if (this.buffer === undefined) throw new Error('Consume the externally owned history buffer directly')
83
+ try {
84
+ yield* this.buffer.items()
85
+ } finally {
86
+ this[Symbol.dispose]()
87
+ }
88
+ }
89
+
90
+ private recordFirst(seq: number): void {
91
+ this.firstReceivedSeq = this.firstReceivedSeq === undefined ? seq : Math.min(this.firstReceivedSeq, seq)
92
+ }
93
+
94
+ [Symbol.dispose](): void {
95
+ for (const dispose of this.disposes.splice(0).reverse()) dispose()
96
+ this.buffer?.[Symbol.dispose]()
97
+ }
98
+ }
99
+
100
+ /**
101
+ * Select the uncovered events represented by one notification.
102
+ * @param item - one buffered notification.
103
+ * @param next - next required seq, or undefined before the first event.
104
+ * @returns uncovered events and the next required seq without acquiring an observation.
105
+ */
106
+ export function eventItem(item: EventItem, next?: number): {
107
+ events: readonly SessionEvent[]
108
+ next: number | undefined
109
+ } {
110
+ if (item.type === 'event') {
111
+ if (next !== undefined && item.event.seq < next) return { events: [], next }
112
+ if (next !== undefined && item.event.seq !== next) {
113
+ throw new RemoteError('gateway/internal', `session event stream skipped seq ${String(next)}`, {})
114
+ }
115
+ return { events: [item.event], next: item.event.seq + 1 }
116
+ }
117
+ const start = next ?? item.session.firstLiveSeq
118
+ if (start >= item.end) return { events: [], next }
119
+ // oxlint-disable-next-line typescript/no-deprecated -- Existing Session-created history adaptation.
120
+ const events = item.session.snapshotEvents(SessionLogOffset(start), SessionLogOffset(item.end))
121
+ for (const event of events) {
122
+ if (next !== undefined && event.seq !== next) {
123
+ throw new RemoteError('gateway/internal', `session event stream skipped seq ${String(next)}`, {})
124
+ }
125
+ next = event.seq + 1
126
+ }
127
+ return { events, next }
128
+ }
129
+
130
+ /** Projection changes of one Session, one change per committed event that changed a projection. */
131
+ export class ProjectionListener implements Disposable {
132
+ private readonly buffer: ListenerBuffer<{ session: Session; change: SessionProjectionChange }>
133
+
134
+ /**
135
+ * @param ctx - context owning projection notifications.
136
+ * @param sessionId - Session whose notifications are emitted.
137
+ * @param signal - cancellation that removes registrations and wakes consumers.
138
+ */
139
+ constructor(ctx: Context, sessionId: SessionId, signal: AbortSignal) {
140
+ this.buffer = new ListenerBuffer(ctx, signal)
141
+ const input = this.buffer.createInput<{ session: Session; change: SessionProjectionChange }>(item => [item])
142
+ const target = sessionId
143
+ try {
144
+ this.buffer.own(ctx.sessionProjections.onEventChanged((session, changes, seq) => {
145
+ if (session.id !== target) return
146
+ this.buffer.capture(() => {
147
+ // Every projection definition validates its value before change publication.
148
+ const change: SessionProjectionChange = { type: 'projection', seq, changes: changes as SessionProjectionChange['changes'] }
149
+ input.append({ session, change })
150
+ })
151
+ }))
152
+ } catch (error: unknown) {
153
+ this.buffer[Symbol.dispose]()
154
+ throw error
155
+ }
156
+ }
157
+
158
+ /** Consume per-event projection changes.
159
+ * @returns validated change frames, one per committed event; projection seqs need not be contiguous. */
160
+ async *changes(): AsyncIterable<SessionProjectionChange> {
161
+ try {
162
+ for await (const { change } of this.buffer.items()) {
163
+ yield change
164
+ }
165
+ } finally {
166
+ this[Symbol.dispose]()
167
+ }
168
+ }
169
+
170
+ [Symbol.dispose](): void {
171
+ this.buffer[Symbol.dispose]()
172
+ }
173
+ }
174
+
175
+ /** Owns buffering, callback failure and registration cleanup for one consumer. */
176
+ export class ListenerBuffer<T> implements Disposable {
177
+ private readonly values = new Deque<unknown>()
178
+ private readonly transformIds = new Deque<number>()
179
+ private readonly transforms: ((value: unknown) => Iterable<T>)[] = []
180
+ private readonly cleanup: (() => void)[] = []
181
+ private wake: (() => void) | undefined
182
+ private closed = false
183
+ private failure: { readonly error: unknown } | undefined
184
+ private consumed = false
185
+
186
+ constructor(ctx: Context, signal: AbortSignal) {
187
+ signal.throwIfAborted()
188
+ const close = (): void => { this[Symbol.dispose]() }
189
+ signal.addEventListener('abort', close, { once: true })
190
+ this.own(() => { signal.removeEventListener('abort', close) })
191
+ try {
192
+ const dispose = ctx.effect(() => close, 'session-controller.listener-buffer')
193
+ this.own(() => { void dispose() })
194
+ } catch (error: unknown) {
195
+ this[Symbol.dispose]()
196
+ throw error
197
+ }
198
+ }
199
+
200
+ /**
201
+ * Register cleanup, or run it immediately when already closed.
202
+ * @param dispose - synchronous cleanup.
203
+ */
204
+ own(dispose: () => void): void {
205
+ if (this.closed) dispose()
206
+ else this.cleanup.push(dispose)
207
+ }
208
+
209
+ /**
210
+ * Contain producer failure and wake the consumer with that failure.
211
+ * @param action - synchronous producer operation.
212
+ */
213
+ capture(action: () => void): void {
214
+ if (this.closed) return
215
+ try {
216
+ action()
217
+ } catch (error: unknown) {
218
+ this.failure = { error }
219
+ this[Symbol.dispose]()
220
+ }
221
+ }
222
+
223
+ /**
224
+ * Register a dequeue transform and obtain its write-only input.
225
+ * @param transform - conversion bound once and evaluated when each input is dequeued.
226
+ * @returns a write-only input sharing this buffer's storage and lifetime.
227
+ * @throws when this buffer is already closed.
228
+ */
229
+ createInput<Input>(transform: (item: Input) => Iterable<T>): { append(item: Input): void; prepend(item: Input): void } {
230
+ if (this.closed) throw new Error('Cannot register a transform on a closed listener buffer')
231
+ const transformId = this.transforms.length
232
+ // Only this typed input can enqueue values with its private transform id.
233
+ this.transforms.push(value => transform(value as Input))
234
+ return {
235
+ append: (item) => {
236
+ if (this.closed) return
237
+ this.values.pushBack(item)
238
+ this.transformIds.pushBack(transformId)
239
+ this.notify()
240
+ },
241
+ prepend: (item) => {
242
+ if (this.closed) return
243
+ this.values.pushFront(item)
244
+ this.transformIds.pushFront(transformId)
245
+ this.notify()
246
+ },
247
+ }
248
+ }
249
+
250
+ /**
251
+ * Consume queued values once, releasing the buffer when iteration ends.
252
+ * @returns transformed output values.
253
+ */
254
+ async *items(): AsyncIterable<T> {
255
+ if (this.consumed) throw new RemoteError('gateway/internal', 'Session listener already has a consumer', {})
256
+ this.consumed = true
257
+ try {
258
+ for (;;) {
259
+ if (this.failure !== undefined) throw this.failure.error
260
+ if (this.closed) return
261
+ if (this.transformIds.size === 0) {
262
+ await new Promise<void>((resolve) => { this.wake = resolve })
263
+ continue
264
+ }
265
+ const transformId = this.transformIds.popFront() as number
266
+ const value = this.values.popFront()
267
+ for (const item of (this.transforms[transformId] as (value: unknown) => Iterable<T>)(value)) {
268
+ this.throwIfFailed()
269
+ if (this.isClosed()) return
270
+ yield item
271
+ }
272
+ }
273
+ } finally {
274
+ this[Symbol.dispose]()
275
+ }
276
+ }
277
+
278
+ private throwIfFailed(): void {
279
+ if (this.failure !== undefined) throw this.failure.error
280
+ }
281
+
282
+ /** @returns whether disposal ended this buffer while a transform was yielding. */
283
+ private isClosed(): boolean {
284
+ return this.closed
285
+ }
286
+
287
+ private notify(): void {
288
+ const wake = this.wake
289
+ this.wake = undefined
290
+ wake?.()
291
+ }
292
+
293
+ [Symbol.dispose](): void {
294
+ if (this.closed) return
295
+ this.closed = true
296
+ this.values.clear()
297
+ this.transformIds.clear()
298
+ this.transforms.length = 0
299
+ this.notify()
300
+ for (const dispose of this.cleanup.splice(0).reverse()) dispose()
301
+ }
302
+ }
package/src/history.ts ADDED
@@ -0,0 +1,189 @@
1
+ /** Shared Session history pagination, address validation and wire conversion. */
2
+
3
+ import {
4
+ isAppendSurfaceEvent,
5
+ SessionLogOffset,
6
+ } from '@unieai/rabi-session'
7
+ import type {
8
+ SessionEvent,
9
+ SessionHeader,
10
+ SessionId,
11
+ SessionLogOffset as SessionLogOffsetType,
12
+ SessionSeqCursor,
13
+ } from '@unieai/rabi-session'
14
+ import type { SessionObservation } from '@unieai/rabi-session-query'
15
+ import type {} from '@unieai/rabi-subagent'
16
+ import { RemoteError } from '@unieai/rabi-typert-protocol'
17
+ import type {
18
+ SessionAddress,
19
+ SessionEventEntry,
20
+ SessionHistoryRecord,
21
+ SessionPageRequest,
22
+ SessionWireEvent,
23
+ } from './types.ts'
24
+
25
+ /** Message budget applied when a history request omits `maxMessages`. */
26
+ export const DEFAULT_MAX_MESSAGES = 50
27
+ const MESSAGE_TYPES = new Set(['user/message', 'assistant/message'])
28
+
29
+ /**
30
+ * Reject an invalid message budget or turn window.
31
+ * @param request - history window fields.
32
+ */
33
+ export function validateHistoryWindow(request: Pick<SessionPageRequest, 'maxMessages' | 'turnWindow'>): void {
34
+ if (request.maxMessages !== undefined
35
+ && (!Number.isSafeInteger(request.maxMessages) || request.maxMessages <= 0)) {
36
+ throw new RemoteError('gateway/bad-request', 'maxMessages must be a positive safe integer', {})
37
+ }
38
+ const window = request.turnWindow
39
+ if (window !== undefined) {
40
+ if (!Number.isSafeInteger(window.minMessages) || window.minMessages <= 0
41
+ || window.minMessages > (request.maxMessages ?? DEFAULT_MAX_MESSAGES)) {
42
+ throw new RemoteError('gateway/bad-request', 'turnWindow.minMessages must be a positive safe integer no greater than maxMessages', {})
43
+ }
44
+ if (!Number.isSafeInteger(window.minTurns) || window.minTurns <= 0) {
45
+ throw new RemoteError('gateway/bad-request', 'turnWindow.minTurns must be a positive safe integer', {})
46
+ }
47
+ }
48
+ }
49
+
50
+ /**
51
+ * Select the Session whose log an address names.
52
+ * @param address - ordinary Session or direct-subagent address.
53
+ * @returns the Session whose log the address reads.
54
+ */
55
+ export function addressId(address: SessionAddress): SessionId {
56
+ return address.kind === 'session' ? address.sessionId : address.childSessionId
57
+ }
58
+
59
+ /**
60
+ * Reject an address that does not match the observed Session.
61
+ * @param address - ordinary Session or direct-subagent address.
62
+ * @param header - observed Session header.
63
+ * @param inheritedEventCount - observed fork-inherited event count.
64
+ * @param projections - observed projections; subagent addresses require them.
65
+ */
66
+ export function validateAddress(
67
+ address: SessionAddress,
68
+ header: SessionHeader,
69
+ inheritedEventCount: SessionLogOffsetType,
70
+ projections: SessionObservation['projections'],
71
+ ): void {
72
+ if (address.kind === 'session') {
73
+ if (header.origin === 'subagent') {
74
+ throw new RemoteError('session/agent-busy', 'subagent Sessions require their durable parent address', {
75
+ reason: 'use subagent delivery for this child session',
76
+ })
77
+ }
78
+ return
79
+ }
80
+ if (header.origin !== 'subagent' || header.parentSession !== address.parentSessionId) {
81
+ throw new RemoteError('subagent/unauthorized', 'subagent does not belong to the supplied parent', {
82
+ childSessionId: address.childSessionId,
83
+ })
84
+ }
85
+ const identity = projections?.values.subagent
86
+ if (identity === null) {
87
+ throw new RemoteError('subagent/catalog-diagnostic', 'subagent descriptor is corrupt', {
88
+ parentSessionId: address.parentSessionId,
89
+ childSessionId: address.childSessionId,
90
+ reason: 'corrupt',
91
+ })
92
+ }
93
+ if (identity === undefined || identity.seq < inheritedEventCount) {
94
+ throw new RemoteError('subagent/catalog-diagnostic', 'subagent descriptor is unavailable', {
95
+ parentSessionId: address.parentSessionId,
96
+ childSessionId: address.childSessionId,
97
+ reason: 'unsupported',
98
+ })
99
+ }
100
+ if (address.mode !== 'unknown' && identity.mode !== address.mode) {
101
+ throw new RemoteError('subagent/unauthorized', 'subagent mode does not match the supplied address', {
102
+ childSessionId: address.childSessionId,
103
+ })
104
+ }
105
+ }
106
+
107
+ /**
108
+ * Reject a missing Session using its address-specific error.
109
+ * @param address - ordinary Session or direct-subagent address.
110
+ * @returns never; this operation always throws.
111
+ * @throws RemoteError `session/not-found` or `subagent/not-found`.
112
+ */
113
+ export function rejectNotFound(address: SessionAddress): never {
114
+ if (address.kind === 'session') {
115
+ throw new RemoteError('session/not-found', `session "${address.sessionId}" not found`, { sessionId: address.sessionId })
116
+ }
117
+ throw new RemoteError('subagent/not-found', 'subagent is unavailable', {
118
+ parentSessionId: address.parentSessionId,
119
+ childSessionId: address.childSessionId,
120
+ })
121
+ }
122
+
123
+ /**
124
+ * Cut one message-aligned backwards page from a contiguous event prefix.
125
+ * @param events - contiguous events starting at seq 0.
126
+ * @param beforeSeq - exclusive upper offset of an older page.
127
+ * @param maxMessages - message budget.
128
+ * @param throughSeq - inclusive log cut.
129
+ * @param turnWindow - optional turn-boundary stop rule.
130
+ * @returns the page events and whether older events remain.
131
+ */
132
+ export function paginate(
133
+ events: readonly SessionEvent[],
134
+ beforeSeq: SessionLogOffsetType | undefined,
135
+ maxMessages: number,
136
+ throughSeq: SessionSeqCursor,
137
+ turnWindow?: SessionPageRequest['turnWindow'],
138
+ ): { readonly events: SessionEvent[]; readonly hasMore: boolean } {
139
+ const end = SessionLogOffset(Math.min(throughSeq + 1, beforeSeq ?? throughSeq + 1))
140
+ let count = 0
141
+ let turns = 0
142
+ let cut = SessionLogOffset(0)
143
+ for (let index = end - 1; index >= 0; index--) {
144
+ const event = events[index] as SessionEvent
145
+ if (turnWindow !== undefined && event.type === 'turn/start') {
146
+ turns++
147
+ if (count >= turnWindow.minMessages && turns >= turnWindow.minTurns) {
148
+ cut = SessionLogOffset(index)
149
+ break
150
+ }
151
+ }
152
+ if (!MESSAGE_TYPES.has(event.type) || !isAppendSurfaceEvent(event)) continue
153
+ count++
154
+ const sources = event.sourceEventSeqs
155
+ let groupStart = event.seq
156
+ if (sources !== undefined) {
157
+ for (const source of sources) {
158
+ if (source < groupStart) groupStart = source
159
+ }
160
+ }
161
+ if (count >= maxMessages) {
162
+ cut = SessionLogOffset(groupStart)
163
+ break
164
+ }
165
+ }
166
+ return { events: events.slice(cut, end), hasMore: cut > 0 }
167
+ }
168
+
169
+ /**
170
+ * Convert a committed event to its wire entry.
171
+ * @param event - committed Session event.
172
+ * @returns the wire event entry.
173
+ */
174
+ export function entryFor(event: SessionEvent): SessionEventEntry {
175
+ return {
176
+ type: 'event',
177
+ // Session.append validates and freezes event data as JSON before publication.
178
+ event: event as unknown as SessionWireEvent,
179
+ }
180
+ }
181
+
182
+ /**
183
+ * Encode one bounded logical page without changing its pagination cut.
184
+ * @param events - page events.
185
+ * @returns the wire records.
186
+ */
187
+ export function pageRecords(events: readonly SessionEvent[]): SessionHistoryRecord[] {
188
+ return events.map(entryFor)
189
+ }