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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +7 -2
  3. package/lib/client.js +4 -0
  4. package/lib/index.js +4300 -0
  5. package/lib/typert.host.d.ts +3 -0
  6. package/lib/typert.host.js +5013 -0
  7. package/lib/typert.remote-client.d.ts +115 -0
  8. package/lib/typert.remote-client.js +2714 -0
  9. package/lib/types/agent.d.ts +164 -0
  10. package/lib/types/agent.js +484 -0
  11. package/lib/types/archived-session-gate.d.ts +33 -0
  12. package/lib/types/archived-session-gate.js +54 -0
  13. package/lib/types/assistant-stream.d.ts +26 -0
  14. package/lib/types/assistant-stream.js +82 -0
  15. package/lib/types/catalog.d.ts +24 -0
  16. package/lib/types/catalog.js +107 -0
  17. package/lib/types/client/contract/events.d.ts +102 -0
  18. package/lib/types/client/contract/events.js +111 -0
  19. package/lib/types/client/contract/session.d.ts +178 -0
  20. package/lib/types/client/contract/session.js +1 -0
  21. package/lib/types/client/contract/sessions.d.ts +162 -0
  22. package/lib/types/client/contract/sessions.js +1 -0
  23. package/lib/types/client/contract/snapshot.d.ts +84 -0
  24. package/lib/types/client/contract/snapshot.js +1 -0
  25. package/lib/types/client/index.d.ts +39 -0
  26. package/lib/types/client/index.js +60 -0
  27. package/lib/types/client/ordered-baseline.d.ts +12 -0
  28. package/lib/types/client/ordered-baseline.js +40 -0
  29. package/lib/types/client/scope.d.ts +46 -0
  30. package/lib/types/client/scope.js +46 -0
  31. package/lib/types/client/session-wire-event.d.ts +11 -0
  32. package/lib/types/client/session-wire-event.js +42 -0
  33. package/lib/types/client/sessions/assistant-stream.d.ts +56 -0
  34. package/lib/types/client/sessions/assistant-stream.js +182 -0
  35. package/lib/types/client/sessions/history-records.d.ts +22 -0
  36. package/lib/types/client/sessions/history-records.js +25 -0
  37. package/lib/types/client/sessions/lineage.d.ts +48 -0
  38. package/lib/types/client/sessions/lineage.js +55 -0
  39. package/lib/types/client/sessions/manager.d.ts +272 -0
  40. package/lib/types/client/sessions/manager.js +774 -0
  41. package/lib/types/client/sessions/notifier.d.ts +39 -0
  42. package/lib/types/client/sessions/notifier.js +97 -0
  43. package/lib/types/client/sessions/projection-store.d.ts +128 -0
  44. package/lib/types/client/sessions/projection-store.js +161 -0
  45. package/lib/types/client/sessions/remotes.d.ts +29 -0
  46. package/lib/types/client/sessions/remotes.js +7 -0
  47. package/lib/types/client/sessions/service.d.ts +263 -0
  48. package/lib/types/client/sessions/service.js +597 -0
  49. package/lib/types/client/sessions/session.d.ts +303 -0
  50. package/lib/types/client/sessions/session.js +991 -0
  51. package/lib/types/client/time-zone.d.ts +8 -0
  52. package/lib/types/client/time-zone.js +13 -0
  53. package/lib/types/client/transport.d.ts +77 -0
  54. package/lib/types/client/transport.js +130 -0
  55. package/lib/types/commands.d.ts +92 -0
  56. package/lib/types/commands.js +575 -0
  57. package/lib/types/continuation.d.ts +35 -0
  58. package/lib/types/continuation.js +47 -0
  59. package/lib/types/control.d.ts +20 -0
  60. package/lib/types/control.js +106 -0
  61. package/lib/types/file-references.d.ts +27 -0
  62. package/lib/types/file-references.js +68 -0
  63. package/lib/types/history/assistant-stream.d.ts +43 -0
  64. package/lib/types/history/assistant-stream.js +79 -0
  65. package/lib/types/history/controller.d.ts +104 -0
  66. package/lib/types/history/controller.js +293 -0
  67. package/lib/types/history/listener.d.ts +105 -0
  68. package/lib/types/history/listener.js +296 -0
  69. package/lib/types/history.d.ts +58 -0
  70. package/lib/types/history.js +152 -0
  71. package/lib/types/index.d.ts +262 -0
  72. package/lib/types/index.js +693 -0
  73. package/lib/types/list.d.ts +62 -0
  74. package/lib/types/list.js +343 -0
  75. package/lib/types/media-references.d.ts +18 -0
  76. package/lib/types/media-references.js +84 -0
  77. package/lib/types/remote-events.d.ts +8 -0
  78. package/lib/types/remote-events.js +1 -0
  79. package/lib/types/skill-catalog.d.ts +28 -0
  80. package/lib/types/skill-catalog.js +203 -0
  81. package/lib/types/state/controller.d.ts +45 -0
  82. package/lib/types/state/controller.js +288 -0
  83. package/lib/types/state/listener.d.ts +40 -0
  84. package/lib/types/state/listener.js +111 -0
  85. package/lib/types/types.d.ts +687 -0
  86. package/lib/types/types.js +5 -0
  87. package/lib/types/web/controller.d.ts +25 -0
  88. package/lib/types/web/controller.js +138 -0
  89. package/locale/de.json +6 -0
  90. package/locale/en.json +5 -0
  91. package/locale/es.json +6 -0
  92. package/locale/fr.json +6 -0
  93. package/locale/ja.json +6 -0
  94. package/locale/pt.json +6 -0
  95. package/locale/ru.json +6 -0
  96. package/locale/zh.json +6 -0
  97. package/package.json +119 -4
  98. package/src/agent.ts +474 -0
  99. package/src/archived-session-gate.ts +59 -0
  100. package/src/assistant-stream.ts +102 -0
  101. package/src/catalog.ts +117 -0
  102. package/src/client/contract/events.ts +205 -0
  103. package/src/client/contract/session.ts +174 -0
  104. package/src/client/contract/sessions.ts +169 -0
  105. package/src/client/contract/snapshot.ts +94 -0
  106. package/src/client/index.ts +149 -0
  107. package/src/client/ordered-baseline.ts +43 -0
  108. package/src/client/scope.ts +76 -0
  109. package/src/client/session-wire-event.ts +46 -0
  110. package/src/client/sessions/assistant-stream.ts +229 -0
  111. package/src/client/sessions/history-records.ts +35 -0
  112. package/src/client/sessions/lineage.ts +96 -0
  113. package/src/client/sessions/manager.ts +857 -0
  114. package/src/client/sessions/notifier.ts +97 -0
  115. package/src/client/sessions/projection-store.ts +244 -0
  116. package/src/client/sessions/remotes.ts +44 -0
  117. package/src/client/sessions/service.ts +741 -0
  118. package/src/client/sessions/session.ts +1055 -0
  119. package/src/client/time-zone.ts +14 -0
  120. package/src/client/transport.ts +247 -0
  121. package/src/commands.ts +602 -0
  122. package/src/continuation.ts +58 -0
  123. package/src/control.ts +121 -0
  124. package/src/file-references.ts +42 -0
  125. package/src/history/assistant-stream.ts +102 -0
  126. package/src/history/controller.ts +256 -0
  127. package/src/history/listener.ts +302 -0
  128. package/src/history.ts +189 -0
  129. package/src/index.ts +651 -0
  130. package/src/list.ts +382 -0
  131. package/src/media-references.ts +84 -0
  132. package/src/remote-events.ts +14 -0
  133. package/src/skill-catalog.ts +108 -0
  134. package/src/state/controller.ts +221 -0
  135. package/src/state/listener.ts +116 -0
  136. package/src/types.ts +720 -0
  137. package/src/web/controller.ts +78 -0
