@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/agent.ts ADDED
@@ -0,0 +1,474 @@
1
+ /** Agent activation, composition, and initial model route owned by API Session. */
2
+
3
+ import { randomUUID } from 'node:crypto'
4
+ import { mkdir } from 'node:fs/promises'
5
+ import type { Context } from '@unieai/cordis'
6
+ import type { Agent, AgentOptions, AgentSetup } from '@unieai/rabi-agent'
7
+ import type {} from '@unieai/rabi-agent-default-model'
8
+ import { installModelSelection } from '@unieai/rabi-agent'
9
+ import type {} from '@unieai/rabi-agent-preset-registry'
10
+ import { brandString } from '@unieai/rabi-brand'
11
+ import type { Session, SessionId } from '@unieai/rabi-session'
12
+ import { SessionQueryError, type SessionObservation } from '@unieai/rabi-session-query'
13
+ import { RemoteError, remoteErrorOf } from '@unieai/rabi-typert-protocol'
14
+ import type {} from '@unieai/rabi-typert-registry'
15
+
16
+ /** Cold Session identity absent from persistence. */
17
+ export class ApiSessionNotFound extends Error {}
18
+
19
+ /** Session identity whose lifecycle belongs to subagent routing. */
20
+ export class ApiSessionSubagentOwnership extends Error {
21
+ /** @param sessionId - identity reserved to subagent routing. */
22
+ constructor(readonly sessionId: SessionId) {
23
+ super(`session "${sessionId}" is a subagent session; use subagent delivery`)
24
+ }
25
+ }
26
+
27
+ /** Explicit-id creation attempted to adopt a Session under another cwd. */
28
+ export class ApiSessionCwdConflict extends Error {
29
+ constructor(
30
+ readonly sessionId: SessionId,
31
+ readonly requestedCwd: string,
32
+ readonly existingCwd: string | undefined,
33
+ ) {
34
+ super(
35
+ existingCwd === undefined
36
+ ? `session "${sessionId}" records no cwd and cannot be adopted for "${requestedCwd}"`
37
+ : `session "${sessionId}" belongs to "${existingCwd}", not "${requestedCwd}"`,
38
+ )
39
+ }
40
+ }
41
+
42
+ /** Reuse of a Session named an Agent preset while the deployment composes no preset roster. */
43
+ export class ApiSessionPresetConflict extends Error {
44
+ constructor(
45
+ readonly sessionId: SessionId,
46
+ readonly requestedPreset: string,
47
+ ) {
48
+ super(`the deployment composes no agent preset roster, so session "${sessionId}" cannot run preset "${requestedPreset}"`)
49
+ }
50
+ }
51
+
52
+ /** A blank Session chosen for reuse started a turn before this Host acquired its writer. */
53
+ class ApiSessionStartedSinceObserved extends Error {}
54
+
55
+ /** Placement and Agent preset for one Session created for a new conversation. */
56
+ export interface ApiSessionCreateRequest {
57
+ /** Blank Session to reuse, or the identity of a new Session when none is stored under it. */
58
+ readonly sessionId?: SessionId
59
+ /** Directory the Session owns. */
60
+ readonly cwd: string
61
+ /** Preset the Session runs; the configured default when omitted. */
62
+ readonly agentPreset?: string
63
+ /**
64
+ * Placement rule the caller owns, such as Workspace membership and archive state.
65
+ * @param sessionId - existing Session named by the request.
66
+ * @returns whether that Session may be reused.
67
+ */
68
+ readonly reusable: (sessionId: SessionId) => boolean
69
+ }
70
+
71
+ /** The Session one creation request created or reused. */
72
+ export interface ApiSessionCreated {
73
+ /** Live Agent of the Session. */
74
+ readonly agent: Agent
75
+ /** Preset the Session ran when the request finished, before a later request for the same identity; absent without a roster. */
76
+ readonly agentPreset: string | undefined
77
+ }
78
+
79
+ /** Resolved preset and pre-publication Agent setup for one create or resume. */
80
+ interface ApiSessionComposition {
81
+ readonly agentPreset?: string
82
+ readonly setup: AgentSetup
83
+ }
84
+
85
+ /** Failures produced while resolving one ordinary Session identity to its live Agent. */
86
+ export type ApiSessionAgentError = RemoteError<'session/not-found' | 'session/agent-busy' | 'session/writer-held' | 'gateway/internal'>
87
+
88
+ /** Result of resolving one ordinary Session identity to its live Agent. */
89
+ export type ApiSessionAgentResult =
90
+ | { readonly agent: Agent }
91
+ | { readonly error: ApiSessionAgentError }
92
+
93
+ /**
94
+ * Test whether generic Session routing must leave an identity to subagent routing.
95
+ * @param session - Attached or live Session whose origin is tested.
96
+ * @returns whether subagent routing owns the Session identity.
97
+ */
98
+ export function hasApiSessionSubagentOwner(session: Pick<Session, 'header'>): boolean {
99
+ return session.header.origin === 'subagent'
100
+ }
101
+
102
+ /**
103
+ * Build the stable caller-facing subagent ownership rejection.
104
+ * @param sessionId - Session identity owned by subagent routing.
105
+ * @returns a stable Session-domain failure.
106
+ */
107
+ export function apiSessionSubagentOwnershipError(sessionId: SessionId): ApiSessionAgentError {
108
+ return new RemoteError(
109
+ 'session/agent-busy',
110
+ `session "${sessionId}" is owned by subagent routing`,
111
+ { reason: 'use subagent delivery for this child session' },
112
+ )
113
+ }
114
+
115
+ /** Owns every operation that may create, resume, or configure a Web Agent. */
116
+ export class ApiSessionAgentController {
117
+ private readonly resumes = new Map<SessionId, Promise<Agent>>()
118
+ private readonly claims = new Map<SessionId, Promise<void>>()
119
+ private readonly imageAdmissionChains = new WeakMap<Agent, Promise<void>>()
120
+
121
+ /** @param ctx - Host context carrying Agent, model, persistence, and Typert services. */
122
+ constructor(private readonly ctx: Context) {}
123
+
124
+ /**
125
+ * Configure Session and Agent lookups for Typert.
126
+ */
127
+ initialize(): void {
128
+ const ctx = this.ctx
129
+ ctx.typert.lookups.configure('agent', async (sessionId: SessionId) => {
130
+ const found = await this.resolveAgent(sessionId)
131
+ if ('error' in found) throw found.error
132
+ return found.agent
133
+ })
134
+ ctx.typert.lookups.configure('session', async (sessionId: SessionId) => {
135
+ const found = await this.resolveAgent(sessionId)
136
+ if ('error' in found) throw found.error
137
+ return found.agent.session
138
+ })
139
+ ctx.typert.contexts.configureHost('agent', async (sessionId: SessionId) => {
140
+ const found = await this.resolveAgent(sessionId)
141
+ if ('error' in found) throw found.error
142
+ return found.agent.ctx
143
+ })
144
+ }
145
+
146
+ /**
147
+ * Resolve or resume one ordinary Session, deduplicating concurrent resumes.
148
+ * @param sessionId - ordinary Session identity.
149
+ * @returns the live Agent or a stable Session-domain failure.
150
+ */
151
+ async resolveAgent(sessionId: SessionId): Promise<ApiSessionAgentResult> {
152
+ return this.resolve(sessionId)
153
+ }
154
+
155
+ /**
156
+ * Resolve one ordinary Session from an already-retained exact observation.
157
+ * @param observation - Host-owned observation whose preparation stays pinned through setup.
158
+ * @returns the live Agent or a stable Session-domain failure.
159
+ */
160
+ async resolveObservedAgent(observation: SessionObservation): Promise<ApiSessionAgentResult> {
161
+ return this.resolve(observation.header.id, observation)
162
+ }
163
+
164
+ private async resolve(
165
+ sessionId: SessionId,
166
+ observation?: SessionObservation,
167
+ ): Promise<ApiSessionAgentResult> {
168
+ const live = this.liveAgent(sessionId)
169
+ if (live !== undefined) return live
170
+ const attached = this.ctx.sessions.get(sessionId)
171
+ if (attached !== undefined && hasApiSessionSubagentOwner(attached)) {
172
+ return { error: apiSessionSubagentOwnershipError(sessionId) }
173
+ }
174
+
175
+ let resume = this.resumes.get(sessionId)
176
+ if (resume === undefined) {
177
+ resume = this.resume(sessionId, observation).finally(() => { this.resumes.delete(sessionId) })
178
+ this.resumes.set(sessionId, resume)
179
+ }
180
+ try {
181
+ const agent = await resume
182
+ // A shared resume can publish an identity that subagent routing adopts
183
+ // before every waiter observes it; apply the live ownership policy again.
184
+ const published = this.liveAgent(sessionId)
185
+ return published ?? { agent }
186
+ } catch (error: unknown) {
187
+ if (error instanceof ApiSessionNotFound) {
188
+ return { error: new RemoteError('session/not-found', error.message, { sessionId }) }
189
+ }
190
+ if (error instanceof ApiSessionSubagentOwnership) {
191
+ return { error: apiSessionSubagentOwnershipError(error.sessionId) }
192
+ }
193
+ const raced = this.liveAgent(sessionId)
194
+ if (raced !== undefined) return raced
195
+ const racedSession = this.ctx.sessions.get(sessionId)
196
+ if (racedSession !== undefined && hasApiSessionSubagentOwner(racedSession)) {
197
+ return { error: apiSessionSubagentOwnershipError(sessionId) }
198
+ }
199
+ if (error instanceof Error && error.name === 'SessionAlreadyOwnedError') {
200
+ return { error: new RemoteError('session/writer-held', error.message, { sessionId }) }
201
+ }
202
+ return {
203
+ error: new RemoteError(
204
+ 'gateway/internal',
205
+ `resume failed for session "${sessionId}": ${String(error)}`,
206
+ {},
207
+ ),
208
+ }
209
+ }
210
+ }
211
+
212
+ /**
213
+ * Create a Session for a new conversation, reusing the named blank Session
214
+ * while it is still reusable. A reused Session runs the requested preset, or
215
+ * the configured default when the request names none; the preset it recorded
216
+ * is not resolved, and a change is logged as `agent-preset/selected` before
217
+ * the Agent is published. A named Session that has started a turn, fails the
218
+ * caller's placement rule, or is written by another owner stays unchanged,
219
+ * and a new Session is created instead. Requests naming one identity run in
220
+ * arrival order, including their preset resolution, and check the named
221
+ * Session's directory and ownership before resolving the preset.
222
+ * @param request - optional Session to reuse, directory, preset, and placement rule.
223
+ * @returns the reused or created Session and the preset it ran when this request finished.
224
+ * @throws ApiSessionCwdConflict when the named Session belongs to another directory.
225
+ * @throws ApiSessionSubagentOwnership when subagent routing owns the named Session.
226
+ * @throws RemoteError `agent-preset/not-found` or `agent-preset/invalid` for the requested or default preset.
227
+ * @throws ApiSessionPresetConflict when no roster is composed and the request names a preset for a reused Session.
228
+ */
229
+ async createSession(request: ApiSessionCreateRequest): Promise<ApiSessionCreated> {
230
+ const named = request.sessionId
231
+ if (named === undefined) return this.created(await this.createMinted(request.cwd, await this.composeAgent(request.agentPreset)))
232
+ return this.inOrder(named, async () => this.created(await this.claim(named, request)))
233
+ }
234
+
235
+ /**
236
+ * Read the current Agent preset from the Session projection.
237
+ * @param session - live Session whose projection state is available.
238
+ * @returns the current preset, or undefined without a preset service or recorded selection.
239
+ */
240
+ presetForSession(session: Session): string | undefined {
241
+ return this.ctx.get('agentPresets')?.presetForSession(session) ?? undefined
242
+ }
243
+
244
+ /**
245
+ * Serialize image admission and model selection for one Agent.
246
+ * @param agent - live Agent that owns the serialization chain.
247
+ * @param operation - asynchronous operation admitted after prior work settles.
248
+ * @returns the operation result or rejection.
249
+ */
250
+ serializeImageAdmission<Value>(agent: Agent, operation: () => Promise<Value>): Promise<Value> {
251
+ const result = (this.imageAdmissionChains.get(agent) ?? Promise.resolve()).then(operation)
252
+ this.imageAdmissionChains.set(agent, result.then(() => undefined, () => undefined))
253
+ return result
254
+ }
255
+
256
+ /**
257
+ * Resolve the preset id and pre-publication Agent setup for a create or resume.
258
+ * @param presetId - requested preset or the configured default when omitted.
259
+ * @returns the resolved preset identity and Agent setup callback.
260
+ */
261
+ async composeAgent(presetId: string | undefined): Promise<ApiSessionComposition> {
262
+ const presets = this.ctx.get('agentPresets')
263
+ if (presets === undefined) {
264
+ return { setup: (agentCtx) => { installModelSelection(agentCtx) } }
265
+ }
266
+ const resolvedId = (await presets.resolve(presetId)).id
267
+ return {
268
+ agentPreset: resolvedId,
269
+ setup: async (agentCtx) => {
270
+ installModelSelection(agentCtx)
271
+ await presets.mount(agentCtx, resolvedId)
272
+ },
273
+ }
274
+ }
275
+
276
+ private liveAgent(sessionId: SessionId): ApiSessionAgentResult | undefined {
277
+ const agent = this.ctx.agents.get(sessionId)
278
+ if (agent === undefined) return undefined
279
+ return hasApiSessionSubagentOwner(agent.session)
280
+ ? { error: apiSessionSubagentOwnershipError(sessionId) }
281
+ : { agent }
282
+ }
283
+
284
+ private async resume(sessionId: SessionId, supplied?: SessionObservation): Promise<Agent> {
285
+ if (supplied !== undefined) return this.resumeObserved(sessionId, supplied)
286
+ try {
287
+ using observation = await this.ctx.sessionQuery.observeSession(sessionId)
288
+ return await this.resumeObserved(sessionId, observation)
289
+ } catch (error: unknown) {
290
+ if (error instanceof SessionQueryError
291
+ && error.code === 'SESSION_QUERY_SESSION_NOT_FOUND') {
292
+ throw new ApiSessionNotFound(`session "${sessionId}" not found`)
293
+ }
294
+ throw error
295
+ }
296
+ }
297
+
298
+ private async resumeObserved(
299
+ sessionId: SessionId,
300
+ observation: SessionObservation,
301
+ ): Promise<Agent> {
302
+ if (observation.header.id !== sessionId || observation.header.cwd === undefined) {
303
+ throw new ApiSessionNotFound(`session "${sessionId}" not found`)
304
+ }
305
+ if (hasApiSessionSubagentOwner({ header: observation.header })) {
306
+ throw new ApiSessionSubagentOwnership(sessionId)
307
+ }
308
+ const composition = await this.composeAgent(this.presetForObservation(observation))
309
+ const published = this.ctx.sessions.get(sessionId)
310
+ if (published !== undefined && hasApiSessionSubagentOwner(published)) {
311
+ throw new ApiSessionSubagentOwnership(sessionId)
312
+ }
313
+ return (await this.ctx.agents.resume({
314
+ resumeSessionId: sessionId,
315
+ agentOptions: this.agentOptions(),
316
+ setup: composition.setup,
317
+ })).agent
318
+ }
319
+
320
+ private async inOrder<Value>(sessionId: SessionId, operation: () => Promise<Value>): Promise<Value> {
321
+ const result = (this.claims.get(sessionId) ?? Promise.resolve()).then(operation)
322
+ const settled = result.then(() => undefined, () => undefined)
323
+ this.claims.set(sessionId, settled)
324
+ try {
325
+ return await result
326
+ } finally {
327
+ if (this.claims.get(sessionId) === settled) this.claims.delete(sessionId)
328
+ }
329
+ }
330
+
331
+ /** @returns the reused Session, a new Session under `sessionId` when none is stored, or a new Session under a minted identity. */
332
+ private async claim(sessionId: SessionId, request: ApiSessionCreateRequest): Promise<Agent> {
333
+ const attached = this.ctx.sessions.get(sessionId)
334
+ const live = this.ctx.agents.get(sessionId)
335
+ if (attached !== undefined && hasApiSessionSubagentOwner(attached)) {
336
+ throw new ApiSessionSubagentOwnership(sessionId)
337
+ }
338
+ if (live !== undefined) {
339
+ if (live.session.header.cwd !== request.cwd) {
340
+ throw new ApiSessionCwdConflict(live.id, request.cwd, live.session.header.cwd)
341
+ }
342
+ const composition = await this.composeAgent(request.agentPreset)
343
+ return await this.reuseLive(live, request, composition) ?? this.createMinted(request.cwd, composition)
344
+ }
345
+ let observation: SessionObservation
346
+ try {
347
+ observation = await this.ctx.sessionQuery.observeSession(sessionId)
348
+ } catch (error: unknown) {
349
+ if (!(error instanceof SessionQueryError) || error.code !== 'SESSION_QUERY_SESSION_NOT_FOUND') throw error
350
+ return this.createAgent(sessionId, request.cwd, await this.composeAgent(request.agentPreset))
351
+ }
352
+ let reusable: boolean
353
+ {
354
+ using observed = observation
355
+ if (hasApiSessionSubagentOwner({ header: observed.header })) {
356
+ throw new ApiSessionSubagentOwnership(sessionId)
357
+ }
358
+ if (observed.header.cwd !== request.cwd) {
359
+ throw new ApiSessionCwdConflict(sessionId, request.cwd, observed.header.cwd)
360
+ }
361
+ reusable = request.reusable(sessionId) && !observed.events.some(event => event.type === 'turn/start')
362
+ }
363
+ const composition = await this.composeAgent(request.agentPreset)
364
+ if (!reusable) return this.createMinted(request.cwd, composition)
365
+ this.assertPresetApplicable(sessionId, request.agentPreset)
366
+ try {
367
+ return (await this.ctx.agents.resume({
368
+ resumeSessionId: sessionId,
369
+ agentOptions: this.agentOptions(),
370
+ setup: this.reuseSetup(composition),
371
+ })).agent
372
+ } catch (error: unknown) {
373
+ if (error instanceof ApiSessionStartedSinceObserved) return this.createMinted(request.cwd, composition)
374
+ if (!(error instanceof Error) || error.name !== 'SessionAlreadyOwnedError') throw error
375
+ // Another resume in this process may hold the writer for the Agent it published.
376
+ return this.ctx.agents.get(sessionId) === undefined
377
+ ? this.createMinted(request.cwd, composition)
378
+ : this.claim(sessionId, request)
379
+ }
380
+ }
381
+
382
+ /** @returns the live blank Session under the requested preset, or undefined when it cannot be reused. */
383
+ private async reuseLive(
384
+ live: Agent,
385
+ request: ApiSessionCreateRequest,
386
+ composition: ApiSessionComposition,
387
+ ): Promise<Agent | undefined> {
388
+ if (!request.reusable(live.id) || !this.isBlank(live.session)) return undefined
389
+ this.assertPresetApplicable(live.id, request.agentPreset)
390
+ const current = this.presetForSession(live.session)
391
+ const presets = this.ctx.get('agentPresets')
392
+ const target = composition.agentPreset
393
+ if (presets === undefined || target === undefined || target === current) return live
394
+ try {
395
+ await presets.select(live, target)
396
+ } catch (error: unknown) {
397
+ if (remoteErrorOf(error)?.code !== 'agent-preset/locked') throw error
398
+ return undefined
399
+ }
400
+ return live
401
+ }
402
+
403
+ /** Setup that re-checks blankness under the acquired writer, then records a preset change before publication. */
404
+ private reuseSetup(composition: ApiSessionComposition): AgentSetup {
405
+ return async (agentCtx, agent) => {
406
+ if (!this.isBlank(agent.session)) throw new ApiSessionStartedSinceObserved()
407
+ const commit = await composition.setup(agentCtx, agent)
408
+ const target = composition.agentPreset
409
+ if (target !== undefined && this.presetForSession(agent.session) !== target) {
410
+ agent.session.append('agent-preset/selected', { agentPreset: target })
411
+ }
412
+ return commit
413
+ }
414
+ }
415
+
416
+ /** Whether no turn has started, by the predicate the preset registry's `select` enforces. */
417
+ private isBlank(session: Session): boolean {
418
+ const boundary = this.ctx.agents.turnBoundaryOf(session)
419
+ return boundary.openTurnStartSeq === null && boundary.lastTurn === 0
420
+ }
421
+
422
+ /** Without a roster, reuse cannot apply a named preset. */
423
+ private assertPresetApplicable(sessionId: SessionId, requested: string | undefined): void {
424
+ if (requested === undefined || this.ctx.get('agentPresets') !== undefined) return
425
+ throw new ApiSessionPresetConflict(sessionId, requested)
426
+ }
427
+
428
+ private created(agent: Agent): ApiSessionCreated {
429
+ return { agent, agentPreset: this.presetForSession(agent.session) }
430
+ }
431
+
432
+ private createMinted(cwd: string, composition: ApiSessionComposition): Promise<Agent> {
433
+ return this.createAgent(brandString<SessionId>(`session-${randomUUID()}`), cwd, composition)
434
+ }
435
+
436
+ private async createAgent(sessionId: SessionId, cwd: string, composition: ApiSessionComposition): Promise<Agent> {
437
+ try {
438
+ await mkdir(cwd, { recursive: true })
439
+ } catch (error: unknown) {
440
+ throw new Error(`failed to ensure project directory "${cwd}": ${String(error)}`, { cause: error })
441
+ }
442
+ return (await this.ctx.agents.create({
443
+ sessionId,
444
+ agentOptions: this.agentOptions(),
445
+ meta: {
446
+ cwd,
447
+ ...(composition.agentPreset === undefined ? {} : { agentPreset: composition.agentPreset }),
448
+ },
449
+ setup: composition.setup,
450
+ })).agent
451
+ }
452
+
453
+ private agentOptions(): AgentOptions {
454
+ const defaults = this.ctx.agentDefaultModel
455
+ // A Session that records no selection or request follows default changes.
456
+ return {
457
+ get provider() { return defaults.currentSelection().provider },
458
+ get model() { return defaults.currentSelection().model },
459
+ get reasoningEffort() { return defaults.currentSelection().reasoningEffort },
460
+ }
461
+ }
462
+
463
+ /**
464
+ * Read the current Agent preset from an all-projections observation.
465
+ * @param observation - exact Session observation carrying its projection snapshot.
466
+ * @returns the current preset, or undefined when the capability is absent.
467
+ */
468
+ presetForObservation(observation: SessionObservation): string | undefined {
469
+ if (observation.projections === undefined) {
470
+ throw new Error('api-session: Agent activation requires a projected Session observation')
471
+ }
472
+ return observation.projections.values.agentPreset ?? undefined
473
+ }
474
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * The controller's admission gate for archived Sessions: an archived
3
+ * Session, or a subagent descendant of one, must not run a model step until
4
+ * it is restored. The work a Session still runs is reported and stopped by
5
+ * its owners — the Agent registry (`turn`), the job registry seam (`job`),
6
+ * the Subagent runtime (`subagent`), and the Schedule plugin (`schedule`) —
7
+ * through the Workspace registry's archive-admission events. The Subagent
8
+ * runtime also checks its retained ancestry before each step, so a released
9
+ * intermediate Session cannot hide an archived ancestor.
10
+ */
11
+
12
+ import type { Context, Plugin } from '@unieai/cordis'
13
+ import type { Agent } from '@unieai/rabi-agent'
14
+ import type { SessionId } from '@unieai/rabi-session'
15
+ import type {} from '@unieai/rabi-workspace'
16
+
17
+ /**
18
+ * The gate as a plugin for `ctx.plugin(...)`: it loads once the Agent
19
+ * registry, Session store, and Workspace registry are available and unwinds
20
+ * with the plugin's fiber. A late waking delivery to an archived Session — a
21
+ * subagent settlement, a queued follow-up — proposes a step the gate rejects,
22
+ * which the loop ends as `blocked` without a request; unarchiving lifts the
23
+ * gate for the whole lineage.
24
+ */
25
+ export const ArchivedSessionGate: Plugin.Object<void> = {
26
+ name: 'archived-session-gate',
27
+ inject: ['agents', 'sessions', 'workspaceRegistry'],
28
+ apply(ctx: Context): void {
29
+ ctx.on('agent/pre-step', (payload, next) =>
30
+ underArchivedSession(ctx, payload.agent)
31
+ ? Promise.resolve({ kind: 'reject' as const })
32
+ : next())
33
+ },
34
+ }
35
+
36
+ /**
37
+ * Whether the Agent's Session, or a Session above it in its subagent lineage,
38
+ * is archived. This header-only check follows the durable fields through
39
+ * subagent-origin Sessions only: a fork of an archived Session is an
40
+ * independent conversation. The Subagent runtime separately checks managed
41
+ * ancestry when an intermediate Session is unavailable here.
42
+ * @param ctx - Host context.
43
+ * @param agent - the Agent proposing a step.
44
+ * @returns whether an archived Session owns the step.
45
+ */
46
+ export function underArchivedSession(ctx: Context, agent: Agent): boolean {
47
+ const archived = ctx.workspaceRegistry.archivedSessionIds
48
+ let header = agent.session.header
49
+ const visited = new Set<SessionId>()
50
+ while (!visited.has(header.id)) {
51
+ if (archived.includes(header.id)) return true
52
+ visited.add(header.id)
53
+ if (header.origin !== 'subagent' || header.parentSession === undefined) return false
54
+ const parent = ctx.sessions.get(header.parentSession)
55
+ if (parent === undefined) return archived.includes(header.parentSession)
56
+ header = parent.header
57
+ }
58
+ return false
59
+ }
@@ -0,0 +1,102 @@
1
+ /** Process-local assistant state retained for reconnecting Web followers. */
2
+
3
+ import type { AssistantStreamFrame } from '@unieai/rabi-agent'
4
+ import { AssistantStreamAccumulator } from '@unieai/rabi-llm'
5
+ import type { SessionSeqCursor } from '@unieai/rabi-session'
6
+ import type { JsonValue } from '@unieai/rabi-util-values'
7
+ import type {
8
+ SessionAssistantStreamAttempt,
9
+ SessionAssistantStreamBaseline,
10
+ } from './types.ts'
11
+
12
+ interface MutableAttempt {
13
+ readonly attemptId: SessionAssistantStreamAttempt['attemptId']
14
+ readonly startedAfterSeq: SessionSeqCursor
15
+ readonly turn: number
16
+ readonly step: number
17
+ readonly stream: AssistantStreamAccumulator
18
+ nextIndex: number
19
+ }
20
+
21
+ const EMPTY_BASELINE: SessionAssistantStreamBaseline = { revision: 0 }
22
+
23
+ /**
24
+ * Folds dense Agent frames and materializes one shared immutable reconnect
25
+ * baseline per accepted revision.
26
+ */
27
+ export class SessionAssistantStreamAccumulator {
28
+ private activeAttempt: MutableAttempt | undefined
29
+ private revision = 0
30
+ private snapshotValue: SessionAssistantStreamBaseline = EMPTY_BASELINE
31
+ private dirty = false
32
+
33
+ /**
34
+ * Fold one trusted frame from the current attached Agent lifecycle.
35
+ * @param frame - next dense process-local Assistant frame.
36
+ * @param durableCursor - last committed Session seq when this frame was observed.
37
+ */
38
+ accept(frame: AssistantStreamFrame, durableCursor: SessionSeqCursor): void {
39
+ if (frame.type === 'start' && frame.revision === 1 && this.revision !== 0) {
40
+ this.activeAttempt = undefined
41
+ this.revision = 0
42
+ }
43
+ if (frame.revision !== this.revision + 1) {
44
+ this.activeAttempt = undefined
45
+ this.revision = frame.revision
46
+ this.dirty = true
47
+ return
48
+ }
49
+ this.revision = frame.revision
50
+ switch (frame.type) {
51
+ case 'start':
52
+ this.activeAttempt = {
53
+ attemptId: frame.attemptId,
54
+ startedAfterSeq: durableCursor,
55
+ turn: frame.turn,
56
+ step: frame.step,
57
+ stream: new AssistantStreamAccumulator(),
58
+ nextIndex: 0,
59
+ }
60
+ break
61
+ case 'chunk': {
62
+ const attempt = this.activeAttempt
63
+ if (attempt === undefined
64
+ || attempt.attemptId !== frame.attemptId
65
+ || frame.index !== attempt.nextIndex) {
66
+ this.activeAttempt = undefined
67
+ break
68
+ }
69
+ attempt.stream.push({ time: frame.time, chunk: frame.chunk })
70
+ attempt.nextIndex += 1
71
+ break
72
+ }
73
+ case 'end':
74
+ this.activeAttempt = undefined
75
+ break
76
+ }
77
+ this.dirty = true
78
+ }
79
+
80
+ /**
81
+ * Read the cached reconnect baseline, materializing it after a state change.
82
+ * @returns the identity-stable baseline for the latest accepted revision.
83
+ */
84
+ snapshot(): SessionAssistantStreamBaseline {
85
+ if (!this.dirty) return this.snapshotValue
86
+ this.snapshotValue = {
87
+ revision: this.revision,
88
+ ...this.activeAttempt === undefined ? {} : {
89
+ activeAttempt: {
90
+ attemptId: this.activeAttempt.attemptId,
91
+ startedAfterSeq: this.activeAttempt.startedAfterSeq,
92
+ turn: this.activeAttempt.turn,
93
+ step: this.activeAttempt.step,
94
+ nextIndex: this.activeAttempt.nextIndex,
95
+ stream: this.activeAttempt.stream.snapshot() as unknown as readonly JsonValue[],
96
+ },
97
+ },
98
+ }
99
+ this.dirty = false
100
+ return this.snapshotValue
101
+ }
102
+ }