@unieai/rabi-api-session-controller 0.0.0-stage → 0.2.1-rc.3

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 (79) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +7 -2
  3. package/lib/client.js +4325 -0
  4. package/lib/index.js +3367 -0
  5. package/lib/typert.host.d.ts +3 -0
  6. package/lib/typert.host.js +4053 -0
  7. package/lib/typert.remote-client.d.ts +97 -0
  8. package/lib/typert.remote-client.js +2013 -0
  9. package/lib/types/agent.d.ts +198 -0
  10. package/lib/types/agent.js +609 -0
  11. package/lib/types/archived-session-gate.d.ts +30 -0
  12. package/lib/types/archived-session-gate.js +51 -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 +106 -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 +157 -0
  20. package/lib/types/client/contract/session.js +1 -0
  21. package/lib/types/client/contract/sessions.d.ts +161 -0
  22. package/lib/types/client/contract/sessions.js +1 -0
  23. package/lib/types/client/contract/snapshot.d.ts +81 -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 +40 -0
  38. package/lib/types/client/sessions/lineage.js +54 -0
  39. package/lib/types/client/sessions/manager.d.ts +269 -0
  40. package/lib/types/client/sessions/manager.js +799 -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 +258 -0
  48. package/lib/types/client/sessions/service.js +582 -0
  49. package/lib/types/client/sessions/session.d.ts +287 -0
  50. package/lib/types/client/sessions/session.js +866 -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 +129 -0
  55. package/lib/types/commands.d.ts +86 -0
  56. package/lib/types/commands.js +624 -0
  57. package/lib/types/control.d.ts +20 -0
  58. package/lib/types/control.js +106 -0
  59. package/lib/types/file-references.d.ts +27 -0
  60. package/lib/types/file-references.js +68 -0
  61. package/lib/types/history.d.ts +32 -0
  62. package/lib/types/history.js +441 -0
  63. package/lib/types/index.d.ts +222 -0
  64. package/lib/types/index.js +658 -0
  65. package/lib/types/list.d.ts +50 -0
  66. package/lib/types/list.js +325 -0
  67. package/lib/types/media-references.d.ts +16 -0
  68. package/lib/types/media-references.js +76 -0
  69. package/lib/types/model-selection-projection.d.ts +8 -0
  70. package/lib/types/model-selection-projection.js +65 -0
  71. package/lib/types/remote-events.d.ts +8 -0
  72. package/lib/types/remote-events.js +1 -0
  73. package/lib/types/skill-catalog.d.ts +28 -0
  74. package/lib/types/skill-catalog.js +203 -0
  75. package/lib/types/types.d.ts +611 -0
  76. package/lib/types/types.js +4 -0
  77. package/locale/en.json +5 -0
  78. package/locale/zh.json +6 -0
  79. package/package.json +114 -4
