@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/index.ts ADDED
@@ -0,0 +1,651 @@
1
+ /** Session Remote owner: cold reads, explicit Agent commands, and live control state. */
2
+
3
+ import { hostname } from 'node:os'
4
+ import { resolve } from 'node:path'
5
+ import type { Agent } from '@unieai/rabi-agent'
6
+ import type {} from '@unieai/rabi-fs'
7
+ import { Context, Service } from '@unieai/cordis'
8
+ import z from '@unieai/schemastery'
9
+ import { errorChain, ReasoningEffortId, type MessageSource } from '@unieai/rabi-llm'
10
+ import type {} from '@unieai/rabi-client-file-upload'
11
+ import { canOpenNativePath, nativeFileManager, nativeFileApplications, openNativeFileApplication, openNativeAssociatedPath, revealNativePath } from '@unieai/rabi-native-command'
12
+ import type { SessionId } from '@unieai/rabi-session'
13
+ import type {} from '@unieai/rabi-session-projection-cache'
14
+ import type { SessionObservation } from '@unieai/rabi-session-query'
15
+ import { Remote, RemoteError, TypertRemoteService, principalOf, type TypertResourceResolveInput } from '@unieai/rabi-typert-protocol'
16
+ import { canonicalClientTimeZone } from '@unieai/rabi-util-time'
17
+ import { assertNever } from '@unieai/rabi-util-values'
18
+ import type {} from '@unieai/rabi-api-remote-access'
19
+ import {
20
+ ApiSessionAgentController,
21
+ type ApiSessionAgentResult,
22
+ } from './agent.ts'
23
+ import { SessionCommandController, hasPromptContent } from './commands.ts'
24
+ import { SessionControlController } from './control.ts'
25
+ import { HistoryController } from './history/controller.ts'
26
+ import { StateController } from './state/controller.ts'
27
+ import { WebController } from './web/controller.ts'
28
+ import { SessionFileReferences } from './file-references.ts'
29
+ import { ApiSessionList } from './list.ts'
30
+ import { buildModelCatalog, hasProviderApiKey } from './catalog.ts'
31
+ import { SessionSkillCatalog } from './skill-catalog.ts'
32
+ import { SessionMediaReferences } from './media-references.ts'
33
+ import { ArchivedSessionGate } from './archived-session-gate.ts'
34
+ import type {
35
+ ModelCatalog,
36
+ SessionWorkspacePathApplication,
37
+ SessionAddress,
38
+ SessionAttachmentRequest,
39
+ SessionAttachmentValue,
40
+ SessionCancelRequest,
41
+ SessionCancelValue,
42
+ SessionControlFrame,
43
+ SessionCreateRequest,
44
+ SessionCreateValue,
45
+ SessionFollowFrame,
46
+ SessionFollowRequest,
47
+ SessionForkRequest,
48
+ SessionForkValue,
49
+ SessionListRequest,
50
+ SessionListValue,
51
+ SessionOpenWorkspacePathRequest,
52
+ SessionOpenWorkspacePathValue,
53
+ SessionEventsPage, SessionPageRequest, SessionEventFrame, SessionObserveEventRequest,
54
+ SessionProjectionFrame, SessionStateRequest, SessionState, SessionWaitRequest, SessionWaitValue,
55
+ SessionPromptRequest,
56
+ SessionPromptValue,
57
+ SessionRenameRequest,
58
+ SessionRenameValue,
59
+ SessionSearchRequest,
60
+ SessionSearchValue,
61
+ SessionSelectModelRequest,
62
+ SessionSelectModelValue,
63
+ SessionProjectionsRequest,
64
+ SessionProjectionsValue,
65
+ SessionUpdateQueueRequest,
66
+ SessionUpdateQueueValue,
67
+ } from './types.ts'
68
+
69
+ export type * from './types.ts'
70
+ export { ApiSessionNotFound } from './agent.ts'
71
+ export { SessionFileReferences } from './file-references.ts'
72
+ export { SessionSkillCatalog } from './skill-catalog.ts'
73
+
74
+ declare module '@unieai/cordis' {
75
+ interface Context {
76
+ /** Host Session business API and Remote namespace owner. */
77
+ sessionController: SessionController
78
+ }
79
+ }
80
+
81
+ /**
82
+ * Extract the Session resource from an ID or a history address.
83
+ *
84
+ * Registers as the `session` kind default, so it applies to every Remote method of
85
+ * every namespace: a top-level `sessionId` parameter, otherwise the first object
86
+ * parameter carrying `sessionId` or an `address`. A new request type whose first
87
+ * object parameter has an unrelated `address` field would be read as an address.
88
+ * @param input - validated wire arguments and their ordered parameter descriptions.
89
+ * @returns the named Session identity, otherwise the first object's Session identity or history address.
90
+ * @throws Error when the request object supplies both sessionId and address.
91
+ */
92
+ function resolveSessionResource({ args, parameters }: TypertResourceResolveInput): SessionId | undefined {
93
+ const sessionParameter = parameters.find(parameter => parameter.name === 'sessionId' || parameter.wire === 'sessionId')
94
+ if (sessionParameter !== undefined) return args[sessionParameter.wire] as SessionId | undefined
95
+ for (const parameter of parameters) {
96
+ const value = args[parameter.wire]
97
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) continue
98
+ const request = value as { readonly sessionId?: SessionId; readonly address?: SessionAddress }
99
+ const address = request.address
100
+ if (request.sessionId !== undefined && address !== undefined) {
101
+ throw new Error('Session resource request must not contain both sessionId and address')
102
+ }
103
+ return request.sessionId ?? (address === undefined ? undefined
104
+ : address.kind === 'session' ? address.sessionId : address.childSessionId)
105
+ }
106
+ return undefined
107
+ }
108
+
109
+ /** Session Controller deployment policy. */
110
+ export interface Config {
111
+ /** Override platform desktop-opener detection. */
112
+ readonly nativeOpen?: boolean
113
+ /** Positive integral milliseconds of list work before yielding between complete rows. */
114
+ readonly listWorkSliceMs?: number
115
+ }
116
+
117
+ /** Deployment policy after schema defaults have been applied. */
118
+ type ResolvedConfig = Config & { readonly listWorkSliceMs: number }
119
+
120
+ /** Host integrations replaceable by direct unit tests. */
121
+ export interface SessionControllerInternals {
122
+ /** Native default-application handoff. */
123
+ readonly openPath?: (path: string, signal: AbortSignal) => Promise<void>
124
+ /** Native file-association query. */
125
+ readonly fileApplications?: typeof nativeFileApplications
126
+ /** Explicit registered-application handoff. */
127
+ readonly openFileApplication?: typeof openNativeFileApplication
128
+ /** Native file-manager handoff. */
129
+ readonly revealPath?: (path: string, signal: AbortSignal) => Promise<void>
130
+ /** Native handoff availability probe. */
131
+ readonly canOpenPath?: () => boolean
132
+ }
133
+
134
+ /** Host service backing the generated `ctx.remote.session` namespace. */
135
+ export class SessionController extends TypertRemoteService {
136
+ static inject = [
137
+ 'agentDefaultModel',
138
+ 'agents',
139
+ 'attachments',
140
+ 'fileUploads',
141
+ 'fs',
142
+ 'llm',
143
+ 'remoteAccess',
144
+ 'sessions',
145
+ 'sessionProjections',
146
+ 'sessionQuery',
147
+ 'typert',
148
+ 'typertGateway',
149
+ 'workspaceRegistry',
150
+ ]
151
+
152
+ static Config: z<Config, ResolvedConfig> = z.object({
153
+ nativeOpen: z.boolean(),
154
+ listWorkSliceMs: z.natural().min(1).default(16),
155
+ })
156
+
157
+ private historyController!: HistoryController
158
+ private stateController!: StateController
159
+ private webController!: WebController
160
+
161
+ private agents!: ApiSessionAgentController
162
+ private commands!: SessionCommandController
163
+ private controlState!: SessionControlController
164
+ private listState!: ApiSessionList
165
+ private readonly openPath: (path: string, signal: AbortSignal) => Promise<void>
166
+ private readonly fileApplications: typeof nativeFileApplications
167
+ private readonly openFileApplication: typeof openNativeFileApplication
168
+ private readonly revealPath: (path: string, signal: AbortSignal) => Promise<void>
169
+ private readonly canOpenPath: () => boolean
170
+ private readonly listWorkSliceMs: number
171
+ private readonly promotions = new Set<Promise<void>>()
172
+
173
+ /**
174
+ * @param ctx - Host context containing the Session capability assembly.
175
+ * @param config - native-opener and list-scheduling deployment policy.
176
+ * @param internals - host integrations replaceable by direct unit tests.
177
+ */
178
+ constructor(ctx: Context, config: Config, internals: SessionControllerInternals = {}) {
179
+ super(ctx, 'sessionController', { namespace: 'session' })
180
+ this.listWorkSliceMs = SessionController.Config(config).listWorkSliceMs
181
+ this.fileApplications = internals.fileApplications ?? nativeFileApplications
182
+ this.openFileApplication = internals.openFileApplication ?? openNativeFileApplication
183
+ this.openPath = internals.openPath ?? openNativeAssociatedPath
184
+ this.revealPath = internals.revealPath ?? revealNativePath
185
+ this.canOpenPath = internals.canOpenPath
186
+ ?? (() => config.nativeOpen ?? (internals.openPath !== undefined || canOpenNativePath()))
187
+ }
188
+
189
+ protected async [Service.init](): Promise<void> {
190
+ const ctx = this.ctx
191
+ ctx.typert.resources.register('session', { resolve: resolveSessionResource })
192
+ this.agents = new ApiSessionAgentController(ctx)
193
+ this.agents.initialize()
194
+ this.commands = new SessionCommandController(ctx, this.agents, process.cwd())
195
+ ctx.effect(() => ctx.fileUploads.registerAgentResolver(async (sessionId) => {
196
+ const result = await this.agents.resolveAgent(sessionId)
197
+ if ('error' in result) throw result.error
198
+ return result.agent
199
+ }), 'session-controller: file-upload Agent resolver')
200
+ this.controlState = new SessionControlController(ctx)
201
+ // Registered before history so reverse-order teardown closes every
202
+ // follower before waiting for already-admitted promotions.
203
+ ctx.effect(() => async () => {
204
+ await Promise.allSettled([...this.promotions])
205
+ }, 'session-controller.promotions')
206
+ // Assistant-stream observation must be live before the list read yields: an Agent's
207
+ // opening frame arriving during that await would otherwise have no listener.
208
+ this.historyController = new HistoryController(ctx)
209
+ this.stateController = new StateController(ctx, this.historyController)
210
+ this.webController = new WebController(ctx, this.historyController, (observation) => { this.promote(observation) })
211
+ this.listState = new ApiSessionList(ctx, this.listWorkSliceMs)
212
+ await this.commands.initialize()
213
+ ctx.fiber.assertActive()
214
+ await this.listState.initialize()
215
+ ctx.fiber.assertActive()
216
+ ctx.plugin(SessionFileReferences)
217
+ ctx.plugin(SessionMediaReferences)
218
+ ctx.plugin(SessionSkillCatalog)
219
+ // An archived Session, or a subagent descendant of one, runs no model step
220
+ // until it is restored; what it still runs is stopped by the owners that
221
+ // answer the Workspace registry's archive-admission events.
222
+ ctx.plugin(ArchivedSessionGate)
223
+
224
+ ctx.on('session/created', (session) => {
225
+ ctx.emit('api-session/added', this.listState.summaryFor(session))
226
+ })
227
+ ctx.on('session/disposed', (session) => {
228
+ ctx.emit('api-session/removed', session.id)
229
+ })
230
+ const publishAgentAvailability = ({ agent }: { agent: Agent }): undefined => {
231
+ if (ctx.sessions.get(agent.id) === agent.session) {
232
+ ctx.emit('api-session/added', this.listState.summaryFor(agent.session))
233
+ }
234
+ }
235
+ ctx.on('agent/created', publishAgentAvailability)
236
+ ctx.on('agent/disposed', publishAgentAvailability)
237
+ ctx.on('agent/status', ({ agent, status }) => {
238
+ ctx.emit('api-session/status', agent.id, status === 'running')
239
+ })
240
+ ctx.on('agent/error', ({ agent, error }) => {
241
+ ctx.emit('api-session/error', agent.id, errorChain(error))
242
+ })
243
+ ctx.on('session/event', (session, event) => {
244
+ if (event.type !== 'user/message' || event.data.source.kind !== 'user') return
245
+ ctx.emit('api-session/activity', session.id, event.time)
246
+ })
247
+ }
248
+
249
+ /**
250
+ * Request background activation through the existing Session Agent controller.
251
+ * @param observation - owned lease disposed by the background task; callers retain their own lease separately.
252
+ */
253
+ private promote(observation: SessionObservation): void {
254
+ const sessionId = observation.header.id
255
+ const task = (async () => {
256
+ using ownedObservation = observation
257
+ const result = await this.agents.resolveObservedAgent(ownedObservation)
258
+ if ('error' in result) this.ctx.emit('api-session/error', sessionId, result.error.message)
259
+ })().catch((error: unknown) => {
260
+ this.ctx.logger.error(`session-controller: background activation for "${sessionId}" failed: ${errorChain(error)}`)
261
+ })
262
+ this.promotions.add(task)
263
+ void task.finally(() => { this.promotions.delete(task) })
264
+ }
265
+
266
+ /**
267
+ * Resolve or resume one ordinary Session for another Host API domain.
268
+ * @param sessionId - Session identity whose Agent owns the operation.
269
+ * @returns the live Agent or the stable Session-domain failure.
270
+ */
271
+ resolveAgent(sessionId: SessionId): Promise<ApiSessionAgentResult> {
272
+ return this.agents.resolveAgent(sessionId)
273
+ }
274
+
275
+ /**
276
+ * Read all visible Session rows without resuming an Agent.
277
+ * @param _request - reserved empty list request.
278
+ * @param signal - cancellation for persistence reads and summary generation.
279
+ * @returns visible Session summaries ordered by activity.
280
+ */
281
+ @Remote('list')
282
+ async list(_request: SessionListRequest, signal: AbortSignal): Promise<SessionListValue> {
283
+ const items = await this.listState.list(signal)
284
+ return { items: items.filter(item => this.ctx.remoteAccess.allows({ kind: 'session', id: item.sessionId })) }
285
+ }
286
+
287
+ /**
288
+ * Search visible Session content without resuming an Agent. A non-owner
289
+ * receives only the hits whose Session `allows()` admits; `hasMore`
290
+ * describes the bounded result before that filtering.
291
+ * @param request - literal message-content query.
292
+ * @param signal - cancellation for list and search reads.
293
+ * @returns authorized bounded Session search results.
294
+ */
295
+ @Remote('search')
296
+ async search(request: SessionSearchRequest, signal: AbortSignal): Promise<SessionSearchValue> {
297
+ const result = await this.listState.search(request.query, signal)
298
+ return { ...result, items: result.items.filter(item => this.ctx.remoteAccess.allows({ kind: 'session', id: item.sessionId })) }
299
+ }
300
+
301
+ /**
302
+ * Create one ordinary Session for a new conversation, reusing the named blank Session while it is reusable.
303
+ * @param request - optional blank Session to reuse, location, and Agent preset.
304
+ * @returns the created or reused Session identity and its preset when configured.
305
+ */
306
+ @Remote('create')
307
+ create(request: SessionCreateRequest): Promise<SessionCreateValue> {
308
+ return this.commands.create(request)
309
+ }
310
+
311
+ /**
312
+ * Select one Session-local model after explicitly resuming the Session; save the default in the background.
313
+ * @param request - Session identity and requested model selection.
314
+ * @returns the normalized selection installed for the Session, without waiting for default persistence.
315
+ */
316
+ @Remote('selectModel')
317
+ selectModel(request: SessionSelectModelRequest): Promise<SessionSelectModelValue> {
318
+ return this.commands.selectModel(request)
319
+ }
320
+
321
+ /**
322
+ * Select the first available account model after login when no provider API key is configured.
323
+ * @returns after saving the first available model or retaining the existing default.
324
+ */
325
+ @Remote
326
+ async initializeDefaultModel(): Promise<void> {
327
+ const provider = 'deepseek-account'
328
+ if (await hasProviderApiKey(this.ctx)) return
329
+ const catalog = await buildModelCatalog(this.ctx)
330
+ const model = catalog.groups.find(group => group.id === provider)?.models[0]
331
+ if (model === undefined) throw new RemoteError('session/provider-models-unavailable',
332
+ `provider "${provider}" has no available models`, { provider })
333
+ const selection = { provider, model: model.id,
334
+ ...model.reasoning?.defaultEffort === undefined ? {} : { reasoningEffort: ReasoningEffortId(model.reasoning.defaultEffort) },
335
+ }
336
+ await this.ctx.agentDefaultModel.saveSelection(selection)
337
+ }
338
+
339
+ /**
340
+ * Describe every currently routable model for Host-generation selectors.
341
+ * @returns provider-grouped models, the deployment default, and isolated provider failures.
342
+ */
343
+ @Remote('modelCatalog')
344
+ modelCatalog(): Promise<ModelCatalog> {
345
+ return buildModelCatalog(this.ctx)
346
+ }
347
+
348
+ /**
349
+ * Report whether this deployment can hand a Session workspace path to a native desktop.
350
+ * @returns true when the matching open operation is available.
351
+ */
352
+ @Remote
353
+ canOpenWorkspacePath(): boolean {
354
+ return this.canOpenPath()
355
+ }
356
+
357
+ /**
358
+ * Describe the serving desktop for authenticated file-action routes.
359
+ * @returns Host name, configured availability, and platform-specific file-manager behavior.
360
+ */
361
+ workspaceDesktop(): { name: string; available: boolean; fileManager: 'finder' | 'explorer' | 'directory' | null } {
362
+ const fileManager = nativeFileManager()
363
+ return { name: hostname(), available: fileManager !== null && this.canOpenPath(), fileManager }
364
+ }
365
+
366
+ /**
367
+ * Verify one path through the composed filesystem and open it on the Host desktop.
368
+ * @param request - path after best-effort Session workspace resolution.
369
+ * @param signal - caller lifetime; abort terminates the native command.
370
+ * @returns confirmation after the native opener accepts the path.
371
+ * @throws RemoteError when the request is invalid, has no verified Host mapping, is cancelled, or the opener fails.
372
+ */
373
+ @Remote('openWorkspacePath')
374
+ async openWorkspacePath(
375
+ request: SessionOpenWorkspacePathRequest,
376
+ signal: AbortSignal,
377
+ ): Promise<SessionOpenWorkspacePathValue> {
378
+ try {
379
+ const path = await this.verifyDesktopPath(request.path, signal)
380
+ if (request.action === 'reveal') await this.revealPath(path, signal)
381
+ else if (request.application !== undefined) await this.openFileApplication(path, request.application, signal)
382
+ else await this.openPath(path, signal)
383
+ return { opened: true }
384
+ } catch (error: unknown) {
385
+ if (signal.aborted) throw new RemoteError('gateway/cancelled', 'path open was aborted', {})
386
+ if (error instanceof RemoteError) throw error
387
+ throw new RemoteError(
388
+ 'gateway/internal',
389
+ 'path open failed',
390
+ {},
391
+ { cause: error },
392
+ )
393
+ }
394
+ }
395
+
396
+ /**
397
+ * Query current file handlers on the serving desktop without activating an Agent.
398
+ * @param request - file path in Host filesystem syntax.
399
+ * @param signal - caller lifetime, propagated to filesystem and desktop queries.
400
+ * @returns OS application names, icons, and default selection; empty when desktop opening is unavailable.
401
+ * @throws RemoteError when the path is invalid, the query is cancelled, or native discovery fails.
402
+ */
403
+ @Remote('workspacePathApplications')
404
+ async workspacePathApplications(
405
+ request: { readonly path: string }, signal: AbortSignal,
406
+ ): Promise<readonly SessionWorkspacePathApplication[]> {
407
+ if (!this.canOpenPath()) return []
408
+ try {
409
+ const path = await this.verifyDesktopPath(request.path, signal)
410
+ return await this.fileApplications(path, signal)
411
+ } catch (error: unknown) {
412
+ if (signal.aborted) throw new RemoteError('gateway/cancelled', 'application query was aborted', {})
413
+ if (error instanceof RemoteError) throw error
414
+ throw new RemoteError('gateway/internal', 'file application query failed', {}, { cause: error })
415
+ }
416
+ }
417
+
418
+ private async verifyDesktopPath(path: string, signal: AbortSignal): Promise<string> {
419
+ if (path.length === 0) throw new RemoteError('gateway/bad-request', 'A non-empty file path is required', {})
420
+ signal.throwIfAborted()
421
+ const hostPath = resolve(path)
422
+ const { fs } = this.ctx
423
+ const mapped = fs.processPathFromHostPath(hostPath)
424
+ if (mapped === undefined || fs.processPath(await fs.resolve(mapped, { signal })) !== hostPath) {
425
+ throw new RemoteError('gateway/bad-request', 'Path has no verified Host path', {})
426
+ }
427
+ signal.throwIfAborted()
428
+ return hostPath
429
+ }
430
+
431
+ /**
432
+ * Rename one Session after explicitly resuming it.
433
+ * @param request - Session identity and proposed title.
434
+ * @returns the accepted title and durable event sequence.
435
+ */
436
+ @Remote('rename')
437
+ rename(request: SessionRenameRequest): Promise<SessionRenameValue> {
438
+ return this.commands.rename(request)
439
+ }
440
+
441
+ /**
442
+ * Fork one cold-readable exact event prefix into a new Session. An omitted
443
+ * boundary selects the latest completed-turn prefix; an open cut receives
444
+ * synthetic fork closers.
445
+ * @param request - source Session, optional exact inclusive event boundary, and migration preflight choice.
446
+ * @returns the new Session identity.
447
+ */
448
+ @Remote('fork')
449
+ async fork(request: SessionForkRequest): Promise<SessionForkValue> {
450
+ if (request.allowMigration === false && this.ctx.sessions.get(request.sessionId) === undefined) {
451
+ const stored = await this.ctx.get('sessionPersistence')?.stat(request.sessionId)
452
+ if (stored?.formatStatus === 'migration-required' && this.ctx.sessions.get(request.sessionId) === undefined) {
453
+ throw new RemoteError('session/migration-required', 'Open the source Session to complete migration before forking', {
454
+ sessionId: request.sessionId,
455
+ })
456
+ }
457
+ }
458
+ return this.commands.fork(request)
459
+ }
460
+
461
+ /**
462
+ * Admit one prompt after explicitly resuming its Session.
463
+ * @param request - Session identity, prompt content, source metadata, and delivery mode.
464
+ * @param signal - caller cancellation before prompt admission begins.
465
+ * @returns acknowledgement that the Agent accepted the prompt.
466
+ */
467
+ @Remote('prompt')
468
+ async prompt(request: SessionPromptRequest, signal: AbortSignal): Promise<SessionPromptValue> {
469
+ signal.throwIfAborted()
470
+ if (request.content.length > 0 && !hasPromptContent(request.content)) {
471
+ throw new RemoteError('gateway/bad-request', 'prompt content must include non-whitespace text or an attachment', {})
472
+ }
473
+ const clientTimeZone = request.clientTimeZone === undefined
474
+ ? undefined
475
+ : canonicalClientTimeZone(request.clientTimeZone)
476
+ if (request.clientTimeZone !== undefined && clientTimeZone === undefined) {
477
+ throw new RemoteError(
478
+ 'session/invalid-time-zone',
479
+ 'clientTimeZone must be UTC or a valid IANA Area/Location name',
480
+ { value: request.clientTimeZone },
481
+ )
482
+ }
483
+ // The caller is recorded only when it is not the owner, so owner messages keep their exact source.
484
+ const principal = principalOf(this.ctx.invocation)
485
+ const source: MessageSource = {
486
+ kind: request.content.length === 0 ? 'retry' : 'user',
487
+ rpcId: request.requestId,
488
+ ...(clientTimeZone === undefined ? {} : { clientTimeZone }),
489
+ ...(principal === undefined ? {} : { principal }),
490
+ }
491
+ return this.commands.prompt(request, source)
492
+ }
493
+
494
+ /**
495
+ * Read one image from the attachment store after gateway authorization.
496
+ * @param request - image reference and gateway permission scope; Session existence is not checked.
497
+ * @returns the durable attachment reference and base64-encoded bytes.
498
+ */
499
+ @Remote('attachment')
500
+ attachment(request: SessionAttachmentRequest): Promise<SessionAttachmentValue> {
501
+ return this.commands.attachment(request)
502
+ }
503
+
504
+ /**
505
+ * Mutate one still-pending queue occurrence, resuming a cold Agent first.
506
+ * @param request - Session, queue item, and requested mutation.
507
+ * @returns acknowledgement that the queue mutation was applied.
508
+ */
509
+ @Remote('updateQueue')
510
+ updateQueue(request: SessionUpdateQueueRequest): Promise<SessionUpdateQueueValue> {
511
+ return this.commands.updateQueue(request)
512
+ }
513
+
514
+ /**
515
+ * Cancel one active Agent turn without dropping its pending inbox.
516
+ * @param request - Session whose active Agent turn is cancelled.
517
+ * @returns acknowledgement that cancellation was requested.
518
+ */
519
+ @Remote('cancel')
520
+ cancel(request: SessionCancelRequest): SessionCancelValue {
521
+ return this.commands.cancel(request)
522
+ }
523
+
524
+ /**
525
+ * Read one cold-safe, message-aligned Session history page.
526
+ * @deprecated Use `events`; this entry point remains for existing Web callers.
527
+ * @param request - durable address, optional fixed cut, backward cursor, and page budget.
528
+ * @param signal - cancellation for persistence reads.
529
+ * @returns one chronological page with its inclusive cursor; an omitted `throughSeq` selects the observed log end.
530
+ */
531
+ @Remote('page')
532
+ page(request: SessionPageRequest, signal: AbortSignal): Promise<SessionEventsPage> {
533
+ return this.historyController.events(request, signal)
534
+ }
535
+
536
+ /**
537
+ * Read one cold-safe, message-aligned Session history page.
538
+ * @param request - durable address, optional fixed cut, backward cursor, and page budget.
539
+ * @param signal - cancellation for persistence reads.
540
+ * @returns one chronological page with its inclusive cursor.
541
+ */
542
+ @Remote
543
+ events(request: SessionPageRequest, signal: AbortSignal): Promise<SessionEventsPage> {
544
+ return this.historyController.events(request, signal)
545
+ }
546
+
547
+ /**
548
+ * Subscribe to Session events without reading a snapshot.
549
+ * @param request - Session address.
550
+ * @param signal - subscription cancellation.
551
+ * @returns readiness and subsequent events, without a snapshot.
552
+ */
553
+ @Remote({ mode: 'stream' })
554
+ observeEvent(request: SessionObserveEventRequest, signal: AbortSignal): AsyncIterable<SessionEventFrame> {
555
+ return this.historyController.observeEvent(request, signal)
556
+ }
557
+
558
+ /**
559
+ * Subscribe to Session projection changes.
560
+ * @param request - target Session.
561
+ * @param signal - subscription cancellation.
562
+ * @returns readiness followed by one projection change frame per committed event.
563
+ */
564
+ @Remote({ mode: 'stream' })
565
+ observeProjections(request: SessionProjectionsRequest, signal: AbortSignal): AsyncIterable<SessionProjectionFrame> {
566
+ return this.historyController.observeProjections(request, signal)
567
+ }
568
+
569
+ /**
570
+ * Read passive Session state.
571
+ * @param request - target Session.
572
+ * @param signal - read cancellation.
573
+ * @returns current passive state.
574
+ */
575
+ @Remote
576
+ state(request: SessionStateRequest, signal: AbortSignal): Promise<SessionState> {
577
+ return this.stateController.state(request, signal)
578
+ }
579
+
580
+ /**
581
+ * Subscribe to complete Session state replacements.
582
+ * @param request - target Session.
583
+ * @param signal - subscription cancellation.
584
+ * @returns complete passive state replacements.
585
+ */
586
+ @Remote({ mode: 'stream' })
587
+ observeState(request: SessionStateRequest, signal: AbortSignal): AsyncIterable<SessionState> {
588
+ return this.stateController.observeState(request, signal)
589
+ }
590
+
591
+ /**
592
+ * Wait for Session quiescence or pending input with bounded assistant output.
593
+ * @param request - Session, wait bounds and output window.
594
+ * @param signal - caller cancellation.
595
+ * @returns stopping state and bounded assistant output.
596
+ */
597
+ @Remote
598
+ wait(request: SessionWaitRequest, signal: AbortSignal): Promise<SessionWaitValue> {
599
+ return this.stateController.wait(request, signal)
600
+ }
601
+
602
+ /**
603
+ * Follow one Session log from its opening or resume cursor.
604
+ * @param request - durable address and last committed sequence already held by the caller.
605
+ * @param signal - cancellation owned by the Remote stream carrier.
606
+ * @returns a complete opening snapshot followed by gap-free durable event
607
+ * frames and optional cursorless assistant-stream frames.
608
+ */
609
+ @Remote({ mode: 'stream' })
610
+ follow(request: SessionFollowRequest, signal: AbortSignal): AsyncIterable<SessionFollowFrame> {
611
+ return this.webController.follow(request, signal)
612
+ }
613
+
614
+ /**
615
+ * Read exact projections, returning cached hints only when migration is required.
616
+ * @param request - Session whose current values are required.
617
+ * @param signal - cancellation for the Session read.
618
+ * @returns a sequenced baseline, cached hints when migration is deferred, or null when absent.
619
+ */
620
+ @Remote('projections')
621
+ projections(request: SessionProjectionsRequest, signal: AbortSignal): Promise<SessionProjectionsValue> {
622
+ return this.historyController.projections(request, signal)
623
+ }
624
+
625
+ /**
626
+ * Stream a complete live-control baseline followed by replacement frames.
627
+ * @param signal - cancellation owned by the Remote stream carrier.
628
+ * @returns one complete baseline followed by live replacement frames.
629
+ */
630
+ @Remote({ mode: 'stream' })
631
+ async *control(signal: AbortSignal): AsyncIterable<SessionControlFrame> {
632
+ for await (const frame of this.controlState.control(signal)) {
633
+ switch (frame.type) {
634
+ case 'baseline': {
635
+ const projections = Object.fromEntries(Object.entries(frame.value.projections)
636
+ .filter(([sessionId]) => this.ctx.remoteAccess.allows({ kind: 'session', id: sessionId as SessionId })))
637
+ yield { type: 'baseline', value: { ...frame.value, projections } }
638
+ break
639
+ }
640
+ case 'projection':
641
+ if (this.ctx.remoteAccess.allows({ kind: 'session', id: frame.sessionId })) yield frame
642
+ break
643
+ /* v8 ignore next -- closed control-frame union. */
644
+ default:
645
+ assertNever(frame)
646
+ }
647
+ }
648
+ }
649
+ }
650
+
651
+ export default SessionController