package/src/list.ts ADDED
@@ -0,0 +1,382 @@
1
+ /** Cold-safe Session list and search projection. */
2
+
3
+ import { performance } from 'node:perf_hooks'
4
+ import { scheduler } from 'node:timers/promises'
5
+ import type { Context } from '@unieai/cordis'
6
+ import type {} from '@unieai/rabi-agent-preset-registry'
7
+ import type { ImageAttachmentLimits } from '@unieai/rabi-attachment'
8
+ import type { Session, SessionEvent, SessionHeader, SessionId } from '@unieai/rabi-session'
9
+ import type { ProjectionHandle, ProjectionSnapshot } from '@unieai/rabi-session-projection'
10
+ import type {} from '@unieai/rabi-session-projection-cache'
11
+ import { SessionQueryError, type SessionRecord, type SessionSearchCursor } from '@unieai/rabi-session-query'
12
+ import { RemoteError } from '@unieai/rabi-typert-protocol'
13
+ import { z } from 'zod'
14
+ import {
15
+ SESSION_SEARCH_RESULT_LIMIT,
16
+ SESSION_SEARCH_SNIPPET_MAX_CODE_POINTS,
17
+ } from './types.ts'
18
+ import type {
19
+ SessionListMetadata, SessionProjectionHints, SessionSearchItem,
20
+ SessionSearchValue, SessionSummary,
21
+ } from './types.ts'
22
+
23
+ const SEARCH_PROVIDER_CALL_LIMIT = 100
24
+ const SESSION_SEARCH_QUERY_MAX_CHARS = 500
25
+ const MESSAGE_TYPES = new Set(['user/message', 'assistant/message'])
26
+
27
+ const sessionListMetadataSchema: z.ZodType<SessionListMetadata> = z.object({
28
+ blank: z.boolean(),
29
+ lastPromptAt: z.number().nullable(),
30
+ })
31
+
32
+ const imageLimitsSchema = z.object({
33
+ maxImageBytes: z.number().int().positive(),
34
+ maxImagesPerMessage: z.number().int().positive(),
35
+ maxMessageImageBytes: z.number().int().positive(),
36
+ maxImagePixels: z.number().int().positive(),
37
+ maxImageDimension: z.number().int().positive(),
38
+ mediaTypes: z.array(z.string()),
39
+ }) as unknown as z.ZodType<ImageAttachmentLimits>
40
+
41
+ /**
42
+ * Advance the Session-list metadata projection by one committed event.
43
+ * @param state - metadata before the event.
44
+ * @param event - next committed Session event.
45
+ * @returns the original or advanced metadata value.
46
+ */
47
+ export function applySessionListMetadata(
48
+ state: SessionListMetadata,
49
+ event: SessionEvent,
50
+ ): SessionListMetadata {
51
+ const blank = state.blank && event.type !== 'turn/start'
52
+ const lastPromptAt = event.type === 'user/message' && event.data.source.kind === 'user'
53
+ ? event.time
54
+ : state.lastPromptAt
55
+ return blank === state.blank && lastPromptAt === state.lastPromptAt
56
+ ? state
57
+ : { blank, lastPromptAt }
58
+ }
59
+
60
+ /**
61
+ * Return the longest prefix containing at most `maximum` Unicode code points.
62
+ * @param value - source text.
63
+ * @param maximum - maximum number of Unicode code points.
64
+ * @returns the source text or its longest allowed prefix.
65
+ */
66
+ export function truncateUnicodeCodePoints(value: string, maximum: number): string {
67
+ let count = 0
68
+ let end = 0
69
+ for (const codePoint of value) {
70
+ if (count === maximum) return value.slice(0, end)
71
+ count++
72
+ end += codePoint.length
73
+ }
74
+ return value
75
+ }
76
+
77
+ /** Owns list projection registration, bounded cold summaries, and authorized search. */
78
+ export class ApiSessionList {
79
+ private listMetadata!: ProjectionHandle<SessionListMetadata>
80
+
81
+ /**
82
+ * @param ctx - Host context carrying Session, query, persistence, and projection services.
83
+ * @param workSliceMs - Resolved positive integral list-work budget in milliseconds.
84
+ */
85
+ constructor(private readonly ctx: Context, private readonly workSliceMs: number) {}
86
+
87
+ /**
88
+ * Acquire projection readers before exposing dependent operations.
89
+ * @returns when all required registrations are ready.
90
+ */
91
+ async initialize(): Promise<void> {
92
+ this.listMetadata = await this.ctx.sessionProjections.register<'sessionListMetadata', SessionListMetadata>({
93
+ key: 'sessionListMetadata',
94
+ stateSchema: sessionListMetadataSchema,
95
+ init: () => ({ blank: true, lastPromptAt: null }),
96
+ apply: applySessionListMetadata,
97
+ wire: { viewSchema: sessionListMetadataSchema, view: state => state },
98
+ stateVersion: 1,
99
+ })
100
+ await this.ctx.sessionProjections.register<'imageLimits', null>({
101
+ key: 'imageLimits',
102
+ stateSchema: z.null(),
103
+ init: () => null,
104
+ apply: state => state,
105
+ wire: {
106
+ viewSchema: imageLimitsSchema,
107
+ view: () => this.ctx.attachments.imageLimits,
108
+ summary: false,
109
+ },
110
+ stateVersion: 1,
111
+ })
112
+ }
113
+
114
+ /**
115
+ * Build one current attached-Session summary.
116
+ * Blankness and recency come from the `sessionListMetadata` handle; projection
117
+ * hints carry every summary key computed through `snapshot`. The first call
118
+ * for a Session computes these projections over its whole in-memory log, and
119
+ * later calls advance them incrementally. The handle read and the hint with
120
+ * the same key come from one cell; the handle read does not depend on any
121
+ * other unit's view.
122
+ * @param session - attached Session to summarize.
123
+ * @returns current list metadata and available projections.
124
+ */
125
+ summaryFor(session: Session): SessionSummary {
126
+ const metadata = this.listMetadata.stateOf(session)
127
+ const projections = this.projectionsFor(session.header, session)
128
+ return {
129
+ sessionId: session.id,
130
+ updatedAt: updatedAt(session.header, metadata),
131
+ agentAvailable: this.ctx.agents.get(session.id)?.session === session,
132
+ formatStatus: 'current',
133
+ running: this.ctx.agents.get(session.id)?.status === 'running',
134
+ blank: metadata.blank,
135
+ ...listFields(session.header),
136
+ ...(projections === undefined ? {} : { projections }),
137
+ }
138
+ }
139
+
140
+ /**
141
+ * Read every visible attached and persisted Session without activating an Agent.
142
+ * @param signal - optional cancellation for persistence reads and summary generation.
143
+ * @returns visible Session summaries ordered by activity.
144
+ */
145
+ async list(signal?: AbortSignal): Promise<SessionSummary[]> {
146
+ signal?.throwIfAborted()
147
+ const records = await this.ctx.sessionQuery.listSessions(signal)
148
+ signal?.throwIfAborted()
149
+ const items: SessionSummary[] = []
150
+ const cold: SessionRecord[] = []
151
+ let yieldDeadline = performance.now() + this.workSliceMs
152
+ for (const record of records) {
153
+ signal?.throwIfAborted()
154
+ const live = this.ctx.sessions.get(record.header.id)
155
+ if (live !== undefined) {
156
+ items.push(this.summaryFor(live))
157
+ } else if (record.header.cwd !== undefined) {
158
+ cold.push(record)
159
+ }
160
+ if (performance.now() >= yieldDeadline) {
161
+ await scheduler.yield()
162
+ signal?.throwIfAborted()
163
+ yieldDeadline = performance.now() + this.workSliceMs
164
+ }
165
+ }
166
+ for (const record of cold) {
167
+ signal?.throwIfAborted()
168
+ items.push(this.summarizeCold(record))
169
+ if (performance.now() >= yieldDeadline) {
170
+ await scheduler.yield()
171
+ signal?.throwIfAborted()
172
+ yieldDeadline = performance.now() + this.workSliceMs
173
+ }
174
+ }
175
+ signal?.throwIfAborted()
176
+ items.sort((left, right) => right.updatedAt - left.updatedAt)
177
+ return items
178
+ }
179
+
180
+ private summarizeCold({ header, formatStatus }: SessionRecord): SessionSummary {
181
+ const projections = this.projectionsFor(header, undefined)
182
+ const metadata = projections?.values.sessionListMetadata
183
+ return {
184
+ sessionId: header.id,
185
+ updatedAt: updatedAt(header, metadata),
186
+ agentAvailable: false,
187
+ ...(formatStatus === undefined ? {} : { formatStatus }),
188
+ running: false,
189
+ // A large, metadata-less, or inaccessible cache miss remains unknown and visible.
190
+ blank: metadata?.blank ?? false,
191
+ ...listFields(header),
192
+ ...(projections === undefined ? {} : { projections }),
193
+ }
194
+ }
195
+
196
+ /**
197
+ * Search current visible message content without activating any matching Session.
198
+ * @param query - literal message-content query.
199
+ * @param signal - cancellation for list and search reads.
200
+ * @returns authorized bounded Session search results.
201
+ */
202
+ async search(query: string, signal: AbortSignal): Promise<SessionSearchValue> {
203
+ const normalizedQuery = normalizeSearchQuery(query)
204
+ signal.throwIfAborted()
205
+ const provider = this.ctx.get('sessionQuery')
206
+ if (provider === undefined) {
207
+ throw new RemoteError(
208
+ 'gateway/internal',
209
+ 'session search is unavailable: this deployment does not mount @unieai/rabi-session-query',
210
+ {},
211
+ )
212
+ }
213
+ try {
214
+ const visible = await provider.listSessions(signal)
215
+ signal.throwIfAborted()
216
+ const visibleIds = new Set(visible
217
+ .filter(record => record.header.cwd !== undefined)
218
+ .map(record => record.header.id))
219
+ if (visibleIds.size === 0) return { items: [], hasMore: false }
220
+ const authorized: SessionSearchItem[] = []
221
+ const acceptedIds = new Set<SessionId>()
222
+ const seenCursors = new Set<SessionSearchCursor>()
223
+ let cursor: SessionSearchCursor | undefined
224
+ let providerCalls = 0
225
+ let pageLimit = SESSION_SEARCH_RESULT_LIMIT
226
+ while (authorized.length <= SESSION_SEARCH_RESULT_LIMIT) {
227
+ signal.throwIfAborted()
228
+ if (providerCalls >= SEARCH_PROVIDER_CALL_LIMIT) {
229
+ throw new Error(`session search provider exceeded the ${SEARCH_PROVIDER_CALL_LIMIT}-call work budget`)
230
+ }
231
+ providerCalls++
232
+ const requestedCursor = cursor
233
+ const requestedLimit = pageLimit
234
+ let page
235
+ try {
236
+ page = await provider.searchSessions({
237
+ query: normalizedQuery,
238
+ eventFilters: [
239
+ { kind: 'type', values: ['user/message', 'assistant/message'] },
240
+ { kind: 'surface', values: ['current'] },
241
+ ],
242
+ limit: requestedLimit,
243
+ ...(requestedCursor === undefined ? {} : { cursor: requestedCursor }),
244
+ }, { signal })
245
+ signal.throwIfAborted()
246
+ } catch (error: unknown) {
247
+ signal.throwIfAborted()
248
+ if (requestedCursor === undefined
249
+ && error instanceof SessionQueryError
250
+ && error.code === 'SESSION_QUERY_INVALID_LIMIT'
251
+ && requestedLimit > 1) {
252
+ pageLimit = Math.max(1, Math.floor(requestedLimit / 2))
253
+ continue
254
+ }
255
+ if (requestedCursor !== undefined
256
+ && error instanceof SessionQueryError
257
+ && error.code === 'SESSION_QUERY_STALE_CURSOR') {
258
+ authorized.length = 0
259
+ acceptedIds.clear()
260
+ seenCursors.clear()
261
+ cursor = undefined
262
+ continue
263
+ }
264
+ throw error
265
+ }
266
+ if (page.items.length > requestedLimit) {
267
+ throw new Error(`session search provider returned ${String(page.items.length)} items; maximum is ${String(requestedLimit)}`)
268
+ }
269
+ for (const hit of page.items) {
270
+ if (authorized.length > SESSION_SEARCH_RESULT_LIMIT) continue
271
+ if (!visibleIds.has(hit.header.id)
272
+ || hit.bestMatch.sessionId !== hit.header.id
273
+ || hit.bestMatch.surface !== 'current'
274
+ || !MESSAGE_TYPES.has(hit.bestMatch.type)
275
+ || acceptedIds.has(hit.header.id)) continue
276
+ acceptedIds.add(hit.header.id)
277
+ authorized.push({
278
+ sessionId: hit.header.id,
279
+ snippet: truncateUnicodeCodePoints(hit.bestMatch.snippet, SESSION_SEARCH_SNIPPET_MAX_CODE_POINTS),
280
+ })
281
+ }
282
+ if (page.nextCursor !== undefined) {
283
+ if (seenCursors.has(page.nextCursor)) {
284
+ throw new Error('session search provider repeated a continuation cursor')
285
+ }
286
+ seenCursors.add(page.nextCursor)
287
+ }
288
+ if (authorized.length > SESSION_SEARCH_RESULT_LIMIT || page.nextCursor === undefined) break
289
+ cursor = page.nextCursor
290
+ }
291
+ return {
292
+ items: authorized.slice(0, SESSION_SEARCH_RESULT_LIMIT),
293
+ hasMore: authorized.length > SESSION_SEARCH_RESULT_LIMIT,
294
+ }
295
+ } catch (error: unknown) {
296
+ signal.throwIfAborted()
297
+ if (error instanceof SessionQueryError && error.code === 'SESSION_QUERY_ABORTED') {
298
+ throw new RemoteError('gateway/cancelled', 'session search was aborted', {})
299
+ }
300
+ throw new RemoteError('gateway/internal', `session search failed: ${String(error)}`, {})
301
+ }
302
+ }
303
+
304
+ private projectionsFor(
305
+ header: SessionHeader,
306
+ session: Session | undefined,
307
+ ): SessionProjectionHints | undefined {
308
+ try {
309
+ // The registry derives the summary key set from its registrations and
310
+ // hands back one stable set until the key table changes; both faces below
311
+ // serve only those keys, so a list row cannot carry a unit that declares
312
+ // itself summary-excluded.
313
+ const keys = this.ctx.sessionProjections.summaryKeys()
314
+ if (session !== undefined) {
315
+ // The live registry computes the block for this Session: its watermark
316
+ // shares the sequence space of the Session's baselines and frames.
317
+ return hintsOf('sequenced', this.ctx.sessionProjections.snapshot(session, keys))
318
+ }
319
+ // A cold row reads the persisted cache by header alone; the cache serves
320
+ // seeded and unseeded lifecycles alike because a listing never seeds a
321
+ // fold. The watermark is the stored record's own.
322
+ const cache = this.ctx.get('sessionProjectionCache')
323
+ return hintsOf('cached', cache?.cachedSnapshot(header, keys) ?? cache?.cachedPredecessorTitle(header))
324
+ } catch (error) {
325
+ this.ctx.logger.warn(
326
+ `api-session.list: projection column for "${header.id}" failed; serving the row without it: ${String(error)}`,
327
+ )
328
+ return undefined
329
+ }
330
+ }
331
+ }
332
+
333
+ /**
334
+ * Wrap one summary projection block as Session-list hints of the named sequence space.
335
+ * The block is the summary key set's values, not every value the source holds.
336
+ * @param kind - which sequence space the block's watermark belongs to.
337
+ * @param block - the block, or `undefined` when no source served one.
338
+ * @returns the hints, or `undefined` when the block is absent or carries no value.
339
+ */
340
+ function hintsOf(
341
+ kind: SessionProjectionHints['kind'],
342
+ block: ProjectionSnapshot | undefined,
343
+ ): SessionProjectionHints | undefined {
344
+ if (block === undefined || Object.keys(block.values).length === 0) return undefined
345
+ // Listing hints contain every summary wire value the source holds; cached
346
+ // hints remain partial because missing cache rows are never folded here.
347
+ return { kind, asOfSeq: block.asOfSeq, values: block.values }
348
+ }
349
+
350
+ function normalizeSearchQuery(query: string): string {
351
+ const normalized = query.trim()
352
+ if (normalized.length === 0) {
353
+ throw new RemoteError('gateway/bad-request', 'session search query must not be empty', {})
354
+ }
355
+ if (normalized.length > SESSION_SEARCH_QUERY_MAX_CHARS) {
356
+ throw new RemoteError(
357
+ 'gateway/bad-request',
358
+ `session search query must contain at most ${SESSION_SEARCH_QUERY_MAX_CHARS} UTF-16 code units`,
359
+ {},
360
+ )
361
+ }
362
+ if (normalized.includes('\0')) {
363
+ throw new RemoteError('gateway/bad-request', 'session search query must not contain NUL', {})
364
+ }
365
+ return normalized
366
+ }
367
+
368
+ function updatedAt(header: SessionHeader, metadata: SessionListMetadata | undefined): number {
369
+ return Math.max(header.createdAt, metadata?.lastPromptAt ?? 0)
370
+ }
371
+
372
+ function listFields(header: SessionHeader): {
373
+ readonly parentSessionId?: SessionId
374
+ readonly origin?: 'subagent'
375
+ readonly cwd?: string
376
+ } {
377
+ return {
378
+ ...(header.parentSession === undefined ? {} : { parentSessionId: header.parentSession }),
379
+ ...(header.origin === undefined ? {} : { origin: header.origin }),
380
+ ...(header.cwd === undefined ? {} : { cwd: header.cwd }),
381
+ }
382
+ }
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Authenticated GET/HEAD /api/file reads bounded file responses through
3
+ * the composed filesystem provider. Paths and MIME types do not restrict access;
4
+ * the connection service authenticates requests before this handler. A request
5
+ * without the current `v` version is redirected, uncached, to the versioned URL,
6
+ * whose response is cacheable indefinitely.
7
+ * @module @unieai/rabi-api-session-controller/media-references
8
+ */
9
+
10
+ import { isAbsolute } from 'node:path'
11
+ import type { Context } from '@unieai/cordis'
12
+ import type {} from '@unieai/rabi-client-connection'
13
+ import type {} from '@unieai/rabi-attachment'
14
+ import { FsError, type FileSystem } from '@unieai/rabi-fs'
15
+ import mime from 'mime-types'
16
+
17
+ const BASE_HEADERS = {
18
+ 'X-Content-Type-Options': 'nosniff',
19
+ // HTML and SVG files may be opened directly on the authenticated API origin.
20
+ 'Content-Security-Policy': "sandbox; default-src 'none'",
21
+ }
22
+ const NO_STORE = { ...BASE_HEADERS, 'Cache-Control': 'private, no-store' }
23
+ // A versioned URL names one file version, so its response never changes.
24
+ const VERSIONED = { ...BASE_HEADERS, 'Cache-Control': 'private, max-age=31536000, immutable' }
25
+
26
+ async function serveFile(request: Request, fs: FileSystem, maxBytes: number): Promise<Response> {
27
+ const fail = (status: number, text: string): Response =>
28
+ new Response(request.method === 'HEAD' ? null : text, { status, headers: NO_STORE })
29
+ const params = new URL(request.url).searchParams
30
+ const path = params.get('path')
31
+ if (path === null || path.length === 0) return fail(400, 'missing path')
32
+ if (path.includes('\0') || !isAbsolute(path)) return fail(400, 'absolute path required')
33
+ try {
34
+ const target = await fs.resolve(path, { signal: request.signal })
35
+ const info = await fs.stat(target, request.signal)
36
+ if (info === undefined) return fail(404, 'not found')
37
+ if (info.type !== 'file') return fail(403, 'not a regular file')
38
+ if (info.size !== undefined && info.size > maxBytes) return fail(413, 'file exceeds byte limit')
39
+ if (params.get('v') !== info.version) {
40
+ // Relative to the request URL, so deployment prefixes and the Desktop scheme are kept.
41
+ const location = `?${new URLSearchParams({ path, v: info.version }).toString()}`
42
+ return new Response(null, { status: 302, headers: { ...NO_STORE, Location: location } })
43
+ }
44
+ const headers: Record<string, string> = {
45
+ ...VERSIONED,
46
+ 'Content-Type': mime.lookup(target.displayPath) || 'application/octet-stream',
47
+ }
48
+ if (request.method === 'HEAD') {
49
+ if (info.size !== undefined) headers['Content-Length'] = String(info.size)
50
+ return new Response(null, { headers })
51
+ }
52
+ const bytes = await fs.readBytes(target, request.signal, maxBytes)
53
+ headers['Content-Length'] = String(bytes.byteLength)
54
+ return new Response(bytes.slice(), { headers })
55
+ } catch (error: unknown) {
56
+ if (!(error instanceof FsError)) throw error
57
+ const statuses: Partial<Record<FsError['code'], number>> = {
58
+ FS_NOT_FOUND: 404,
59
+ FS_NOT_REGULAR_FILE: 403,
60
+ FS_PERMISSION_DENIED: 403,
61
+ FS_SANDBOX_DENIED: 403,
62
+ FS_TOO_LARGE: 413,
63
+ FS_ABORTED: 499,
64
+ }
65
+ return fail(statuses[error.code] ?? 500, error.code)
66
+ }
67
+ }
68
+
69
+ /**
70
+ * File-display contribution. The connection service supplies authentication;
71
+ * `ctx.fs` supplies the execution world's paths, reads, and access policy.
72
+ */
73
+ export const SessionMediaReferences = {
74
+ inject: ['connection', 'fs', 'attachments'],
75
+ apply(ctx: Context): void {
76
+ const maxBytes = ctx.attachments.imageLimits.maxImageBytes
77
+ ctx.effect(() => ctx.connection.fetch.register({
78
+ path: '/api/file',
79
+ methods: ['GET', 'HEAD'],
80
+ requestBody: 'buffered',
81
+ fetch: request => serveFile(request, ctx.fs, maxBytes),
82
+ }), 'session-controller: /api/file')
83
+ },
84
+ }
@@ -0,0 +1,14 @@
1
+ /** Session Controller events available to a Remote Event assembly. */
2
+ type SessionControllerRemoteEvent =
3
+ | 'api-session/activity'
4
+ | 'api-session/added'
5
+ | 'api-session/error'
6
+ | 'api-session/removed'
7
+ | 'api-session/status'
8
+
9
+ declare module '@unieai/rabi-typert-protocol' {
10
+ interface TypertRemoteEventSelection extends
11
+ Record<SessionControllerRemoteEvent, true> {}
12
+ }
13
+
14
+ export {}
@@ -0,0 +1,108 @@
1
+ /** Session-addressed, cold-readable skill catalog Remote. */
2
+
3
+ import type { Context } from '@unieai/cordis'
4
+ import type {} from '@unieai/rabi-agent-preset-registry/types'
5
+ import { SessionQueryError } from '@unieai/rabi-session-query'
6
+ import { isUserInvocable } from '@unieai/rabi-skill'
7
+ import type {} from '@unieai/rabi-working-directory'
8
+ import type { ScopeKey } from '@unieai/rabi-scope'
9
+ import { Remote, RemoteError, TypertRemoteService } from '@unieai/rabi-typert-protocol'
10
+ import type { SkillListRequest, SkillListValue } from './types.ts'
11
+
12
+ declare module '@unieai/cordis' {
13
+ interface Context {
14
+ /** Host owner of the Session-addressed `skills` Remote namespace. */
15
+ sessionSkillCatalog: SessionSkillCatalog
16
+ }
17
+ }
18
+
19
+ /** Host service backing `ctx.remote.skills` without activating a cold Agent. */
20
+ export class SessionSkillCatalog extends TypertRemoteService {
21
+ static inject = ['agents', 'sessionQuery', 'typert', 'workingDirectory']
22
+
23
+ /** @param ctx - Host context carrying Session reads and optional skill/preset services. */
24
+ constructor(ctx: Context) {
25
+ super(ctx, 'sessionSkillCatalog', { namespace: 'skills' })
26
+ }
27
+
28
+ /**
29
+ * List the user-invocable skills visible to one Session composition.
30
+ * @param request - Session identity whose cwd and preset select the catalog view.
31
+ * @param signal - caller lifetime carried by the Remote transport; admitted catalog reads retain their existing completion semantics.
32
+ * @returns user-invocable skill metadata without loading skill bodies.
33
+ * @throws RemoteError when the Session cannot be inspected or no registry can serve it.
34
+ */
35
+ @Remote
36
+ async list(request: SkillListRequest, signal: AbortSignal): Promise<SkillListValue> {
37
+ const { sessionId } = request
38
+ let cwd: string
39
+ let agentPreset: string | undefined
40
+ try {
41
+ using observation = await this.ctx.sessionQuery.observeSession(sessionId)
42
+ if (observation.projections === undefined) {
43
+ throw new Error('skill catalog requires a projected Session observation')
44
+ }
45
+ cwd = observation.projections.values.workingDirectory
46
+ ?? observation.header.cwd
47
+ ?? this.ctx.workingDirectory.defaultDirectory
48
+ agentPreset = observation.projections.values.agentPreset ?? undefined
49
+ const live = this.ctx.agents.get(sessionId)
50
+ if (live !== undefined) cwd = await this.ctx.workingDirectory.ensure(live, signal)
51
+ } catch (error: unknown) {
52
+ if (error instanceof SessionQueryError
53
+ && error.code === 'SESSION_QUERY_SESSION_NOT_FOUND') {
54
+ throw new RemoteError('session/not-found', `session "${sessionId}" not found`, { sessionId })
55
+ }
56
+ throw new RemoteError(
57
+ 'gateway/internal',
58
+ `session "${sessionId}" could not be inspected: ${String(error)}`,
59
+ {},
60
+ )
61
+ }
62
+
63
+ const live = this.ctx.agents.get(sessionId)
64
+ const presets = this.ctx.get('agentPresets')
65
+ const scoped = live === undefined ? undefined : presets?.serviceFor(live, 'skills')
66
+ const skillRegistry = scoped ?? this.ctx.get('skills')
67
+ if (skillRegistry === undefined) {
68
+ throw new RemoteError(
69
+ 'gateway/internal',
70
+ 'skill registry is absent: neither this session\'s agent preset nor the host composition mounts @unieai/rabi-skill',
71
+ {},
72
+ )
73
+ }
74
+
75
+ await using lease = live === undefined ? await this.scopeFor(agentPreset) : undefined
76
+ const scope = live ?? lease?.key
77
+ try {
78
+ const skills = (await skillRegistry.list({ cwd, scope })).filter(isUserInvocable)
79
+ return {
80
+ skills: skills.map(skill => ({
81
+ name: skill.name,
82
+ ...skill.path === undefined ? {} : { path: skill.path },
83
+ description: skill.description,
84
+ ...skill.whenToUse === undefined ? {} : { whenToUse: skill.whenToUse },
85
+ modelInvocable: skill.invocation.modelInvocable,
86
+ })),
87
+ }
88
+ } catch (error: unknown) {
89
+ throw new RemoteError('gateway/internal', `skill listing failed: ${String(error)}`, {})
90
+ }
91
+ }
92
+
93
+ /** Resolve a live or standing preset scope without creating an Agent. */
94
+ private async scopeFor(
95
+ agentPreset: string | undefined,
96
+ ): Promise<({ key: ScopeKey } & AsyncDisposable) | undefined> {
97
+ const presets = this.ctx.get('agentPresets')
98
+ if (presets === undefined) return undefined
99
+ try {
100
+ return await presets.acquireScope(agentPreset)
101
+ } catch {
102
+ // An unknown or unusable recorded preset falls back to the global registry.
103
+ return undefined
104
+ }
105
+ }
106
+ }
107
+
108
+ export default SessionSkillCatalog