@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/catalog.ts ADDED
@@ -0,0 +1,117 @@
1
+ /** Shared projection of the live LLM registry into the browser model catalog. */
2
+
3
+ import { RemoteError } from '@unieai/rabi-typert-protocol'
4
+ import { credentialRef } from '@unieai/rabi-credentials'
5
+ import type {} from '@unieai/rabi-settings'
6
+ import type { LlmModelInfo } from '@unieai/rabi-llm'
7
+ import type { Context } from '@unieai/cordis'
8
+ import type {
9
+ ModelCatalog,
10
+ ModelReasoning,
11
+ ModelSelection,
12
+ } from './types.ts'
13
+
14
+ /**
15
+ * Build the browser model catalog without requiring a Session.
16
+ * @param ctx - Host context carrying the live LLM registry.
17
+ * @param defaultSelection - deployment default used before a Session selects a model.
18
+ * @returns successful non-empty provider groups and isolated provider failures.
19
+ */
20
+ export async function buildModelCatalog(
21
+ ctx: Context,
22
+ defaultSelection: ModelSelection = ctx.agentDefaultModel.currentSelection(),
23
+ ): Promise<ModelCatalog> {
24
+ const providers = ctx.llm.listProviders()
25
+ const catalog = await Promise.all(providers.map(async (provider) => {
26
+ try {
27
+ const models = await ctx.llm.listModels(provider.id)
28
+ const entries = await Promise.all(models.map(async (model) => {
29
+ const resolved = await ctx.llm.resolveModelInfo(provider.id, model.id)
30
+ const reasoning: ModelReasoning | undefined = resolved.reasoning === undefined
31
+ ? undefined
32
+ : {
33
+ efforts: resolved.reasoning.efforts.map(effort => ({
34
+ id: effort.id,
35
+ name: effort.name,
36
+ ...(effort.description === undefined ? {} : { description: effort.description }),
37
+ })),
38
+ ...(resolved.reasoning.defaultEffort === undefined
39
+ ? {}
40
+ : { defaultEffort: resolved.reasoning.defaultEffort }),
41
+ }
42
+ return {
43
+ id: model.id,
44
+ name: model.name,
45
+ ...(model.description === undefined ? {} : { description: model.description }),
46
+ ...(reasoning === undefined ? {} : { reasoning }),
47
+ ...(model.badge === undefined ? {} : { badge: model.badge }),
48
+ }
49
+ }))
50
+ return {
51
+ kind: 'group' as const,
52
+ group: { id: provider.id, name: provider.name, models: entries },
53
+ }
54
+ } catch (error) {
55
+ return {
56
+ kind: 'failure' as const,
57
+ failure: {
58
+ id: provider.id,
59
+ name: provider.name,
60
+ message: error instanceof Error ? error.message : String(error),
61
+ },
62
+ }
63
+ }
64
+ }))
65
+ const groups = catalog.flatMap(item => item.kind === 'group' ? [item.group] : [])
66
+ .filter(group => group.models.length > 0)
67
+ return {
68
+ default: { ...defaultSelection },
69
+ routableProviders: groups.map(group => group.id),
70
+ groups,
71
+ failures: catalog.flatMap(item => item.kind === 'failure' ? [item.failure] : []),
72
+ }
73
+ }
74
+
75
+ /**
76
+ * Check a GUI selection against the current available provider catalog.
77
+ * @param ctx - Host LLM registry.
78
+ * @param selection - stored or explicitly requested selection.
79
+ * @returns whether the exact model is currently advertised as available.
80
+ */
81
+ export async function modelAvailable(ctx: Context, selection: ModelSelection): Promise<boolean> {
82
+ if (!ctx.llm.listProviders().some(provider => provider.id === selection.provider)) return false
83
+ let models: readonly LlmModelInfo[]
84
+ try { models = await ctx.llm.listModels(selection.provider) }
85
+ catch (error) {
86
+ throw new RemoteError('session/model-unavailable',
87
+ error instanceof Error ? error.message : String(error),
88
+ { provider: selection.provider, model: selection.model })
89
+ }
90
+ return models.some(model => model.id === selection.model)
91
+ }
92
+
93
+ /**
94
+ * Check configured provider API-key references independently of model availability.
95
+ * @param ctx - Host registry, settings, and credential services.
96
+ * @returns whether any API-key provider has a configured credential.
97
+ */
98
+ export async function hasProviderApiKey(ctx: Context): Promise<boolean> {
99
+ const settings = ctx.get('settings')
100
+ const credentials = ctx.get('credentials')
101
+ if (settings === undefined || credentials === undefined) {
102
+ throw new RemoteError('session/provider-credentials-unavailable', 'provider credentials are unavailable', {})
103
+ }
104
+ const namespaces = settings.describe({ redactSecrets: true })
105
+ for (const provider of ctx.llm.listConfigurableProviders()) {
106
+ if (provider.provider === 'deepseek-account') continue
107
+ let profile = namespaces.find(namespace => namespace.ns === provider.settingsNs)?.value
108
+ for (const key of provider.settingsPath) {
109
+ profile = typeof profile === 'object' && profile !== null ? Reflect.get(profile, key) : undefined
110
+ }
111
+ if (typeof profile !== 'object' || profile === null) continue
112
+ const ref: unknown = Reflect.get(profile, 'apiKeyEnv')
113
+ if (typeof ref === 'string' && ref.length > 0
114
+ && (await credentials.describe(credentialRef(ref))).configured) return true
115
+ }
116
+ return false
117
+ }
@@ -0,0 +1,205 @@
1
+ /** Observable contiguous Session event window consumed by domain assemblers. */
2
+ import { notifySubscribers, type ObservableSnapshot } from '@unieai/rabi-client-store'
3
+ import type { LlmAttemptId, StreamChunk } from '@unieai/rabi-llm'
4
+ import type { SessionEvent } from '@unieai/rabi-session/types'
5
+
6
+ /** Client-only live chunk presentation; `seq` orders the transient row between durable Session seqs. */
7
+ export interface AssistantLiveChunkEvent {
8
+ readonly type: 'assistant/live-chunk'
9
+ readonly seq: number
10
+ readonly time: number
11
+ readonly data: {
12
+ readonly attemptId: LlmAttemptId
13
+ readonly turn: number
14
+ readonly step: number
15
+ readonly chunk: StreamChunk
16
+ }
17
+ }
18
+
19
+ /** Current durable Session event or one client-only live chunk presentation. */
20
+ export type SessionEventLike = SessionEvent | AssistantLiveChunkEvent
21
+
22
+ /** Client history entry retaining its coarse transport discriminator. */
23
+ export type SessionEventLikeEntry =
24
+ | { readonly type: 'event'; readonly event: SessionEvent }
25
+ | { readonly type: 'transient'; readonly event: AssistantLiveChunkEvent }
26
+
27
+ /** Scalar live entry accepted by append-only Client paths. */
28
+ export type SessionLiveEventEntry = Extract<SessionEventLikeEntry, { readonly type: 'event' }>
29
+ /** Durable Assistant event that atomically supersedes one attempt's transient rows. */
30
+ export interface SessionAssistantSettlementEntry {
31
+ readonly type: 'event'
32
+ readonly event: SessionEvent<'assistant/message'> | SessionEvent<'assistant/attempt'>
33
+ }
34
+ /** Client-only Assistant frame admitted outside durable cursor algebra. */
35
+ export type SessionTransientEventEntry = Extract<SessionEventLikeEntry, { readonly type: 'transient' }>
36
+
37
+ interface EventWindowLeaf {
38
+ readonly kind: 'leaf'
39
+ readonly entries: readonly SessionEventLikeEntry[]
40
+ readonly length: number
41
+ }
42
+
43
+ interface EventWindowConcat {
44
+ readonly kind: 'concat'
45
+ readonly left: EventWindowNode
46
+ readonly right: EventWindowNode
47
+ readonly length: number
48
+ }
49
+
50
+ type EventWindowNode = EventWindowLeaf | EventWindowConcat
51
+
52
+ function leaf(entries: readonly SessionEventLikeEntry[]): EventWindowLeaf {
53
+ return { kind: 'leaf', entries, length: entries.length }
54
+ }
55
+
56
+ function concat(left: EventWindowNode, right: EventWindowNode): EventWindowConcat {
57
+ return { kind: 'concat', left, right, length: left.length + right.length }
58
+ }
59
+
60
+ function materialize(node: EventWindowNode): readonly SessionEventLikeEntry[] {
61
+ if (node.kind === 'leaf') return node.entries
62
+ const entries = new Array<SessionEventLikeEntry>(node.length)
63
+ const pending: EventWindowNode[] = [node]
64
+ let index = 0
65
+ while (pending.length > 0) {
66
+ const current = pending.pop() as EventWindowNode
67
+ if (current.kind === 'concat') {
68
+ pending.push(current.right, current.left)
69
+ continue
70
+ }
71
+ for (const entry of current.entries) {
72
+ entries[index] = entry
73
+ index += 1
74
+ }
75
+ }
76
+ return entries
77
+ }
78
+
79
+ function windowSnapshot(
80
+ node: EventWindowNode,
81
+ hasMore: boolean,
82
+ revision: number,
83
+ change: SessionEventChange,
84
+ ): SessionEventWindow {
85
+ let entries: readonly SessionEventLikeEntry[] | undefined
86
+ return {
87
+ get entries() {
88
+ entries ??= materialize(node)
89
+ return entries
90
+ },
91
+ hasMore,
92
+ revision,
93
+ change,
94
+ }
95
+ }
96
+
97
+ /** Exact delta that produced the latest event-window revision. */
98
+ export type SessionEventChange =
99
+ | { readonly kind: 'replace'; readonly entries: readonly SessionEventLikeEntry[] }
100
+ | { readonly kind: 'prepend'; readonly entries: readonly SessionEventLikeEntry[] }
101
+ | { readonly kind: 'append'; readonly entries: readonly SessionEventLikeEntry[] }
102
+ | {
103
+ readonly kind: 'settle-assistant'
104
+ readonly attemptId: LlmAttemptId
105
+ readonly entry?: SessionAssistantSettlementEntry
106
+ }
107
+
108
+ /** Current contiguous event window and its latest synchronous delta. */
109
+ export interface SessionEventWindow {
110
+ readonly entries: readonly SessionEventLikeEntry[]
111
+ readonly hasMore: boolean
112
+ readonly revision: number
113
+ readonly change: SessionEventChange
114
+ }
115
+
116
+ /** Conversation-facing event source exposed by one Session binding. */
117
+ export type SessionEventSource = ObservableSnapshot<SessionEventWindow>
118
+
119
+ /** Session-owned event feed; every accepted window mutation publishes synchronously. */
120
+ export class MutableSessionEventSource implements SessionEventSource {
121
+ private readonly listeners = new Set<() => void>()
122
+ private window: EventWindowNode = leaf([])
123
+ private snapshot: SessionEventWindow = windowSnapshot(
124
+ this.window,
125
+ false,
126
+ 0,
127
+ { kind: 'replace', entries: [] },
128
+ )
129
+
130
+ /** @returns the cached event-window snapshot. */
131
+ getSnapshot(): SessionEventWindow { return this.snapshot }
132
+
133
+ /**
134
+ * Subscribe to synchronous window publication.
135
+ * @param listener - invalidation callback.
136
+ * @returns unsubscribe function.
137
+ */
138
+ subscribe(listener: () => void): () => void {
139
+ this.listeners.add(listener)
140
+ return () => { this.listeners.delete(listener) }
141
+ }
142
+
143
+ /**
144
+ * Replace the complete contiguous window.
145
+ * @param entries - complete window.
146
+ * @param hasMore - whether older history remains.
147
+ */
148
+ replace(entries: readonly SessionEventLikeEntry[], hasMore: boolean): void {
149
+ this.window = leaf(entries)
150
+ this.publish(hasMore, { kind: 'replace', entries })
151
+ }
152
+
153
+ /**
154
+ * Prepend one older contiguous page.
155
+ * @param entries - newly loaded older entries.
156
+ * @param hasMore - whether still older history remains.
157
+ */
158
+ prepend(entries: readonly SessionEventLikeEntry[], hasMore: boolean): void {
159
+ this.window = concat(leaf(entries), this.window)
160
+ this.publish(hasMore, { kind: 'prepend', entries })
161
+ }
162
+
163
+ /**
164
+ * Append one contiguous live entry.
165
+ * @param entry - live tail entry.
166
+ */
167
+ append(entry: SessionEventLikeEntry): void {
168
+ const entries = [entry]
169
+ this.window = concat(this.window, leaf(entries))
170
+ this.publish(this.snapshot.hasMore, {
171
+ kind: 'append',
172
+ entries,
173
+ })
174
+ }
175
+
176
+ /**
177
+ * Replace one attempt's transient rows with its committed durable settlement.
178
+ * @param attemptId - process-local attempt whose live rows are now redundant.
179
+ * @param entry - durable settlement committed for that attempt.
180
+ */
181
+ settleAssistant(attemptId: LlmAttemptId, entry?: SessionAssistantSettlementEntry): void {
182
+ const entries = materialize(this.window).filter(candidate => (
183
+ candidate.type !== 'transient' || candidate.event.data.attemptId !== attemptId
184
+ ))
185
+ if (entry !== undefined) {
186
+ const index = entries.findIndex(candidate => candidate.event.seq > entry.event.seq)
187
+ if (index < 0) entries.push(entry)
188
+ else entries.splice(index, 0, entry)
189
+ }
190
+ this.window = leaf(entries)
191
+ this.publish(this.snapshot.hasMore, {
192
+ kind: 'settle-assistant',
193
+ attemptId,
194
+ ...(entry === undefined ? {} : { entry }),
195
+ })
196
+ }
197
+
198
+ private publish(
199
+ hasMore: boolean,
200
+ change: SessionEventChange,
201
+ ): void {
202
+ this.snapshot = windowSnapshot(this.window, hasMore, this.snapshot.revision + 1, change)
203
+ notifySubscribers(this.listeners, '[session-controller] event feed')
204
+ }
205
+ }
@@ -0,0 +1,174 @@
1
+ /**
2
+ * The outward session face. Feature packages never see the concrete Session
3
+ * class: components read lifecycle state through `useSession` (the
4
+ * ObservableSnapshot half), and orchestration code calls the behavior verbs
5
+ * below — nothing else. Widening this interface is the explicit act of
6
+ * widening what features may do to a session (and what every test fixture
7
+ * must stub); implementation-internal wire-frame dispatch stays on the class,
8
+ * invisible out here.
9
+ */
10
+ import type { FileAttachmentRef, ImageAttachmentRef } from '@unieai/rabi-attachment'
11
+ import type { MessageId } from '@unieai/rabi-llm/brand'
12
+ import type { SessionId, SessionSeq } from '@unieai/rabi-session/types'
13
+ import type { RemoteResult } from '@unieai/rabi-typert-protocol'
14
+ import type { ObservableSnapshot } from '@unieai/rabi-client-store'
15
+ import type { PromptContentPart, QueueAction, SessionRequestId } from '../../types.ts'
16
+ import type { PendingSubmissionAttachment, SessionSnapshot } from './snapshot.ts'
17
+
18
+ /**
19
+ * Why a local submission echo left the snapshot: `observed` when its durable
20
+ * `user/message` event or host queue occurrence arrived (with the admitted
21
+ * attachment references in prompt order), `failed` when the prompt was rejected,
22
+ * threw, or was aborted before acceptance.
23
+ */
24
+ export type PendingSubmissionRetirement =
25
+ | {
26
+ readonly reason: 'observed'
27
+ readonly attachments: readonly (ImageAttachmentRef | FileAttachmentRef)[]
28
+ }
29
+ | { readonly reason: 'failed' }
30
+
31
+ /** Input registering one local submission echo ahead of its prompt call. */
32
+ export interface BeginSubmissionInput {
33
+ /** Delivery mode used with the upcoming prompt. */
34
+ readonly mode: 'queue' | 'steer'
35
+ /** Prompt text exactly as the upcoming prompt will send it. */
36
+ readonly text: string
37
+ /** Ordered image previews and durable file metadata matching the upcoming prompt attachments. */
38
+ readonly attachments: readonly PendingSubmissionAttachment[]
39
+ /**
40
+ * Called once when the Host accepted the prompt, in the same update that
41
+ * publishes the echo, whether the receipt or an Inbox row showed it first.
42
+ */
43
+ readonly onAccept?: () => void
44
+ /** Settlement callback fired exactly once when the echo retires. */
45
+ readonly onRetire?: (retirement: PendingSubmissionRetirement) => void
46
+ }
47
+
48
+ /** One registered submission echo: the identity its prompt must carry, and the pre-prompt escape hatch. */
49
+ export interface SubmissionHandle {
50
+ /** The prompt RPC identity; pass it to {@link ISession.prompt}. */
51
+ readonly requestId: SessionRequestId
52
+ /** Retire the echo as failed when the caller cannot reach prompt() (serialization failure); no-op after any other settlement. */
53
+ abandon(): void
54
+ }
55
+
56
+ /** Key-addressed projection read face (the useProjection resolution path; see ProjectionValueStore). */
57
+ export interface ProjectionsFace {
58
+ /**
59
+ * The identity-stable bare observable for one projection key (absence is
60
+ * an `undefined` snapshot, never a missing face).
61
+ * @param key - projection key.
62
+ * @returns the key's value face.
63
+ */
64
+ faceOf(key: string): ObservableSnapshot<unknown>
65
+ }
66
+
67
+ /** Identity plus the behavior verbs features may invoke on a session. */
68
+ export interface ISession {
69
+ /** The session's host identity (agent id — same axis). */
70
+ readonly sessionId: SessionId
71
+ /** Host-computed projection values by key (the useProjection seat). */
72
+ readonly projections: ProjectionsFace
73
+ /**
74
+ * Register one local submission echo before the caller serializes and sends
75
+ * the prompt. The echo reconciles against Host events from then on, and
76
+ * enters `snapshot.pendingSubmissions` once the Host accepted the prompt:
77
+ * when {@link prompt} reports the receipt or an Inbox row carrying the
78
+ * request id arrives, whichever comes first. The Chat echoes persist until
79
+ * durable admission; transcript identities also wait for the Inbox claim
80
+ * watermark so stale queue rows stay suppressed. Queued echoes retire on
81
+ * queue acceptance. Identified failures retire submissions that have not
82
+ * already reached durable admission.
83
+ * @param input - echo content and the optional settlement callback.
84
+ * @returns the minted identity for {@link prompt} plus the pre-prompt abandon path.
85
+ */
86
+ beginSubmission(input: BeginSubmissionInput): SubmissionHandle
87
+ /**
88
+ * Send a prompt into the session. The Host can hold the prompt at its
89
+ * admission stage, so the call can stay open; acceptance publishes the
90
+ * prompt's echo and moves a blank Session to engaging, before the call
91
+ * returns when an Inbox row carrying the request id arrives first.
92
+ * @param content - text plus browser-owned temporary image uploads.
93
+ * @param mode - 'queue' appends a turn; 'steer' interrupts the running one.
94
+ * @param signal - optional caller cancellation for the complete admission round-trip.
95
+ * @param requestId - identity from {@link beginSubmission}; a failed identified prompt retires its echo.
96
+ * @returns acceptance, or the business error (also mirrored into snapshot.promptError).
97
+ */
98
+ prompt(
99
+ content: PromptContentPart[],
100
+ mode: 'queue' | 'steer',
101
+ signal?: AbortSignal,
102
+ requestId?: SessionRequestId,
103
+ ): Promise<RemoteResult<{ accepted: true }>>
104
+ /**
105
+ * Resolve one stored image using this Session's gateway permission scope.
106
+ * @param attachment - complete image reference from the folded session log.
107
+ * @returns the supplied reference after storage verification, and decoded bytes.
108
+ */
109
+ readAttachment(
110
+ attachment: ImageAttachmentRef,
111
+ ): Promise<RemoteResult<{ attachment: ImageAttachmentRef; data: Uint8Array }>>
112
+ /**
113
+ * Apply one edit, remove, or Steer action to a still-pending queue occurrence.
114
+ * @param itemId - agent-owned inbox occurrence identity.
115
+ * @param action - requested queue operation.
116
+ * @returns acceptance, or a business/transport error.
117
+ */
118
+ updateQueue(itemId: MessageId, action: QueueAction): Promise<RemoteResult<{ accepted: true }>>
119
+ /**
120
+ * Cancel the running turn. Pending queued work remains and resumes in FIFO
121
+ * order after the Host reaches cancellation quiescence.
122
+ * @returns acceptance, or the business error.
123
+ */
124
+ cancel(): Promise<RemoteResult<{ accepted: true }>>
125
+ /**
126
+ * Rename this session (explicit user title; pins it against automatic
127
+ * regeneration).
128
+ * @param title - raw title text (the host normalizes acceptance).
129
+ * @returns the normalized accepted title and its event seq, or the business error.
130
+ */
131
+ rename(title: string): Promise<RemoteResult<{ title: string; seq: SessionSeq }>>
132
+ /**
133
+ * Extend history by at least 50 messages and two Turn starts, including a
134
+ * partial Turn at the window's beginning. Stop at 500 messages or history
135
+ * exhaustion even when those minima cannot be met. At most one page may be
136
+ * loading or awaiting consumption; live events remain independently visible.
137
+ * @param options - deferConsumption keeps the page unpublished until consumeOlder; omitted consumes before completion.
138
+ * @returns request completion; failures and no progress set snapshot.historyLoadStatus to error.
139
+ */
140
+ loadOlder(options?: { deferConsumption?: boolean }): Promise<void>
141
+ /**
142
+ * Publish the prepared page synchronously if its generation and starting cursor still match.
143
+ * A terminal empty page may publish hasMore=false; an invalidated page is discarded.
144
+ * @returns whether a prepared page was published; false while loading, absent, or invalidated.
145
+ */
146
+ consumeOlder(): boolean
147
+ /**
148
+ * Page history backwards until the window covers `seq` (inclusive) — the
149
+ * turn-jump loader. Repeated calls while a jump is paging lower its shared
150
+ * target and return the in-flight completion; `snapshot.loadingOlder` is
151
+ * the busy signal for the whole jump.
152
+ * Each page uses the same Turn alignment as loadOlder, with a 200-message
153
+ * minimum. The 500-message limit applies per page, not to the whole jump.
154
+ * Older pages publish together at completion, including successful pages
155
+ * before a later failure; live events remain independently visible.
156
+ * @param seq - durable event seq the window must reach (a turn's `turn/start` seq).
157
+ * @returns completion once covered, exhausted, superseded, or failed soft.
158
+ */
159
+ loadThrough(seq: SessionSeq): Promise<void>
160
+ /**
161
+ * Execute one slash-command line against this session's agent — pure
162
+ * admission semantics (the host executor durably logs the lifecycle).
163
+ * @param line - the full command line, leading slash included.
164
+ * @returns the admission result, or the Remote face's error branch.
165
+ */
166
+ command(line: string): Promise<RemoteResult<{ matched: boolean }>>
167
+ }
168
+
169
+ /**
170
+ * The full outward face: behavior verbs plus the Session lifecycle read side
171
+ * (the `useSession` hook source). This is the type carried by
172
+ * `SessionBinding.session` and the provide channel.
173
+ */
174
+ export type SessionFace = ISession & ObservableSnapshot<SessionSnapshot>
@@ -0,0 +1,169 @@
1
+ /**
2
+ * The outward sessions-service face — what `ctx.sessions` exposes to feature
3
+ * packages. Transport entry points and implementation internals stay on
4
+ * the concrete class. Widening this interface is the
5
+ * explicit act of widening what features may do to the sessions domain.
6
+ */
7
+ import type { Context } from '@unieai/cordis'
8
+ import type { SubagentAddress } from '@unieai/rabi-subagent/client'
9
+ import type { SessionId } from '@unieai/rabi-session/types'
10
+ import type { WorkspaceId } from '@unieai/rabi-workspace/types'
11
+ import type { RemoteResult } from '@unieai/rabi-typert-protocol'
12
+ import type { AgentContext } from '../scope.ts'
13
+ import type { SessionSearchResultItem } from '../sessions/manager.ts'
14
+ import type { SessionBinding, SessionListState } from '../sessions/service.ts'
15
+ import type { SessionFace } from './session.ts'
16
+ import type { ObservableSnapshot } from '@unieai/rabi-client-store'
17
+ import type { SessionReferenceSource } from '../index.ts'
18
+
19
+ export type { AgentContext } from '../scope.ts'
20
+
21
+ /** Known Session identity or durable direct-parent subagent address; an address owns no lifetime. */
22
+ export type SessionTarget = SessionId | SubagentAddress
23
+
24
+ /** One independent use of an exact Client generation, without Host Agent ownership. */
25
+ export interface SessionReference extends Disposable {
26
+ readonly sessionId: SessionId
27
+ /** Shared binding; access fails after reference release or generation disposal. */
28
+ readonly binding: SessionBinding
29
+ /** This reference's cancellable wait for the shared initial `Session.open()` attempt to settle. */
30
+ readonly ready: Promise<SessionBinding>
31
+ /** Release once; the final reference starts local scope and history teardown. */
32
+ release(): void
33
+ }
34
+
35
+ /** Consumer identity and optional cancellation of one acquisition waiter. */
36
+ export interface SessionRetainOptions {
37
+ readonly source: SessionReferenceSource
38
+ readonly signal?: AbortSignal | undefined
39
+ }
40
+
41
+ /** Local ownership counts, independent of catalog membership and never persisted. */
42
+ export interface SessionRetainInfo {
43
+ readonly referenceCount: number
44
+ /** Positive source counts only; a source without references is absent. */
45
+ readonly retainedBy: Readonly<Partial<Record<SessionReferenceSource, number>>>
46
+ }
47
+
48
+ /** The sessions-service face injected as `ctx.sessions`. */
49
+ export interface ISessions {
50
+ /** Host catalog and local reference-source counts; navigation belongs to view owners. */
51
+ readonly list: ObservableSnapshot<SessionListState>
52
+ /**
53
+ * Retain an exact Client generation and start its shared initial history opening.
54
+ * @param target - known identity or durable direct-parent address.
55
+ * @param options - required consumer source and optional independent waiter cancellation.
56
+ * @returns an owned reference immediately; await `reference.ready` when the initial open attempt must settle first.
57
+ */
58
+ retain(target: SessionTarget, options: SessionRetainOptions): SessionReference
59
+ /**
60
+ * Hold one reference through callback settlement, including synchronous and asynchronous failures.
61
+ * @param target - Session to acquire.
62
+ * @param options - source and acquisition cancellation.
63
+ * @param operation - callback using the reference only until its returned value or Promise settles.
64
+ * @returns the callback result after release; acquisition and callback failures propagate unchanged.
65
+ */
66
+ using<T>(target: SessionTarget, options: SessionRetainOptions, operation: (reference: SessionReference) => T | Promise<T>): Promise<T>
67
+ /**
68
+ * Observe local reference counts without retaining, creating a scope, or opening history.
69
+ * The returned source keeps stable identity across same-id generations and remains allocated
70
+ * until the Client root is disposed, even after its final subscriber leaves.
71
+ * @param id - explicit Session identity; Host existence is not implied.
72
+ * @returns a stable read-only source across same-id generations, with zero counts when none is live.
73
+ */
74
+ retainInfo(id: SessionId): ObservableSnapshot<SessionRetainInfo>
75
+ /**
76
+ * The `session.search` result bound the wire schema fixes, exposed to
77
+ * presentation as injected data. Not per-connection state: every transport
78
+ * (fixture included) reports the same number.
79
+ */
80
+ readonly searchResultLimit: number
81
+ /**
82
+ * Create a Session for a new conversation on the Host. The Host reuses the
83
+ * named blank Session while it is reusable and otherwise creates another; the
84
+ * Session runs the named preset, or the Host default when none is named.
85
+ * @param opts - target workspace or directory, an optional blank Session to reuse, and an optional Agent preset.
86
+ * @returns the catalogued identity the Host created or reused; retain it before borrowing its binding.
87
+ */
88
+ create(opts?: {
89
+ workspaceId?: WorkspaceId
90
+ cwd?: string
91
+ sessionId?: SessionId
92
+ agentPreset?: string
93
+ }): Promise<SessionId>
94
+ /**
95
+ * Resolve an already discovered direct-parent address without opening it.
96
+ * @param id - possible addressed child id.
97
+ * @returns a retained, catalog-derived, or unknown-mode listed address, without retaining a new selection or scope.
98
+ */
99
+ subagentAddress(id: SessionId): SubagentAddress | undefined
100
+
101
+ /**
102
+ * Read projections without starting migration; retry failed or migration-deferred reads.
103
+ * @param sessionId - Session to inspect without opening its conversation.
104
+ * @returns completion of the current or newly started refresh.
105
+ */
106
+ refreshProjections(sessionId: SessionId): Promise<void>
107
+
108
+ /**
109
+ * Refresh the Host-authoritative Session list.
110
+ * @returns completion of the current or newly started Session-list refresh.
111
+ */
112
+ refresh(): Promise<void>
113
+ /**
114
+ * Search the Host's visible message-content index. Results stay
115
+ * request-local; the list snapshot remains the metadata authority.
116
+ * @param query - non-blank literal phrase.
117
+ * @param signal - cancellation for a superseded search.
118
+ * @returns bounded results, or a business/transport error.
119
+ */
120
+ search(
121
+ query: string,
122
+ signal: AbortSignal,
123
+ ): Promise<RemoteResult<{ items: SessionSearchResultItem[]; hasMore: boolean }>>
124
+ /**
125
+ * Fork a session from an exact inclusive prefix of the source; on
126
+ * resolution the child is catalogued and can be explicitly retained.
127
+ * @param opts - source session id, the optional exact inclusive boundary
128
+ * seq (a real event seq the caller already knows; a cut inside an open
129
+ * turn is balanced Host-side with synthetic closers, and omission selects
130
+ * the latest completed-turn prefix), and whether to increment an
131
+ * inherited durable title, skipping numbers Host-listed titles already use,
132
+ * before resolving. `onCreated` observes the catalogued child before that optional rename.
133
+ * @returns the child session id.
134
+ * @throws when the fork fails, or when a requested child-title rename fails after creation.
135
+ */
136
+ fork(opts: {
137
+ sessionId: SessionId
138
+ atSeq?: number
139
+ increaseTitle?: boolean
140
+ onCreated?: (childId: SessionId) => void
141
+ /** False refuses source migration; omission preserves the Host default. */
142
+ allowMigration?: boolean
143
+ }): Promise<SessionId>
144
+ /**
145
+ * Borrow an already-retained Agent-scoped Context without extending its lifetime.
146
+ * @param id - session id.
147
+ * @returns the live scoped Context, or undefined without a retained generation.
148
+ */
149
+ scope(id: SessionId): AgentContext | undefined
150
+ /**
151
+ * Read the Agent scope tag off a context (service-method boundary: fetch
152
+ * bundles must reach scope resolution through ctx.sessions).
153
+ * @param ctx - any client context.
154
+ * @returns the session id, or undefined on root contexts.
155
+ */
156
+ scopeOf(ctx: Context): SessionId | undefined
157
+ /**
158
+ * Resolve the session face behind an Agent-scoped context.
159
+ * @param ctx - an Agent-scoped context.
160
+ * @returns the matching live Session, or undefined for an untagged, foreign, or ended generation.
161
+ */
162
+ sessionOf(ctx: Context): SessionFace | undefined
163
+ /**
164
+ * Borrow an already-retained Session binding without extending its lifetime.
165
+ * @param id - session id.
166
+ * @returns the live binding, or undefined without a retained generation.
167
+ */
168
+ binding(id: SessionId): SessionBinding | undefined
169
+ }