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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +7 -2
  3. package/lib/client.js +4 -0
  4. package/lib/index.js +4300 -0
  5. package/lib/typert.host.d.ts +3 -0
  6. package/lib/typert.host.js +5013 -0
  7. package/lib/typert.remote-client.d.ts +115 -0
  8. package/lib/typert.remote-client.js +2714 -0
  9. package/lib/types/agent.d.ts +164 -0
  10. package/lib/types/agent.js +484 -0
  11. package/lib/types/archived-session-gate.d.ts +33 -0
  12. package/lib/types/archived-session-gate.js +54 -0
  13. package/lib/types/assistant-stream.d.ts +26 -0
  14. package/lib/types/assistant-stream.js +82 -0
  15. package/lib/types/catalog.d.ts +24 -0
  16. package/lib/types/catalog.js +107 -0
  17. package/lib/types/client/contract/events.d.ts +102 -0
  18. package/lib/types/client/contract/events.js +111 -0
  19. package/lib/types/client/contract/session.d.ts +178 -0
  20. package/lib/types/client/contract/session.js +1 -0
  21. package/lib/types/client/contract/sessions.d.ts +162 -0
  22. package/lib/types/client/contract/sessions.js +1 -0
  23. package/lib/types/client/contract/snapshot.d.ts +84 -0
  24. package/lib/types/client/contract/snapshot.js +1 -0
  25. package/lib/types/client/index.d.ts +39 -0
  26. package/lib/types/client/index.js +60 -0
  27. package/lib/types/client/ordered-baseline.d.ts +12 -0
  28. package/lib/types/client/ordered-baseline.js +40 -0
  29. package/lib/types/client/scope.d.ts +46 -0
  30. package/lib/types/client/scope.js +46 -0
  31. package/lib/types/client/session-wire-event.d.ts +11 -0
  32. package/lib/types/client/session-wire-event.js +42 -0
  33. package/lib/types/client/sessions/assistant-stream.d.ts +56 -0
  34. package/lib/types/client/sessions/assistant-stream.js +182 -0
  35. package/lib/types/client/sessions/history-records.d.ts +22 -0
  36. package/lib/types/client/sessions/history-records.js +25 -0
  37. package/lib/types/client/sessions/lineage.d.ts +48 -0
  38. package/lib/types/client/sessions/lineage.js +55 -0
  39. package/lib/types/client/sessions/manager.d.ts +272 -0
  40. package/lib/types/client/sessions/manager.js +774 -0
  41. package/lib/types/client/sessions/notifier.d.ts +39 -0
  42. package/lib/types/client/sessions/notifier.js +97 -0
  43. package/lib/types/client/sessions/projection-store.d.ts +128 -0
  44. package/lib/types/client/sessions/projection-store.js +161 -0
  45. package/lib/types/client/sessions/remotes.d.ts +29 -0
  46. package/lib/types/client/sessions/remotes.js +7 -0
  47. package/lib/types/client/sessions/service.d.ts +263 -0
  48. package/lib/types/client/sessions/service.js +597 -0
  49. package/lib/types/client/sessions/session.d.ts +303 -0
  50. package/lib/types/client/sessions/session.js +991 -0
  51. package/lib/types/client/time-zone.d.ts +8 -0
  52. package/lib/types/client/time-zone.js +13 -0
  53. package/lib/types/client/transport.d.ts +77 -0
  54. package/lib/types/client/transport.js +130 -0
  55. package/lib/types/commands.d.ts +92 -0
  56. package/lib/types/commands.js +575 -0
  57. package/lib/types/continuation.d.ts +35 -0
  58. package/lib/types/continuation.js +47 -0
  59. package/lib/types/control.d.ts +20 -0
  60. package/lib/types/control.js +106 -0
  61. package/lib/types/file-references.d.ts +27 -0
  62. package/lib/types/file-references.js +68 -0
  63. package/lib/types/history/assistant-stream.d.ts +43 -0
  64. package/lib/types/history/assistant-stream.js +79 -0
  65. package/lib/types/history/controller.d.ts +104 -0
  66. package/lib/types/history/controller.js +293 -0
  67. package/lib/types/history/listener.d.ts +105 -0
  68. package/lib/types/history/listener.js +296 -0
  69. package/lib/types/history.d.ts +58 -0
  70. package/lib/types/history.js +152 -0
  71. package/lib/types/index.d.ts +262 -0
  72. package/lib/types/index.js +693 -0
  73. package/lib/types/list.d.ts +62 -0
  74. package/lib/types/list.js +343 -0
  75. package/lib/types/media-references.d.ts +18 -0
  76. package/lib/types/media-references.js +84 -0
  77. package/lib/types/remote-events.d.ts +8 -0
  78. package/lib/types/remote-events.js +1 -0
  79. package/lib/types/skill-catalog.d.ts +28 -0
  80. package/lib/types/skill-catalog.js +203 -0
  81. package/lib/types/state/controller.d.ts +45 -0
  82. package/lib/types/state/controller.js +288 -0
  83. package/lib/types/state/listener.d.ts +40 -0
  84. package/lib/types/state/listener.js +111 -0
  85. package/lib/types/types.d.ts +687 -0
  86. package/lib/types/types.js +5 -0
  87. package/lib/types/web/controller.d.ts +25 -0
  88. package/lib/types/web/controller.js +138 -0
  89. package/locale/de.json +6 -0
  90. package/locale/en.json +5 -0
  91. package/locale/es.json +6 -0
  92. package/locale/fr.json +6 -0
  93. package/locale/ja.json +6 -0
  94. package/locale/pt.json +6 -0
  95. package/locale/ru.json +6 -0
  96. package/locale/zh.json +6 -0
  97. package/package.json +119 -4
  98. package/src/agent.ts +474 -0
  99. package/src/archived-session-gate.ts +59 -0
  100. package/src/assistant-stream.ts +102 -0
  101. package/src/catalog.ts +117 -0
  102. package/src/client/contract/events.ts +205 -0
  103. package/src/client/contract/session.ts +174 -0
  104. package/src/client/contract/sessions.ts +169 -0
  105. package/src/client/contract/snapshot.ts +94 -0
  106. package/src/client/index.ts +149 -0
  107. package/src/client/ordered-baseline.ts +43 -0
  108. package/src/client/scope.ts +76 -0
  109. package/src/client/session-wire-event.ts +46 -0
  110. package/src/client/sessions/assistant-stream.ts +229 -0
  111. package/src/client/sessions/history-records.ts +35 -0
  112. package/src/client/sessions/lineage.ts +96 -0
  113. package/src/client/sessions/manager.ts +857 -0
  114. package/src/client/sessions/notifier.ts +97 -0
  115. package/src/client/sessions/projection-store.ts +244 -0
  116. package/src/client/sessions/remotes.ts +44 -0
  117. package/src/client/sessions/service.ts +741 -0
  118. package/src/client/sessions/session.ts +1055 -0
  119. package/src/client/time-zone.ts +14 -0
  120. package/src/client/transport.ts +247 -0
  121. package/src/commands.ts +602 -0
  122. package/src/continuation.ts +58 -0
  123. package/src/control.ts +121 -0
  124. package/src/file-references.ts +42 -0
  125. package/src/history/assistant-stream.ts +102 -0
  126. package/src/history/controller.ts +256 -0
  127. package/src/history/listener.ts +302 -0
  128. package/src/history.ts +189 -0
  129. package/src/index.ts +651 -0
  130. package/src/list.ts +382 -0
  131. package/src/media-references.ts +84 -0
  132. package/src/remote-events.ts +14 -0
  133. package/src/skill-catalog.ts +108 -0
  134. package/src/state/controller.ts +221 -0
  135. package/src/state/listener.ts +116 -0
  136. package/src/types.ts +720 -0
  137. package/src/web/controller.ts +78 -0
