@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,178 @@
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
+ * Why a local submission echo left the snapshot: `observed` when its durable
19
+ * `user/message` event or host queue occurrence arrived (with the admitted
20
+ * attachment references in prompt order), `failed` when the prompt was rejected,
21
+ * threw, or was aborted before acceptance.
22
+ */
23
+ export type PendingSubmissionRetirement = {
24
+ readonly reason: 'observed';
25
+ readonly attachments: readonly (ImageAttachmentRef | FileAttachmentRef)[];
26
+ } | {
27
+ readonly reason: 'failed';
28
+ };
29
+ /** Input registering one local submission echo ahead of its prompt call. */
30
+ export interface BeginSubmissionInput {
31
+ /** Delivery mode used with the upcoming prompt. */
32
+ readonly mode: 'queue' | 'steer';
33
+ /** Prompt text exactly as the upcoming prompt will send it. */
34
+ readonly text: string;
35
+ /** Ordered image previews and durable file metadata matching the upcoming prompt attachments. */
36
+ readonly attachments: readonly PendingSubmissionAttachment[];
37
+ /**
38
+ * Called once when the Host accepted the prompt, in the same update that
39
+ * publishes the echo, whether the receipt or an Inbox row showed it first.
40
+ */
41
+ readonly onAccept?: () => void;
42
+ /** Settlement callback fired exactly once when the echo retires. */
43
+ readonly onRetire?: (retirement: PendingSubmissionRetirement) => void;
44
+ }
45
+ /** One registered submission echo: the identity its prompt must carry, and the pre-prompt escape hatch. */
46
+ export interface SubmissionHandle {
47
+ /** The prompt RPC identity; pass it to {@link ISession.prompt}. */
48
+ readonly requestId: SessionRequestId;
49
+ /** Retire the echo as failed when the caller cannot reach prompt() (serialization failure); no-op after any other settlement. */
50
+ abandon(): void;
51
+ }
52
+ /** Key-addressed projection read face (the useProjection resolution path; see ProjectionValueStore). */
53
+ export interface ProjectionsFace {
54
+ /**
55
+ * The identity-stable bare observable for one projection key (absence is
56
+ * an `undefined` snapshot, never a missing face).
57
+ * @param key - projection key.
58
+ * @returns the key's value face.
59
+ */
60
+ faceOf(key: string): ObservableSnapshot<unknown>;
61
+ }
62
+ /** Identity plus the behavior verbs features may invoke on a session. */
63
+ export interface ISession {
64
+ /** The session's host identity (agent id — same axis). */
65
+ readonly sessionId: SessionId;
66
+ /** Host-computed projection values by key (the useProjection seat). */
67
+ readonly projections: ProjectionsFace;
68
+ /**
69
+ * Register one local submission echo before the caller serializes and sends
70
+ * the prompt. The echo reconciles against Host events from then on, and
71
+ * enters `snapshot.pendingSubmissions` once the Host accepted the prompt:
72
+ * when {@link prompt} reports the receipt or an Inbox row carrying the
73
+ * request id arrives, whichever comes first. The Chat echoes persist until
74
+ * durable admission; transcript identities also wait for the Inbox claim
75
+ * watermark so stale queue rows stay suppressed. Queued echoes retire on
76
+ * queue acceptance. Identified failures retire submissions that have not
77
+ * already reached durable admission.
78
+ * @param input - echo content and the optional settlement callback.
79
+ * @returns the minted identity for {@link prompt} plus the pre-prompt abandon path.
80
+ */
81
+ beginSubmission(input: BeginSubmissionInput): SubmissionHandle;
82
+ /**
83
+ * Send a prompt into the session. The Host can hold the prompt at its
84
+ * admission stage, so the call can stay open; acceptance publishes the
85
+ * prompt's echo and moves a blank Session to engaging, before the call
86
+ * returns when an Inbox row carrying the request id arrives first.
87
+ * @param content - text plus browser-owned temporary image uploads.
88
+ * @param mode - 'queue' appends a turn; 'steer' interrupts the running one.
89
+ * @param signal - optional caller cancellation for the complete admission round-trip.
90
+ * @param requestId - identity from {@link beginSubmission}; a failed identified prompt retires its echo.
91
+ * @returns acceptance, or the business error (also mirrored into snapshot.promptError).
92
+ */
93
+ prompt(content: PromptContentPart[], mode: 'queue' | 'steer', signal?: AbortSignal, requestId?: SessionRequestId): Promise<RemoteResult<{
94
+ accepted: true;
95
+ }>>;
96
+ /**
97
+ * Resolve one stored image using this Session's gateway permission scope.
98
+ * @param attachment - complete image reference from the folded session log.
99
+ * @returns the supplied reference after storage verification, and decoded bytes.
100
+ */
101
+ readAttachment(attachment: ImageAttachmentRef): Promise<RemoteResult<{
102
+ attachment: ImageAttachmentRef;
103
+ data: Uint8Array;
104
+ }>>;
105
+ /**
106
+ * Apply one edit, remove, or Steer action to a still-pending queue occurrence.
107
+ * @param itemId - agent-owned inbox occurrence identity.
108
+ * @param action - requested queue operation.
109
+ * @returns acceptance, or a business/transport error.
110
+ */
111
+ updateQueue(itemId: MessageId, action: QueueAction): Promise<RemoteResult<{
112
+ accepted: true;
113
+ }>>;
114
+ /**
115
+ * Cancel the running turn. Pending queued work remains and resumes in FIFO
116
+ * order after the Host reaches cancellation quiescence.
117
+ * @returns acceptance, or the business error.
118
+ */
119
+ cancel(): Promise<RemoteResult<{
120
+ accepted: true;
121
+ }>>;
122
+ /**
123
+ * Rename this session (explicit user title; pins it against automatic
124
+ * regeneration).
125
+ * @param title - raw title text (the host normalizes acceptance).
126
+ * @returns the normalized accepted title and its event seq, or the business error.
127
+ */
128
+ rename(title: string): Promise<RemoteResult<{
129
+ title: string;
130
+ seq: SessionSeq;
131
+ }>>;
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?: {
141
+ deferConsumption?: boolean;
142
+ }): Promise<void>;
143
+ /**
144
+ * Publish the prepared page synchronously if its generation and starting cursor still match.
145
+ * A terminal empty page may publish hasMore=false; an invalidated page is discarded.
146
+ * @returns whether a prepared page was published; false while loading, absent, or invalidated.
147
+ */
148
+ consumeOlder(): boolean;
149
+ /**
150
+ * Page history backwards until the window covers `seq` (inclusive) — the
151
+ * turn-jump loader. Repeated calls while a jump is paging lower its shared
152
+ * target and return the in-flight completion; `snapshot.loadingOlder` is
153
+ * the busy signal for the whole jump.
154
+ * Each page uses the same Turn alignment as loadOlder, with a 200-message
155
+ * minimum. The 500-message limit applies per page, not to the whole jump.
156
+ * Older pages publish together at completion, including successful pages
157
+ * before a later failure; live events remain independently visible.
158
+ * @param seq - durable event seq the window must reach (a turn's `turn/start` seq).
159
+ * @returns completion once covered, exhausted, superseded, or failed soft.
160
+ */
161
+ loadThrough(seq: SessionSeq): Promise<void>;
162
+ /**
163
+ * Execute one slash-command line against this session's agent — pure
164
+ * admission semantics (the host executor durably logs the lifecycle).
165
+ * @param line - the full command line, leading slash included.
166
+ * @returns the admission result, or the Remote face's error branch.
167
+ */
168
+ command(line: string): Promise<RemoteResult<{
169
+ matched: boolean;
170
+ }>>;
171
+ }
172
+ /**
173
+ * The full outward face: behavior verbs plus the Session lifecycle read side
174
+ * (the `useSession` hook source). This is the type carried by
175
+ * `SessionBinding.session` and the provide channel.
176
+ */
177
+ export type SessionFace = ISession & ObservableSnapshot<SessionSnapshot>;
178
+ //# sourceMappingURL=session.d.ts.map
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,162 @@
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
+ export type { AgentContext } from '../scope.ts';
19
+ /** Known Session identity or durable direct-parent subagent address; an address owns no lifetime. */
20
+ export type SessionTarget = SessionId | SubagentAddress;
21
+ /** One independent use of an exact Client generation, without Host Agent ownership. */
22
+ export interface SessionReference extends Disposable {
23
+ readonly sessionId: SessionId;
24
+ /** Shared binding; access fails after reference release or generation disposal. */
25
+ readonly binding: SessionBinding;
26
+ /** This reference's cancellable wait for the shared initial `Session.open()` attempt to settle. */
27
+ readonly ready: Promise<SessionBinding>;
28
+ /** Release once; the final reference starts local scope and history teardown. */
29
+ release(): void;
30
+ }
31
+ /** Consumer identity and optional cancellation of one acquisition waiter. */
32
+ export interface SessionRetainOptions {
33
+ readonly source: SessionReferenceSource;
34
+ readonly signal?: AbortSignal | undefined;
35
+ }
36
+ /** Local ownership counts, independent of catalog membership and never persisted. */
37
+ export interface SessionRetainInfo {
38
+ readonly referenceCount: number;
39
+ /** Positive source counts only; a source without references is absent. */
40
+ readonly retainedBy: Readonly<Partial<Record<SessionReferenceSource, number>>>;
41
+ }
42
+ /** The sessions-service face injected as `ctx.sessions`. */
43
+ export interface ISessions {
44
+ /** Host catalog and local reference-source counts; navigation belongs to view owners. */
45
+ readonly list: ObservableSnapshot<SessionListState>;
46
+ /**
47
+ * Retain an exact Client generation and start its shared initial history opening.
48
+ * @param target - known identity or durable direct-parent address.
49
+ * @param options - required consumer source and optional independent waiter cancellation.
50
+ * @returns an owned reference immediately; await `reference.ready` when the initial open attempt must settle first.
51
+ */
52
+ retain(target: SessionTarget, options: SessionRetainOptions): SessionReference;
53
+ /**
54
+ * Hold one reference through callback settlement, including synchronous and asynchronous failures.
55
+ * @param target - Session to acquire.
56
+ * @param options - source and acquisition cancellation.
57
+ * @param operation - callback using the reference only until its returned value or Promise settles.
58
+ * @returns the callback result after release; acquisition and callback failures propagate unchanged.
59
+ */
60
+ using<T>(target: SessionTarget, options: SessionRetainOptions, operation: (reference: SessionReference) => T | Promise<T>): Promise<T>;
61
+ /**
62
+ * Observe local reference counts without retaining, creating a scope, or opening history.
63
+ * The returned source keeps stable identity across same-id generations and remains allocated
64
+ * until the Client root is disposed, even after its final subscriber leaves.
65
+ * @param id - explicit Session identity; Host existence is not implied.
66
+ * @returns a stable read-only source across same-id generations, with zero counts when none is live.
67
+ */
68
+ retainInfo(id: SessionId): ObservableSnapshot<SessionRetainInfo>;
69
+ /**
70
+ * The `session.search` result bound the wire schema fixes, exposed to
71
+ * presentation as injected data. Not per-connection state: every transport
72
+ * (fixture included) reports the same number.
73
+ */
74
+ readonly searchResultLimit: number;
75
+ /**
76
+ * Create a Session for a new conversation on the Host. The Host reuses the
77
+ * named blank Session while it is reusable and otherwise creates another; the
78
+ * Session runs the named preset, or the Host default when none is named.
79
+ * @param opts - target workspace or directory, an optional blank Session to reuse, and an optional Agent preset.
80
+ * @returns the catalogued identity the Host created or reused; retain it before borrowing its binding.
81
+ */
82
+ create(opts?: {
83
+ workspaceId?: WorkspaceId;
84
+ cwd?: string;
85
+ sessionId?: SessionId;
86
+ agentPreset?: string;
87
+ }): Promise<SessionId>;
88
+ /**
89
+ * Resolve an already discovered direct-parent address without opening it.
90
+ * @param id - possible addressed child id.
91
+ * @returns a retained, catalog-derived, or unknown-mode listed address, without retaining a new selection or scope.
92
+ */
93
+ subagentAddress(id: SessionId): SubagentAddress | undefined;
94
+ /**
95
+ * Read projections without starting migration; retry failed or migration-deferred reads.
96
+ * @param sessionId - Session to inspect without opening its conversation.
97
+ * @returns completion of the current or newly started refresh.
98
+ */
99
+ refreshProjections(sessionId: SessionId): Promise<void>;
100
+ /**
101
+ * Refresh the Host-authoritative Session list.
102
+ * @returns completion of the current or newly started Session-list refresh.
103
+ */
104
+ refresh(): Promise<void>;
105
+ /**
106
+ * Search the Host's visible message-content index. Results stay
107
+ * request-local; the list snapshot remains the metadata authority.
108
+ * @param query - non-blank literal phrase.
109
+ * @param signal - cancellation for a superseded search.
110
+ * @returns bounded results, or a business/transport error.
111
+ */
112
+ search(query: string, signal: AbortSignal): Promise<RemoteResult<{
113
+ items: SessionSearchResultItem[];
114
+ hasMore: boolean;
115
+ }>>;
116
+ /**
117
+ * Fork a session from an exact inclusive prefix of the source; on
118
+ * resolution the child is catalogued and can be explicitly retained.
119
+ * @param opts - source session id, the optional exact inclusive boundary
120
+ * seq (a real event seq the caller already knows; a cut inside an open
121
+ * turn is balanced Host-side with synthetic closers, and omission selects
122
+ * the latest completed-turn prefix), and whether to increment an
123
+ * inherited durable title, skipping numbers Host-listed titles already use,
124
+ * before resolving. `onCreated` observes the catalogued child before that optional rename.
125
+ * @returns the child session id.
126
+ * @throws when the fork fails, or when a requested child-title rename fails after creation.
127
+ */
128
+ fork(opts: {
129
+ sessionId: SessionId;
130
+ atSeq?: number;
131
+ increaseTitle?: boolean;
132
+ onCreated?: (childId: SessionId) => void;
133
+ /** False refuses source migration; omission preserves the Host default. */
134
+ allowMigration?: boolean;
135
+ }): Promise<SessionId>;
136
+ /**
137
+ * Borrow an already-retained Agent-scoped Context without extending its lifetime.
138
+ * @param id - session id.
139
+ * @returns the live scoped Context, or undefined without a retained generation.
140
+ */
141
+ scope(id: SessionId): AgentContext | undefined;
142
+ /**
143
+ * Read the Agent scope tag off a context (service-method boundary: fetch
144
+ * bundles must reach scope resolution through ctx.sessions).
145
+ * @param ctx - any client context.
146
+ * @returns the session id, or undefined on root contexts.
147
+ */
148
+ scopeOf(ctx: Context): SessionId | undefined;
149
+ /**
150
+ * Resolve the session face behind an Agent-scoped context.
151
+ * @param ctx - an Agent-scoped context.
152
+ * @returns the matching live Session, or undefined for an untagged, foreign, or ended generation.
153
+ */
154
+ sessionOf(ctx: Context): SessionFace | undefined;
155
+ /**
156
+ * Borrow an already-retained Session binding without extending its lifetime.
157
+ * @param id - session id.
158
+ * @returns the live binding, or undefined without a retained generation.
159
+ */
160
+ binding(id: SessionId): SessionBinding | undefined;
161
+ }
162
+ //# sourceMappingURL=sessions.d.ts.map
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,84 @@
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
+ /** One image displayed by a local submission echo before durable admission. */
8
+ export interface PendingSubmissionImage {
9
+ /** Browser-owned preview URL; its lifecycle belongs to the submitter, never this snapshot. */
10
+ readonly previewUrl: string;
11
+ /** Browser file name, when the file had one. */
12
+ readonly name?: string;
13
+ /** Intrinsic pixel width, when the submitter has probed it. */
14
+ readonly width?: number;
15
+ /** Intrinsic pixel height, when the submitter has probed it. */
16
+ readonly height?: number;
17
+ }
18
+ /** Image branch of a local submission echo attachment. */
19
+ export interface PendingSubmissionImageAttachment {
20
+ readonly type: 'image';
21
+ readonly value: PendingSubmissionImage;
22
+ }
23
+ /** File branch of a local submission echo attachment. */
24
+ export interface PendingSubmissionFileAttachment {
25
+ readonly type: 'file';
26
+ readonly value: FileAttachmentRef;
27
+ }
28
+ /** One attachment displayed by a local submission echo, in prompt order. */
29
+ export type PendingSubmissionAttachment = PendingSubmissionImageAttachment | PendingSubmissionFileAttachment;
30
+ /** Client surface selected when a local submission begins. */
31
+ export type PendingSubmissionPlacement = 'transcript' | 'queued' | 'steering';
32
+ /**
33
+ * One local prompt-submission echo: registered when a submission begins and
34
+ * published once the Host accepts the prompt, so the conversation shows the
35
+ * message before its durable admission completes. Client-memory only — reload
36
+ * and reconnect rebuild the conversation from durable events alone.
37
+ */
38
+ export interface PendingSubmission {
39
+ /** The prompt RPC identity; the durable `user/message` source echoes it as `rpcId`. */
40
+ readonly requestId: SessionRequestId;
41
+ /** Surface fixed at submission time; Inbox acceptance does not move a Chat echo into the dock. */
42
+ readonly placement: PendingSubmissionPlacement;
43
+ /** Client wall-clock ms when the submission began. */
44
+ readonly time: number;
45
+ /** Prompt text exactly as it will be sent (one text block). */
46
+ readonly text: string;
47
+ /** Ordered image previews and durable file metadata matching the prompt attachments. */
48
+ readonly attachments: readonly PendingSubmissionAttachment[];
49
+ }
50
+ /** History-open lifecycle of a Session event window. */
51
+ export type OpenState = 'cold' | 'loading' | 'open' | 'error';
52
+ /** Send/stop failure surfaced by Session consumers. */
53
+ export interface PromptError {
54
+ readonly op: 'send' | 'stop';
55
+ readonly error: RemoteFailure;
56
+ }
57
+ /** Immutable Session lifecycle and control snapshot. */
58
+ export interface SessionSnapshot {
59
+ readonly sessionId: SessionId;
60
+ /** Local prompt-submission echoes the Host accepted and that are not yet observed as durable events or queue occurrences. */
61
+ readonly pendingSubmissions: readonly PendingSubmission[];
62
+ readonly running: boolean;
63
+ readonly subagent: {
64
+ readonly address: SubagentAddress;
65
+ } | null;
66
+ readonly removed: boolean;
67
+ readonly openState: OpenState;
68
+ readonly openError: RemoteFailure | null;
69
+ readonly hasMore: boolean;
70
+ /** This Client Session has exposed an incomplete history window; remains true across replacements. */
71
+ readonly historyWasPartial: boolean;
72
+ /** Whether historyLoadStatus is loading, including Turn-jump requests. */
73
+ readonly loadingOlder: boolean;
74
+ /** History request status; pendingConsumption retains an unpublished ordinary page. */
75
+ readonly historyLoadStatus: 'idle' | 'loading' | 'pendingConsumption' | 'error';
76
+ readonly promptError: PromptError | null;
77
+ readonly blank: boolean;
78
+ readonly lastAgentError: string | null;
79
+ /** A prompt call has begun on this Client Session object. */
80
+ readonly promptAttempted: boolean;
81
+ /** The first accepted prompt has not reached a durable `turn/start` event. */
82
+ readonly awaitingFirstTurn: boolean;
83
+ }
84
+ //# sourceMappingURL=snapshot.d.ts.map
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,39 @@
1
+ /** Client Session object layer, Agent scopes, and Remote lifecycle wiring. */
2
+ import type { Context } from '@unieai/cordis';
3
+ export { createSessionControlStream, SessionEventStream, SESSION_SEARCH_RESULT_LIMIT, SESSION_SEARCH_SNIPPET_MAX_CODE_POINTS, } from './transport.ts';
4
+ export type { ClientSessionPageRequest, SessionControlStream, SessionControlStreamOptions, SessionEventStreamOptions, SessionJournalChange, SessionRemote, } from './transport.ts';
5
+ export { createScope, scopeOf } from './scope.ts';
6
+ export type { AgentContext, AgentScopeHandle } from './scope.ts';
7
+ export { SessionCreateError, SessionForkError } from './sessions/service.ts';
8
+ export type { SessionBinding, SessionListState, SessionSummary } from './sessions/service.ts';
9
+ export type { SessionListPhase, SessionListSnapshot, SessionSearchResultItem, SessionProjectionSnapshot, } from './sessions/manager.ts';
10
+ export type { Session } from './sessions/session.ts';
11
+ export type { ProjectionsBaseline, ProjectionValueStore, SessionProjectionMap, UseProjection, } from './sessions/projection-store.ts';
12
+ export type { BeginSubmissionInput, ISession, PendingSubmissionRetirement, ProjectionsFace, SessionFace, SubmissionHandle, } from './contract/session.ts';
13
+ export type { ISessions, SessionReference, SessionRetainInfo, SessionRetainOptions, SessionTarget, } from './contract/sessions.ts';
14
+ export { MutableSessionEventSource } from './contract/events.ts';
15
+ export type { AssistantLiveChunkEvent, SessionAssistantSettlementEntry, SessionEventChange, SessionEventLike, SessionEventLikeEntry, SessionEventSource, SessionEventWindow, SessionLiveEventEntry, SessionTransientEventEntry, } from './contract/events.ts';
16
+ export type { OpenState, PendingSubmission, PendingSubmissionAttachment, PendingSubmissionFileAttachment, PendingSubmissionImage, PendingSubmissionImageAttachment, PendingSubmissionPlacement, PromptError, SessionSnapshot, } from './contract/snapshot.ts';
17
+ /** Consumer-owned reference labels; extend this map through the package's canonical /client entry. */
18
+ export interface SessionReferenceSourceMap {
19
+ /** Temporary Client Controller work, including fork-title preparation. */
20
+ controllerOperation: unknown;
21
+ /** A Client Gateway invocation's synchronous Context ownership. */
22
+ gateway: unknown;
23
+ }
24
+ /** Declaration-merge-extensible labels carried by independent Client references. */
25
+ export type SessionReferenceSource = Extract<keyof SessionReferenceSourceMap, string>;
26
+ declare module '@unieai/cordis' {
27
+ interface Context {
28
+ /** Client Session object layer and Agent scope owner. */
29
+ sessions: import('./contract/sessions.ts').ISessions;
30
+ }
31
+ }
32
+ /** Required Remote and Context projection services. */
33
+ export declare const inject: string[];
34
+ /**
35
+ * Install Client Session state and its reconnecting control stream.
36
+ * @param ctx - Client Cordis context.
37
+ */
38
+ export declare function apply(ctx: Context): void;
39
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,60 @@
1
+ /** Client Session object layer, Agent scopes, and Remote lifecycle wiring. */
2
+ import { typertOwnedValue } from '@unieai/rabi-typert-protocol';
3
+ import { createSessionControlStream } from "./transport.js";
4
+ import { ClientSessions } from "./sessions/service.js";
5
+ export { createSessionControlStream, SessionEventStream, SESSION_SEARCH_RESULT_LIMIT, SESSION_SEARCH_SNIPPET_MAX_CODE_POINTS, } from "./transport.js";
6
+ export { createScope, scopeOf } from "./scope.js";
7
+ export { SessionCreateError, SessionForkError } from "./sessions/service.js";
8
+ export { MutableSessionEventSource } from "./contract/events.js";
9
+ /** Required Remote and Context projection services. */
10
+ export const inject = [
11
+ 'connection',
12
+ 'fileUpload',
13
+ 'typert',
14
+ 'remote',
15
+ 'remote.commands',
16
+ 'remote.session',
17
+ 'remote.subagents',
18
+ ];
19
+ /**
20
+ * Install Client Session state and its reconnecting control stream.
21
+ * @param ctx - Client Cordis context.
22
+ */
23
+ export function apply(ctx) {
24
+ const remotes = ctx.remote;
25
+ const connection = ctx.get('connection');
26
+ const sessions = new ClientSessions(ctx, remotes);
27
+ ctx.remote.$on('api-session/added', (summary) => { sessions.handleSessionAdded(summary); });
28
+ ctx.remote.$on('api-session/removed', (sessionId) => { sessions.handleSessionRemoved(sessionId); });
29
+ ctx.remote.$on('api-session/status', (sessionId, running) => {
30
+ sessions.handleSessionStatus(sessionId, running);
31
+ });
32
+ ctx.remote.$on('api-session/activity', (sessionId, updatedAt) => {
33
+ sessions.handleSessionActivity(sessionId, updatedAt);
34
+ });
35
+ ctx.remote.$on('api-session/error', (sessionId, message) => {
36
+ sessions.handleSessionError(sessionId, message);
37
+ });
38
+ const control = createSessionControlStream(remotes, {
39
+ accept: (frame) => { sessions.handleControlFrame(frame); },
40
+ failed: (error) => { console.error('[session-controller] control stream failed:', error); },
41
+ });
42
+ const connected = () => {
43
+ if (connection.generation.getSnapshot() === undefined)
44
+ return;
45
+ // A ready control baseline may arrive before Cordis delivers connection/reset.
46
+ sessions.handleConnected();
47
+ control.restart();
48
+ control.start();
49
+ };
50
+ ctx.effect(() => connection.generation.subscribe(connected), 'session-controller.client.generation');
51
+ connected();
52
+ ctx.typert.contexts.registerClient('agent', {
53
+ identity: candidate => sessions.sessionOf(candidate)?.sessionId,
54
+ resolve: (sessionId) => {
55
+ const reference = sessions.retainAgentScope(sessionId);
56
+ return typertOwnedValue(reference.binding.ctx, () => { reference.release(); });
57
+ },
58
+ });
59
+ ctx.effect(() => async () => { await control.dispose(); }, 'session-controller.client.control');
60
+ }
@@ -0,0 +1,12 @@
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 declare function mergeOrderedBaseline<T>(current: readonly T[], baseline: readonly T[], keyOf: (value: T) => unknown): T[];
12
+ //# sourceMappingURL=ordered-baseline.d.ts.map
@@ -0,0 +1,40 @@
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(current, baseline, keyOf) {
12
+ const baselineByKey = new Map();
13
+ for (const value of baseline)
14
+ baselineByKey.set(keyOf(value), value);
15
+ const merged = current
16
+ .map(value => baselineByKey.get(keyOf(value)))
17
+ .filter((value) => value !== undefined);
18
+ const mergedKeys = new Set(merged.map(keyOf));
19
+ for (let index = 0; index < baseline.length; index++) {
20
+ const value = baseline[index];
21
+ /* v8 ignore next -- dense-array guard: index is bounded by baseline.length. */
22
+ if (value === undefined || mergedKeys.has(keyOf(value)))
23
+ continue;
24
+ let insertion = merged.length;
25
+ for (let following = index + 1; following < baseline.length; following++) {
26
+ const candidate = baseline[following];
27
+ /* v8 ignore next -- dense-array guard: following is bounded by baseline.length. */
28
+ if (candidate === undefined)
29
+ continue;
30
+ const known = merged.findIndex(item => keyOf(item) === keyOf(candidate));
31
+ if (known !== -1) {
32
+ insertion = known;
33
+ break;
34
+ }
35
+ }
36
+ merged.splice(insertion, 0, value);
37
+ mergedKeys.add(keyOf(value));
38
+ }
39
+ return merged;
40
+ }
@@ -0,0 +1,46 @@
1
+ import type { Context, Fiber } from '@unieai/cordis';
2
+ import type { ClientRemote } from '@unieai/rabi-api-gateway/client';
3
+ import type { SessionId } from '@unieai/rabi-session/types';
4
+ import type { TypertRemoteScopeApi } from '@unieai/rabi-typert-protocol';
5
+ /** Client Cordis Context carrying one Agent identity and its scoped Remote namespaces. */
6
+ export type AgentContext = Omit<Context, 'remote'> & {
7
+ readonly remote: ClientRemote & TypertRemoteScopeApi<'agent'>;
8
+ };
9
+ interface ScopeIdentity {
10
+ readonly sessionId: SessionId;
11
+ }
12
+ /** A minted Agent scope and its disposal boundary. */
13
+ export interface AgentScopeHandle {
14
+ /**
15
+ * Tagged context: scope-owned registrations and scoped dispatch both go
16
+ * through it (passing it as the dispatch subject routes to this generation's
17
+ * tagged listeners plus every untagged one).
18
+ */
19
+ ctx: AgentContext;
20
+ /** Backing fiber (dispose tears down every scope-owned registration). */
21
+ fiber: Fiber;
22
+ }
23
+ /**
24
+ * Mint an Agent scope under `ctx`: a no-op plugin fiber whose context
25
+ * carries the agent tag and the dispatch filter — untagged listeners are
26
+ * admitted globally, tagged listeners only for the same Client generation.
27
+ * Registrations through the returned ctx dispose with the fiber.
28
+ * @param ctx - client root context the scope fiber mounts under.
29
+ * @param key - durable Session identity carried by this generation.
30
+ * @returns the tagged context and its backing fiber.
31
+ */
32
+ export declare function createScope(ctx: Context, key: SessionId): AgentScopeHandle;
33
+ /**
34
+ * Read the nearest agent tag inherited by a context.
35
+ * @param ctx - any client context.
36
+ * @returns its agent identity (the session id), or undefined for root contexts.
37
+ */
38
+ export declare function scopeOf(ctx: Context): SessionId | undefined;
39
+ /**
40
+ * Read the exact generation identity inherited by a Client Context.
41
+ * @param ctx - scoped or root Client Context.
42
+ * @returns the generation identity, or undefined for an unscoped Context.
43
+ */
44
+ export declare function scopeIdentityOf(ctx: Context): ScopeIdentity | undefined;
45
+ export {};
46
+ //# sourceMappingURL=scope.d.ts.map