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