@@ -0,0 +1,94 @@
1
+ /** Session-owned observable state excluding Conversation target data. */
2
+ import type { FileAttachmentRef } from '@unieai/rabi-attachment'
3
+ import type { SessionId } from '@unieai/rabi-session/types'
4
+ import type { SubagentAddress } from '@unieai/rabi-subagent/client'
5
+ import type { RemoteFailure } from '@unieai/rabi-typert-protocol'
6
+ import type { SessionRequestId } from '../../types.ts'
7
+
8
+ /** One image displayed by a local submission echo before durable admission. */
9
+ export interface PendingSubmissionImage {
10
+ /** Browser-owned preview URL; its lifecycle belongs to the submitter, never this snapshot. */
11
+ readonly previewUrl: string
12
+ /** Browser file name, when the file had one. */
13
+ readonly name?: string
14
+ /** Intrinsic pixel width, when the submitter has probed it. */
15
+ readonly width?: number
16
+ /** Intrinsic pixel height, when the submitter has probed it. */
17
+ readonly height?: number
18
+ }
19
+
20
+ /** Image branch of a local submission echo attachment. */
21
+ export interface PendingSubmissionImageAttachment {
22
+ readonly type: 'image'
23
+ readonly value: PendingSubmissionImage
24
+ }
25
+
26
+ /** File branch of a local submission echo attachment. */
27
+ export interface PendingSubmissionFileAttachment {
28
+ readonly type: 'file'
29
+ readonly value: FileAttachmentRef
30
+ }
31
+
32
+ /** One attachment displayed by a local submission echo, in prompt order. */
33
+ export type PendingSubmissionAttachment =
34
+ | PendingSubmissionImageAttachment
35
+ | PendingSubmissionFileAttachment
36
+
37
+ /** Client surface selected when a local submission begins. */
38
+ export type PendingSubmissionPlacement = 'transcript' | 'queued' | 'steering'
39
+
40
+ /**
41
+ * One local prompt-submission echo: registered when a submission begins and
42
+ * published once the Host accepts the prompt, so the conversation shows the
43
+ * message before its durable admission completes. Client-memory only — reload
44
+ * and reconnect rebuild the conversation from durable events alone.
45
+ */
46
+ export interface PendingSubmission {
47
+ /** The prompt RPC identity; the durable `user/message` source echoes it as `rpcId`. */
48
+ readonly requestId: SessionRequestId
49
+ /** Surface fixed at submission time; Inbox acceptance does not move a Chat echo into the dock. */
50
+ readonly placement: PendingSubmissionPlacement
51
+ /** Client wall-clock ms when the submission began. */
52
+ readonly time: number
53
+ /** Prompt text exactly as it will be sent (one text block). */
54
+ readonly text: string
55
+ /** Ordered image previews and durable file metadata matching the prompt attachments. */
56
+ readonly attachments: readonly PendingSubmissionAttachment[]
57
+ }
58
+
59
+ /** History-open lifecycle of a Session event window. */
60
+ export type OpenState = 'cold' | 'loading' | 'open' | 'error'
61
+
62
+ /** Send/stop failure surfaced by Session consumers. */
63
+ export interface PromptError {
64
+ readonly op: 'send' | 'stop'
65
+ readonly error: RemoteFailure
66
+ }
67
+
68
+ /** Immutable Session lifecycle and control snapshot. */
69
+ export interface SessionSnapshot {
70
+ readonly sessionId: SessionId
71
+ /** Local prompt-submission echoes the Host accepted and that are not yet observed as durable events or queue occurrences. */
72
+ readonly pendingSubmissions: readonly PendingSubmission[]
73
+ readonly running: boolean
74
+ readonly subagent: {
75
+ readonly address: SubagentAddress
76
+ } | null
77
+ readonly removed: boolean
78
+ readonly openState: OpenState
79
+ readonly openError: RemoteFailure | null
80
+ readonly hasMore: boolean
81
+ /** This Client Session has exposed an incomplete history window; remains true across replacements. */
82
+ readonly historyWasPartial: boolean
83
+ /** Whether historyLoadStatus is loading, including Turn-jump requests. */
84
+ readonly loadingOlder: boolean
85
+ /** History request status; pendingConsumption retains an unpublished ordinary page. */
86
+ readonly historyLoadStatus: 'idle' | 'loading' | 'pendingConsumption' | 'error'
87
+ readonly promptError: PromptError | null
88
+ readonly blank: boolean
89
+ readonly lastAgentError: string | null
90
+ /** A prompt call has begun on this Client Session object. */
91
+ readonly promptAttempted: boolean
92
+ /** The first accepted prompt has not reached a durable `turn/start` event. */
93
+ readonly awaitingFirstTurn: boolean
94
+ }
@@ -0,0 +1,149 @@
1
+ /** Client Session object layer, Agent scopes, and Remote lifecycle wiring. */
2
+
3
+ import type { Context } from '@unieai/cordis'
4
+ import type {} from '@unieai/rabi-agent/types'
5
+ import type { ConnectionHandle } from '@unieai/rabi-client-connection/client'
6
+ import type {} from '@unieai/rabi-client-file-upload/client'
7
+ import { typertOwnedValue } from '@unieai/rabi-typert-protocol'
8
+ import { createSessionControlStream } from './transport.ts'
9
+ import { ClientSessions } from './sessions/service.ts'
10
+ import type { SessionRemotes } from './sessions/remotes.ts'
11
+ import type {} from '../remote-events.ts'
12
+
13
+ export {
14
+ createSessionControlStream,
15
+ SessionEventStream,
16
+ SESSION_SEARCH_RESULT_LIMIT,
17
+ SESSION_SEARCH_SNIPPET_MAX_CODE_POINTS,
18
+ } from './transport.ts'
19
+ export type {
20
+ ClientSessionPageRequest,
21
+ SessionControlStream,
22
+ SessionControlStreamOptions,
23
+ SessionEventStreamOptions,
24
+ SessionJournalChange,
25
+ SessionRemote,
26
+ } from './transport.ts'
27
+ export { createScope, scopeOf } from './scope.ts'
28
+ export type { AgentContext, AgentScopeHandle } from './scope.ts'
29
+ export { SessionCreateError, SessionForkError } from './sessions/service.ts'
30
+ export type { SessionBinding, SessionListState, SessionSummary } from './sessions/service.ts'
31
+ export type {
32
+ SessionListPhase,
33
+ SessionListSnapshot,
34
+ SessionSearchResultItem,
35
+ SessionProjectionSnapshot,
36
+ } from './sessions/manager.ts'
37
+ export type { Session } from './sessions/session.ts'
38
+ export type {
39
+ ProjectionsBaseline,
40
+ ProjectionValueStore,
41
+ SessionProjectionMap,
42
+ UseProjection,
43
+ } from './sessions/projection-store.ts'
44
+ export type {
45
+ BeginSubmissionInput,
46
+ ISession,
47
+ PendingSubmissionRetirement,
48
+ ProjectionsFace,
49
+ SessionFace,
50
+ SubmissionHandle,
51
+ } from './contract/session.ts'
52
+ export type {
53
+ ISessions, SessionReference, SessionRetainInfo, SessionRetainOptions, SessionTarget,
54
+ } from './contract/sessions.ts'
55
+ export { MutableSessionEventSource } from './contract/events.ts'
56
+ export type {
57
+ AssistantLiveChunkEvent,
58
+ SessionAssistantSettlementEntry,
59
+ SessionEventChange,
60
+ SessionEventLike,
61
+ SessionEventLikeEntry,
62
+ SessionEventSource,
63
+ SessionEventWindow,
64
+ SessionLiveEventEntry,
65
+ SessionTransientEventEntry,
66
+ } from './contract/events.ts'
67
+ export type {
68
+ OpenState,
69
+ PendingSubmission,
70
+ PendingSubmissionAttachment,
71
+ PendingSubmissionFileAttachment,
72
+ PendingSubmissionImage,
73
+ PendingSubmissionImageAttachment,
74
+ PendingSubmissionPlacement,
75
+ PromptError,
76
+ SessionSnapshot,
77
+ } from './contract/snapshot.ts'
78
+
79
+ /** Consumer-owned reference labels; extend this map through the package's canonical /client entry. */
80
+ export interface SessionReferenceSourceMap {
81
+ /** Temporary Client Controller work, including fork-title preparation. */
82
+ controllerOperation: unknown
83
+ /** A Client Gateway invocation's synchronous Context ownership. */
84
+ gateway: unknown
85
+ }
86
+
87
+ /** Declaration-merge-extensible labels carried by independent Client references. */
88
+ export type SessionReferenceSource = Extract<keyof SessionReferenceSourceMap, string>
89
+
90
+ declare module '@unieai/cordis' {
91
+ interface Context {
92
+ /** Client Session object layer and Agent scope owner. */
93
+ sessions: import('./contract/sessions.ts').ISessions
94
+ }
95
+ }
96
+
97
+ /** Required Remote and Context projection services. */
98
+ export const inject = [
99
+ 'connection',
100
+ 'fileUpload',
101
+ 'typert',
102
+ 'remote',
103
+ 'remote.commands',
104
+ 'remote.session',
105
+ 'remote.subagents',
106
+ ]
107
+
108
+ /**
109
+ * Install Client Session state and its reconnecting control stream.
110
+ * @param ctx - Client Cordis context.
111
+ */
112
+ export function apply(ctx: Context): void {
113
+ const remotes = ctx.remote as unknown as SessionRemotes
114
+ const connection = ctx.get('connection') as ConnectionHandle
115
+ const sessions = new ClientSessions(ctx, remotes)
116
+ ctx.remote.$on('api-session/added', (summary) => { sessions.handleSessionAdded(summary) })
117
+ ctx.remote.$on('api-session/removed', (sessionId) => { sessions.handleSessionRemoved(sessionId) })
118
+ ctx.remote.$on('api-session/status', (sessionId, running) => {
119
+ sessions.handleSessionStatus(sessionId, running)
120
+ })
121
+ ctx.remote.$on('api-session/activity', (sessionId, updatedAt) => {
122
+ sessions.handleSessionActivity(sessionId, updatedAt)
123
+ })
124
+ ctx.remote.$on('api-session/error', (sessionId, message) => {
125
+ sessions.handleSessionError(sessionId, message)
126
+ })
127
+
128
+ const control = createSessionControlStream(remotes, {
129
+ accept: (frame) => { sessions.handleControlFrame(frame) },
130
+ failed: (error) => { console.error('[session-controller] control stream failed:', error) },
131
+ })
132
+ const connected = (): void => {
133
+ if (connection.generation.getSnapshot() === undefined) return
134
+ // A ready control baseline may arrive before Cordis delivers connection/reset.
135
+ sessions.handleConnected()
136
+ control.restart()
137
+ control.start()
138
+ }
139
+ ctx.effect(() => connection.generation.subscribe(connected), 'session-controller.client.generation')
140
+ connected()
141
+ ctx.typert.contexts.registerClient('agent', {
142
+ identity: candidate => sessions.sessionOf(candidate)?.sessionId,
143
+ resolve: (sessionId) => {
144
+ const reference = sessions.retainAgentScope(sessionId)
145
+ return typertOwnedValue(reference.binding.ctx, () => { reference.release() })
146
+ },
147
+ })
148
+ ctx.effect(() => async () => { await control.dispose() }, 'session-controller.client.control')
149
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Merge an authoritative baseline without moving identities already visible to
3
+ * the client. Baseline-only identities are inserted relative to the nearest
4
+ * following known identity; identities absent from the baseline are removed.
5
+ *
6
+ * @param current - the established client order.
7
+ * @param baseline - the latest authoritative rows.
8
+ * @param keyOf - stable identity selector.
9
+ * @returns baseline-valued rows with the established relative order retained.
10
+ */
11
+ export function mergeOrderedBaseline<T>(
12
+ current: readonly T[],
13
+ baseline: readonly T[],
14
+ keyOf: (value: T) => unknown,
15
+ ): T[] {
16
+ const baselineByKey = new Map<unknown, T>()
17
+ for (const value of baseline) baselineByKey.set(keyOf(value), value)
18
+
19
+ const merged = current
20
+ .map(value => baselineByKey.get(keyOf(value)))
21
+ .filter((value): value is T => value !== undefined)
22
+ const mergedKeys = new Set(merged.map(keyOf))
23
+
24
+ for (let index = 0; index < baseline.length; index++) {
25
+ const value = baseline[index]
26
+ /* v8 ignore next -- dense-array guard: index is bounded by baseline.length. */
27
+ if (value === undefined || mergedKeys.has(keyOf(value))) continue
28
+ let insertion = merged.length
29
+ for (let following = index + 1; following < baseline.length; following++) {
30
+ const candidate = baseline[following]
31
+ /* v8 ignore next -- dense-array guard: following is bounded by baseline.length. */
32
+ if (candidate === undefined) continue
33
+ const known = merged.findIndex(item => keyOf(item) === keyOf(candidate))
34
+ if (known !== -1) {
35
+ insertion = known
36
+ break
37
+ }
38
+ }
39
+ merged.splice(insertion, 0, value)
40
+ mergedKeys.add(keyOf(value))
41
+ }
42
+ return merged
43
+ }
@@ -0,0 +1,76 @@
1
+ /** Client scope generations route local events independently of Host Agent residency. */
2
+ import { Context as CordisContext } from '@unieai/cordis'
3
+ import type { Context, Fiber } from '@unieai/cordis'
4
+ import type { ClientRemote } from '@unieai/rabi-api-gateway/client'
5
+ import type { SessionId } from '@unieai/rabi-session/types'
6
+ import type { TypertRemoteScopeApi } from '@unieai/rabi-typert-protocol'
7
+
8
+ /** Client Cordis Context carrying one Agent identity and its scoped Remote namespaces. */
9
+ export type AgentContext = Omit<Context, 'remote'> & {
10
+ readonly remote: ClientRemote & TypertRemoteScopeApi<'agent'>
11
+ }
12
+
13
+ /** Context tag written by {@link createScope}. */
14
+ const kScope = Symbol('rabi.client.scope')
15
+
16
+ interface ScopeIdentity {
17
+ readonly sessionId: SessionId
18
+ }
19
+
20
+ /** A minted Agent scope and its disposal boundary. */
21
+ export interface AgentScopeHandle {
22
+ /**
23
+ * Tagged context: scope-owned registrations and scoped dispatch both go
24
+ * through it (passing it as the dispatch subject routes to this generation's
25
+ * tagged listeners plus every untagged one).
26
+ */
27
+ ctx: AgentContext
28
+ /** Backing fiber (dispose tears down every scope-owned registration). */
29
+ fiber: Fiber
30
+ }
31
+
32
+ /** Shared no-op plugin backing each Agent scope fiber. */
33
+ function agentScope(): void {}
34
+
35
+ /**
36
+ * Mint an Agent scope under `ctx`: a no-op plugin fiber whose context
37
+ * carries the agent tag and the dispatch filter — untagged listeners are
38
+ * admitted globally, tagged listeners only for the same Client generation.
39
+ * Registrations through the returned ctx dispose with the fiber.
40
+ * @param ctx - client root context the scope fiber mounts under.
41
+ * @param key - durable Session identity carried by this generation.
42
+ * @returns the tagged context and its backing fiber.
43
+ */
44
+ export function createScope(ctx: Context, key: SessionId): AgentScopeHandle {
45
+ const fiber = ctx.plugin(agentScope)
46
+ const identity: ScopeIdentity = { sessionId: key }
47
+ const scoped = fiber.ctx.extend({
48
+ [kScope]: identity,
49
+ [CordisContext.filter](listenerCtx: Context): boolean {
50
+ const tag = scopeIdentityOf(listenerCtx)
51
+ return tag === undefined || tag === identity
52
+ },
53
+ }) as AgentContext
54
+ return {
55
+ fiber,
56
+ ctx: scoped,
57
+ }
58
+ }
59
+
60
+ /**
61
+ * Read the nearest agent tag inherited by a context.
62
+ * @param ctx - any client context.
63
+ * @returns its agent identity (the session id), or undefined for root contexts.
64
+ */
65
+ export function scopeOf(ctx: Context): SessionId | undefined {
66
+ return scopeIdentityOf(ctx)?.sessionId
67
+ }
68
+
69
+ /**
70
+ * Read the exact generation identity inherited by a Client Context.
71
+ * @param ctx - scoped or root Client Context.
72
+ * @returns the generation identity, or undefined for an unscoped Context.
73
+ */
74
+ export function scopeIdentityOf(ctx: Context): ScopeIdentity | undefined {
75
+ return (ctx as Context & { [kScope]?: ScopeIdentity })[kScope]
76
+ }
@@ -0,0 +1,46 @@
1
+ /** Event-local acceptance for raw Session journal responses; payloads remain owner-defined JSON. */
2
+
3
+ import { validateSessionEventData, validateSurfaceMetadata } from '@unieai/rabi-session/surface'
4
+ import type { SessionEvent } from '@unieai/rabi-session/types'
5
+ import type { SessionWireEvent } from '../types.ts'
6
+
7
+ /**
8
+ * Reject non-current event envelopes without stripping or normalizing wire fields.
9
+ * Range membership and source existence require the durable log and remain Host-owned.
10
+ * @param value - one event received in a follow frame or history page.
11
+ * @returns nothing after narrowing the accepted event envelope.
12
+ * @throws when the envelope or current event-local metadata is invalid.
13
+ */
14
+ export function assertSessionWireEvent(value: unknown): asserts value is SessionWireEvent {
15
+ const subject = 'session wire event'
16
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
17
+ throw new Error(`${subject} must be an object`)
18
+ }
19
+ const event = value as Record<string, unknown>
20
+ for (const key of Object.keys(event)) {
21
+ switch (key) {
22
+ case 'type':
23
+ case 'seq':
24
+ case 'time':
25
+ case 'data':
26
+ case 'ignorable':
27
+ case 'surfaceOp':
28
+ case 'sourceEventSeqs':
29
+ break
30
+ default:
31
+ throw new Error(`${subject} has unexpected field ${key}`)
32
+ }
33
+ }
34
+ const seq = event['seq']
35
+ if (typeof event['type'] !== 'string'
36
+ || typeof seq !== 'number' || !Number.isSafeInteger(seq) || seq < 0 || Object.is(seq, -0)
37
+ || typeof event['time'] !== 'number' || !Number.isSafeInteger(event['time'])
38
+ || !Object.hasOwn(event, 'data') || event['data'] === undefined
39
+ || (Object.hasOwn(event, 'ignorable') && event['ignorable'] !== true)) {
40
+ throw new Error(`${subject} has an invalid envelope`)
41
+ }
42
+ // Event names and payloads are merge-extensible; only event-local owner rules run here.
43
+ const current = event as SessionEvent
44
+ validateSurfaceMetadata(current)
45
+ validateSessionEventData(current, subject)
46
+ }
@@ -0,0 +1,229 @@
1
+ /** Web presentation fold joining transient Assistant frames to one durable v2 settlement. */
2
+
3
+ import type {
4
+ SessionAssistantStreamBaseline,
5
+ SessionAssistantStreamFrame,
6
+ } from '../../types.ts'
7
+ import { expandAssistantStream } from '@unieai/rabi-llm/assistant-stream'
8
+ import type { AssistantStreamRecord } from '@unieai/rabi-llm/assistant-stream'
9
+ import type { LlmAttemptId } from '@unieai/rabi-llm/brand'
10
+ import type {
11
+ SessionAssistantSettlementEntry,
12
+ SessionEventLikeEntry,
13
+ SessionLiveEventEntry,
14
+ SessionTransientEventEntry,
15
+ } from '../contract/events.ts'
16
+
17
+ interface ActiveAttempt {
18
+ readonly attemptId: LlmAttemptId
19
+ readonly startedAfterSeq: number
20
+ readonly turn: number
21
+ readonly step: number
22
+ nextIndex: number
23
+ }
24
+
25
+ /** One Web publication decision from the assistant stream fold. */
26
+ export type ClientAssistantStreamResult =
27
+ | {
28
+ readonly type: 'publish'
29
+ readonly entry: SessionLiveEventEntry
30
+ /** Retire the successful attempt's transient rows after publishing its Step end. */
31
+ readonly retireAttemptId?: LlmAttemptId
32
+ }
33
+ | {
34
+ readonly type: 'settlement'
35
+ readonly attemptId: LlmAttemptId
36
+ readonly entry: SessionAssistantSettlementEntry
37
+ }
38
+ | { readonly type: 'abandonment'; readonly attemptId: LlmAttemptId }
39
+ | { readonly type: 'transient'; readonly entry: SessionTransientEventEntry }
40
+ | { readonly type: 'rebaseline' }
41
+ | undefined
42
+
43
+ /** Keeps transient Assistant presentation behind one settlement-aware interface. */
44
+ export class ClientAssistantStream {
45
+ private activeAttempt: ActiveAttempt | undefined
46
+ private retainedAttempt: Pick<ActiveAttempt, 'attemptId' | 'turn' | 'step'> | undefined
47
+ private readonly pending = new Map<number, SessionAssistantSettlementEntry>()
48
+ private publishedSeqs = new Set<number>()
49
+ private durableCursor = -1
50
+ private transientInGap = 0
51
+
52
+ /**
53
+ * Replace the durable Web window and adopt an optional reconnect baseline.
54
+ * @param entries - durable entries in the replacement window.
55
+ * @param baseline - compact prefix for an Assistant attempt that is still live.
56
+ * @returns immediately visible durable entries plus reconstructed transient chunks.
57
+ */
58
+ replace(
59
+ entries: readonly SessionEventLikeEntry[],
60
+ baseline?: SessionAssistantStreamBaseline,
61
+ ): readonly SessionEventLikeEntry[] {
62
+ this.pending.clear()
63
+ this.transientInGap = 0
64
+ this.activeAttempt = undefined
65
+ this.retainedAttempt = undefined
66
+ const opening = baseline?.activeAttempt
67
+ if (opening !== undefined) {
68
+ this.activeAttempt = {
69
+ attemptId: opening.attemptId,
70
+ startedAfterSeq: opening.startedAfterSeq,
71
+ turn: opening.turn,
72
+ step: opening.step,
73
+ nextIndex: opening.nextIndex,
74
+ }
75
+ }
76
+ const visible: SessionEventLikeEntry[] = [...entries]
77
+ this.publishedSeqs = new Set(visible.map(entry => entry.event.seq))
78
+ this.durableCursor = visible.reduce((cursor, entry) => Math.max(cursor, entry.event.seq), -1)
79
+ if (opening !== undefined) {
80
+ for (const [index, member] of expandAssistantStream(
81
+ opening.stream as unknown as readonly AssistantStreamRecord[],
82
+ ).entries()) {
83
+ this.transientInGap += 1
84
+ visible.push({
85
+ type: 'transient',
86
+ event: {
87
+ type: 'assistant/live-chunk',
88
+ seq: this.durableCursor + 1 - 1 / (this.transientInGap + 1),
89
+ time: member.time,
90
+ data: {
91
+ attemptId: opening.attemptId,
92
+ turn: opening.turn,
93
+ step: opening.step,
94
+ chunk: member.chunk,
95
+ },
96
+ },
97
+ })
98
+ if (index + 1 >= opening.nextIndex) break
99
+ }
100
+ }
101
+ return visible
102
+ }
103
+
104
+ /**
105
+ * Stage one durable v2 settlement while its matching live attempt is open.
106
+ * @param entry - newly followed durable entry.
107
+ * @returns a publication decision, or `undefined` when no entry becomes visible.
108
+ */
109
+ acceptDurable(entry: SessionLiveEventEntry): ClientAssistantStreamResult {
110
+ const event = entry.event
111
+ this.durableCursor = Math.max(this.durableCursor, event.seq)
112
+ this.transientInGap = 0
113
+ const settlement = assistantSettlementEntry(entry)
114
+ if (settlement !== undefined && this.attemptForSettlement(settlement.event) !== undefined) {
115
+ if (this.pending.has(event.seq)) return { type: 'rebaseline' }
116
+ this.pending.set(event.seq, settlement)
117
+ return undefined
118
+ }
119
+ return this.publish(entry)
120
+ }
121
+
122
+ /**
123
+ * Fold one dense transient frame and release its named durable settlement.
124
+ * Successful messages retain their transient rows until the owning Step ends;
125
+ * interrupted messages, failed attempts, and abandonment retire them immediately.
126
+ * @param frame - next Assistant stream frame received by the follow connection.
127
+ * @returns a transient, publication, or rebaseline decision, or `undefined` when no entry becomes visible.
128
+ */
129
+ acceptFrame(frame: SessionAssistantStreamFrame): ClientAssistantStreamResult {
130
+ switch (frame.type) {
131
+ case 'start':
132
+ if (this.activeAttempt !== undefined || this.retainedAttempt !== undefined
133
+ || this.pending.size > 0) return { type: 'rebaseline' }
134
+ this.pending.clear()
135
+ this.activeAttempt = {
136
+ attemptId: frame.attemptId,
137
+ startedAfterSeq: frame.startedAfterSeq,
138
+ turn: frame.turn,
139
+ step: frame.step,
140
+ nextIndex: 0,
141
+ }
142
+ return undefined
143
+ case 'chunk': {
144
+ const attempt = this.activeAttempt
145
+ // A controller mounted after the Host saw this attempt has no start
146
+ // frame to reconstruct. Its durable settlement publishes directly;
147
+ // ignore the transient suffix until the next known start.
148
+ if (attempt === undefined || attempt.attemptId !== frame.attemptId) return undefined
149
+ if (frame.index !== attempt.nextIndex) return { type: 'rebaseline' }
150
+ attempt.nextIndex += 1
151
+ this.transientInGap += 1
152
+ return {
153
+ type: 'transient',
154
+ entry: {
155
+ type: 'transient',
156
+ event: {
157
+ type: 'assistant/live-chunk',
158
+ seq: this.durableCursor + 1 - 1 / (this.transientInGap + 1),
159
+ time: frame.time,
160
+ data: {
161
+ attemptId: frame.attemptId,
162
+ turn: attempt.turn,
163
+ step: attempt.step,
164
+ chunk: frame.chunk as never,
165
+ },
166
+ },
167
+ },
168
+ }
169
+ }
170
+ case 'end': {
171
+ const attempt = this.activeAttempt
172
+ if (attempt === undefined || attempt.attemptId !== frame.attemptId) {
173
+ return undefined
174
+ }
175
+ this.activeAttempt = undefined
176
+ if (frame.index !== attempt.nextIndex) return { type: 'rebaseline' }
177
+ if (frame.outcome.kind === 'abandoned') {
178
+ return this.pending.size === 0
179
+ ? { type: 'abandonment', attemptId: attempt.attemptId }
180
+ : { type: 'rebaseline' }
181
+ }
182
+ if (this.publishedSeqs.has(frame.outcome.seq)) return undefined
183
+ const entry = this.pending.get(frame.outcome.seq)
184
+ if (entry === undefined
185
+ || entry.event.type !== frame.outcome.eventType) {
186
+ return { type: 'rebaseline' }
187
+ }
188
+ this.pending.delete(frame.outcome.seq)
189
+ if (entry.event.type === 'assistant/message' && entry.event.data.interrupted !== true) {
190
+ this.retainedAttempt = { attemptId: attempt.attemptId, turn: attempt.turn, step: attempt.step }
191
+ return this.publish(entry)
192
+ }
193
+ this.publishedSeqs.add(entry.event.seq)
194
+ return { type: 'settlement', attemptId: attempt.attemptId, entry }
195
+ }
196
+ }
197
+ }
198
+
199
+ private attemptForSettlement(
200
+ event: SessionAssistantSettlementEntry['event'],
201
+ ): ActiveAttempt | undefined {
202
+ const attempt = this.activeAttempt
203
+ if (attempt === undefined
204
+ || (event.type === 'assistant/message' && event.surfaceOp !== 'append')
205
+ || event.seq <= attempt.startedAfterSeq
206
+ || attempt.turn !== event.data.turn
207
+ || attempt.step !== event.data.step) return undefined
208
+ return attempt
209
+ }
210
+
211
+ private publish(entry: SessionLiveEventEntry): ClientAssistantStreamResult {
212
+ this.publishedSeqs.add(entry.event.seq)
213
+ const retained = this.retainedAttempt
214
+ if (retained !== undefined && entry.event.type === 'step/end'
215
+ && entry.event.data.turn === retained.turn && entry.event.data.step === retained.step) {
216
+ this.retainedAttempt = undefined
217
+ return { type: 'publish', entry, retireAttemptId: retained.attemptId }
218
+ }
219
+ return { type: 'publish', entry }
220
+ }
221
+ }
222
+
223
+ function assistantSettlementEntry(
224
+ entry: SessionLiveEventEntry,
225
+ ): SessionAssistantSettlementEntry | undefined {
226
+ return entry.event.type === 'assistant/message' || entry.event.type === 'assistant/attempt'
227
+ ? entry as SessionAssistantSettlementEntry
228
+ : undefined
229
+ }
@@ -0,0 +1,35 @@
1
+ /** Client range access and type narrowing for aligned Session history records. */
2
+
3
+ import type {
4
+ SessionHistoryRecord,
5
+ } from '../../types.ts'
6
+ import type { SessionEventLikeEntry } from '../contract/events.ts'
7
+
8
+ /**
9
+ * Narrow aligned wire records to their Client event types without allocation.
10
+ * @param records - validated history transport records.
11
+ * @returns the same record array with typed inner events.
12
+ */
13
+ export function historyEntries(
14
+ records: readonly SessionHistoryRecord[],
15
+ ): readonly SessionEventLikeEntry[] {
16
+ return records as unknown as readonly SessionEventLikeEntry[]
17
+ }
18
+
19
+ /**
20
+ * Read the first logical sequence represented by one wire record.
21
+ * @param record - validated Session event.
22
+ * @returns inclusive first Session sequence.
23
+ */
24
+ export function historyRecordFirstSeq(record: SessionHistoryRecord): number {
25
+ return record.event.seq
26
+ }
27
+
28
+ /**
29
+ * Read the final logical sequence represented by one wire record.
30
+ * @param record - validated Session event.
31
+ * @returns inclusive final Session sequence.
32
+ */
33
+ export function historyRecordLastSeq(record: SessionHistoryRecord): number {
34
+ return record.event.seq
35
+ }