@@ -0,0 +1,866 @@
1
+ // Sessions remain resident after creation so their open Remote sources keep running off-screen.
2
+ import { randomUUID } from '@unieai/rabi-util-crypto';
3
+ import { SessionLogOffset, SessionSeq } from '@unieai/rabi-session/types';
4
+ import { SessionEventStream } from "../transport.js";
5
+ import { MutableSessionEventSource } from "../contract/events.js";
6
+ import { Notifier } from "./notifier.js";
7
+ import { isRemoteFailure } from '@unieai/rabi-api-gateway/client';
8
+ import { RemoteError } from '@unieai/rabi-typert-protocol';
9
+ import { ProjectionValueStore } from "./projection-store.js";
10
+ import { resolvedClientTimeZone } from "../time-zone.js";
11
+ import { ClientAssistantStream, } from "./assistant-stream.js";
12
+ function projectionsBaseline(value) {
13
+ return {
14
+ ...value,
15
+ asOfSeq: value.asOfSeq === -1 ? -1 : SessionSeq(value.asOfSeq),
16
+ };
17
+ }
18
+ /** Minimum message count for ordinary history windows. */
19
+ export const PAGE_MESSAGES = 50;
20
+ const HISTORY_PAGE_OPTIONS = { maxMessages: 500, turnWindow: { minMessages: PAGE_MESSAGES, minTurns: 2 } };
21
+ /** Minimum messages per page while a turn jump loops backwards. */
22
+ export const JUMP_PAGE_MESSAGES = 200;
23
+ const JUMP_PAGE_OPTIONS = {
24
+ ...HISTORY_PAGE_OPTIONS,
25
+ turnWindow: { ...HISTORY_PAGE_OPTIONS.turnWindow, minMessages: JUMP_PAGE_MESSAGES },
26
+ };
27
+ /**
28
+ * Owns a session's event window, lifecycle state, and observable
29
+ * snapshot. React bindings remain outside this data layer. Features see only
30
+ * the {@link SessionFace} slice (ISession verbs + the snapshot source); the
31
+ * remaining public members are Session Controller internals.
32
+ */
33
+ export class Session {
34
+ sessionId;
35
+ remote;
36
+ options;
37
+ // ---- Window and derived state (all private; the snapshot is the only read API) ----
38
+ baseSeq = SessionLogOffset(0);
39
+ hasMore = false;
40
+ openState = 'cold';
41
+ openError = null;
42
+ openPromise = null;
43
+ /** Bumped by stream replacement to invalidate an in-flight doOpen. Stale
44
+ * passes drop all writes once the generation moves on. */
45
+ openGeneration = 0;
46
+ loadingOlder = false;
47
+ /** Shared low-water target of the running jump loop; null when no jump is paging. */
48
+ jumpTargetSeq = null;
49
+ /** The running jump loop's completion, shared by retargeting callers. */
50
+ jumpPromise = null;
51
+ pendingHistory = null;
52
+ stopObservingInbox;
53
+ assistantStream = new ClientAssistantStream();
54
+ running = false;
55
+ address;
56
+ parentAvailable;
57
+ /**
58
+ * Sticky send marker, private input of the composerPhase derivation: set
59
+ * synchronously before prompt()'s first await, never reset — the blank →
60
+ * engaging edge of the phase machine (see ComposerPhase).
61
+ */
62
+ promptAttempted = false;
63
+ /** A first accepted prompt stays in the engaging phase until its turn is observable. */
64
+ firstPromptPendingTurn = false;
65
+ /** New Session display state; unknown bare sessions begin conservatively blank. */
66
+ blankBit = true;
67
+ removed = false;
68
+ promptError = null;
69
+ lastAgentError = null;
70
+ /** Local submission echoes, insertion-ordered (see SessionSnapshot.pendingSubmissions). */
71
+ pendingSubmissions = [];
72
+ /** Per-echo settlement state; `retiring` latches the first observation so a
73
+ * Inbox projection and its durable event cannot both retire one echo. */
74
+ submissionSettlements = new Map();
75
+ /** Owns the addressed page/follow lifecycle while this Session is open. */
76
+ events;
77
+ /**
78
+ * Per-session projection value store (push model; see the session-projection
79
+ * subsystem page, docs/subsystems/session-projection.md): finished whole
80
+ * values computed on the Host, seeded by the tail page's
81
+ * projections block and updated by Session Controller control frames;
82
+ * Host-sequenced writes merge under higher-seq-wins and cached list blocks
83
+ * yield to them (projection-store.ts). Keys are read via `projections.faceOf(key)`
84
+ * (the useProjection resolution face); the conversation snapshot never
85
+ * carries projection values, and no client-side domain folding exists.
86
+ * Manager-owned when constructed through SessionManager (frames route and
87
+ * the store outlives instantiation, the title-snapshot precedent); a bare
88
+ * construction gets a private store.
89
+ */
90
+ projections;
91
+ /** Contiguous history and live tail consumed by Conversation assembly. */
92
+ eventSource = new MutableSessionEventSource();
93
+ snapshotCache;
94
+ notifier;
95
+ /**
96
+ * Agent-scoped cordis context, bound once by ClientSessions when it
97
+ * mints the scope (the client mirror of the host Agent's loopCtx). The
98
+ * Session dispatches its own scoped events through it; undefined means
99
+ * unbound (bare object-layer construction) or already pruned — both skip
100
+ * dispatch-dependent behavior rather than fail.
101
+ */
102
+ actx;
103
+ /**
104
+ * @param sessionId - Host session identity (client sessions are always Host-born).
105
+ * @param remote - generated Remote namespaces this session calls.
106
+ * @param options - optional manager-owned state observers.
107
+ */
108
+ constructor(sessionId, remote, options = {}) {
109
+ this.sessionId = sessionId;
110
+ this.remote = remote;
111
+ this.options = options;
112
+ this.projections = options.projections ?? new ProjectionValueStore();
113
+ this.address = options.address;
114
+ this.parentAvailable = options.parentAvailable;
115
+ this.notifier = new Notifier(() => {
116
+ this.snapshotCache = this.buildSnapshot();
117
+ });
118
+ this.snapshotCache = this.buildSnapshot();
119
+ this.stopObservingInbox = this.projections.faceOf('inbox').subscribe(() => {
120
+ this.observeSubmissionInbox();
121
+ });
122
+ }
123
+ /**
124
+ * Bind the Agent-scoped context minted by ClientSessions (single write;
125
+ * a second bind is a wiring error and throws). Direction stays one-way at
126
+ * this binding boundary: consumers still reach the Session via `sessions.sessionOf`,
127
+ * while the Session holds its own dispatch point (host Agent.loopCtx
128
+ * mirror).
129
+ * @param actx - the agent's scoped context.
130
+ */
131
+ bindScope(actx) {
132
+ if (this.actx !== undefined)
133
+ throw new Error(`session ${this.sessionId} already has a bound scope`);
134
+ this.actx = actx;
135
+ }
136
+ /** Release the bound scope at prune time (a later rebind accompanies a freshly minted scope). */
137
+ unbindScope() {
138
+ this.actx = undefined;
139
+ }
140
+ // ---- Operations ----
141
+ /**
142
+ * Register one local submission echo (see the ISession declaration).
143
+ * Synchronous through markDirty: the echo is in the very next snapshot, so
144
+ * the conversation can paint it before the caller starts serializing.
145
+ * @param input - echo content and the optional settlement callback.
146
+ * @returns the minted identity for {@link prompt} plus the pre-prompt abandon path.
147
+ */
148
+ beginSubmission(input) {
149
+ const requestId = randomUUID();
150
+ const placement = this.running ? input.mode === 'steer' ? 'steering' : 'queued' : 'transcript';
151
+ this.pendingSubmissions = [...this.pendingSubmissions, {
152
+ requestId,
153
+ placement,
154
+ time: Date.now(),
155
+ text: input.text,
156
+ attachments: input.attachments,
157
+ }];
158
+ this.submissionSettlements.set(requestId, { placement, onRetire: input.onRetire, retiring: false });
159
+ // The blank → engaging edge flips here, ahead of prompt(): the composer
160
+ // docks and the echo renders on the click's own frame.
161
+ this.promptAttempted = true;
162
+ this.notifier.markDirty();
163
+ return { requestId, abandon: () => { this.retireFailedSubmission(requestId); } };
164
+ }
165
+ /**
166
+ * Send (queue/steer passed through 1:1); failures land in the snapshot's promptError.
167
+ * @param content - text, browser-owned temporary image uploads, and staged-file receipts.
168
+ * @param mode - queue appends after the current turn; steer interrupts it.
169
+ * @param signal - optional caller cancellation for the complete admission round-trip.
170
+ * @param requestId - identity from {@link beginSubmission}; a failed identified prompt retires its echo.
171
+ * @returns the prompt result (also mirrored into promptError on failure).
172
+ */
173
+ async prompt(content, mode, signal, requestId) {
174
+ this.promptError = null;
175
+ this.lastAgentError = null;
176
+ // Synchronous, before the first await: the blank → engaging edge must be
177
+ // visible on the session area's very first frame when a caller sends
178
+ // ahead of navigation (first-send flow).
179
+ this.promptAttempted = true;
180
+ if (this.blankBit)
181
+ this.firstPromptPendingTurn = true;
182
+ this.notifier.markDirty();
183
+ let result;
184
+ if (this.address === undefined) {
185
+ const clientTimeZone = resolvedClientTimeZone();
186
+ result = await this.remote.session.prompt({
187
+ requestId: requestId ?? randomUUID(),
188
+ sessionId: this.sessionId,
189
+ mode,
190
+ content,
191
+ clientTimeZone,
192
+ }, signal);
193
+ }
194
+ else if (content.some(part => part.type === 'file')) {
195
+ result = {
196
+ ok: false,
197
+ error: new RemoteError('subagent/attachment-invalid', 'subagent continuation does not accept files', { reason: 'SUBAGENT_FILE_UNSUPPORTED' }),
198
+ };
199
+ }
200
+ else {
201
+ // The preceding branch rejects file parts before the narrower subagent
202
+ // wire type is used; this array is not filtered or reordered.
203
+ const routedContent = content;
204
+ const routed = await this.remote.subagents.prompt({
205
+ requestId: requestId ?? randomUUID(),
206
+ parentSessionId: this.address.parentSessionId,
207
+ childSessionId: this.address.childSessionId,
208
+ mode: 'continuable',
209
+ delivery: mode,
210
+ content: routedContent,
211
+ clientTimeZone: resolvedClientTimeZone(),
212
+ }, signal);
213
+ result = routed.ok ? { ok: true, value: { accepted: true } } : routed;
214
+ }
215
+ if (!result.ok) {
216
+ if (requestId !== undefined)
217
+ this.retireFailedSubmission(requestId);
218
+ this.promptError = { op: 'send', error: result.error };
219
+ this.notifier.markDirty();
220
+ return result;
221
+ }
222
+ // Rejection must leave a first prompt blank and eligible for workspace reuse.
223
+ if (this.blankBit) {
224
+ this.blankBit = false;
225
+ this.notifier.markDirty();
226
+ }
227
+ this.options.onEngaged?.(this);
228
+ return result;
229
+ }
230
+ /**
231
+ * Resolve one image referenced by this session into browser-consumable bytes.
232
+ * @param attachmentId - opaque id found in the folded session log.
233
+ * @returns the authenticated reference and decoded bytes.
234
+ */
235
+ async readAttachment(attachmentId) {
236
+ const result = await this.remote.session.attachment({
237
+ sessionId: this.sessionId,
238
+ attachmentId,
239
+ });
240
+ if (!result.ok)
241
+ return result;
242
+ const binary = atob(result.value.data);
243
+ const data = Uint8Array.from(binary, char => char.charCodeAt(0));
244
+ return { ok: true, value: { attachment: result.value.attachment, data } };
245
+ }
246
+ /** Apply one operation to a still-pending queue occurrence. */
247
+ async updateQueue(itemId, action) {
248
+ return this.remote.session.updateQueue({ sessionId: this.sessionId, itemId, action });
249
+ }
250
+ /**
251
+ * Stop the active turn while the Host preserves pending inbox work; failures
252
+ * land in promptError (same error-strip display slot). A subagent address
253
+ * routes through `subagents.interruptByParent`, whose durable parent-address
254
+ * authority works without a live parent Agent.
255
+ * @returns the cancel result.
256
+ */
257
+ async cancel() {
258
+ const address = this.address;
259
+ const result = address !== undefined
260
+ ? await this.remote.subagents.interruptByParent(address.childSessionId, address.parentSessionId, 'continuable')
261
+ : await this.remote.session.cancel({ sessionId: this.sessionId });
262
+ if (!result.ok) {
263
+ this.promptError = { op: 'stop', error: result.error };
264
+ this.notifier.markDirty();
265
+ }
266
+ return result;
267
+ }
268
+ /**
269
+ * Rename: contract session.rename 1:1. On success settle the 'title'
270
+ * projection cell from the response's `{title, seq}` under the store's
271
+ * higher-seq-wins rule (the push frame arriving later is a no-op replay),
272
+ * so the list row and any useProjection('title') reader update without
273
+ * waiting for the control-stream projection update.
274
+ * @param title - raw title text (the host normalizes acceptance).
275
+ * @returns the rename result (normalized accepted title + title event seq).
276
+ */
277
+ async rename(title) {
278
+ const result = await this.remote.session.rename({ sessionId: this.sessionId, title });
279
+ if (!result.ok)
280
+ return result;
281
+ const seq = SessionSeq(result.value.seq);
282
+ this.projections.apply('title', result.value.title, seq);
283
+ return { ok: true, value: { title: result.value.title, seq } };
284
+ }
285
+ /**
286
+ * Execute one slash-command line against this session's agent — pure
287
+ * admission semantics (the host executor durably logs the lifecycle;
288
+ * outcomes render as flow nodes, never as a response echo).
289
+ * @param line - the full command line, leading slash included.
290
+ * @returns the admission result.
291
+ */
292
+ async command(line) {
293
+ const result = await this.remote.commands.execute(this.sessionId, line, []);
294
+ if (!result.ok)
295
+ return result;
296
+ return { ok: true, value: { matched: result.value !== undefined } };
297
+ }
298
+ /** First open: pull the tail page (idempotent — in-flight/already-open returns the existing promise). */
299
+ open() {
300
+ if (this.openState === 'open')
301
+ return Promise.resolve();
302
+ if (this.openPromise !== null)
303
+ return this.openPromise;
304
+ const promise = this.doOpen(this.openGeneration).finally(() => {
305
+ // Identity-guarded: a superseded open must not null out the promise resync just started.
306
+ if (this.openPromise === promise)
307
+ this.openPromise = null;
308
+ });
309
+ this.openPromise = promise;
310
+ return promise;
311
+ }
312
+ /** Prepend one Turn-aligned page: at least 50 messages and two Turn starts, capped at 500 messages. */
313
+ async loadOlder() {
314
+ if (this.openState !== 'open' || !this.hasMore || this.loadingOlder)
315
+ return;
316
+ const events = this.events;
317
+ if (events === undefined)
318
+ return;
319
+ this.loadingOlder = true;
320
+ this.notifier.markDirty();
321
+ try {
322
+ await events.prepend({
323
+ beforeSeq: this.baseSeq,
324
+ ...HISTORY_PAGE_OPTIONS,
325
+ });
326
+ }
327
+ catch (error) {
328
+ if (!isRemoteFailure(error)) {
329
+ console.error('[session-controller] loadOlder failed:', error);
330
+ }
331
+ }
332
+ finally {
333
+ this.loadingOlder = false;
334
+ this.notifier.markDirty();
335
+ }
336
+ }
337
+ /** Jump loader: page backwards until the window covers seq (see ISession.loadThrough). */
338
+ loadThrough(seq) {
339
+ if (this.openState !== 'open' || !this.hasMore || this.baseSeq <= seq)
340
+ return Promise.resolve();
341
+ if (this.jumpPromise !== null) {
342
+ // Retarget the running loop to the lowest requested seq.
343
+ this.jumpTargetSeq = SessionSeq(Math.min(this.jumpTargetSeq ?? seq, seq));
344
+ return this.jumpPromise;
345
+ }
346
+ // A plain single-page pull owns the busy flag; the jump does not queue
347
+ // behind it (the caller retries once it settles) and must leave no
348
+ // target behind — only the loop's finally clears that field, and no
349
+ // loop starts here.
350
+ if (this.loadingOlder)
351
+ return Promise.resolve();
352
+ const events = this.events;
353
+ if (events === undefined)
354
+ return Promise.resolve();
355
+ const pending = {
356
+ beforeSeq: this.baseSeq,
357
+ hasMore: this.hasMore,
358
+ pages: [],
359
+ };
360
+ this.pendingHistory = pending;
361
+ this.jumpTargetSeq = seq;
362
+ this.loadingOlder = true;
363
+ this.notifier.markDirty();
364
+ // Stale-pass guard (the doOpen pattern): a resync mid-loop replaces the
365
+ // stream generation; this pass then stops instead of paging the new
366
+ // generation toward its old target.
367
+ const generation = this.openGeneration;
368
+ this.jumpPromise = (async () => {
369
+ try {
370
+ while (pending.hasMore && this.jumpTargetSeq !== null && pending.beforeSeq > this.jumpTargetSeq) {
371
+ if (generation !== this.openGeneration)
372
+ return;
373
+ const before = pending.beforeSeq;
374
+ await events.prepend({ beforeSeq: before, ...JUMP_PAGE_OPTIONS });
375
+ // No-progress guard: an empty or dropped page that still claims more
376
+ // history must end the loop, not spin it.
377
+ if (pending.beforeSeq >= before)
378
+ return;
379
+ }
380
+ }
381
+ catch (error) {
382
+ if (!isRemoteFailure(error)) {
383
+ console.error('[session-controller] loadThrough failed:', error);
384
+ }
385
+ }
386
+ finally {
387
+ this.jumpTargetSeq = null;
388
+ this.jumpPromise = null;
389
+ this.pendingHistory = null;
390
+ this.loadingOlder = false;
391
+ if (generation === this.openGeneration && pending.pages.length > 0) {
392
+ this.prependWindow(pending.pages.reverse().flat(), pending.hasMore);
393
+ }
394
+ this.notifier.markDirty();
395
+ }
396
+ })();
397
+ return this.jumpPromise;
398
+ }
399
+ /** Rebuild an opened history source after address replacement.
400
+ * Invalidates any in-flight open first; projection state belongs to the independently
401
+ * reconnecting control stream and remains untouched. */
402
+ async resync() {
403
+ if (this.openState === 'cold')
404
+ return; // never opened: no window to rebuild (doOpen flips to 'loading' synchronously, so cold implies no in-flight open)
405
+ this.openGeneration++;
406
+ const events = this.events;
407
+ this.events = undefined;
408
+ await events?.dispose();
409
+ this.openPromise = null;
410
+ this.openState = 'cold';
411
+ this.openError = null;
412
+ this.baseSeq = SessionLogOffset(0);
413
+ this.notifier.markDirty();
414
+ await this.open();
415
+ }
416
+ // ---- Subscription API (useSyncExternalStore direct wiring) ----
417
+ /**
418
+ * uSES subscription entry.
419
+ * @param listener - change callback.
420
+ * @returns the unsubscribe function.
421
+ */
422
+ subscribe(listener) {
423
+ return this.notifier.subscribe(listener);
424
+ }
425
+ /**
426
+ * Cached Session snapshot (rebuilt lazily when dirty with no listeners).
427
+ * @returns the cached reference (stable until the next flush).
428
+ */
429
+ getSnapshot() {
430
+ this.notifier.ensureFresh();
431
+ return this.snapshotCache;
432
+ }
433
+ // ---- Manager-only entry points (@internal; never called by the UI) ----
434
+ /**
435
+ * Running-bit relay from the host stream (list entry and snapshot stay consistent).
436
+ * @param running - the new running state.
437
+ */
438
+ handleRunning(running) {
439
+ // Running converts display state without establishing durable turn history.
440
+ if (running && this.blankBit) {
441
+ this.blankBit = false;
442
+ this.notifier.markDirty();
443
+ }
444
+ if (running)
445
+ this.firstPromptPendingTurn = false;
446
+ if (this.running === running)
447
+ return;
448
+ this.running = running;
449
+ this.notifier.markDirty();
450
+ }
451
+ /**
452
+ * Install or clear the catalog-discovered transport address. A changed
453
+ * address rebuilds an already-open window through its new history route.
454
+ * @param address - direct parent/child address, or undefined for ordinary transport.
455
+ * @param parentAvailable - latest exact-parent availability hint, or undefined before a catalog read.
456
+ */
457
+ configureSubagent(address, parentAvailable) {
458
+ const same = this.address?.parentSessionId === address?.parentSessionId
459
+ && this.address?.childSessionId === address?.childSessionId
460
+ && this.address?.mode === address?.mode;
461
+ this.address = address;
462
+ this.parentAvailable = parentAvailable;
463
+ if (!same && this.openState !== 'cold')
464
+ void this.resync();
465
+ else
466
+ this.notifier.markDirty();
467
+ }
468
+ /**
469
+ * Update only the parent availability hint from a catalog refresh.
470
+ * @param available - whether the exact direct parent is live.
471
+ */
472
+ handleSubagentParentAvailable(available) {
473
+ if (this.parentAvailable === available)
474
+ return;
475
+ this.parentAvailable = available;
476
+ this.notifier.markDirty();
477
+ }
478
+ /**
479
+ * Apply the Manager's effective display blank, further reconciled with the
480
+ * current `sessionListMetadata` projection. Local send attempts and current
481
+ * running state prevent re-blanking; an earlier false summary alone does not.
482
+ * The Manager retains acceptance and earlier running observations across
483
+ * Session-object replacement.
484
+ * @param blank - New Session display state after Manager reconciliation.
485
+ */
486
+ handleBlank(blank) {
487
+ blank = blank && this.projections.values().sessionListMetadata?.blank !== false;
488
+ if (blank === this.blankBit)
489
+ return;
490
+ if (blank && (this.promptAttempted || this.running))
491
+ return;
492
+ this.blankBit = blank;
493
+ this.notifier.markDirty();
494
+ }
495
+ /** `api-session/removed` relay: flag the snapshot while retaining the resident instance. */
496
+ handleRemoved() {
497
+ this.removed = true;
498
+ this.notifier.markDirty();
499
+ }
500
+ /**
501
+ * `api-session/error` relay: the outlet for live failures with no turn position.
502
+ * @param message - the stringified error.
503
+ */
504
+ handleAgentError(message) {
505
+ this.lastAgentError = message;
506
+ this.notifier.markDirty();
507
+ }
508
+ /**
509
+ * Stop the Session's live Remote source.
510
+ * @returns when the Remote iterator has completed teardown.
511
+ */
512
+ async dispose() {
513
+ this.stopObservingInbox();
514
+ // Unsettled echoes retire as failed so their owners can restore or
515
+ // release browser resources; admitted echoes keep their observed outcome.
516
+ for (const [requestId, settlement] of [...this.submissionSettlements]) {
517
+ if (settlement.admitted !== undefined)
518
+ this.scheduleObservedRetirement(requestId, settlement.admitted);
519
+ else
520
+ this.retireFailedSubmission(requestId);
521
+ }
522
+ this.openGeneration++;
523
+ const events = this.events;
524
+ this.events = undefined;
525
+ await events?.dispose();
526
+ }
527
+ // ---- Private ----
528
+ /** @param generation - openGeneration at launch; stale passes cannot publish after replacement. */
529
+ async doOpen(generation) {
530
+ this.openState = 'loading';
531
+ this.openError = null;
532
+ this.notifier.markDirty();
533
+ const events = new SessionEventStream(this.remote, this.sessionAddress(), {
534
+ publish: (change) => {
535
+ if (generation !== this.openGeneration || this.events !== events)
536
+ return;
537
+ this.acceptEventChange(change);
538
+ },
539
+ failed: (error) => {
540
+ this.failEventStream(events, generation, error);
541
+ },
542
+ });
543
+ this.events = events;
544
+ try {
545
+ await events.open(HISTORY_PAGE_OPTIONS);
546
+ if (generation !== this.openGeneration || this.events !== events)
547
+ return;
548
+ this.openState = 'open';
549
+ }
550
+ catch (error) {
551
+ if (generation !== this.openGeneration || this.events !== events)
552
+ return;
553
+ if (!isRemoteFailure(error))
554
+ throw error;
555
+ this.events = undefined;
556
+ this.openState = 'error';
557
+ this.openError = error;
558
+ }
559
+ finally {
560
+ if (generation === this.openGeneration)
561
+ this.notifier.markDirty();
562
+ }
563
+ }
564
+ /** Apply one contiguous journal update already reconciled by the Remote stream. */
565
+ acceptEventChange(change) {
566
+ switch (change.type) {
567
+ case 'replace':
568
+ this.installWindow(change.entries, change.hasMore, change.page.projections === undefined ? undefined : projectionsBaseline(change.page.projections), change.page.assistantStream);
569
+ return;
570
+ case 'prepend':
571
+ this.prependWindow(change.entries, change.hasMore);
572
+ return;
573
+ case 'append':
574
+ this.publishAssistantEntry(this.assistantStream.acceptDurable(change.entry));
575
+ return;
576
+ case 'assistant-stream':
577
+ this.publishAssistantEntry(this.assistantStream.acceptFrame(change.frame));
578
+ }
579
+ }
580
+ /** Replace the complete contiguous window and apply page-owned projection metadata. */
581
+ installWindow(entries, hasMore, projections, assistantStream) {
582
+ // A durable gap-repair page has no assistant baseline. Clearing transient
583
+ // attempts makes a held notification reopen follow once for an atomic
584
+ // page/baseline pair instead of applying it to an unrelated repair cut.
585
+ const visible = this.assistantStream.replace(entries, assistantStream);
586
+ this.baseSeq = SessionLogOffset(entries[0]?.event.seq ?? 0);
587
+ this.hasMore = hasMore;
588
+ if (this.pendingHistory !== null) {
589
+ this.pendingHistory.beforeSeq = this.baseSeq;
590
+ this.pendingHistory.hasMore = hasMore;
591
+ this.pendingHistory.pages.length = 0;
592
+ }
593
+ if (visible.some(entry => entry.event.type === 'turn/start'))
594
+ this.firstPromptPendingTurn = false;
595
+ if (projections !== undefined)
596
+ this.projections.seed(projections);
597
+ this.eventSource.replace(visible, hasMore);
598
+ // A new follow baseline replaces confirmed optimistic inputs with Host-owned rows.
599
+ // Receipt-backed inputs are accepted, not failed, even if their history is outside this window.
600
+ if (projections !== undefined) {
601
+ for (const [requestId, { receipt }] of this.submissionSettlements) {
602
+ if (receipt !== undefined && receipt.seq <= projections.asOfSeq) {
603
+ this.scheduleObservedRetirement(requestId, receipt.attachments);
604
+ }
605
+ }
606
+ }
607
+ for (const entry of visible)
608
+ this.observeSubmissionEvent(entry.event);
609
+ if (projections !== undefined) {
610
+ const inbox = projections.values.inbox;
611
+ for (const target of ['next-turn', 'next-step']) {
612
+ this.observeSubmissionInsertions(target, inbox?.[target] ?? [], 0, projections.asOfSeq);
613
+ }
614
+ }
615
+ this.notifier.markDirty();
616
+ }
617
+ publishAssistantEntry(result) {
618
+ if (result?.type === 'rebaseline') {
619
+ const events = this.events;
620
+ queueMicrotask(() => {
621
+ if (events !== undefined && this.events === events)
622
+ events.restart();
623
+ });
624
+ return;
625
+ }
626
+ if (result?.type === 'settlement') {
627
+ this.eventSource.settleAssistant(result.attemptId, result.entry);
628
+ this.observeSubmissionEvent(result.entry.event);
629
+ this.notifier.markDirty();
630
+ return;
631
+ }
632
+ if (result?.type === 'abandonment') {
633
+ this.eventSource.settleAssistant(result.attemptId);
634
+ this.notifier.markDirty();
635
+ return;
636
+ }
637
+ if (result?.type === 'publish') {
638
+ const changed = this.appendLive(result.entry);
639
+ if (result.retireAttemptId !== undefined)
640
+ this.eventSource.settleAssistant(result.retireAttemptId);
641
+ if (changed || result.retireAttemptId !== undefined)
642
+ this.notifier.markDirty();
643
+ }
644
+ else if (result?.type === 'transient') {
645
+ this.eventSource.append(result.entry);
646
+ this.notifier.markDirty();
647
+ }
648
+ }
649
+ /** Prepend one stream-validated history page. */
650
+ prependWindow(entries, hasMore) {
651
+ if (this.pendingHistory !== null) {
652
+ const pending = this.pendingHistory;
653
+ pending.beforeSeq = entries[0] === undefined ? pending.beforeSeq : SessionLogOffset(entries[0].event.seq);
654
+ pending.hasMore = hasMore;
655
+ pending.pages.push(entries);
656
+ return;
657
+ }
658
+ this.baseSeq = entries[0] === undefined ? this.baseSeq : SessionLogOffset(entries[0].event.seq);
659
+ this.hasMore = hasMore;
660
+ this.eventSource.prepend(entries, hasMore);
661
+ }
662
+ /** Append one stream-validated live event. */
663
+ appendLive(entry) {
664
+ const event = entry.event;
665
+ const awaitingFirstTurn = this.firstPromptPendingTurn;
666
+ if (event.type === 'turn/start')
667
+ this.firstPromptPendingTurn = false;
668
+ this.eventSource.append(entry);
669
+ // After the feed append: the conversation assembly's animation frame is
670
+ // registered by the feed subscribers above, so the echo-retirement frame
671
+ // scheduled here always runs after the durable node became renderable.
672
+ this.observeSubmissionEvent(event);
673
+ return awaitingFirstTurn !== this.firstPromptPendingTurn;
674
+ }
675
+ /** Observe durable acceptance even when insertion and claim share one projection notification. */
676
+ observeSubmissionEvent(event) {
677
+ if (this.submissionSettlements.size === 0)
678
+ return;
679
+ if (event.type === 'agent/inbox/spliced') {
680
+ const { target, start, removedCount = 0, inserted, outcome } = event.data;
681
+ for (const [requestId, settlement] of this.submissionSettlements) {
682
+ const receipt = settlement.receipt;
683
+ if (receipt?.target !== target || receipt.index === null || receipt.seq >= event.seq)
684
+ continue;
685
+ const removed = receipt.index >= start && receipt.index < start + removedCount;
686
+ if (removed && outcome === 'canceled')
687
+ this.retireFailedSubmission(requestId);
688
+ else
689
+ settlement.receipt = {
690
+ ...receipt,
691
+ seq: event.seq,
692
+ index: removed ? null : receipt.index < start ? receipt.index : receipt.index + inserted.length - removedCount,
693
+ };
694
+ }
695
+ this.observeSubmissionInsertions(target, inserted, start, event.seq);
696
+ for (const message of inserted)
697
+ this.observeSubmissionMessage(message, false);
698
+ return;
699
+ }
700
+ if (event.type === 'request/context' || event.type === 'turn/end') {
701
+ for (const [requestId, settlement] of this.submissionSettlements) {
702
+ if (settlement.admitted === undefined && settlement.receipt?.index === null
703
+ && settlement.receipt.seq < event.seq)
704
+ this.retireFailedSubmission(requestId);
705
+ }
706
+ return;
707
+ }
708
+ if (event.type === 'user/message')
709
+ this.observeSubmissionMessage(event.data, true);
710
+ }
711
+ observeSubmissionInsertions(target, messages, start, seq) {
712
+ for (const [index, message] of messages.entries()) {
713
+ const source = message.source;
714
+ if (source.kind !== 'user' || !('rpcId' in source))
715
+ continue;
716
+ const settlement = this.submissionSettlements.get(source.rpcId);
717
+ if (settlement === undefined || settlement.placement === 'queued'
718
+ || settlement.retiring || (settlement.receipt?.seq ?? -1) > seq)
719
+ continue;
720
+ settlement.receipt = { target, seq, index: start + index, attachments: attachmentRefsIn(message.content) };
721
+ }
722
+ }
723
+ observeSubmissionMessage(message, admitted) {
724
+ const source = message.source;
725
+ if (source.kind !== 'user' || !('rpcId' in source))
726
+ return;
727
+ const settlement = this.submissionSettlements.get(source.rpcId);
728
+ if (settlement === undefined || settlement.retiring)
729
+ return;
730
+ if (!admitted) {
731
+ if (settlement.placement === 'queued')
732
+ this.scheduleObservedRetirement(source.rpcId, attachmentRefsIn(message.content));
733
+ return;
734
+ }
735
+ settlement.admitted = attachmentRefsIn(message.content);
736
+ this.retireAdmittedSubmission(source.rpcId);
737
+ }
738
+ /** Retire admitted Chat identities only after stale Inbox rows can no longer reappear. */
739
+ retireAdmittedSubmission(requestId) {
740
+ const settlement = this.submissionSettlements.get(requestId);
741
+ if (settlement?.admitted === undefined)
742
+ return;
743
+ const receipt = settlement.receipt;
744
+ if (receipt?.index === null
745
+ && (this.projections.seqOf('inbox') ?? -1) < receipt.seq)
746
+ return;
747
+ this.scheduleObservedRetirement(requestId, settlement.admitted);
748
+ }
749
+ /** Inbox acceptance retires queued echoes; its watermark completes admitted Chat handoffs. */
750
+ observeSubmissionInbox() {
751
+ if (this.submissionSettlements.size === 0)
752
+ return;
753
+ const inbox = this.projections.get('inbox');
754
+ if (inbox === undefined)
755
+ return;
756
+ const seq = this.projections.seqOf('inbox');
757
+ for (const target of ['next-turn', 'next-step']) {
758
+ if (seq !== undefined)
759
+ this.observeSubmissionInsertions(target, inbox[target], 0, seq);
760
+ for (const message of inbox[target])
761
+ this.observeSubmissionMessage(message, false);
762
+ }
763
+ for (const requestId of this.submissionSettlements.keys())
764
+ this.retireAdmittedSubmission(requestId);
765
+ }
766
+ /**
767
+ * Latch one observed settlement and remove the echo an animation frame
768
+ * later. The delay keeps the echo in the snapshot until the frame in which
769
+ * the durable node (whose assembly frame was registered first) is
770
+ * renderable; the render-time rpcId dedupe hides the one-frame overlap.
771
+ */
772
+ scheduleObservedRetirement(requestId, attachments) {
773
+ const settlement = this.submissionSettlements.get(requestId);
774
+ if (settlement === undefined || settlement.retiring)
775
+ return;
776
+ settlement.retiring = true;
777
+ scheduleFrame(() => { this.finishSubmission(requestId, { reason: 'observed', attachments }); });
778
+ }
779
+ /** Remove one unsettled echo immediately (prompt rejection, abort, or disposal). */
780
+ retireFailedSubmission(requestId) {
781
+ const settlement = this.submissionSettlements.get(requestId);
782
+ if (settlement === undefined || settlement.retiring || settlement.admitted !== undefined)
783
+ return;
784
+ settlement.retiring = true;
785
+ this.finishSubmission(requestId, { reason: 'failed' });
786
+ }
787
+ /** Single removal point: drop the echo, publish, then notify the owner. */
788
+ finishSubmission(requestId, retirement) {
789
+ const settlement = this.submissionSettlements.get(requestId);
790
+ /* v8 ignore next -- retiring latches before every schedule, so one settlement never finishes twice. */
791
+ if (settlement === undefined)
792
+ return;
793
+ this.submissionSettlements.delete(requestId);
794
+ this.pendingSubmissions = this.pendingSubmissions.filter(echo => echo.requestId !== requestId);
795
+ this.notifier.markDirty();
796
+ settlement.onRetire?.(retirement);
797
+ }
798
+ /** Publish a terminal background failure only while this stream still owns the Session. */
799
+ failEventStream(events, generation, error) {
800
+ if (generation !== this.openGeneration || this.events !== events)
801
+ return;
802
+ if (!isRemoteFailure(error))
803
+ throw error;
804
+ this.openGeneration++;
805
+ this.events = undefined;
806
+ this.openPromise = null;
807
+ this.openState = 'error';
808
+ this.openError = error;
809
+ void events.dispose();
810
+ this.notifier.markDirty();
811
+ }
812
+ buildSnapshot() {
813
+ const identity = this.projections.values().subagent;
814
+ return {
815
+ sessionId: this.sessionId,
816
+ pendingSubmissions: this.pendingSubmissions,
817
+ running: this.running,
818
+ subagent: this.address === undefined
819
+ ? null
820
+ : {
821
+ address: this.address.mode === 'unknown' && identity != null
822
+ ? { ...this.address, mode: identity.mode }
823
+ : this.address,
824
+ ...(this.parentAvailable === undefined ? {} : { parentAvailable: this.parentAvailable }),
825
+ },
826
+ removed: this.removed,
827
+ openState: this.openState,
828
+ openError: this.openError,
829
+ hasMore: this.hasMore,
830
+ loadingOlder: this.loadingOlder,
831
+ promptError: this.promptError,
832
+ blank: this.blankBit,
833
+ lastAgentError: this.lastAgentError,
834
+ promptAttempted: this.promptAttempted,
835
+ awaitingFirstTurn: this.firstPromptPendingTurn,
836
+ };
837
+ }
838
+ sessionAddress() {
839
+ return this.address === undefined
840
+ ? { kind: 'session', sessionId: this.sessionId }
841
+ : { kind: 'subagent', ...this.address };
842
+ }
843
+ }
844
+ /** Run one callback on the next animation frame, or a macrotask where no frame clock exists. */
845
+ function scheduleFrame(fn) {
846
+ if (typeof requestAnimationFrame === 'function')
847
+ requestAnimationFrame(() => { fn(); });
848
+ else
849
+ setTimeout(fn, 0);
850
+ }
851
+ /** Attachment references in one structurally-read content block list, in block order. */
852
+ function attachmentRefsIn(content) {
853
+ if (!Array.isArray(content))
854
+ return [];
855
+ const refs = [];
856
+ for (const block of content) {
857
+ if (typeof block !== 'object' || block === null)
858
+ continue;
859
+ const candidate = block;
860
+ if ((candidate.type === 'image' || candidate.type === 'file')
861
+ && typeof candidate.attachment === 'object' && candidate.attachment !== null) {
862
+ refs.push(candidate.attachment);
863
+ }
864
+ }
865
+ return refs;
866
+ }