@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.
- package/LICENSE +21 -0
- package/README.md +7 -2
- package/lib/client.js +4325 -0
- package/lib/index.js +3367 -0
- package/lib/typert.host.d.ts +3 -0
- package/lib/typert.host.js +4053 -0
- package/lib/typert.remote-client.d.ts +97 -0
- package/lib/typert.remote-client.js +2013 -0
- package/lib/types/agent.d.ts +198 -0
- package/lib/types/agent.js +609 -0
- package/lib/types/archived-session-gate.d.ts +30 -0
- package/lib/types/archived-session-gate.js +51 -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 +106 -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 +157 -0
- package/lib/types/client/contract/session.js +1 -0
- package/lib/types/client/contract/sessions.d.ts +161 -0
- package/lib/types/client/contract/sessions.js +1 -0
- package/lib/types/client/contract/snapshot.d.ts +81 -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 +40 -0
- package/lib/types/client/sessions/lineage.js +54 -0
- package/lib/types/client/sessions/manager.d.ts +269 -0
- package/lib/types/client/sessions/manager.js +799 -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 +258 -0
- package/lib/types/client/sessions/service.js +582 -0
- package/lib/types/client/sessions/session.d.ts +287 -0
- package/lib/types/client/sessions/session.js +866 -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 +129 -0
- package/lib/types/commands.d.ts +86 -0
- package/lib/types/commands.js +624 -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.d.ts +32 -0
- package/lib/types/history.js +441 -0
- package/lib/types/index.d.ts +222 -0
- package/lib/types/index.js +658 -0
- package/lib/types/list.d.ts +50 -0
- package/lib/types/list.js +325 -0
- package/lib/types/media-references.d.ts +16 -0
- package/lib/types/media-references.js +76 -0
- package/lib/types/model-selection-projection.d.ts +8 -0
- package/lib/types/model-selection-projection.js +65 -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/types.d.ts +611 -0
- package/lib/types/types.js +4 -0
- package/locale/en.json +5 -0
- package/locale/zh.json +6 -0
- package/package.json +114 -4
package/lib/client.js
ADDED
|
@@ -0,0 +1,4325 @@
|
|
|
1
|
+
window.__ModuleLoader__.load({
|
|
2
|
+
id: "@unieai/rabi-api-session-controller",
|
|
3
|
+
factory: (require) => {
|
|
4
|
+
var module = { exports: {} };
|
|
5
|
+
var exports = module.exports;
|
|
6
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
7
|
+
let _unieai_cordis = require("@unieai/cordis");
|
|
8
|
+
let _unieai_rabi_api_gateway_client = require("@unieai/rabi-api-gateway/client");
|
|
9
|
+
let _unieai_rabi_client_store = require("@unieai/rabi-client-store");
|
|
10
|
+
//#region ../../typert/protocol/lib/index.js
|
|
11
|
+
/** The one Remote failure class shared by owners, the Gateway, and consumers. */
|
|
12
|
+
/**
|
|
13
|
+
* One Remote call failure: a real Error carrying its stable code and typed
|
|
14
|
+
* details. Owners throw it at the failure point; the Host Gateway encodes it
|
|
15
|
+
* onto the wire unchanged; the Client face rebuilds an instance for the
|
|
16
|
+
* `RemoteResult` error branch, so `throw result.error` keeps throw semantics.
|
|
17
|
+
* Discrimination is always by `code`, never by instanceof.
|
|
18
|
+
*/
|
|
19
|
+
var RemoteError = class extends Error {
|
|
20
|
+
code;
|
|
21
|
+
details;
|
|
22
|
+
/** Structural marker: cross-realm/bundle identification never uses instanceof. */
|
|
23
|
+
isRABIRemoteError = true;
|
|
24
|
+
/**
|
|
25
|
+
* @param code - stable failure code declared in {@link RemoteErrorDetailsMap}.
|
|
26
|
+
* @param message - human diagnostic carried across the wire.
|
|
27
|
+
* @param details - structured payload typed by the code.
|
|
28
|
+
* @param options - standard Error options (`cause` survives in-process only).
|
|
29
|
+
*/
|
|
30
|
+
constructor(code, message, details, options) {
|
|
31
|
+
super(message, options);
|
|
32
|
+
this.code = code;
|
|
33
|
+
this.details = details;
|
|
34
|
+
this.name = "RemoteError";
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
/** Generic invocation-owned values returned by synchronous Client Context resolvers. */
|
|
38
|
+
/** Shared identity across independently bundled Context providers and Gateway. */
|
|
39
|
+
const TYPERT_OWNED_VALUE = Symbol.for("rabi.typert.owned-value");
|
|
40
|
+
/**
|
|
41
|
+
* Transfer cleanup ownership without adding another resource reference count.
|
|
42
|
+
* @param value - resolved payload passed to the invocation.
|
|
43
|
+
* @param release - non-throwing synchronous release, called at most once.
|
|
44
|
+
* @returns an owned payload disposed after invocation and reply settlement.
|
|
45
|
+
*/
|
|
46
|
+
function typertOwnedValue(value, release) {
|
|
47
|
+
let active = true;
|
|
48
|
+
return {
|
|
49
|
+
[TYPERT_OWNED_VALUE]: true,
|
|
50
|
+
value,
|
|
51
|
+
[Symbol.dispose]() {
|
|
52
|
+
if (!active) return;
|
|
53
|
+
active = false;
|
|
54
|
+
release();
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
//#endregion
|
|
59
|
+
//#region lib/types/client/sessions/history-records.js
|
|
60
|
+
/** Client range access and type narrowing for aligned Session history records. */
|
|
61
|
+
/**
|
|
62
|
+
* Narrow aligned wire records to their Client event types without allocation.
|
|
63
|
+
* @param records - validated history transport records.
|
|
64
|
+
* @returns the same record array with typed inner events.
|
|
65
|
+
*/
|
|
66
|
+
function historyEntries(records) {
|
|
67
|
+
return records;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Read the first logical sequence represented by one wire record.
|
|
71
|
+
* @param record - validated Session event.
|
|
72
|
+
* @returns inclusive first Session sequence.
|
|
73
|
+
*/
|
|
74
|
+
function historyRecordFirstSeq(record) {
|
|
75
|
+
return record.event.seq;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Read the final logical sequence represented by one wire record.
|
|
79
|
+
* @param record - validated Session event.
|
|
80
|
+
* @returns inclusive final Session sequence.
|
|
81
|
+
*/
|
|
82
|
+
function historyRecordLastSeq(record) {
|
|
83
|
+
return record.event.seq;
|
|
84
|
+
}
|
|
85
|
+
//#endregion
|
|
86
|
+
//#region ../../util/brand/lib/index.js
|
|
87
|
+
/**
|
|
88
|
+
* Apply a compile-time number brand without changing the value.
|
|
89
|
+
* @param value - number admitted by the domain that owns the target brand.
|
|
90
|
+
* @returns the same number with the requested compile-time brand.
|
|
91
|
+
*/
|
|
92
|
+
function brandNumber(value) {
|
|
93
|
+
return value;
|
|
94
|
+
}
|
|
95
|
+
//#endregion
|
|
96
|
+
//#region ../../core/session/lib/types/types.js
|
|
97
|
+
/**
|
|
98
|
+
* Admit a numeric value as an existing Session event position.
|
|
99
|
+
* @param value - non-negative safe integer admitted by the owning log operation.
|
|
100
|
+
* @returns the same number with the Session-sequence brand.
|
|
101
|
+
*/
|
|
102
|
+
function SessionSeq(value) {
|
|
103
|
+
if (!Number.isSafeInteger(value) || value < 0 || Object.is(value, -0)) throw new TypeError(`SessionSeq must be a non-negative safe integer, got ${String(value)}`);
|
|
104
|
+
return brandNumber(value);
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Admit a numeric value as a Session log offset.
|
|
108
|
+
* @param value - non-negative safe integer used as a gap or prefix length.
|
|
109
|
+
* @returns the same number with the Session-log-offset brand.
|
|
110
|
+
*/
|
|
111
|
+
function SessionLogOffset(value) {
|
|
112
|
+
if (!Number.isSafeInteger(value) || value < 0 || Object.is(value, -0)) throw new TypeError(`SessionLogOffset must be a non-negative safe integer, got ${String(value)}`);
|
|
113
|
+
return brandNumber(value);
|
|
114
|
+
}
|
|
115
|
+
//#endregion
|
|
116
|
+
//#region ../../core/session/lib/types/known-event-types.js
|
|
117
|
+
/**
|
|
118
|
+
* GENERATED by `scripts/gen-persistence-catalog.ts` — do not edit by hand; run
|
|
119
|
+
* `pnpm run gen-persistence-catalog` to regenerate (verified fresh by
|
|
120
|
+
* `pnpm run verify-persistence-catalog`, part of `doc-sync`).
|
|
121
|
+
* @module @unieai/rabi-session/known-event-types
|
|
122
|
+
*/
|
|
123
|
+
/**
|
|
124
|
+
* Every `SessionEventMap` member declared in this repository — the event
|
|
125
|
+
* vocabulary this build understands. The persistence read path refuses to
|
|
126
|
+
* interpret a log containing a type outside this set unless the event
|
|
127
|
+
* carries the envelope's `ignorable` marker (see `SessionEvent.ignorable`
|
|
128
|
+
* in `./types.ts`): such a log was likely written by a newer harness, and
|
|
129
|
+
* silently skipping a required event would reconstruct a wrong session.
|
|
130
|
+
* Downstream (out-of-repo) plugin events are outside this list by
|
|
131
|
+
* construction. The persisted `SessionEvent.ignorable` marker is the
|
|
132
|
+
* compatibility mechanism; event-name registration was rejected because
|
|
133
|
+
* it does not classify omission safety and would make reads
|
|
134
|
+
* composition-dependent. The rationale is in
|
|
135
|
+
* `.agents/notes/implemented/architecture/2026-08-30-retain-ignorable-external-session-events.md`.
|
|
136
|
+
*/
|
|
137
|
+
const KNOWN_SESSION_EVENT_TYPES = new Set([
|
|
138
|
+
"agent-preset/selected",
|
|
139
|
+
"agent/inbox/spliced",
|
|
140
|
+
"approval/asked",
|
|
141
|
+
"approval/decided",
|
|
142
|
+
"approval/policy",
|
|
143
|
+
"assistant/attempt",
|
|
144
|
+
"assistant/message",
|
|
145
|
+
"command/done",
|
|
146
|
+
"command/run",
|
|
147
|
+
"compaction/end",
|
|
148
|
+
"compaction/prune",
|
|
149
|
+
"compaction/start",
|
|
150
|
+
"compaction/summary",
|
|
151
|
+
"deliverables/presented",
|
|
152
|
+
"developer/message",
|
|
153
|
+
"feedback/message-delete",
|
|
154
|
+
"feedback/message-put",
|
|
155
|
+
"feedback/record",
|
|
156
|
+
"goal/change",
|
|
157
|
+
"hook/invoked",
|
|
158
|
+
"hook/result",
|
|
159
|
+
"image/offload",
|
|
160
|
+
"job/registered",
|
|
161
|
+
"job/settled",
|
|
162
|
+
"llm/retry",
|
|
163
|
+
"llm/retry-started",
|
|
164
|
+
"model/selection",
|
|
165
|
+
"permission/preset",
|
|
166
|
+
"plan/mode",
|
|
167
|
+
"request/context",
|
|
168
|
+
"request/header",
|
|
169
|
+
"sandbox/mode",
|
|
170
|
+
"schedule/change",
|
|
171
|
+
"session-log-deepseek/delivery-accepted",
|
|
172
|
+
"session/end-seed",
|
|
173
|
+
"session/title",
|
|
174
|
+
"session/title-llm-request",
|
|
175
|
+
"step/end",
|
|
176
|
+
"step/start",
|
|
177
|
+
"subagent/catalog",
|
|
178
|
+
"subagent/descriptor",
|
|
179
|
+
"subagent/model-selection-policy",
|
|
180
|
+
"system/message",
|
|
181
|
+
"team/member",
|
|
182
|
+
"team/message/delivered",
|
|
183
|
+
"team/message/queued",
|
|
184
|
+
"team/task",
|
|
185
|
+
"todo/write",
|
|
186
|
+
"tool-workflow/agent-end",
|
|
187
|
+
"tool-workflow/agent-start",
|
|
188
|
+
"tool-workflow/run-end",
|
|
189
|
+
"tool-workflow/run-start",
|
|
190
|
+
"tool/call",
|
|
191
|
+
"tool/ptc-dispatch",
|
|
192
|
+
"tool/ptc-dispatch-start",
|
|
193
|
+
"tool/result",
|
|
194
|
+
"turn/end",
|
|
195
|
+
"turn/start",
|
|
196
|
+
"user/message",
|
|
197
|
+
"web/deepseek-search-llm-request",
|
|
198
|
+
"working-directory/change",
|
|
199
|
+
"workspace/changes"
|
|
200
|
+
]);
|
|
201
|
+
//#endregion
|
|
202
|
+
//#region ../../core/session/lib/types/surface.js
|
|
203
|
+
/** Runtime counterpart of the message-producing event union. */
|
|
204
|
+
const SURFACE_EVENT_TYPES = new Set([
|
|
205
|
+
"system/message",
|
|
206
|
+
"developer/message",
|
|
207
|
+
"user/message",
|
|
208
|
+
"assistant/message",
|
|
209
|
+
"tool/result"
|
|
210
|
+
]);
|
|
211
|
+
/**
|
|
212
|
+
* Whether an event type can join the model-visible surface.
|
|
213
|
+
* @param type - event type to test.
|
|
214
|
+
* @returns true for one of the message-producing event types.
|
|
215
|
+
*/
|
|
216
|
+
function isSurfaceEligibleType(type) {
|
|
217
|
+
return SURFACE_EVENT_TYPES.has(type);
|
|
218
|
+
}
|
|
219
|
+
/** Whether a payload field is a JSON object rather than an array or scalar. */
|
|
220
|
+
function isRecord(value) {
|
|
221
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* Reject noncanonical request-header fields, developer roles/content, and contradictory tool failure metadata.
|
|
225
|
+
* This does not validate complete event payloads or embedded provider streams.
|
|
226
|
+
* @param event - event whose locally related payload fields are inspected.
|
|
227
|
+
* @param subject - event location to include in validation errors.
|
|
228
|
+
* @throws when request-header fields, developer roles/content, or tool failure metadata are invalid.
|
|
229
|
+
*/
|
|
230
|
+
function validateSessionEventData(event, subject) {
|
|
231
|
+
const data = event.data;
|
|
232
|
+
if (SURFACE_EVENT_TYPES.has(event.type) && isRecord(data)) {
|
|
233
|
+
const message = event.type === "user/message" ? data : data["message"];
|
|
234
|
+
if (isRecord(message)) {
|
|
235
|
+
if (event.type === "developer/message" !== (message["role"] === "developer")) throw new Error(`${subject} developer/message and developer role must occur together`);
|
|
236
|
+
if (message["role"] !== "developer" && Array.isArray(message["content"]) && message["content"].some((block) => isRecord(block) && (block["type"] === "tool-addition" || block["type"] === "tool-removal"))) throw new Error(`${subject} tool-change blocks require developer role`);
|
|
237
|
+
if (event.type === "developer/message" && Array.isArray(message["content"])) {
|
|
238
|
+
let hasAdditions = false;
|
|
239
|
+
for (const block of message["content"]) {
|
|
240
|
+
if (!isRecord(block) || block["type"] !== "tool-addition" && block["type"] !== "tool-removal") continue;
|
|
241
|
+
if (typeof block["toolName"] !== "string" || block["toolName"].length === 0) throw new Error(`${subject} ${block["type"]} requires a nonempty toolName`);
|
|
242
|
+
if (block["type"] === "tool-addition") {
|
|
243
|
+
hasAdditions = true;
|
|
244
|
+
if (Object.hasOwn(block, "tool")) throw new Error(`${subject} tool-addition must omit inline tool definitions`);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
if (hasAdditions ? !isEventSeq(data["headerSeq"]) : Object.hasOwn(data, "headerSeq")) throw new Error(`${subject} requires headerSeq exactly when tool additions are present`);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
if (event.type === "request/header") {
|
|
252
|
+
if (!isRecord(data)) throw new Error(`${subject} data must be an object`);
|
|
253
|
+
const header = data["header"];
|
|
254
|
+
if (!isRecord(header)) throw new Error(`${subject} header must be an object`);
|
|
255
|
+
if (Object.hasOwn(header, "system")) throw new Error(`${subject} must omit header.system; use system/message`);
|
|
256
|
+
if (Array.isArray(header["tools"]) && header["tools"].length === 0) throw new Error(`${subject} must omit empty tools`);
|
|
257
|
+
const defaults = header["adapterDefaults"];
|
|
258
|
+
if (isRecord(defaults) && Object.keys(defaults).length === 0) throw new Error(`${subject} must omit empty adapterDefaults`);
|
|
259
|
+
} else if (event.type === "tool/result") {
|
|
260
|
+
if (!isRecord(data)) throw new Error(`${subject} data must be an object`);
|
|
261
|
+
if (data["error"] === void 0) return;
|
|
262
|
+
const message = data["message"];
|
|
263
|
+
if (!isRecord(message) || message["isError"] !== true) throw new Error(`${subject} error requires message.isError === true`);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
/** Whether a runtime value is a non-negative safe event sequence. */
|
|
267
|
+
function isEventSeq(value) {
|
|
268
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 && !Object.is(value, -0);
|
|
269
|
+
}
|
|
270
|
+
/** Whether a runtime value is the exact positional-replacement shape. */
|
|
271
|
+
function isReplaceOp(value) {
|
|
272
|
+
const op = value;
|
|
273
|
+
return Object.keys(op).length === 3 && Object.hasOwn(op, "op") && Object.hasOwn(op, "startSeq") && Object.hasOwn(op, "endSeq") && op["op"] === "replace" && isEventSeq(op["startSeq"]) && isEventSeq(op["endSeq"]);
|
|
274
|
+
}
|
|
275
|
+
/** Validate event-local surface eligibility and return its operation. */
|
|
276
|
+
function surfaceOpOf(event) {
|
|
277
|
+
const raw = event;
|
|
278
|
+
if (!isSurfaceEligibleType(event.type)) {
|
|
279
|
+
if (!KNOWN_SESSION_EVENT_TYPES.has(event.type) && event.ignorable === true) return;
|
|
280
|
+
if (raw.surfaceOp !== void 0) throw new Error(`session event "${event.type}" is not surface-eligible and cannot carry surfaceOp`);
|
|
281
|
+
if (raw.sourceEventSeqs !== void 0) throw new Error(`session event "${event.type}" is not surface-eligible and cannot carry sourceEventSeqs`);
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
284
|
+
const op = raw.surfaceOp;
|
|
285
|
+
if (op === void 0) throw new Error(`session event "${event.type}" is surface-eligible and requires a surfaceOp marker`);
|
|
286
|
+
if (op === "append") return op;
|
|
287
|
+
if (op === null || typeof op !== "object" || Array.isArray(op)) throw new Error(`session event "${event.type}" carries an invalid surfaceOp`);
|
|
288
|
+
if (!isReplaceOp(op)) throw new Error(`session event "${event.type}" carries an invalid replace surfaceOp`);
|
|
289
|
+
return op;
|
|
290
|
+
}
|
|
291
|
+
/** Validate cited source-event seqs against prior log entries and the replacement range. */
|
|
292
|
+
function assertSourceEventReferences(event, shadowedSeqs) {
|
|
293
|
+
const raw = event.sourceEventSeqs;
|
|
294
|
+
if (event.type === "assistant/message" && raw !== void 0) throw new Error("assistant/message embeds its source stream and cannot carry sourceEventSeqs");
|
|
295
|
+
const sources = /* @__PURE__ */ new Set();
|
|
296
|
+
if (raw !== void 0) {
|
|
297
|
+
if (!Array.isArray(raw)) throw new Error(`sourceEventSeqs on event at seq ${event.seq} must be an array when present`);
|
|
298
|
+
if (raw.length === 0) throw new Error("sourceEventSeqs must not be empty");
|
|
299
|
+
let nonEarlierSource;
|
|
300
|
+
for (const source of raw) {
|
|
301
|
+
if (!isEventSeq(source)) throw new Error(`session event "${event.type}" sourceEventSeqs must densely contain non-negative safe integers`);
|
|
302
|
+
sources.add(source);
|
|
303
|
+
if (nonEarlierSource === void 0 && source >= event.seq) nonEarlierSource = source;
|
|
304
|
+
}
|
|
305
|
+
if (sources.size !== raw.length) throw new Error("sourceEventSeqs must not contain duplicates");
|
|
306
|
+
if (nonEarlierSource !== void 0) throw new Error(`sourceEventSeqs must reference earlier events: ${nonEarlierSource} >= current seq ${event.seq}`);
|
|
307
|
+
}
|
|
308
|
+
const missing = shadowedSeqs.filter((seq) => !sources.has(seq));
|
|
309
|
+
if (missing.length > 0) throw new Error(`surface replace: sourceEventSeqs must include every shadowed surface node; missing ${missing.join(", ")}`);
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Validate one event's surface metadata without checking membership in a log or surface.
|
|
313
|
+
* @param event - event whose marker and source sequence values are inspected.
|
|
314
|
+
* Unknown ignorable records retain opaque metadata and never change the surface.
|
|
315
|
+
* @returns the validated operation, or undefined for a log-only or unknown ignorable event.
|
|
316
|
+
* @throws when metadata violates event-local eligibility, marker, or source-sequence rules.
|
|
317
|
+
*/
|
|
318
|
+
function validateSurfaceMetadata(event) {
|
|
319
|
+
const op = surfaceOpOf(event);
|
|
320
|
+
if (op !== void 0 && op !== "append" && (op.startSeq >= event.seq || op.endSeq >= event.seq)) throw new Error(`surface replace at seq ${event.seq}: startSeq and endSeq must reference earlier events`);
|
|
321
|
+
if (op !== void 0) assertSourceEventReferences(event, []);
|
|
322
|
+
return op;
|
|
323
|
+
}
|
|
324
|
+
//#endregion
|
|
325
|
+
//#region lib/types/client/session-wire-event.js
|
|
326
|
+
/** Event-local acceptance for raw Session journal responses; payloads remain owner-defined JSON. */
|
|
327
|
+
/**
|
|
328
|
+
* Reject non-current event envelopes without stripping or normalizing wire fields.
|
|
329
|
+
* Range membership and source existence require the durable log and remain Host-owned.
|
|
330
|
+
* @param value - one event received in a follow frame or history page.
|
|
331
|
+
* @returns nothing after narrowing the accepted event envelope.
|
|
332
|
+
* @throws when the envelope or current event-local metadata is invalid.
|
|
333
|
+
*/
|
|
334
|
+
function assertSessionWireEvent(value) {
|
|
335
|
+
const subject = "session wire event";
|
|
336
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`${subject} must be an object`);
|
|
337
|
+
const event = value;
|
|
338
|
+
for (const key of Object.keys(event)) switch (key) {
|
|
339
|
+
case "type":
|
|
340
|
+
case "seq":
|
|
341
|
+
case "time":
|
|
342
|
+
case "data":
|
|
343
|
+
case "ignorable":
|
|
344
|
+
case "surfaceOp":
|
|
345
|
+
case "sourceEventSeqs": break;
|
|
346
|
+
default: throw new Error(`${subject} has unexpected field ${key}`);
|
|
347
|
+
}
|
|
348
|
+
const seq = event["seq"];
|
|
349
|
+
if (typeof event["type"] !== "string" || typeof seq !== "number" || !Number.isSafeInteger(seq) || seq < 0 || Object.is(seq, -0) || typeof event["time"] !== "number" || !Number.isSafeInteger(event["time"]) || !Object.hasOwn(event, "data") || event["data"] === void 0 || Object.hasOwn(event, "ignorable") && event["ignorable"] !== true) throw new Error(`${subject} has an invalid envelope`);
|
|
350
|
+
const current = event;
|
|
351
|
+
validateSurfaceMetadata(current);
|
|
352
|
+
validateSessionEventData(current, subject);
|
|
353
|
+
}
|
|
354
|
+
//#endregion
|
|
355
|
+
//#region lib/types/types.js
|
|
356
|
+
/** Maximum number of Sessions returned by one search. */
|
|
357
|
+
const SESSION_SEARCH_RESULT_LIMIT = 20;
|
|
358
|
+
/** Maximum search snippet length in Unicode code points. */
|
|
359
|
+
const SESSION_SEARCH_SNIPPET_MAX_CODE_POINTS = 240;
|
|
360
|
+
//#endregion
|
|
361
|
+
//#region lib/types/client/transport.js
|
|
362
|
+
/** Session-specific adapters for Gateway-owned Remote stream lifecycles. */
|
|
363
|
+
function toSessionJournalChange(change) {
|
|
364
|
+
switch (change.type) {
|
|
365
|
+
case "replace":
|
|
366
|
+
case "prepend": return {
|
|
367
|
+
...change,
|
|
368
|
+
entries: historyEntries(change.entries)
|
|
369
|
+
};
|
|
370
|
+
case "append": return {
|
|
371
|
+
type: "append",
|
|
372
|
+
entry: change.entry
|
|
373
|
+
};
|
|
374
|
+
case "notification": return {
|
|
375
|
+
type: "assistant-stream",
|
|
376
|
+
frame: change.notification
|
|
377
|
+
};
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
/**
|
|
381
|
+
* Create the Host-wide Session control snapshot stream.
|
|
382
|
+
* @param remote - generated Session namespace and Gateway stream factory.
|
|
383
|
+
* @param options - Session state destinations.
|
|
384
|
+
* @returns an unstarted stream owned by the Client Session runtime.
|
|
385
|
+
*/
|
|
386
|
+
function createSessionControlStream(remote, options) {
|
|
387
|
+
return new _unieai_rabi_api_gateway_client.RemoteSnapshotStream(remote.$stream({
|
|
388
|
+
name: "session control stream",
|
|
389
|
+
open: (signal) => remote.session.control(signal),
|
|
390
|
+
ended: (accepted) => accepted ? new _unieai_rabi_api_gateway_client.RemoteStreamCarrierError("session control stream ended without a terminal result") : /* @__PURE__ */ new Error("session control stream ended before its opening snapshot"),
|
|
391
|
+
...options.carrierFailed === void 0 ? {} : { carrierFailed: options.carrierFailed }
|
|
392
|
+
}), {
|
|
393
|
+
name: "session control stream",
|
|
394
|
+
isSnapshot: (frame) => frame.type === "baseline",
|
|
395
|
+
replace: options.accept,
|
|
396
|
+
update: options.accept,
|
|
397
|
+
failed: options.failed
|
|
398
|
+
});
|
|
399
|
+
}
|
|
400
|
+
/** Gateway-owned event journal bound to one ordinary or direct-subagent Session address. */
|
|
401
|
+
var SessionEventStream = class extends _unieai_rabi_api_gateway_client.RemoteJournalStream {
|
|
402
|
+
remote;
|
|
403
|
+
address;
|
|
404
|
+
/**
|
|
405
|
+
* @param remote - generated Session namespace and Gateway stream factory.
|
|
406
|
+
* @param address - durable ordinary-Session or direct-subagent address.
|
|
407
|
+
* @param options - Session event-window destinations.
|
|
408
|
+
*/
|
|
409
|
+
constructor(remote, address, options) {
|
|
410
|
+
super(remote, {
|
|
411
|
+
name: "session event stream",
|
|
412
|
+
emptyCursor: -1,
|
|
413
|
+
entries: (page) => page.records,
|
|
414
|
+
hasMore: (page) => page.hasMore,
|
|
415
|
+
first: historyRecordFirstSeq,
|
|
416
|
+
last: historyRecordLastSeq,
|
|
417
|
+
compare: (left, right) => left - right,
|
|
418
|
+
follows: (left, right) => right === left + 1,
|
|
419
|
+
publish: (change) => {
|
|
420
|
+
options.publish(toSessionJournalChange(change));
|
|
421
|
+
},
|
|
422
|
+
...options.carrierFailed === void 0 ? {} : { carrierFailed: options.carrierFailed },
|
|
423
|
+
failed: options.failed
|
|
424
|
+
});
|
|
425
|
+
this.remote = remote;
|
|
426
|
+
this.address = address;
|
|
427
|
+
}
|
|
428
|
+
/** @inheritdoc */
|
|
429
|
+
async *follow(request, signal) {
|
|
430
|
+
let assistantRevision;
|
|
431
|
+
for await (const frame of this.remote.session.follow({
|
|
432
|
+
address: this.address,
|
|
433
|
+
assistantStream: true,
|
|
434
|
+
...this.repairRequest(request)
|
|
435
|
+
}, signal)) {
|
|
436
|
+
if (frame.type === "snapshot") {
|
|
437
|
+
for (const record of frame.records) assertSessionWireEvent(record.event);
|
|
438
|
+
if (frame.assistantStream === void 0) throw new RemoteError("gateway/internal", "session assistant stream omitted its opted-in opening baseline", {});
|
|
439
|
+
assistantRevision = frame.assistantStream.revision;
|
|
440
|
+
yield {
|
|
441
|
+
type: "opened",
|
|
442
|
+
cursor: frame.cursor,
|
|
443
|
+
page: {
|
|
444
|
+
records: frame.records,
|
|
445
|
+
hasMore: frame.hasMore,
|
|
446
|
+
projections: frame.projections,
|
|
447
|
+
assistantStream: frame.assistantStream
|
|
448
|
+
}
|
|
449
|
+
};
|
|
450
|
+
continue;
|
|
451
|
+
}
|
|
452
|
+
if (frame.type === "assistant-stream") {
|
|
453
|
+
const expected = (assistantRevision ?? 0) + 1;
|
|
454
|
+
if (frame.frame.revision !== expected) throw new _unieai_rabi_api_gateway_client.RemoteStreamCarrierError(`session assistant stream skipped revision ${String(expected)}`);
|
|
455
|
+
assistantRevision = frame.frame.revision;
|
|
456
|
+
yield {
|
|
457
|
+
type: "notification",
|
|
458
|
+
notification: frame.frame
|
|
459
|
+
};
|
|
460
|
+
continue;
|
|
461
|
+
}
|
|
462
|
+
assertSessionWireEvent(frame.event);
|
|
463
|
+
yield {
|
|
464
|
+
type: "entry",
|
|
465
|
+
entry: frame
|
|
466
|
+
};
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
/** @inheritdoc */
|
|
470
|
+
async readPage(request, throughSeq, signal) {
|
|
471
|
+
const result = await this.remote.session.page({
|
|
472
|
+
address: this.address,
|
|
473
|
+
throughSeq,
|
|
474
|
+
...request
|
|
475
|
+
}, signal);
|
|
476
|
+
if (!result.ok) throw result.error;
|
|
477
|
+
for (const record of result.value.records) assertSessionWireEvent(record.event);
|
|
478
|
+
return result.value;
|
|
479
|
+
}
|
|
480
|
+
/** @inheritdoc */
|
|
481
|
+
repairRequest(request) {
|
|
482
|
+
return {
|
|
483
|
+
...request.maxMessages === void 0 ? {} : { maxMessages: request.maxMessages },
|
|
484
|
+
...request.turnWindow === void 0 ? {} : { turnWindow: request.turnWindow }
|
|
485
|
+
};
|
|
486
|
+
}
|
|
487
|
+
};
|
|
488
|
+
//#endregion
|
|
489
|
+
//#region ../../util/workspace-path/lib/index.js
|
|
490
|
+
/**
|
|
491
|
+
* Read the final non-empty segment of a Workspace path for display.
|
|
492
|
+
* Workspace-label surfaces use this helper instead of deriving another basename.
|
|
493
|
+
* @param path - Workspace directory path using POSIX or Windows separators.
|
|
494
|
+
* @returns the final segment, or an empty string for a separator-only path.
|
|
495
|
+
*/
|
|
496
|
+
function workspaceTitleOf(path) {
|
|
497
|
+
const trimmed = path.replace(/[/\\]+$/, "");
|
|
498
|
+
const separator = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));
|
|
499
|
+
return trimmed.slice(separator + 1);
|
|
500
|
+
}
|
|
501
|
+
//#endregion
|
|
502
|
+
//#region lib/types/client/scope.js
|
|
503
|
+
/** Client scope generations route local events independently of Host Agent residency. */
|
|
504
|
+
/** Context tag written by {@link createScope}. */
|
|
505
|
+
const kScope = Symbol("rabi.client.scope");
|
|
506
|
+
/** Shared no-op plugin backing each Agent scope fiber. */
|
|
507
|
+
function agentScope() {}
|
|
508
|
+
/**
|
|
509
|
+
* Mint an Agent scope under `ctx`: a no-op plugin fiber whose context
|
|
510
|
+
* carries the agent tag and the dispatch filter — untagged listeners are
|
|
511
|
+
* admitted globally, tagged listeners only for the same Client generation.
|
|
512
|
+
* Registrations through the returned ctx dispose with the fiber.
|
|
513
|
+
* @param ctx - client root context the scope fiber mounts under.
|
|
514
|
+
* @param key - durable Session identity carried by this generation.
|
|
515
|
+
* @returns the tagged context and its backing fiber.
|
|
516
|
+
*/
|
|
517
|
+
function createScope(ctx, key) {
|
|
518
|
+
const fiber = ctx.plugin(agentScope);
|
|
519
|
+
const identity = { sessionId: key };
|
|
520
|
+
return {
|
|
521
|
+
fiber,
|
|
522
|
+
ctx: fiber.ctx.extend({
|
|
523
|
+
[kScope]: identity,
|
|
524
|
+
[_unieai_cordis.Context.filter](listenerCtx) {
|
|
525
|
+
const tag = scopeIdentityOf(listenerCtx);
|
|
526
|
+
return tag === void 0 || tag === identity;
|
|
527
|
+
}
|
|
528
|
+
})
|
|
529
|
+
};
|
|
530
|
+
}
|
|
531
|
+
/**
|
|
532
|
+
* Read the nearest agent tag inherited by a context.
|
|
533
|
+
* @param ctx - any client context.
|
|
534
|
+
* @returns its agent identity (the session id), or undefined for root contexts.
|
|
535
|
+
*/
|
|
536
|
+
function scopeOf(ctx) {
|
|
537
|
+
return scopeIdentityOf(ctx)?.sessionId;
|
|
538
|
+
}
|
|
539
|
+
/**
|
|
540
|
+
* Read the exact generation identity inherited by a Client Context.
|
|
541
|
+
* @param ctx - scoped or root Client Context.
|
|
542
|
+
* @returns the generation identity, or undefined for an unscoped Context.
|
|
543
|
+
*/
|
|
544
|
+
function scopeIdentityOf(ctx) {
|
|
545
|
+
return ctx[kScope];
|
|
546
|
+
}
|
|
547
|
+
//#endregion
|
|
548
|
+
//#region lib/types/client/ordered-baseline.js
|
|
549
|
+
/**
|
|
550
|
+
* Merge an authoritative baseline without moving identities already visible to
|
|
551
|
+
* the client. Baseline-only identities are inserted relative to the nearest
|
|
552
|
+
* following known identity; identities absent from the baseline are removed.
|
|
553
|
+
*
|
|
554
|
+
* @param current - the established client order.
|
|
555
|
+
* @param baseline - the latest authoritative rows.
|
|
556
|
+
* @param keyOf - stable identity selector.
|
|
557
|
+
* @returns baseline-valued rows with the established relative order retained.
|
|
558
|
+
*/
|
|
559
|
+
function mergeOrderedBaseline(current, baseline, keyOf) {
|
|
560
|
+
const baselineByKey = /* @__PURE__ */ new Map();
|
|
561
|
+
for (const value of baseline) baselineByKey.set(keyOf(value), value);
|
|
562
|
+
const merged = current.map((value) => baselineByKey.get(keyOf(value))).filter((value) => value !== void 0);
|
|
563
|
+
const mergedKeys = new Set(merged.map(keyOf));
|
|
564
|
+
for (let index = 0; index < baseline.length; index++) {
|
|
565
|
+
const value = baseline[index];
|
|
566
|
+
/* v8 ignore next -- dense-array guard: index is bounded by baseline.length. */
|
|
567
|
+
if (value === void 0 || mergedKeys.has(keyOf(value))) continue;
|
|
568
|
+
let insertion = merged.length;
|
|
569
|
+
for (let following = index + 1; following < baseline.length; following++) {
|
|
570
|
+
const candidate = baseline[following];
|
|
571
|
+
/* v8 ignore next -- dense-array guard: following is bounded by baseline.length. */
|
|
572
|
+
if (candidate === void 0) continue;
|
|
573
|
+
const known = merged.findIndex((item) => keyOf(item) === keyOf(candidate));
|
|
574
|
+
if (known !== -1) {
|
|
575
|
+
insertion = known;
|
|
576
|
+
break;
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
merged.splice(insertion, 0, value);
|
|
580
|
+
mergedKeys.add(keyOf(value));
|
|
581
|
+
}
|
|
582
|
+
return merged;
|
|
583
|
+
}
|
|
584
|
+
//#endregion
|
|
585
|
+
//#region ../../util/values/lib/index.js
|
|
586
|
+
/**
|
|
587
|
+
* Lazily scanned view of one JSON object's top-level fields, built from text
|
|
588
|
+
* that may still be streaming or from an already parsed object. Nothing is
|
|
589
|
+
* scanned until a reader asks; the view remembers every question it answered
|
|
590
|
+
* and reports changed answers when the owner refreshes for publication.
|
|
591
|
+
* Used for model tool-call arguments: a row reads the fields it
|
|
592
|
+
* cares about at whatever granularity it displays, at every stage of the call.
|
|
593
|
+
* @module @unieai/rabi-util-values/src/partial-json
|
|
594
|
+
*/
|
|
595
|
+
const SIMPLE_ESCAPES = {
|
|
596
|
+
"\"": "\"",
|
|
597
|
+
"\\": "\\",
|
|
598
|
+
"/": "/",
|
|
599
|
+
b: "\b",
|
|
600
|
+
f: "\f",
|
|
601
|
+
n: "\n",
|
|
602
|
+
r: "\r",
|
|
603
|
+
t: " "
|
|
604
|
+
};
|
|
605
|
+
const CONTENT_ESCAPE = /[\\\u0000-\u001f]/u;
|
|
606
|
+
function isWhitespace(c) {
|
|
607
|
+
return c === " " || c === "\n" || c === "\r" || c === " ";
|
|
608
|
+
}
|
|
609
|
+
function isHex(c) {
|
|
610
|
+
return c >= "0" && c <= "9" || c >= "a" && c <= "f" || c >= "A" && c <= "F";
|
|
611
|
+
}
|
|
612
|
+
(class PartialArguments {
|
|
613
|
+
/** The view of a call with no arguments available. */
|
|
614
|
+
static EMPTY = PartialArguments.fromObject({});
|
|
615
|
+
/**
|
|
616
|
+
* View finished argument text without scanning it until a reader asks.
|
|
617
|
+
* @param text - the complete argument JSON text.
|
|
618
|
+
* @returns a sealed view.
|
|
619
|
+
*/
|
|
620
|
+
static fromText(text) {
|
|
621
|
+
const view = new PartialArguments();
|
|
622
|
+
view.append(text);
|
|
623
|
+
view.sealed = true;
|
|
624
|
+
return view;
|
|
625
|
+
}
|
|
626
|
+
/**
|
|
627
|
+
* View an already parsed argument payload, such as a PTC dispatch object.
|
|
628
|
+
* @param value - the parsed argument value.
|
|
629
|
+
* @returns a sealed view; a non-object payload has no fields.
|
|
630
|
+
*/
|
|
631
|
+
static fromObject(value) {
|
|
632
|
+
const view = new PartialArguments();
|
|
633
|
+
view.object = typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
|
|
634
|
+
view.sealed = true;
|
|
635
|
+
return view;
|
|
636
|
+
}
|
|
637
|
+
/**
|
|
638
|
+
* The source: text so far or a parsed object, plus whether it can still grow.
|
|
639
|
+
* These are the only enumerable fields, so two views over the same source
|
|
640
|
+
* compare equal structurally however far each has been read.
|
|
641
|
+
*/
|
|
642
|
+
chunks = [];
|
|
643
|
+
object;
|
|
644
|
+
sealed = false;
|
|
645
|
+
#ends = [];
|
|
646
|
+
#size = 0;
|
|
647
|
+
#consumed = 0;
|
|
648
|
+
#mode = "root";
|
|
649
|
+
#escape = false;
|
|
650
|
+
#keyStart = 0;
|
|
651
|
+
#keyEscaped = false;
|
|
652
|
+
#key = "";
|
|
653
|
+
#current = null;
|
|
654
|
+
#nestedEnds = [];
|
|
655
|
+
#nestedInString = false;
|
|
656
|
+
#invalidAt;
|
|
657
|
+
#invalidValue = false;
|
|
658
|
+
#entries = /* @__PURE__ */ new Map();
|
|
659
|
+
#order = [];
|
|
660
|
+
#reads = /* @__PURE__ */ new Map();
|
|
661
|
+
/** Whether this view rejects further appends; does not scan text or register reads. */
|
|
662
|
+
get isSealed() {
|
|
663
|
+
return this.sealed;
|
|
664
|
+
}
|
|
665
|
+
/** Whether indexing or a content read found invalid JSON; unread value contents are not validated. */
|
|
666
|
+
get invalid() {
|
|
667
|
+
this.scan();
|
|
668
|
+
return this.#mode === "invalid" || this.#invalidValue;
|
|
669
|
+
}
|
|
670
|
+
/**
|
|
671
|
+
* Retain streamed argument text without scanning or comparing observed answers.
|
|
672
|
+
* @param fragment - the text following every fragment appended before.
|
|
673
|
+
*/
|
|
674
|
+
append(fragment) {
|
|
675
|
+
if (this.sealed) throw new Error("PartialArguments: cannot append to a sealed view");
|
|
676
|
+
if (fragment.length === 0) return;
|
|
677
|
+
this.chunks.push(fragment);
|
|
678
|
+
this.#size += fragment.length;
|
|
679
|
+
this.#ends.push(this.#size);
|
|
680
|
+
}
|
|
681
|
+
/**
|
|
682
|
+
* Reconcile a streamed prefix with authoritative complete text without joining the fragments.
|
|
683
|
+
* @param text - the final argument text, which replaces missing or conflicting deltas.
|
|
684
|
+
* @returns this view sealed with its caches retained when every character matches; otherwise a new sealed view.
|
|
685
|
+
*/
|
|
686
|
+
settle(text) {
|
|
687
|
+
if (this.object !== void 0 || text.length !== this.#size) return PartialArguments.fromText(text);
|
|
688
|
+
let offset = 0;
|
|
689
|
+
for (const chunk of this.chunks) {
|
|
690
|
+
if (!text.startsWith(chunk, offset)) return PartialArguments.fromText(text);
|
|
691
|
+
offset += chunk.length;
|
|
692
|
+
}
|
|
693
|
+
this.chunks = text.length === 0 ? [] : [text];
|
|
694
|
+
this.#ends = text.length === 0 ? [] : [text.length];
|
|
695
|
+
this.sealed = true;
|
|
696
|
+
return this;
|
|
697
|
+
}
|
|
698
|
+
/**
|
|
699
|
+
* Compare observed answers and advance their publication baseline. Unread views remain unscanned.
|
|
700
|
+
* @returns whether any observed answer changed since its first read or the preceding refresh.
|
|
701
|
+
*/
|
|
702
|
+
refresh() {
|
|
703
|
+
if (this.#reads.size === 0) return false;
|
|
704
|
+
this.scan();
|
|
705
|
+
let changed = false;
|
|
706
|
+
let completions = false;
|
|
707
|
+
for (const read of this.#reads.values()) {
|
|
708
|
+
if (read.completion) {
|
|
709
|
+
completions = true;
|
|
710
|
+
continue;
|
|
711
|
+
}
|
|
712
|
+
changed = this.refreshRead(read) || changed;
|
|
713
|
+
}
|
|
714
|
+
if (completions) {
|
|
715
|
+
for (const read of this.#reads.values()) if (read.completion) changed = this.refreshRead(read) || changed;
|
|
716
|
+
}
|
|
717
|
+
if (this.sealed) this.#reads.clear();
|
|
718
|
+
return changed;
|
|
719
|
+
}
|
|
720
|
+
refreshRead(read) {
|
|
721
|
+
const now = read.answer();
|
|
722
|
+
if (Object.is(now, read.last)) return false;
|
|
723
|
+
read.last = now;
|
|
724
|
+
return true;
|
|
725
|
+
}
|
|
726
|
+
/**
|
|
727
|
+
* Check whether no further fields can arrive.
|
|
728
|
+
* @returns whether the outer object closed, indexing failed, or the view is sealed; unread values are not validated.
|
|
729
|
+
*/
|
|
730
|
+
closed() {
|
|
731
|
+
return this.remember("closed", "", () => this.closedNow());
|
|
732
|
+
}
|
|
733
|
+
/**
|
|
734
|
+
* List discovered fields in first-appearance order.
|
|
735
|
+
* @returns top-level keys seen so far, in first-appearance order.
|
|
736
|
+
*/
|
|
737
|
+
keys() {
|
|
738
|
+
return this.remember("keys", "", () => this.keysNow(), (keys) => keys.length);
|
|
739
|
+
}
|
|
740
|
+
/**
|
|
741
|
+
* Check whether a top-level field has appeared.
|
|
742
|
+
* @param key - argument name.
|
|
743
|
+
* @returns whether the field has appeared (a string opened or another value began).
|
|
744
|
+
*/
|
|
745
|
+
has(key) {
|
|
746
|
+
return this.remember("has", key, () => this.hasNow(key));
|
|
747
|
+
}
|
|
748
|
+
/**
|
|
749
|
+
* Check whether a field's closing delimiter has arrived, without validating its contents.
|
|
750
|
+
* @param key - argument name.
|
|
751
|
+
* @returns whether its delimiter arrived and no content reader has reported an error for this value.
|
|
752
|
+
*/
|
|
753
|
+
complete(key) {
|
|
754
|
+
return this.remember("complete", key, () => this.completeNow(key));
|
|
755
|
+
}
|
|
756
|
+
/**
|
|
757
|
+
* Read string length without materializing its text.
|
|
758
|
+
* @param key - argument name.
|
|
759
|
+
* @param options - change granularity for a streaming string.
|
|
760
|
+
* @returns decoded UTF-16 length of the string field so far; undefined when absent or not a string.
|
|
761
|
+
*/
|
|
762
|
+
stringLength(key, options) {
|
|
763
|
+
const step = Math.max(1, Math.floor(options?.step ?? 1));
|
|
764
|
+
const offset = options?.offset ?? 0;
|
|
765
|
+
return this.remember(`length:${step}:${offset}`, key, () => this.lengthNow(key), (length) => length === void 0 ? void 0 : Math.ceil((length + offset) / step));
|
|
766
|
+
}
|
|
767
|
+
/**
|
|
768
|
+
* Check a string against a decoded UTF-16 length limit without materializing it.
|
|
769
|
+
* @param key - argument name.
|
|
770
|
+
* @param maxLength - decoded UTF-16 limit, floored to at least zero.
|
|
771
|
+
* @returns whether the string is longer than the limit; false when absent or not a string.
|
|
772
|
+
*/
|
|
773
|
+
stringExceeds(key, maxLength) {
|
|
774
|
+
const limit = Math.max(0, Math.floor(maxLength));
|
|
775
|
+
return this.remember(`exceeds:${limit}`, key, () => (this.lengthNow(key, limit + 1) ?? 0) > limit);
|
|
776
|
+
}
|
|
777
|
+
/**
|
|
778
|
+
* Read a decoded string, including a streaming prefix.
|
|
779
|
+
* @param key - argument name.
|
|
780
|
+
* @returns the string field's decoded text so far; undefined when absent or not a string.
|
|
781
|
+
*/
|
|
782
|
+
text(key) {
|
|
783
|
+
return this.remember("text", key, () => this.textNow(key));
|
|
784
|
+
}
|
|
785
|
+
/**
|
|
786
|
+
* Read at most the first decoded UTF-16 units of a string.
|
|
787
|
+
* @param key - argument name.
|
|
788
|
+
* @param maxLength - maximum decoded UTF-16 length, floored to at least one.
|
|
789
|
+
* @returns the bounded string prefix; undefined when absent or not a string.
|
|
790
|
+
*/
|
|
791
|
+
textPrefix(key, maxLength) {
|
|
792
|
+
const limit = Math.max(1, Math.floor(maxLength));
|
|
793
|
+
return this.remember(`prefix:${limit}`, key, () => this.textPrefixNow(key, limit));
|
|
794
|
+
}
|
|
795
|
+
/**
|
|
796
|
+
* Read a completed non-string argument.
|
|
797
|
+
* @param key - argument name.
|
|
798
|
+
* @returns the parsed non-string value once it closed; undefined while open, absent, or a string.
|
|
799
|
+
*/
|
|
800
|
+
value(key) {
|
|
801
|
+
return this.remember("value", key, () => this.valueNow(key));
|
|
802
|
+
}
|
|
803
|
+
/** Answer a question and, on a streaming view, remember it for change detection. */
|
|
804
|
+
remember(kind, key, read, comparison) {
|
|
805
|
+
this.scan();
|
|
806
|
+
const result = read();
|
|
807
|
+
if (!this.sealed) {
|
|
808
|
+
const id = `${kind}/${key}`;
|
|
809
|
+
if (!this.#reads.has(id)) this.#reads.set(id, {
|
|
810
|
+
completion: kind === "complete",
|
|
811
|
+
answer: comparison === void 0 ? read : () => comparison(read()),
|
|
812
|
+
last: comparison === void 0 ? result : comparison(result)
|
|
813
|
+
});
|
|
814
|
+
}
|
|
815
|
+
return result;
|
|
816
|
+
}
|
|
817
|
+
closedNow() {
|
|
818
|
+
return this.sealed || this.#mode === "closed" || this.#mode === "invalid";
|
|
819
|
+
}
|
|
820
|
+
keysNow() {
|
|
821
|
+
return this.object === void 0 ? this.#order : Object.keys(this.object);
|
|
822
|
+
}
|
|
823
|
+
hasNow(key) {
|
|
824
|
+
return this.object === void 0 ? this.#entries.has(key) : Object.hasOwn(this.object, key);
|
|
825
|
+
}
|
|
826
|
+
completeNow(key) {
|
|
827
|
+
if (this.object !== void 0) return Object.hasOwn(this.object, key);
|
|
828
|
+
const entry = this.#entries.get(key);
|
|
829
|
+
return entry !== void 0 && entry.end >= 0 && (entry.kind === "string" ? entry.invalidAt === void 0 : !entry.invalid);
|
|
830
|
+
}
|
|
831
|
+
lengthNow(key, limit = Number.POSITIVE_INFINITY) {
|
|
832
|
+
if (this.object !== void 0) {
|
|
833
|
+
const field = Object.hasOwn(this.object, key) ? this.object[key] : void 0;
|
|
834
|
+
return typeof field === "string" ? field.length : void 0;
|
|
835
|
+
}
|
|
836
|
+
const entry = this.#entries.get(key);
|
|
837
|
+
if (entry?.kind !== "string") return void 0;
|
|
838
|
+
if (entry.text !== void 0 && entry.text.at === entry.end) return entry.text.length;
|
|
839
|
+
const read = entry.length ??= {
|
|
840
|
+
at: entry.start,
|
|
841
|
+
length: 0,
|
|
842
|
+
text: ""
|
|
843
|
+
};
|
|
844
|
+
this.readString(entry, read, limit, false);
|
|
845
|
+
return read.length;
|
|
846
|
+
}
|
|
847
|
+
textNow(key) {
|
|
848
|
+
if (this.object !== void 0) {
|
|
849
|
+
const field = Object.hasOwn(this.object, key) ? this.object[key] : void 0;
|
|
850
|
+
return typeof field === "string" ? field : void 0;
|
|
851
|
+
}
|
|
852
|
+
const entry = this.#entries.get(key);
|
|
853
|
+
if (entry?.kind !== "string") return void 0;
|
|
854
|
+
if (entry.text === void 0 && entry.end >= 0 && entry.needsDecoding && entry.invalidAt === void 0) {
|
|
855
|
+
let text;
|
|
856
|
+
try {
|
|
857
|
+
text = JSON.parse(`"${this.slice(entry.start, entry.end)}"`);
|
|
858
|
+
} catch (_error) {}
|
|
859
|
+
if (text !== void 0) entry.text = {
|
|
860
|
+
at: entry.end,
|
|
861
|
+
length: text.length,
|
|
862
|
+
text
|
|
863
|
+
};
|
|
864
|
+
}
|
|
865
|
+
const read = entry.text ??= {
|
|
866
|
+
at: entry.start,
|
|
867
|
+
length: 0,
|
|
868
|
+
text: ""
|
|
869
|
+
};
|
|
870
|
+
this.readString(entry, read, Number.POSITIVE_INFINITY, true);
|
|
871
|
+
return read.text;
|
|
872
|
+
}
|
|
873
|
+
textPrefixNow(key, maxLength) {
|
|
874
|
+
if (this.object !== void 0) {
|
|
875
|
+
const field = Object.hasOwn(this.object, key) ? this.object[key] : void 0;
|
|
876
|
+
return typeof field === "string" ? field.slice(0, maxLength) : void 0;
|
|
877
|
+
}
|
|
878
|
+
const entry = this.#entries.get(key);
|
|
879
|
+
if (entry?.kind !== "string") return void 0;
|
|
880
|
+
const prefixes = entry.prefixes ??= /* @__PURE__ */ new Map();
|
|
881
|
+
let read = prefixes.get(maxLength);
|
|
882
|
+
if (read === void 0) {
|
|
883
|
+
read = {
|
|
884
|
+
at: entry.start,
|
|
885
|
+
length: 0,
|
|
886
|
+
text: ""
|
|
887
|
+
};
|
|
888
|
+
prefixes.set(maxLength, read);
|
|
889
|
+
}
|
|
890
|
+
this.readString(entry, read, maxLength, true);
|
|
891
|
+
return read.text;
|
|
892
|
+
}
|
|
893
|
+
valueNow(key) {
|
|
894
|
+
if (this.object !== void 0) {
|
|
895
|
+
if (!Object.hasOwn(this.object, key)) return void 0;
|
|
896
|
+
const field = this.object[key];
|
|
897
|
+
return typeof field === "string" ? void 0 : field;
|
|
898
|
+
}
|
|
899
|
+
const entry = this.#entries.get(key);
|
|
900
|
+
if (entry?.kind !== "value" || entry.end < 0 || entry.invalid) return void 0;
|
|
901
|
+
if (entry.parsed === void 0) try {
|
|
902
|
+
entry.parsed = JSON.parse(this.slice(entry.start, entry.end));
|
|
903
|
+
} catch (_error) {
|
|
904
|
+
entry.invalid = true;
|
|
905
|
+
this.#invalidValue = true;
|
|
906
|
+
}
|
|
907
|
+
return entry.parsed;
|
|
908
|
+
}
|
|
909
|
+
chunkAt(at) {
|
|
910
|
+
let low = 0;
|
|
911
|
+
let high = this.#ends.length;
|
|
912
|
+
while (low < high) {
|
|
913
|
+
const mid = low + high >>> 1;
|
|
914
|
+
if (this.#ends[mid] <= at) low = mid + 1;
|
|
915
|
+
else high = mid;
|
|
916
|
+
}
|
|
917
|
+
return low;
|
|
918
|
+
}
|
|
919
|
+
/** Materialize only a requested range, never the cumulative source. */
|
|
920
|
+
slice(start, end) {
|
|
921
|
+
if (start >= end) return "";
|
|
922
|
+
const first = this.chunkAt(start);
|
|
923
|
+
const last = this.chunkAt(end - 1);
|
|
924
|
+
const base = first === 0 ? 0 : this.#ends[first - 1];
|
|
925
|
+
if (first === last) return this.chunks[first].slice(start - base, end - base);
|
|
926
|
+
const parts = [this.chunks[first].slice(start - base)];
|
|
927
|
+
for (let i = first + 1; i < last; i++) parts.push(this.chunks[i]);
|
|
928
|
+
parts.push(this.chunks[last].slice(0, end - this.#ends[last - 1]));
|
|
929
|
+
return parts.join("");
|
|
930
|
+
}
|
|
931
|
+
readString(entry, read, limit, materialize) {
|
|
932
|
+
const end = Math.min(entry.end < 0 ? this.#consumed : entry.end, entry.invalidAt ?? Number.POSITIVE_INFINITY, this.#invalidAt ?? Number.POSITIVE_INFINITY);
|
|
933
|
+
if (!entry.needsDecoding) {
|
|
934
|
+
const length = Math.min(end - read.at, limit - read.length);
|
|
935
|
+
if (length <= 0) return;
|
|
936
|
+
if (materialize) read.text += this.slice(read.at, read.at + length);
|
|
937
|
+
read.at += length;
|
|
938
|
+
read.length += length;
|
|
939
|
+
return;
|
|
940
|
+
}
|
|
941
|
+
let chunkIndex = this.chunkAt(read.at);
|
|
942
|
+
while (read.at < end && read.length < limit) {
|
|
943
|
+
const base = chunkIndex === 0 ? 0 : this.#ends[chunkIndex - 1];
|
|
944
|
+
const chunk = this.chunks[chunkIndex];
|
|
945
|
+
const remaining = chunk.slice(read.at - base, Math.min(chunk.length, end - base));
|
|
946
|
+
const boundary = remaining.search(CONTENT_ESCAPE);
|
|
947
|
+
const length = Math.min(boundary < 0 ? remaining.length : boundary, limit - read.length);
|
|
948
|
+
if (length > 0) {
|
|
949
|
+
if (materialize) read.text += remaining.slice(0, length);
|
|
950
|
+
read.at += length;
|
|
951
|
+
read.length += length;
|
|
952
|
+
if (read.at === base + chunk.length) chunkIndex++;
|
|
953
|
+
continue;
|
|
954
|
+
}
|
|
955
|
+
const type = remaining.length > 1 ? remaining[1] : read.at + 1 < end ? this.chunks[chunkIndex + 1][0] : void 0;
|
|
956
|
+
let decoded;
|
|
957
|
+
let width = 2;
|
|
958
|
+
if (remaining[0] === "\\" && type === void 0 && entry.end < 0) return;
|
|
959
|
+
if (remaining[0] === "\\" && type === "u") {
|
|
960
|
+
const hex = this.slice(read.at + 2, Math.min(end, read.at + 6));
|
|
961
|
+
let valid = true;
|
|
962
|
+
for (let i = 0; i < hex.length; i++) if (!isHex(hex[i])) valid = false;
|
|
963
|
+
if (valid) {
|
|
964
|
+
if (hex.length < 4 && entry.end < 0) return;
|
|
965
|
+
if (hex.length === 4) decoded = String.fromCharCode(Number.parseInt(hex, 16));
|
|
966
|
+
}
|
|
967
|
+
width = 6;
|
|
968
|
+
} else if (remaining[0] === "\\" && type !== void 0) decoded = SIMPLE_ESCAPES[type];
|
|
969
|
+
if (decoded === void 0) {
|
|
970
|
+
entry.invalidAt = read.at;
|
|
971
|
+
this.#invalidValue = true;
|
|
972
|
+
return;
|
|
973
|
+
}
|
|
974
|
+
if (materialize) read.text += decoded;
|
|
975
|
+
read.length++;
|
|
976
|
+
read.at += width;
|
|
977
|
+
while (chunkIndex < this.chunks.length && read.at >= this.#ends[chunkIndex]) chunkIndex++;
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
/** Locate new field ranges without decoding or parsing their contents. */
|
|
981
|
+
scan() {
|
|
982
|
+
if (this.object !== void 0 || this.#consumed === this.#size) return;
|
|
983
|
+
for (let i = this.chunkAt(this.#consumed); i < this.chunks.length && this.#invalidAt === void 0; i++) {
|
|
984
|
+
const pending = this.chunks[i];
|
|
985
|
+
const base = i === 0 ? 0 : this.#ends[i - 1];
|
|
986
|
+
for (let index = this.#consumed - base; index < pending.length && this.#mode !== "invalid"; index++) {
|
|
987
|
+
if (this.#mode === "string" || this.#mode === "nested" && this.#nestedInString) {
|
|
988
|
+
const end = this.stringBoundary(pending, index);
|
|
989
|
+
this.#consumed += end - index;
|
|
990
|
+
index = end;
|
|
991
|
+
if (index === pending.length) break;
|
|
992
|
+
}
|
|
993
|
+
this.step(pending[index], this.#consumed);
|
|
994
|
+
this.#consumed++;
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
/** Only raw quotes and their preceding backslash runs can terminate a string. */
|
|
999
|
+
stringBoundary(fragment, start) {
|
|
1000
|
+
let at = start;
|
|
1001
|
+
while (true) {
|
|
1002
|
+
const quote = fragment.indexOf("\"", at);
|
|
1003
|
+
const end = quote < 0 ? fragment.length : quote;
|
|
1004
|
+
if (this.#mode === "string") {
|
|
1005
|
+
const entry = this.#current;
|
|
1006
|
+
if (!entry.needsDecoding && CONTENT_ESCAPE.test(fragment.slice(at, end))) entry.needsDecoding = true;
|
|
1007
|
+
}
|
|
1008
|
+
let slashStart = end;
|
|
1009
|
+
while (slashStart > at && fragment[slashStart - 1] === "\\") slashStart--;
|
|
1010
|
+
const escaped = (end - slashStart) % 2 === 1 !== (slashStart === at && this.#escape);
|
|
1011
|
+
this.#escape = quote < 0 && escaped;
|
|
1012
|
+
if (quote < 0 || !escaped) return end;
|
|
1013
|
+
at = quote + 1;
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1016
|
+
step(c, at) {
|
|
1017
|
+
switch (this.#mode) {
|
|
1018
|
+
case "root":
|
|
1019
|
+
if (isWhitespace(c)) return;
|
|
1020
|
+
if (c === "{") {
|
|
1021
|
+
this.#mode = "key-or-end";
|
|
1022
|
+
return;
|
|
1023
|
+
}
|
|
1024
|
+
this.fail();
|
|
1025
|
+
return;
|
|
1026
|
+
case "key-or-end":
|
|
1027
|
+
if (isWhitespace(c)) return;
|
|
1028
|
+
if (c === "}") {
|
|
1029
|
+
this.#mode = "closed";
|
|
1030
|
+
return;
|
|
1031
|
+
}
|
|
1032
|
+
if (c === "\"") {
|
|
1033
|
+
this.beginKey(at);
|
|
1034
|
+
return;
|
|
1035
|
+
}
|
|
1036
|
+
this.fail();
|
|
1037
|
+
return;
|
|
1038
|
+
case "key-only":
|
|
1039
|
+
if (isWhitespace(c)) return;
|
|
1040
|
+
if (c === "\"") {
|
|
1041
|
+
this.beginKey(at);
|
|
1042
|
+
return;
|
|
1043
|
+
}
|
|
1044
|
+
this.fail();
|
|
1045
|
+
return;
|
|
1046
|
+
case "key":
|
|
1047
|
+
this.stepKey(c, at);
|
|
1048
|
+
return;
|
|
1049
|
+
case "colon":
|
|
1050
|
+
if (isWhitespace(c)) return;
|
|
1051
|
+
if (c === ":") {
|
|
1052
|
+
this.#mode = "value";
|
|
1053
|
+
return;
|
|
1054
|
+
}
|
|
1055
|
+
this.fail();
|
|
1056
|
+
return;
|
|
1057
|
+
case "value":
|
|
1058
|
+
this.beginValue(c, at);
|
|
1059
|
+
return;
|
|
1060
|
+
case "string": {
|
|
1061
|
+
const entry = this.#current;
|
|
1062
|
+
entry.end = at;
|
|
1063
|
+
this.#current = null;
|
|
1064
|
+
this.#mode = "comma-or-end";
|
|
1065
|
+
return;
|
|
1066
|
+
}
|
|
1067
|
+
case "scalar":
|
|
1068
|
+
this.stepScalar(c, at);
|
|
1069
|
+
return;
|
|
1070
|
+
case "nested":
|
|
1071
|
+
this.stepNested(c, at);
|
|
1072
|
+
return;
|
|
1073
|
+
case "comma-or-end":
|
|
1074
|
+
if (isWhitespace(c)) return;
|
|
1075
|
+
if (c === ",") {
|
|
1076
|
+
this.#mode = "key-only";
|
|
1077
|
+
return;
|
|
1078
|
+
}
|
|
1079
|
+
if (c === "}") {
|
|
1080
|
+
this.#mode = "closed";
|
|
1081
|
+
return;
|
|
1082
|
+
}
|
|
1083
|
+
this.fail();
|
|
1084
|
+
return;
|
|
1085
|
+
case "closed":
|
|
1086
|
+
if (isWhitespace(c)) return;
|
|
1087
|
+
this.fail();
|
|
1088
|
+
return;
|
|
1089
|
+
/* v8 ignore next 2 -- scan() stops stepping once the view is invalid. */
|
|
1090
|
+
case "invalid": return;
|
|
1091
|
+
/* v8 ignore next 2 -- Every scanner mode has a handler above. */
|
|
1092
|
+
default: assertNever(this.#mode);
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
fail() {
|
|
1096
|
+
this.#invalidAt = this.#consumed;
|
|
1097
|
+
this.#mode = "invalid";
|
|
1098
|
+
this.#current = null;
|
|
1099
|
+
}
|
|
1100
|
+
beginKey(at) {
|
|
1101
|
+
this.#mode = "key";
|
|
1102
|
+
this.#keyStart = at + 1;
|
|
1103
|
+
this.#keyEscaped = false;
|
|
1104
|
+
this.#escape = false;
|
|
1105
|
+
}
|
|
1106
|
+
stepKey(c, at) {
|
|
1107
|
+
if (c < " ") {
|
|
1108
|
+
this.fail();
|
|
1109
|
+
return;
|
|
1110
|
+
}
|
|
1111
|
+
if (this.#escape) {
|
|
1112
|
+
this.#escape = false;
|
|
1113
|
+
return;
|
|
1114
|
+
}
|
|
1115
|
+
if (c === "\\") {
|
|
1116
|
+
this.#escape = true;
|
|
1117
|
+
this.#keyEscaped = true;
|
|
1118
|
+
return;
|
|
1119
|
+
}
|
|
1120
|
+
if (c !== "\"") return;
|
|
1121
|
+
const raw = this.slice(this.#keyStart, at);
|
|
1122
|
+
if (this.#keyEscaped) try {
|
|
1123
|
+
this.#key = JSON.parse(`"${raw}"`);
|
|
1124
|
+
} catch (_error) {
|
|
1125
|
+
this.fail();
|
|
1126
|
+
return;
|
|
1127
|
+
}
|
|
1128
|
+
else this.#key = raw;
|
|
1129
|
+
this.#mode = "colon";
|
|
1130
|
+
}
|
|
1131
|
+
open(entry) {
|
|
1132
|
+
if (!this.#entries.has(this.#key)) this.#order.push(this.#key);
|
|
1133
|
+
this.#entries.set(this.#key, entry);
|
|
1134
|
+
this.#current = entry;
|
|
1135
|
+
}
|
|
1136
|
+
beginValue(c, at) {
|
|
1137
|
+
if (isWhitespace(c)) return;
|
|
1138
|
+
if (c === "\"") {
|
|
1139
|
+
this.open({
|
|
1140
|
+
kind: "string",
|
|
1141
|
+
start: at + 1,
|
|
1142
|
+
end: -1,
|
|
1143
|
+
needsDecoding: false,
|
|
1144
|
+
invalidAt: void 0,
|
|
1145
|
+
length: void 0,
|
|
1146
|
+
text: void 0,
|
|
1147
|
+
prefixes: void 0
|
|
1148
|
+
});
|
|
1149
|
+
this.#escape = false;
|
|
1150
|
+
this.#mode = "string";
|
|
1151
|
+
return;
|
|
1152
|
+
}
|
|
1153
|
+
if (c === "}" || c === "," || c === ":" || c === "]") {
|
|
1154
|
+
this.fail();
|
|
1155
|
+
return;
|
|
1156
|
+
}
|
|
1157
|
+
this.open({
|
|
1158
|
+
kind: "value",
|
|
1159
|
+
start: at,
|
|
1160
|
+
end: -1,
|
|
1161
|
+
parsed: void 0,
|
|
1162
|
+
invalid: false
|
|
1163
|
+
});
|
|
1164
|
+
if (c === "{" || c === "[") {
|
|
1165
|
+
this.#mode = "nested";
|
|
1166
|
+
this.#nestedEnds = [c === "{" ? "}" : "]"];
|
|
1167
|
+
this.#nestedInString = false;
|
|
1168
|
+
this.#escape = false;
|
|
1169
|
+
return;
|
|
1170
|
+
}
|
|
1171
|
+
this.#mode = "scalar";
|
|
1172
|
+
}
|
|
1173
|
+
stepScalar(c, at) {
|
|
1174
|
+
if (c !== "," && c !== "}" && !isWhitespace(c)) return;
|
|
1175
|
+
this.closeValue(at);
|
|
1176
|
+
this.#mode = c === "," ? "key-only" : c === "}" ? "closed" : "comma-or-end";
|
|
1177
|
+
}
|
|
1178
|
+
stepNested(c, at) {
|
|
1179
|
+
if (this.#nestedInString) {
|
|
1180
|
+
this.#nestedInString = false;
|
|
1181
|
+
return;
|
|
1182
|
+
}
|
|
1183
|
+
if (c === "\"") {
|
|
1184
|
+
this.#nestedInString = true;
|
|
1185
|
+
return;
|
|
1186
|
+
}
|
|
1187
|
+
if (c === "{" || c === "[") {
|
|
1188
|
+
this.#nestedEnds.push(c === "{" ? "}" : "]");
|
|
1189
|
+
return;
|
|
1190
|
+
}
|
|
1191
|
+
if (c === "}" || c === "]") {
|
|
1192
|
+
if (this.#nestedEnds.pop() !== c) {
|
|
1193
|
+
this.fail();
|
|
1194
|
+
return;
|
|
1195
|
+
}
|
|
1196
|
+
if (this.#nestedEnds.length === 0) {
|
|
1197
|
+
this.closeValue(at + 1);
|
|
1198
|
+
this.#mode = "comma-or-end";
|
|
1199
|
+
}
|
|
1200
|
+
}
|
|
1201
|
+
}
|
|
1202
|
+
closeValue(end) {
|
|
1203
|
+
const entry = this.#current;
|
|
1204
|
+
entry.end = end;
|
|
1205
|
+
this.#current = null;
|
|
1206
|
+
}
|
|
1207
|
+
});
|
|
1208
|
+
/** Duplicate-install-safe JSON and immutable-value helpers. @module @unieai/rabi-util-values */
|
|
1209
|
+
/**
|
|
1210
|
+
* Mark an unreachable closed-union branch.
|
|
1211
|
+
* @param value - impossible value; an unhandled typed variant fails at the call site.
|
|
1212
|
+
* @param context - optional switch-site label included in the failure message.
|
|
1213
|
+
* @returns never; a runtime value that escaped its type always throws.
|
|
1214
|
+
*/
|
|
1215
|
+
function assertNever(value, context) {
|
|
1216
|
+
const rendered = JSON.stringify(value) ?? String(value);
|
|
1217
|
+
throw new Error(`unreachable variant${context ? ` in ${context}` : ""}: ${rendered}`);
|
|
1218
|
+
}
|
|
1219
|
+
/** Whether a realm-owned intrinsic prototype has a native constructor matching this engine's representation. */
|
|
1220
|
+
function hasIntrinsicConstructor(prototype, name) {
|
|
1221
|
+
const constructor = Object.getOwnPropertyDescriptor(prototype, "constructor")?.value;
|
|
1222
|
+
if (typeof constructor !== "function") return false;
|
|
1223
|
+
try {
|
|
1224
|
+
return constructor.name === name && constructor.prototype === prototype && Function.prototype.toString.call(constructor) === Function.prototype.toString.call(name === "Array" ? Array : Object);
|
|
1225
|
+
} catch {
|
|
1226
|
+
return false;
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
/** Whether a candidate is one realm's intrinsic `Object.prototype`. */
|
|
1230
|
+
function isIntrinsicObjectPrototype(value) {
|
|
1231
|
+
return Object.getPrototypeOf(value) === null && hasIntrinsicConstructor(value, "Object");
|
|
1232
|
+
}
|
|
1233
|
+
/** Whether an array uses one realm's intrinsic `Array.prototype`, not a subclass or forged prototype. */
|
|
1234
|
+
function hasPlainArrayPrototype(value) {
|
|
1235
|
+
const prototype = Object.getPrototypeOf(value);
|
|
1236
|
+
if (!Array.isArray(prototype) || !hasIntrinsicConstructor(prototype, "Array")) return false;
|
|
1237
|
+
const objectPrototype = Object.getPrototypeOf(prototype);
|
|
1238
|
+
return typeof objectPrototype === "object" && objectPrototype !== null && isIntrinsicObjectPrototype(objectPrototype);
|
|
1239
|
+
}
|
|
1240
|
+
/** Whether an object is a plain or null-prototype record from any JavaScript realm. */
|
|
1241
|
+
function hasPlainObjectPrototype(value) {
|
|
1242
|
+
const prototype = Object.getPrototypeOf(value);
|
|
1243
|
+
return prototype === null || typeof prototype === "object" && isIntrinsicObjectPrototype(prototype);
|
|
1244
|
+
}
|
|
1245
|
+
/** Return every JSON-visible object key, or reject own data JSON would discard. */
|
|
1246
|
+
function enumerableStringKeys(value) {
|
|
1247
|
+
const keys = Reflect.ownKeys(value);
|
|
1248
|
+
if (keys.some((key) => typeof key !== "string" || !Object.prototype.propertyIsEnumerable.call(value, key))) return void 0;
|
|
1249
|
+
return keys;
|
|
1250
|
+
}
|
|
1251
|
+
/** Validate lossless JSON iteratively, optionally materializing a detached snapshot. */
|
|
1252
|
+
function walkJsonValue(value, detach) {
|
|
1253
|
+
const ancestors = /* @__PURE__ */ new Set();
|
|
1254
|
+
let root;
|
|
1255
|
+
const assign = (destination, item) => {
|
|
1256
|
+
if (destination === void 0) return;
|
|
1257
|
+
if (destination.kind === "root") root = item;
|
|
1258
|
+
else if (destination.kind === "array") destination.target[destination.index] = item;
|
|
1259
|
+
else Object.defineProperty(destination.target, destination.key, {
|
|
1260
|
+
value: item,
|
|
1261
|
+
enumerable: true,
|
|
1262
|
+
configurable: true,
|
|
1263
|
+
writable: true
|
|
1264
|
+
});
|
|
1265
|
+
};
|
|
1266
|
+
const tasks = [{
|
|
1267
|
+
kind: "visit",
|
|
1268
|
+
value,
|
|
1269
|
+
...detach ? { destination: { kind: "root" } } : {}
|
|
1270
|
+
}];
|
|
1271
|
+
for (let task = tasks.pop(); task !== void 0; task = tasks.pop()) {
|
|
1272
|
+
if (task.kind === "leave") {
|
|
1273
|
+
ancestors.delete(task.source);
|
|
1274
|
+
continue;
|
|
1275
|
+
}
|
|
1276
|
+
if (task.kind === "array-item") {
|
|
1277
|
+
if (!Object.prototype.hasOwnProperty.call(task.source, task.index)) return void 0;
|
|
1278
|
+
tasks.push({
|
|
1279
|
+
kind: "visit",
|
|
1280
|
+
value: task.source[task.index],
|
|
1281
|
+
...task.target === void 0 ? {} : { destination: {
|
|
1282
|
+
kind: "array",
|
|
1283
|
+
target: task.target,
|
|
1284
|
+
index: task.index
|
|
1285
|
+
} }
|
|
1286
|
+
});
|
|
1287
|
+
continue;
|
|
1288
|
+
}
|
|
1289
|
+
if (task.kind === "object-property") {
|
|
1290
|
+
tasks.push({
|
|
1291
|
+
kind: "visit",
|
|
1292
|
+
value: task.source[task.key],
|
|
1293
|
+
...task.target === void 0 ? {} : { destination: {
|
|
1294
|
+
kind: "object",
|
|
1295
|
+
target: task.target,
|
|
1296
|
+
key: task.key
|
|
1297
|
+
} }
|
|
1298
|
+
});
|
|
1299
|
+
continue;
|
|
1300
|
+
}
|
|
1301
|
+
const current = task.value;
|
|
1302
|
+
if (current === null) {
|
|
1303
|
+
assign(task.destination, null);
|
|
1304
|
+
continue;
|
|
1305
|
+
}
|
|
1306
|
+
if (typeof current === "boolean" || typeof current === "string") {
|
|
1307
|
+
assign(task.destination, current);
|
|
1308
|
+
continue;
|
|
1309
|
+
}
|
|
1310
|
+
if (typeof current === "number") {
|
|
1311
|
+
if (!Number.isFinite(current) || Object.is(current, -0)) return void 0;
|
|
1312
|
+
assign(task.destination, current);
|
|
1313
|
+
continue;
|
|
1314
|
+
}
|
|
1315
|
+
if (typeof current !== "object") return void 0;
|
|
1316
|
+
if (ancestors.has(current)) return void 0;
|
|
1317
|
+
if (Array.isArray(current)) {
|
|
1318
|
+
if (!hasPlainArrayPrototype(current)) return void 0;
|
|
1319
|
+
const length = current.length;
|
|
1320
|
+
if (Reflect.ownKeys(current).length !== length + 1) return void 0;
|
|
1321
|
+
const target = detach ? [] : void 0;
|
|
1322
|
+
if (target !== void 0) assign(task.destination, target);
|
|
1323
|
+
ancestors.add(current);
|
|
1324
|
+
tasks.push({
|
|
1325
|
+
kind: "leave",
|
|
1326
|
+
source: current
|
|
1327
|
+
});
|
|
1328
|
+
for (let index = length - 1; index >= 0; index--) tasks.push({
|
|
1329
|
+
kind: "array-item",
|
|
1330
|
+
source: current,
|
|
1331
|
+
index,
|
|
1332
|
+
...target === void 0 ? {} : { target }
|
|
1333
|
+
});
|
|
1334
|
+
continue;
|
|
1335
|
+
}
|
|
1336
|
+
if (!hasPlainObjectPrototype(current)) return void 0;
|
|
1337
|
+
const keys = enumerableStringKeys(current);
|
|
1338
|
+
if (keys === void 0) return void 0;
|
|
1339
|
+
const target = detach ? {} : void 0;
|
|
1340
|
+
if (target !== void 0) assign(task.destination, target);
|
|
1341
|
+
ancestors.add(current);
|
|
1342
|
+
tasks.push({
|
|
1343
|
+
kind: "leave",
|
|
1344
|
+
source: current
|
|
1345
|
+
});
|
|
1346
|
+
for (let index = keys.length - 1; index >= 0; index--) {
|
|
1347
|
+
const key = keys[index];
|
|
1348
|
+
/* v8 ignore next -- the loop is bounded by the captured key count. */
|
|
1349
|
+
if (key === void 0) return void 0;
|
|
1350
|
+
tasks.push({
|
|
1351
|
+
kind: "object-property",
|
|
1352
|
+
source: current,
|
|
1353
|
+
key,
|
|
1354
|
+
...target === void 0 ? {} : { target }
|
|
1355
|
+
});
|
|
1356
|
+
}
|
|
1357
|
+
}
|
|
1358
|
+
return detach ? root : true;
|
|
1359
|
+
}
|
|
1360
|
+
/**
|
|
1361
|
+
* Validate and detach lossless JSON in one read per property.
|
|
1362
|
+
* @param value - candidate value to validate and detach.
|
|
1363
|
+
* @returns the detached snapshot, or `undefined` when the value is not losslessly JSON-serializable.
|
|
1364
|
+
*/
|
|
1365
|
+
function snapshotJsonValue(value) {
|
|
1366
|
+
return walkJsonValue(value, true);
|
|
1367
|
+
}
|
|
1368
|
+
/**
|
|
1369
|
+
* Deep-freeze an object graph in place while leaving live AbortSignal objects mutable.
|
|
1370
|
+
* @param value - value to freeze.
|
|
1371
|
+
* @returns the same value after every reachable enumerable child is frozen.
|
|
1372
|
+
*/
|
|
1373
|
+
function deepFreeze(value) {
|
|
1374
|
+
const seen = /* @__PURE__ */ new WeakSet();
|
|
1375
|
+
const pending = [{
|
|
1376
|
+
kind: "visit",
|
|
1377
|
+
node: value
|
|
1378
|
+
}];
|
|
1379
|
+
while (pending.length > 0) {
|
|
1380
|
+
const task = pending.pop();
|
|
1381
|
+
/* v8 ignore next -- the loop condition guarantees one pending task. */
|
|
1382
|
+
if (task === void 0) continue;
|
|
1383
|
+
if (task.kind === "property") {
|
|
1384
|
+
pending.push({
|
|
1385
|
+
kind: "visit",
|
|
1386
|
+
node: task.source[task.key]
|
|
1387
|
+
});
|
|
1388
|
+
continue;
|
|
1389
|
+
}
|
|
1390
|
+
const node = task.node;
|
|
1391
|
+
if (node === null || typeof node !== "object") continue;
|
|
1392
|
+
if (node instanceof AbortSignal) continue;
|
|
1393
|
+
if (seen.has(node)) continue;
|
|
1394
|
+
seen.add(node);
|
|
1395
|
+
Object.freeze(node);
|
|
1396
|
+
const keys = Object.keys(node);
|
|
1397
|
+
for (let index = keys.length - 1; index >= 0; index--) {
|
|
1398
|
+
const key = keys[index];
|
|
1399
|
+
/* v8 ignore next -- the loop is bounded by the captured key count. */
|
|
1400
|
+
if (key === void 0) continue;
|
|
1401
|
+
pending.push({
|
|
1402
|
+
kind: "property",
|
|
1403
|
+
source: node,
|
|
1404
|
+
key
|
|
1405
|
+
});
|
|
1406
|
+
}
|
|
1407
|
+
}
|
|
1408
|
+
return value;
|
|
1409
|
+
}
|
|
1410
|
+
//#endregion
|
|
1411
|
+
//#region lib/types/client/sessions/lineage.js
|
|
1412
|
+
/**
|
|
1413
|
+
* Summaries -> flat list with lineage indentation. Root and sibling order
|
|
1414
|
+
* follows the established input order; this projection never re-sorts a
|
|
1415
|
+
* hydrated list from mutable timestamps.
|
|
1416
|
+
* @param summaries - the host's session.list items.
|
|
1417
|
+
* @returns display rows in render order.
|
|
1418
|
+
*/
|
|
1419
|
+
function flattenLineage(summaries) {
|
|
1420
|
+
const byId = /* @__PURE__ */ new Map();
|
|
1421
|
+
for (const s of summaries) byId.set(s.sessionId, s);
|
|
1422
|
+
const children = /* @__PURE__ */ new Map();
|
|
1423
|
+
const roots = [];
|
|
1424
|
+
for (const s of summaries) if (s.parentSessionId !== void 0 && byId.has(s.parentSessionId)) {
|
|
1425
|
+
const list = children.get(s.parentSessionId) ?? [];
|
|
1426
|
+
list.push(s);
|
|
1427
|
+
children.set(s.parentSessionId, list);
|
|
1428
|
+
} else roots.push(s);
|
|
1429
|
+
const out = [];
|
|
1430
|
+
const visited = /* @__PURE__ */ new Set();
|
|
1431
|
+
const walk = (s, depth) => {
|
|
1432
|
+
if (visited.has(s.sessionId)) {
|
|
1433
|
+
console.warn(`[session-controller] lineage cycle at ${s.sessionId}; emitting as root`);
|
|
1434
|
+
return;
|
|
1435
|
+
}
|
|
1436
|
+
visited.add(s.sessionId);
|
|
1437
|
+
const { agentAvailable: _agentAvailable, ...row } = s;
|
|
1438
|
+
out.push({
|
|
1439
|
+
...row,
|
|
1440
|
+
depth
|
|
1441
|
+
});
|
|
1442
|
+
const kids = children.get(s.sessionId);
|
|
1443
|
+
if (kids === void 0) return;
|
|
1444
|
+
for (const kid of kids) walk(kid, depth + 1);
|
|
1445
|
+
};
|
|
1446
|
+
for (const root of roots) walk(root, 0);
|
|
1447
|
+
for (const s of summaries) if (!visited.has(s.sessionId)) walk(s, 0);
|
|
1448
|
+
return out;
|
|
1449
|
+
}
|
|
1450
|
+
//#endregion
|
|
1451
|
+
//#region lib/types/client/sessions/notifier.js
|
|
1452
|
+
/**
|
|
1453
|
+
* Batches structural updates in microtasks and stream updates by animation
|
|
1454
|
+
* frame. Reads may rebuild a dirty snapshot without consuming the pending
|
|
1455
|
+
* subscriber notification.
|
|
1456
|
+
*/
|
|
1457
|
+
var Notifier = class {
|
|
1458
|
+
rebuild;
|
|
1459
|
+
listeners = /* @__PURE__ */ new Set();
|
|
1460
|
+
dirty = false;
|
|
1461
|
+
notifyPending = false;
|
|
1462
|
+
scheduled = "none";
|
|
1463
|
+
scheduleGeneration = 0;
|
|
1464
|
+
/** @param rebuild - snapshot rebuild function injected by the owner (writes the owner's snapshotCache). */
|
|
1465
|
+
constructor(rebuild) {
|
|
1466
|
+
this.rebuild = rebuild;
|
|
1467
|
+
}
|
|
1468
|
+
/**
|
|
1469
|
+
* uSES subscription entry.
|
|
1470
|
+
* @param listener - change callback.
|
|
1471
|
+
* @returns the unsubscribe function.
|
|
1472
|
+
*/
|
|
1473
|
+
subscribe(listener) {
|
|
1474
|
+
this.listeners.add(listener);
|
|
1475
|
+
return () => {
|
|
1476
|
+
this.listeners.delete(listener);
|
|
1477
|
+
};
|
|
1478
|
+
}
|
|
1479
|
+
/** Mark the snapshot dirty and notify in a microtask. */
|
|
1480
|
+
markDirty() {
|
|
1481
|
+
this.dirty = true;
|
|
1482
|
+
this.notifyPending = true;
|
|
1483
|
+
if (this.scheduled === "microtask") return;
|
|
1484
|
+
this.schedule("microtask");
|
|
1485
|
+
}
|
|
1486
|
+
/** Mark the snapshot dirty and publish cumulative state at most once per frame. */
|
|
1487
|
+
markFrameDirty() {
|
|
1488
|
+
this.dirty = true;
|
|
1489
|
+
this.notifyPending = true;
|
|
1490
|
+
if (this.scheduled !== "none") return;
|
|
1491
|
+
this.schedule(typeof globalThis.requestAnimationFrame === "function" ? "frame" : "microtask");
|
|
1492
|
+
}
|
|
1493
|
+
/**
|
|
1494
|
+
* Synchronous flush: controlled-input writes must notify in the same tick as
|
|
1495
|
+
* onChange, or React rolls the DOM back to the stale value and the caret jumps to the end.
|
|
1496
|
+
*/
|
|
1497
|
+
notifyNow() {
|
|
1498
|
+
this.dirty = true;
|
|
1499
|
+
this.notifyPending = true;
|
|
1500
|
+
this.invalidateSchedule();
|
|
1501
|
+
this.flush();
|
|
1502
|
+
}
|
|
1503
|
+
/**
|
|
1504
|
+
* Pre-getSnapshot check: rebuild synchronously when dirty (read path
|
|
1505
|
+
* before first subscribe / while unobserved). Notification stays pending.
|
|
1506
|
+
*/
|
|
1507
|
+
ensureFresh() {
|
|
1508
|
+
if (!this.dirty) return;
|
|
1509
|
+
this.dirty = false;
|
|
1510
|
+
this.rebuild();
|
|
1511
|
+
}
|
|
1512
|
+
schedule(kind) {
|
|
1513
|
+
const generation = ++this.scheduleGeneration;
|
|
1514
|
+
this.scheduled = kind;
|
|
1515
|
+
const publish = () => {
|
|
1516
|
+
if (generation !== this.scheduleGeneration) return;
|
|
1517
|
+
this.scheduled = "none";
|
|
1518
|
+
this.flush();
|
|
1519
|
+
};
|
|
1520
|
+
if (kind === "frame") globalThis.requestAnimationFrame(publish);
|
|
1521
|
+
else queueMicrotask(publish);
|
|
1522
|
+
}
|
|
1523
|
+
invalidateSchedule() {
|
|
1524
|
+
this.scheduleGeneration++;
|
|
1525
|
+
this.scheduled = "none";
|
|
1526
|
+
}
|
|
1527
|
+
flush() {
|
|
1528
|
+
if (!this.notifyPending) return;
|
|
1529
|
+
if (this.listeners.size === 0) return;
|
|
1530
|
+
this.notifyPending = false;
|
|
1531
|
+
if (this.dirty) {
|
|
1532
|
+
this.dirty = false;
|
|
1533
|
+
this.rebuild();
|
|
1534
|
+
}
|
|
1535
|
+
(0, _unieai_rabi_client_store.notifySubscribers)(this.listeners, "[session-controller]");
|
|
1536
|
+
}
|
|
1537
|
+
};
|
|
1538
|
+
//#endregion
|
|
1539
|
+
//#region lib/types/client/sessions/projection-store.js
|
|
1540
|
+
/**
|
|
1541
|
+
* One session's projection values. Framework semantics, uniform across every
|
|
1542
|
+
* key. Sequenced writes (a baseline seeds rows at its cut, a push frame
|
|
1543
|
+
* updates one row) compare seqs among themselves: a lower-or-equal seq within
|
|
1544
|
+
* the Host generation loses, so a replayed frame cannot regress a value and a
|
|
1545
|
+
* stale baseline cannot overwrite a newer frame. Cached writes (the session
|
|
1546
|
+
* list's zero-I/O block) only fill keys no sequenced row holds, and a baseline
|
|
1547
|
+
* discards every cached row before it seeds, regardless of seq: the connected
|
|
1548
|
+
* Session is the truth and a cached value never outranks it. A key the store
|
|
1549
|
+
* has never seen reads `undefined` (capability absent). Faces are identity-stable
|
|
1550
|
+
* per key (create-on-demand, cached) so the React side binds each exactly
|
|
1551
|
+
* once; the store-level channel (`subscribeAny`) serves coarse consumers (the
|
|
1552
|
+
* manager's list projection reads the `title` key).
|
|
1553
|
+
*/
|
|
1554
|
+
var ProjectionValueStore = class {
|
|
1555
|
+
rows = /* @__PURE__ */ new Map();
|
|
1556
|
+
channels = /* @__PURE__ */ new Map();
|
|
1557
|
+
valuesCache;
|
|
1558
|
+
/** Coarse any-key channel (no snapshot cache to rebuild: reads hit rows directly). */
|
|
1559
|
+
anyNotifier = new Notifier(() => {});
|
|
1560
|
+
/**
|
|
1561
|
+
* Key-addressed bare observable face (the useProjection resolution path).
|
|
1562
|
+
* Always defined — absence is an `undefined` snapshot, never a missing
|
|
1563
|
+
* face, so a component may subscribe before the key ever carries a value.
|
|
1564
|
+
* @param key - projection key.
|
|
1565
|
+
* @returns the identity-stable face for this key.
|
|
1566
|
+
*/
|
|
1567
|
+
faceOf(key) {
|
|
1568
|
+
return this.channel(key).face;
|
|
1569
|
+
}
|
|
1570
|
+
/**
|
|
1571
|
+
* Current whole value for a key (erased framework read; typed reads go
|
|
1572
|
+
* through `useProjection`'s map lookup).
|
|
1573
|
+
* @param key - projection key.
|
|
1574
|
+
* @returns the value, or undefined while the key is absent.
|
|
1575
|
+
*/
|
|
1576
|
+
get(key) {
|
|
1577
|
+
return this.rows.get(key)?.value;
|
|
1578
|
+
}
|
|
1579
|
+
/**
|
|
1580
|
+
* Read the accepted Host watermark without subscribing or copying a value.
|
|
1581
|
+
* @param key - projection key.
|
|
1582
|
+
* @returns the current sequence, or undefined for absent and cached values.
|
|
1583
|
+
*/
|
|
1584
|
+
seqOf(key) {
|
|
1585
|
+
const row = this.rows.get(key);
|
|
1586
|
+
return row?.kind === "sequenced" ? row.seq : void 0;
|
|
1587
|
+
}
|
|
1588
|
+
/**
|
|
1589
|
+
* Read every current projection value as one reference-stable snapshot.
|
|
1590
|
+
* @returns The same frozen value map until a row changes.
|
|
1591
|
+
*/
|
|
1592
|
+
values() {
|
|
1593
|
+
if (this.valuesCache === void 0) this.valuesCache = Object.freeze(Object.fromEntries([...this.rows].map(([key, row]) => [key, row.value])));
|
|
1594
|
+
return this.valuesCache;
|
|
1595
|
+
}
|
|
1596
|
+
/**
|
|
1597
|
+
* Subscribe to any-key changes (microtask-batched) — the manager's list
|
|
1598
|
+
* rebuild channel.
|
|
1599
|
+
* @param listener - change callback.
|
|
1600
|
+
* @returns the unsubscribe function.
|
|
1601
|
+
*/
|
|
1602
|
+
subscribeAny(listener) {
|
|
1603
|
+
return this.anyNotifier.subscribe(listener);
|
|
1604
|
+
}
|
|
1605
|
+
/**
|
|
1606
|
+
* Apply one finished value from the Session control stream.
|
|
1607
|
+
* @param key - projection key.
|
|
1608
|
+
* @param value - whole value computed by the host unit.
|
|
1609
|
+
* @param seq - the unit's watermark at emission.
|
|
1610
|
+
*/
|
|
1611
|
+
apply(key, value, seq) {
|
|
1612
|
+
const row = this.rows.get(key);
|
|
1613
|
+
if (row?.kind === "sequenced" && seq <= row.seq) return;
|
|
1614
|
+
this.rows.set(key, {
|
|
1615
|
+
kind: "sequenced",
|
|
1616
|
+
value,
|
|
1617
|
+
seq
|
|
1618
|
+
});
|
|
1619
|
+
this.changed(key);
|
|
1620
|
+
}
|
|
1621
|
+
/**
|
|
1622
|
+
* Fill keys from a Host block labeled `cached`: a zero-I/O
|
|
1623
|
+
* view of the persisted checkpoint. A cached value lands only where no
|
|
1624
|
+
* sequenced row exists: a connected Session has already answered for such
|
|
1625
|
+
* a key, and the list's view of the persisted checkpoint cannot be newer
|
|
1626
|
+
* than it.
|
|
1627
|
+
* @param values - whole values by key viewed from the persisted checkpoint.
|
|
1628
|
+
*/
|
|
1629
|
+
applyCached(values) {
|
|
1630
|
+
for (const key of Object.keys(values)) {
|
|
1631
|
+
if (this.rows.get(key)?.kind === "sequenced") continue;
|
|
1632
|
+
this.rows.set(key, {
|
|
1633
|
+
kind: "cached",
|
|
1634
|
+
value: values[key]
|
|
1635
|
+
});
|
|
1636
|
+
this.changed(key);
|
|
1637
|
+
}
|
|
1638
|
+
}
|
|
1639
|
+
/**
|
|
1640
|
+
* Seed from a history tail page's projections block. Every cached row is
|
|
1641
|
+
* discarded first, regardless of seq: the block comes from the connected
|
|
1642
|
+
* Session, and a value viewed from the persisted checkpoint never outranks
|
|
1643
|
+
* it. Then every carried key lands under the same seq rule as frames, and a
|
|
1644
|
+
* key the block omits is capability-absent as of the cut — its row clears
|
|
1645
|
+
* unless a newer frame already superseded the cut (a stale baseline can
|
|
1646
|
+
* neither overwrite nor clear newer sequenced values).
|
|
1647
|
+
* @param baseline - the response's projections block.
|
|
1648
|
+
*/
|
|
1649
|
+
seed(baseline) {
|
|
1650
|
+
for (const [key, row] of this.rows) {
|
|
1651
|
+
if (row.kind !== "cached") continue;
|
|
1652
|
+
this.rows.delete(key);
|
|
1653
|
+
this.changed(key);
|
|
1654
|
+
}
|
|
1655
|
+
const values = baseline.values;
|
|
1656
|
+
for (const key of Object.keys(values)) this.apply(key, values[key], baseline.asOfSeq);
|
|
1657
|
+
for (const [key, row] of this.rows) {
|
|
1658
|
+
if (Object.hasOwn(values, key)) continue;
|
|
1659
|
+
if (row.kind === "sequenced" && row.seq > baseline.asOfSeq) continue;
|
|
1660
|
+
this.rows.delete(key);
|
|
1661
|
+
this.changed(key);
|
|
1662
|
+
}
|
|
1663
|
+
}
|
|
1664
|
+
/** Discard one Host generation's values and watermarks while preserving subscribed faces. */
|
|
1665
|
+
clear() {
|
|
1666
|
+
for (const key of this.rows.keys()) {
|
|
1667
|
+
this.rows.delete(key);
|
|
1668
|
+
this.changed(key);
|
|
1669
|
+
}
|
|
1670
|
+
}
|
|
1671
|
+
changed(key) {
|
|
1672
|
+
this.valuesCache = void 0;
|
|
1673
|
+
this.channels.get(key)?.notifier.markDirty();
|
|
1674
|
+
this.anyNotifier.markDirty();
|
|
1675
|
+
}
|
|
1676
|
+
channel(key) {
|
|
1677
|
+
let channel = this.channels.get(key);
|
|
1678
|
+
if (channel === void 0) {
|
|
1679
|
+
const notifier = new Notifier(() => {});
|
|
1680
|
+
channel = {
|
|
1681
|
+
notifier,
|
|
1682
|
+
face: {
|
|
1683
|
+
getSnapshot: () => this.rows.get(key)?.value,
|
|
1684
|
+
subscribe: (listener) => notifier.subscribe(listener)
|
|
1685
|
+
}
|
|
1686
|
+
};
|
|
1687
|
+
this.channels.set(key, channel);
|
|
1688
|
+
}
|
|
1689
|
+
return channel;
|
|
1690
|
+
}
|
|
1691
|
+
};
|
|
1692
|
+
//#endregion
|
|
1693
|
+
//#region ../../util/crypto/lib/index.js
|
|
1694
|
+
/**
|
|
1695
|
+
* Random v4 UUID, minted from `crypto.getRandomValues`.
|
|
1696
|
+
* @returns the UUID string.
|
|
1697
|
+
*/
|
|
1698
|
+
function randomUUID() {
|
|
1699
|
+
const bytes = globalThis.crypto.getRandomValues(new Uint8Array(16));
|
|
1700
|
+
const hex = Array.from(bytes, (byte, index) => {
|
|
1701
|
+
return (index === 6 ? byte & 15 | 64 : index === 8 ? byte & 63 | 128 : byte).toString(16).padStart(2, "0");
|
|
1702
|
+
}).join("");
|
|
1703
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
1704
|
+
}
|
|
1705
|
+
//#endregion
|
|
1706
|
+
//#region lib/types/client/contract/events.js
|
|
1707
|
+
/** Observable contiguous Session event window consumed by domain assemblers. */
|
|
1708
|
+
function leaf(entries) {
|
|
1709
|
+
return {
|
|
1710
|
+
kind: "leaf",
|
|
1711
|
+
entries,
|
|
1712
|
+
length: entries.length
|
|
1713
|
+
};
|
|
1714
|
+
}
|
|
1715
|
+
function concat(left, right) {
|
|
1716
|
+
return {
|
|
1717
|
+
kind: "concat",
|
|
1718
|
+
left,
|
|
1719
|
+
right,
|
|
1720
|
+
length: left.length + right.length
|
|
1721
|
+
};
|
|
1722
|
+
}
|
|
1723
|
+
function materialize(node) {
|
|
1724
|
+
if (node.kind === "leaf") return node.entries;
|
|
1725
|
+
const entries = new Array(node.length);
|
|
1726
|
+
const pending = [node];
|
|
1727
|
+
let index = 0;
|
|
1728
|
+
while (pending.length > 0) {
|
|
1729
|
+
const current = pending.pop();
|
|
1730
|
+
if (current.kind === "concat") {
|
|
1731
|
+
pending.push(current.right, current.left);
|
|
1732
|
+
continue;
|
|
1733
|
+
}
|
|
1734
|
+
for (const entry of current.entries) {
|
|
1735
|
+
entries[index] = entry;
|
|
1736
|
+
index += 1;
|
|
1737
|
+
}
|
|
1738
|
+
}
|
|
1739
|
+
return entries;
|
|
1740
|
+
}
|
|
1741
|
+
function windowSnapshot(node, hasMore, revision, change) {
|
|
1742
|
+
let entries;
|
|
1743
|
+
return {
|
|
1744
|
+
get entries() {
|
|
1745
|
+
entries ??= materialize(node);
|
|
1746
|
+
return entries;
|
|
1747
|
+
},
|
|
1748
|
+
hasMore,
|
|
1749
|
+
revision,
|
|
1750
|
+
change
|
|
1751
|
+
};
|
|
1752
|
+
}
|
|
1753
|
+
/** Session-owned event feed; every accepted window mutation publishes synchronously. */
|
|
1754
|
+
var MutableSessionEventSource = class {
|
|
1755
|
+
listeners = /* @__PURE__ */ new Set();
|
|
1756
|
+
window = leaf([]);
|
|
1757
|
+
snapshot = windowSnapshot(this.window, false, 0, {
|
|
1758
|
+
kind: "replace",
|
|
1759
|
+
entries: []
|
|
1760
|
+
});
|
|
1761
|
+
/** @returns the cached event-window snapshot. */
|
|
1762
|
+
getSnapshot() {
|
|
1763
|
+
return this.snapshot;
|
|
1764
|
+
}
|
|
1765
|
+
/**
|
|
1766
|
+
* Subscribe to synchronous window publication.
|
|
1767
|
+
* @param listener - invalidation callback.
|
|
1768
|
+
* @returns unsubscribe function.
|
|
1769
|
+
*/
|
|
1770
|
+
subscribe(listener) {
|
|
1771
|
+
this.listeners.add(listener);
|
|
1772
|
+
return () => {
|
|
1773
|
+
this.listeners.delete(listener);
|
|
1774
|
+
};
|
|
1775
|
+
}
|
|
1776
|
+
/**
|
|
1777
|
+
* Replace the complete contiguous window.
|
|
1778
|
+
* @param entries - complete window.
|
|
1779
|
+
* @param hasMore - whether older history remains.
|
|
1780
|
+
*/
|
|
1781
|
+
replace(entries, hasMore) {
|
|
1782
|
+
this.window = leaf(entries);
|
|
1783
|
+
this.publish(hasMore, {
|
|
1784
|
+
kind: "replace",
|
|
1785
|
+
entries
|
|
1786
|
+
});
|
|
1787
|
+
}
|
|
1788
|
+
/**
|
|
1789
|
+
* Prepend one older contiguous page.
|
|
1790
|
+
* @param entries - newly loaded older entries.
|
|
1791
|
+
* @param hasMore - whether still older history remains.
|
|
1792
|
+
*/
|
|
1793
|
+
prepend(entries, hasMore) {
|
|
1794
|
+
this.window = concat(leaf(entries), this.window);
|
|
1795
|
+
this.publish(hasMore, {
|
|
1796
|
+
kind: "prepend",
|
|
1797
|
+
entries
|
|
1798
|
+
});
|
|
1799
|
+
}
|
|
1800
|
+
/**
|
|
1801
|
+
* Append one contiguous live entry.
|
|
1802
|
+
* @param entry - live tail entry.
|
|
1803
|
+
*/
|
|
1804
|
+
append(entry) {
|
|
1805
|
+
const entries = [entry];
|
|
1806
|
+
this.window = concat(this.window, leaf(entries));
|
|
1807
|
+
this.publish(this.snapshot.hasMore, {
|
|
1808
|
+
kind: "append",
|
|
1809
|
+
entries
|
|
1810
|
+
});
|
|
1811
|
+
}
|
|
1812
|
+
/**
|
|
1813
|
+
* Replace one attempt's transient rows with its committed durable settlement.
|
|
1814
|
+
* @param attemptId - process-local attempt whose live rows are now redundant.
|
|
1815
|
+
* @param entry - durable settlement committed for that attempt.
|
|
1816
|
+
*/
|
|
1817
|
+
settleAssistant(attemptId, entry) {
|
|
1818
|
+
const entries = materialize(this.window).filter((candidate) => candidate.type !== "transient" || candidate.event.data.attemptId !== attemptId);
|
|
1819
|
+
if (entry !== void 0) {
|
|
1820
|
+
const index = entries.findIndex((candidate) => candidate.event.seq > entry.event.seq);
|
|
1821
|
+
if (index < 0) entries.push(entry);
|
|
1822
|
+
else entries.splice(index, 0, entry);
|
|
1823
|
+
}
|
|
1824
|
+
this.window = leaf(entries);
|
|
1825
|
+
this.publish(this.snapshot.hasMore, {
|
|
1826
|
+
kind: "settle-assistant",
|
|
1827
|
+
attemptId,
|
|
1828
|
+
...entry === void 0 ? {} : { entry }
|
|
1829
|
+
});
|
|
1830
|
+
}
|
|
1831
|
+
publish(hasMore, change) {
|
|
1832
|
+
this.snapshot = windowSnapshot(this.window, hasMore, this.snapshot.revision + 1, change);
|
|
1833
|
+
(0, _unieai_rabi_client_store.notifySubscribers)(this.listeners, "[session-controller] event feed");
|
|
1834
|
+
}
|
|
1835
|
+
};
|
|
1836
|
+
//#endregion
|
|
1837
|
+
//#region lib/types/client/time-zone.js
|
|
1838
|
+
/** Browser-owned time-zone sampling for one prompt RPC. */
|
|
1839
|
+
/**
|
|
1840
|
+
* Resolve the current browser IANA zone for one outbound operation.
|
|
1841
|
+
* @returns The browser-provided canonical zone.
|
|
1842
|
+
* @throws when the runtime cannot provide a non-empty zone.
|
|
1843
|
+
*/
|
|
1844
|
+
function resolvedClientTimeZone() {
|
|
1845
|
+
const timeZone = new Intl.DateTimeFormat().resolvedOptions().timeZone;
|
|
1846
|
+
if (typeof timeZone !== "string" || timeZone.length === 0) throw new Error("browser time zone is unavailable");
|
|
1847
|
+
return timeZone;
|
|
1848
|
+
}
|
|
1849
|
+
//#endregion
|
|
1850
|
+
//#region ../../llm/llm/lib/types/assistant-stream.js
|
|
1851
|
+
/**
|
|
1852
|
+
* Lossless compact representation of one model-stream attempt, plus record-level
|
|
1853
|
+
* readers that answer common consumer questions without materializing members.
|
|
1854
|
+
* Readers trust the static record type; expandAssistantStream is the validating
|
|
1855
|
+
* path for records read at a durable boundary.
|
|
1856
|
+
*/
|
|
1857
|
+
function safeTime(value) {
|
|
1858
|
+
if (!Number.isSafeInteger(value)) throw new TypeError(`Assistant stream time must be a safe integer, got ${String(value)}`);
|
|
1859
|
+
return value;
|
|
1860
|
+
}
|
|
1861
|
+
function safeIndex(value, label) {
|
|
1862
|
+
if (!Number.isSafeInteger(value) || value < 0 || Object.is(value, -0)) throw new TypeError(`${label} index must be a non-negative safe integer`);
|
|
1863
|
+
return value;
|
|
1864
|
+
}
|
|
1865
|
+
function snapshotChunk(chunk) {
|
|
1866
|
+
const snapshot = snapshotJsonValue(chunk);
|
|
1867
|
+
if (snapshot === void 0) throw new TypeError("Assistant stream chunk must be losslessly JSON-serializable");
|
|
1868
|
+
return snapshot;
|
|
1869
|
+
}
|
|
1870
|
+
/**
|
|
1871
|
+
* Expand compact records into the exact timed chunk sequence.
|
|
1872
|
+
* @param stream - compact records from one durable Assistant settlement.
|
|
1873
|
+
* @returns detached timed chunks with every original delta boundary preserved.
|
|
1874
|
+
* @throws {TypeError} when a record or reconstructed timestamp is invalid.
|
|
1875
|
+
*/
|
|
1876
|
+
function expandAssistantStream(stream) {
|
|
1877
|
+
const chunks = [];
|
|
1878
|
+
for (const candidate of stream) {
|
|
1879
|
+
const record = validateRecord(candidate);
|
|
1880
|
+
if (record.type === "chunk") {
|
|
1881
|
+
chunks.push({
|
|
1882
|
+
time: record.time,
|
|
1883
|
+
chunk: record.chunk
|
|
1884
|
+
});
|
|
1885
|
+
continue;
|
|
1886
|
+
}
|
|
1887
|
+
const members = record.type === "tool-call-chunks" ? record.args : record.texts;
|
|
1888
|
+
let time = record.time0;
|
|
1889
|
+
for (let index = 0; index < members.length; index += 1) {
|
|
1890
|
+
if (index > 0) time += record.dt[index - 1];
|
|
1891
|
+
let chunk;
|
|
1892
|
+
if (record.type === "text-chunks") chunk = {
|
|
1893
|
+
type: "text-delta",
|
|
1894
|
+
index: record.index,
|
|
1895
|
+
text: members[index]
|
|
1896
|
+
};
|
|
1897
|
+
else if (record.type === "reasoning-chunks") chunk = {
|
|
1898
|
+
type: "reasoning-delta",
|
|
1899
|
+
index: record.index,
|
|
1900
|
+
text: members[index]
|
|
1901
|
+
};
|
|
1902
|
+
else chunk = {
|
|
1903
|
+
type: "tool-call-delta",
|
|
1904
|
+
index: record.index,
|
|
1905
|
+
id: record.id,
|
|
1906
|
+
...Object.hasOwn(record, "name") ? { name: record.name } : {},
|
|
1907
|
+
argumentsDelta: members[index]
|
|
1908
|
+
};
|
|
1909
|
+
chunks.push({
|
|
1910
|
+
time,
|
|
1911
|
+
chunk
|
|
1912
|
+
});
|
|
1913
|
+
}
|
|
1914
|
+
}
|
|
1915
|
+
return chunks;
|
|
1916
|
+
}
|
|
1917
|
+
function validateRecord(value) {
|
|
1918
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError("Assistant stream record must be an object");
|
|
1919
|
+
const record = value;
|
|
1920
|
+
switch (record.type) {
|
|
1921
|
+
case "text-chunks":
|
|
1922
|
+
case "reasoning-chunks": {
|
|
1923
|
+
exactKeys(record, [
|
|
1924
|
+
"type",
|
|
1925
|
+
"time0",
|
|
1926
|
+
"index",
|
|
1927
|
+
"dt",
|
|
1928
|
+
"texts"
|
|
1929
|
+
], record.type);
|
|
1930
|
+
const texts = stringArray(record.texts, `${record.type} texts`);
|
|
1931
|
+
if (texts.length === 0) throw new TypeError(`${record.type} texts must be non-empty`);
|
|
1932
|
+
validateRun(record, texts.length, record.type);
|
|
1933
|
+
return record;
|
|
1934
|
+
}
|
|
1935
|
+
case "tool-call-chunks": {
|
|
1936
|
+
exactKeys(record, Object.hasOwn(record, "name") ? [
|
|
1937
|
+
"type",
|
|
1938
|
+
"time0",
|
|
1939
|
+
"index",
|
|
1940
|
+
"dt",
|
|
1941
|
+
"id",
|
|
1942
|
+
"name",
|
|
1943
|
+
"args"
|
|
1944
|
+
] : [
|
|
1945
|
+
"type",
|
|
1946
|
+
"time0",
|
|
1947
|
+
"index",
|
|
1948
|
+
"dt",
|
|
1949
|
+
"id",
|
|
1950
|
+
"args"
|
|
1951
|
+
], record.type);
|
|
1952
|
+
const args = stringArray(record.args, "tool-call-chunks args");
|
|
1953
|
+
if (args.length === 0) throw new TypeError("tool-call-chunks args must be non-empty");
|
|
1954
|
+
if (typeof record.id !== "string" || record.id.length === 0) throw new TypeError("tool-call-chunks id must be a non-empty string");
|
|
1955
|
+
if (record.name !== void 0 && (typeof record.name !== "string" || record.name.length === 0)) throw new TypeError("tool-call-chunks name must be a non-empty string");
|
|
1956
|
+
validateRun(record, args.length, record.type);
|
|
1957
|
+
return record;
|
|
1958
|
+
}
|
|
1959
|
+
case "chunk": {
|
|
1960
|
+
exactKeys(record, [
|
|
1961
|
+
"type",
|
|
1962
|
+
"time",
|
|
1963
|
+
"chunk"
|
|
1964
|
+
], "chunk");
|
|
1965
|
+
const time = safeTime(record.time);
|
|
1966
|
+
if (typeof record.chunk !== "object" || record.chunk === null || Array.isArray(record.chunk)) throw new TypeError("Assistant stream raw chunk must be a lossless JSON object");
|
|
1967
|
+
let chunk;
|
|
1968
|
+
try {
|
|
1969
|
+
chunk = snapshotChunk(record.chunk);
|
|
1970
|
+
} catch (error) {
|
|
1971
|
+
throw new TypeError("Assistant stream raw chunk must be a lossless JSON object", { cause: error });
|
|
1972
|
+
}
|
|
1973
|
+
return deepFreeze({
|
|
1974
|
+
type: "chunk",
|
|
1975
|
+
time,
|
|
1976
|
+
chunk
|
|
1977
|
+
});
|
|
1978
|
+
}
|
|
1979
|
+
default: throw new TypeError(`Unsupported Assistant stream record ${JSON.stringify(record.type)}`);
|
|
1980
|
+
}
|
|
1981
|
+
}
|
|
1982
|
+
function validateRun(record, members, label) {
|
|
1983
|
+
safeTime(record.time0);
|
|
1984
|
+
safeIndex(record.index, label);
|
|
1985
|
+
if (!Array.isArray(record.dt) || record.dt.some((value) => !Number.isSafeInteger(value))) throw new TypeError(`${label} dt must contain safe integers`);
|
|
1986
|
+
if (record.dt.length !== members - 1) throw new TypeError(`${label} dt length must be one less than its members`);
|
|
1987
|
+
let time = record.time0;
|
|
1988
|
+
for (const gap of record.dt) {
|
|
1989
|
+
time += gap;
|
|
1990
|
+
if (!Number.isSafeInteger(time)) throw new TypeError(`${label} member times must stay safe integers`);
|
|
1991
|
+
}
|
|
1992
|
+
}
|
|
1993
|
+
function stringArray(value, label) {
|
|
1994
|
+
if (!Array.isArray(value) || value.some((member) => typeof member !== "string")) throw new TypeError(`${label} must be a string array`);
|
|
1995
|
+
return value;
|
|
1996
|
+
}
|
|
1997
|
+
function exactKeys(record, keys, label) {
|
|
1998
|
+
if (Object.keys(record).length !== keys.length || !keys.every((key) => Object.hasOwn(record, key))) throw new TypeError(`${label} Assistant stream record must contain exactly ${keys.join(", ")}`);
|
|
1999
|
+
}
|
|
2000
|
+
//#endregion
|
|
2001
|
+
//#region lib/types/client/sessions/assistant-stream.js
|
|
2002
|
+
/** Web presentation fold joining transient Assistant frames to one durable v2 settlement. */
|
|
2003
|
+
/** Keeps transient Assistant presentation behind one settlement-aware interface. */
|
|
2004
|
+
var ClientAssistantStream = class {
|
|
2005
|
+
activeAttempt;
|
|
2006
|
+
retainedAttempt;
|
|
2007
|
+
pending = /* @__PURE__ */ new Map();
|
|
2008
|
+
publishedSeqs = /* @__PURE__ */ new Set();
|
|
2009
|
+
durableCursor = -1;
|
|
2010
|
+
transientInGap = 0;
|
|
2011
|
+
/**
|
|
2012
|
+
* Replace the durable Web window and adopt an optional reconnect baseline.
|
|
2013
|
+
* @param entries - durable entries in the replacement window.
|
|
2014
|
+
* @param baseline - compact prefix for an Assistant attempt that is still live.
|
|
2015
|
+
* @returns immediately visible durable entries plus reconstructed transient chunks.
|
|
2016
|
+
*/
|
|
2017
|
+
replace(entries, baseline) {
|
|
2018
|
+
this.pending.clear();
|
|
2019
|
+
this.transientInGap = 0;
|
|
2020
|
+
this.activeAttempt = void 0;
|
|
2021
|
+
this.retainedAttempt = void 0;
|
|
2022
|
+
const opening = baseline?.activeAttempt;
|
|
2023
|
+
if (opening !== void 0) this.activeAttempt = {
|
|
2024
|
+
attemptId: opening.attemptId,
|
|
2025
|
+
startedAfterSeq: opening.startedAfterSeq,
|
|
2026
|
+
turn: opening.turn,
|
|
2027
|
+
step: opening.step,
|
|
2028
|
+
nextIndex: opening.nextIndex
|
|
2029
|
+
};
|
|
2030
|
+
const visible = [...entries];
|
|
2031
|
+
this.publishedSeqs = new Set(visible.map((entry) => entry.event.seq));
|
|
2032
|
+
this.durableCursor = visible.reduce((cursor, entry) => Math.max(cursor, entry.event.seq), -1);
|
|
2033
|
+
if (opening !== void 0) for (const [index, member] of expandAssistantStream(opening.stream).entries()) {
|
|
2034
|
+
this.transientInGap += 1;
|
|
2035
|
+
visible.push({
|
|
2036
|
+
type: "transient",
|
|
2037
|
+
event: {
|
|
2038
|
+
type: "assistant/live-chunk",
|
|
2039
|
+
seq: this.durableCursor + 1 - 1 / (this.transientInGap + 1),
|
|
2040
|
+
time: member.time,
|
|
2041
|
+
data: {
|
|
2042
|
+
attemptId: opening.attemptId,
|
|
2043
|
+
turn: opening.turn,
|
|
2044
|
+
step: opening.step,
|
|
2045
|
+
chunk: member.chunk
|
|
2046
|
+
}
|
|
2047
|
+
}
|
|
2048
|
+
});
|
|
2049
|
+
if (index + 1 >= opening.nextIndex) break;
|
|
2050
|
+
}
|
|
2051
|
+
return visible;
|
|
2052
|
+
}
|
|
2053
|
+
/**
|
|
2054
|
+
* Stage one durable v2 settlement while its matching live attempt is open.
|
|
2055
|
+
* @param entry - newly followed durable entry.
|
|
2056
|
+
* @returns a publication decision, or `undefined` when no entry becomes visible.
|
|
2057
|
+
*/
|
|
2058
|
+
acceptDurable(entry) {
|
|
2059
|
+
const event = entry.event;
|
|
2060
|
+
this.durableCursor = Math.max(this.durableCursor, event.seq);
|
|
2061
|
+
this.transientInGap = 0;
|
|
2062
|
+
const settlement = assistantSettlementEntry(entry);
|
|
2063
|
+
if (settlement !== void 0 && this.attemptForSettlement(settlement.event) !== void 0) {
|
|
2064
|
+
if (this.pending.has(event.seq)) return { type: "rebaseline" };
|
|
2065
|
+
this.pending.set(event.seq, settlement);
|
|
2066
|
+
return;
|
|
2067
|
+
}
|
|
2068
|
+
return this.publish(entry);
|
|
2069
|
+
}
|
|
2070
|
+
/**
|
|
2071
|
+
* Fold one dense transient frame and release its named durable settlement.
|
|
2072
|
+
* Successful messages retain their transient rows until the owning Step ends;
|
|
2073
|
+
* interrupted messages, failed attempts, and abandonment retire them immediately.
|
|
2074
|
+
* @param frame - next Assistant stream frame received by the follow connection.
|
|
2075
|
+
* @returns a transient, publication, or rebaseline decision, or `undefined` when no entry becomes visible.
|
|
2076
|
+
*/
|
|
2077
|
+
acceptFrame(frame) {
|
|
2078
|
+
switch (frame.type) {
|
|
2079
|
+
case "start":
|
|
2080
|
+
if (this.activeAttempt !== void 0 || this.retainedAttempt !== void 0 || this.pending.size > 0) return { type: "rebaseline" };
|
|
2081
|
+
this.pending.clear();
|
|
2082
|
+
this.activeAttempt = {
|
|
2083
|
+
attemptId: frame.attemptId,
|
|
2084
|
+
startedAfterSeq: frame.startedAfterSeq,
|
|
2085
|
+
turn: frame.turn,
|
|
2086
|
+
step: frame.step,
|
|
2087
|
+
nextIndex: 0
|
|
2088
|
+
};
|
|
2089
|
+
return;
|
|
2090
|
+
case "chunk": {
|
|
2091
|
+
const attempt = this.activeAttempt;
|
|
2092
|
+
if (attempt === void 0 || attempt.attemptId !== frame.attemptId) return void 0;
|
|
2093
|
+
if (frame.index !== attempt.nextIndex) return { type: "rebaseline" };
|
|
2094
|
+
attempt.nextIndex += 1;
|
|
2095
|
+
this.transientInGap += 1;
|
|
2096
|
+
return {
|
|
2097
|
+
type: "transient",
|
|
2098
|
+
entry: {
|
|
2099
|
+
type: "transient",
|
|
2100
|
+
event: {
|
|
2101
|
+
type: "assistant/live-chunk",
|
|
2102
|
+
seq: this.durableCursor + 1 - 1 / (this.transientInGap + 1),
|
|
2103
|
+
time: frame.time,
|
|
2104
|
+
data: {
|
|
2105
|
+
attemptId: frame.attemptId,
|
|
2106
|
+
turn: attempt.turn,
|
|
2107
|
+
step: attempt.step,
|
|
2108
|
+
chunk: frame.chunk
|
|
2109
|
+
}
|
|
2110
|
+
}
|
|
2111
|
+
}
|
|
2112
|
+
};
|
|
2113
|
+
}
|
|
2114
|
+
case "end": {
|
|
2115
|
+
const attempt = this.activeAttempt;
|
|
2116
|
+
if (attempt === void 0 || attempt.attemptId !== frame.attemptId) return;
|
|
2117
|
+
this.activeAttempt = void 0;
|
|
2118
|
+
if (frame.index !== attempt.nextIndex) return { type: "rebaseline" };
|
|
2119
|
+
if (frame.outcome.kind === "abandoned") return this.pending.size === 0 ? {
|
|
2120
|
+
type: "abandonment",
|
|
2121
|
+
attemptId: attempt.attemptId
|
|
2122
|
+
} : { type: "rebaseline" };
|
|
2123
|
+
if (this.publishedSeqs.has(frame.outcome.seq)) return void 0;
|
|
2124
|
+
const entry = this.pending.get(frame.outcome.seq);
|
|
2125
|
+
if (entry === void 0 || entry.event.type !== frame.outcome.eventType) return { type: "rebaseline" };
|
|
2126
|
+
this.pending.delete(frame.outcome.seq);
|
|
2127
|
+
if (entry.event.type === "assistant/message" && entry.event.data.interrupted !== true) {
|
|
2128
|
+
this.retainedAttempt = {
|
|
2129
|
+
attemptId: attempt.attemptId,
|
|
2130
|
+
turn: attempt.turn,
|
|
2131
|
+
step: attempt.step
|
|
2132
|
+
};
|
|
2133
|
+
return this.publish(entry);
|
|
2134
|
+
}
|
|
2135
|
+
this.publishedSeqs.add(entry.event.seq);
|
|
2136
|
+
return {
|
|
2137
|
+
type: "settlement",
|
|
2138
|
+
attemptId: attempt.attemptId,
|
|
2139
|
+
entry
|
|
2140
|
+
};
|
|
2141
|
+
}
|
|
2142
|
+
}
|
|
2143
|
+
}
|
|
2144
|
+
attemptForSettlement(event) {
|
|
2145
|
+
const attempt = this.activeAttempt;
|
|
2146
|
+
if (attempt === void 0 || event.type === "assistant/message" && event.surfaceOp !== "append" || event.seq <= attempt.startedAfterSeq || attempt.turn !== event.data.turn || attempt.step !== event.data.step) return void 0;
|
|
2147
|
+
return attempt;
|
|
2148
|
+
}
|
|
2149
|
+
publish(entry) {
|
|
2150
|
+
this.publishedSeqs.add(entry.event.seq);
|
|
2151
|
+
const retained = this.retainedAttempt;
|
|
2152
|
+
if (retained !== void 0 && entry.event.type === "step/end" && entry.event.data.turn === retained.turn && entry.event.data.step === retained.step) {
|
|
2153
|
+
this.retainedAttempt = void 0;
|
|
2154
|
+
return {
|
|
2155
|
+
type: "publish",
|
|
2156
|
+
entry,
|
|
2157
|
+
retireAttemptId: retained.attemptId
|
|
2158
|
+
};
|
|
2159
|
+
}
|
|
2160
|
+
return {
|
|
2161
|
+
type: "publish",
|
|
2162
|
+
entry
|
|
2163
|
+
};
|
|
2164
|
+
}
|
|
2165
|
+
};
|
|
2166
|
+
function assistantSettlementEntry(entry) {
|
|
2167
|
+
return entry.event.type === "assistant/message" || entry.event.type === "assistant/attempt" ? entry : void 0;
|
|
2168
|
+
}
|
|
2169
|
+
//#endregion
|
|
2170
|
+
//#region lib/types/client/sessions/session.js
|
|
2171
|
+
function projectionsBaseline(value) {
|
|
2172
|
+
return {
|
|
2173
|
+
...value,
|
|
2174
|
+
asOfSeq: value.asOfSeq === -1 ? -1 : SessionSeq(value.asOfSeq)
|
|
2175
|
+
};
|
|
2176
|
+
}
|
|
2177
|
+
const HISTORY_PAGE_OPTIONS = {
|
|
2178
|
+
maxMessages: 500,
|
|
2179
|
+
turnWindow: {
|
|
2180
|
+
minMessages: 50,
|
|
2181
|
+
minTurns: 2
|
|
2182
|
+
}
|
|
2183
|
+
};
|
|
2184
|
+
const JUMP_PAGE_OPTIONS = {
|
|
2185
|
+
...HISTORY_PAGE_OPTIONS,
|
|
2186
|
+
turnWindow: {
|
|
2187
|
+
...HISTORY_PAGE_OPTIONS.turnWindow,
|
|
2188
|
+
minMessages: 200
|
|
2189
|
+
}
|
|
2190
|
+
};
|
|
2191
|
+
/**
|
|
2192
|
+
* Owns a session's event window, lifecycle state, and observable
|
|
2193
|
+
* snapshot. React bindings remain outside this data layer. Features see only
|
|
2194
|
+
* the {@link SessionFace} slice (ISession verbs + the snapshot source); the
|
|
2195
|
+
* remaining public members are Session Controller internals.
|
|
2196
|
+
*/
|
|
2197
|
+
var Session = class {
|
|
2198
|
+
sessionId;
|
|
2199
|
+
remote;
|
|
2200
|
+
options;
|
|
2201
|
+
baseSeq = SessionLogOffset(0);
|
|
2202
|
+
hasMore = false;
|
|
2203
|
+
openState = "cold";
|
|
2204
|
+
openError = null;
|
|
2205
|
+
openPromise = null;
|
|
2206
|
+
/** Bumped by stream replacement to invalidate an in-flight doOpen. Stale
|
|
2207
|
+
* passes drop all writes once the generation moves on. */
|
|
2208
|
+
openGeneration = 0;
|
|
2209
|
+
loadingOlder = false;
|
|
2210
|
+
/** Shared low-water target of the running jump loop; null when no jump is paging. */
|
|
2211
|
+
jumpTargetSeq = null;
|
|
2212
|
+
/** The running jump loop's completion, shared by retargeting callers. */
|
|
2213
|
+
jumpPromise = null;
|
|
2214
|
+
pendingHistory = null;
|
|
2215
|
+
stopObservingInbox;
|
|
2216
|
+
assistantStream = new ClientAssistantStream();
|
|
2217
|
+
running = false;
|
|
2218
|
+
address;
|
|
2219
|
+
parentAvailable;
|
|
2220
|
+
/**
|
|
2221
|
+
* Sticky send marker, private input of the composerPhase derivation: set
|
|
2222
|
+
* synchronously before prompt()'s first await, never reset — the blank →
|
|
2223
|
+
* engaging edge of the phase machine (see ComposerPhase).
|
|
2224
|
+
*/
|
|
2225
|
+
promptAttempted = false;
|
|
2226
|
+
/** A first accepted prompt stays in the engaging phase until its turn is observable. */
|
|
2227
|
+
firstPromptPendingTurn = false;
|
|
2228
|
+
/** New Session display state; unknown bare sessions begin conservatively blank. */
|
|
2229
|
+
blankBit = true;
|
|
2230
|
+
removed = false;
|
|
2231
|
+
promptError = null;
|
|
2232
|
+
lastAgentError = null;
|
|
2233
|
+
/** Local submission echoes, insertion-ordered (see SessionSnapshot.pendingSubmissions). */
|
|
2234
|
+
pendingSubmissions = [];
|
|
2235
|
+
/** Per-echo settlement state; `retiring` latches the first observation so a
|
|
2236
|
+
* Inbox projection and its durable event cannot both retire one echo. */
|
|
2237
|
+
submissionSettlements = /* @__PURE__ */ new Map();
|
|
2238
|
+
/** Owns the addressed page/follow lifecycle while this Session is open. */
|
|
2239
|
+
events;
|
|
2240
|
+
/**
|
|
2241
|
+
* Per-session projection value store (push model; see the session-projection
|
|
2242
|
+
* subsystem page, docs/subsystems/session-projection.md): finished whole
|
|
2243
|
+
* values computed on the Host, seeded by the tail page's
|
|
2244
|
+
* projections block and updated by Session Controller control frames;
|
|
2245
|
+
* Host-sequenced writes merge under higher-seq-wins and cached list blocks
|
|
2246
|
+
* yield to them (projection-store.ts). Keys are read via `projections.faceOf(key)`
|
|
2247
|
+
* (the useProjection resolution face); the conversation snapshot never
|
|
2248
|
+
* carries projection values, and no client-side domain folding exists.
|
|
2249
|
+
* Manager-owned when constructed through SessionManager (frames route and
|
|
2250
|
+
* the store outlives instantiation, the title-snapshot precedent); a bare
|
|
2251
|
+
* construction gets a private store.
|
|
2252
|
+
*/
|
|
2253
|
+
projections;
|
|
2254
|
+
/** Contiguous history and live tail consumed by Conversation assembly. */
|
|
2255
|
+
eventSource = new MutableSessionEventSource();
|
|
2256
|
+
snapshotCache;
|
|
2257
|
+
notifier;
|
|
2258
|
+
/**
|
|
2259
|
+
* Agent-scoped cordis context, bound once by ClientSessions when it
|
|
2260
|
+
* mints the scope (the client mirror of the host Agent's loopCtx). The
|
|
2261
|
+
* Session dispatches its own scoped events through it; undefined means
|
|
2262
|
+
* unbound (bare object-layer construction) or already pruned — both skip
|
|
2263
|
+
* dispatch-dependent behavior rather than fail.
|
|
2264
|
+
*/
|
|
2265
|
+
actx;
|
|
2266
|
+
/**
|
|
2267
|
+
* @param sessionId - Host session identity (client sessions are always Host-born).
|
|
2268
|
+
* @param remote - generated Remote namespaces this session calls.
|
|
2269
|
+
* @param options - optional manager-owned state observers.
|
|
2270
|
+
*/
|
|
2271
|
+
constructor(sessionId, remote, options = {}) {
|
|
2272
|
+
this.sessionId = sessionId;
|
|
2273
|
+
this.remote = remote;
|
|
2274
|
+
this.options = options;
|
|
2275
|
+
this.projections = options.projections ?? new ProjectionValueStore();
|
|
2276
|
+
this.address = options.address;
|
|
2277
|
+
this.parentAvailable = options.parentAvailable;
|
|
2278
|
+
this.notifier = new Notifier(() => {
|
|
2279
|
+
this.snapshotCache = this.buildSnapshot();
|
|
2280
|
+
});
|
|
2281
|
+
this.snapshotCache = this.buildSnapshot();
|
|
2282
|
+
this.stopObservingInbox = this.projections.faceOf("inbox").subscribe(() => {
|
|
2283
|
+
this.observeSubmissionInbox();
|
|
2284
|
+
});
|
|
2285
|
+
}
|
|
2286
|
+
/**
|
|
2287
|
+
* Bind the Agent-scoped context minted by ClientSessions (single write;
|
|
2288
|
+
* a second bind is a wiring error and throws). Direction stays one-way at
|
|
2289
|
+
* this binding boundary: consumers still reach the Session via `sessions.sessionOf`,
|
|
2290
|
+
* while the Session holds its own dispatch point (host Agent.loopCtx
|
|
2291
|
+
* mirror).
|
|
2292
|
+
* @param actx - the agent's scoped context.
|
|
2293
|
+
*/
|
|
2294
|
+
bindScope(actx) {
|
|
2295
|
+
if (this.actx !== void 0) throw new Error(`session ${this.sessionId} already has a bound scope`);
|
|
2296
|
+
this.actx = actx;
|
|
2297
|
+
}
|
|
2298
|
+
/** Release the bound scope at prune time (a later rebind accompanies a freshly minted scope). */
|
|
2299
|
+
unbindScope() {
|
|
2300
|
+
this.actx = void 0;
|
|
2301
|
+
}
|
|
2302
|
+
/**
|
|
2303
|
+
* Register one local submission echo (see the ISession declaration).
|
|
2304
|
+
* Synchronous through markDirty: the echo is in the very next snapshot, so
|
|
2305
|
+
* the conversation can paint it before the caller starts serializing.
|
|
2306
|
+
* @param input - echo content and the optional settlement callback.
|
|
2307
|
+
* @returns the minted identity for {@link prompt} plus the pre-prompt abandon path.
|
|
2308
|
+
*/
|
|
2309
|
+
beginSubmission(input) {
|
|
2310
|
+
const requestId = randomUUID();
|
|
2311
|
+
const placement = this.running ? input.mode === "steer" ? "steering" : "queued" : "transcript";
|
|
2312
|
+
this.pendingSubmissions = [...this.pendingSubmissions, {
|
|
2313
|
+
requestId,
|
|
2314
|
+
placement,
|
|
2315
|
+
time: Date.now(),
|
|
2316
|
+
text: input.text,
|
|
2317
|
+
attachments: input.attachments
|
|
2318
|
+
}];
|
|
2319
|
+
this.submissionSettlements.set(requestId, {
|
|
2320
|
+
placement,
|
|
2321
|
+
onRetire: input.onRetire,
|
|
2322
|
+
retiring: false
|
|
2323
|
+
});
|
|
2324
|
+
this.promptAttempted = true;
|
|
2325
|
+
this.notifier.markDirty();
|
|
2326
|
+
return {
|
|
2327
|
+
requestId,
|
|
2328
|
+
abandon: () => {
|
|
2329
|
+
this.retireFailedSubmission(requestId);
|
|
2330
|
+
}
|
|
2331
|
+
};
|
|
2332
|
+
}
|
|
2333
|
+
/**
|
|
2334
|
+
* Send (queue/steer passed through 1:1); failures land in the snapshot's promptError.
|
|
2335
|
+
* @param content - text, browser-owned temporary image uploads, and staged-file receipts.
|
|
2336
|
+
* @param mode - queue appends after the current turn; steer interrupts it.
|
|
2337
|
+
* @param signal - optional caller cancellation for the complete admission round-trip.
|
|
2338
|
+
* @param requestId - identity from {@link beginSubmission}; a failed identified prompt retires its echo.
|
|
2339
|
+
* @returns the prompt result (also mirrored into promptError on failure).
|
|
2340
|
+
*/
|
|
2341
|
+
async prompt(content, mode, signal, requestId) {
|
|
2342
|
+
this.promptError = null;
|
|
2343
|
+
this.lastAgentError = null;
|
|
2344
|
+
this.promptAttempted = true;
|
|
2345
|
+
if (this.blankBit) this.firstPromptPendingTurn = true;
|
|
2346
|
+
this.notifier.markDirty();
|
|
2347
|
+
let result;
|
|
2348
|
+
if (this.address === void 0) {
|
|
2349
|
+
const clientTimeZone = resolvedClientTimeZone();
|
|
2350
|
+
result = await this.remote.session.prompt({
|
|
2351
|
+
requestId: requestId ?? randomUUID(),
|
|
2352
|
+
sessionId: this.sessionId,
|
|
2353
|
+
mode,
|
|
2354
|
+
content,
|
|
2355
|
+
clientTimeZone
|
|
2356
|
+
}, signal);
|
|
2357
|
+
} else if (content.some((part) => part.type === "file")) result = {
|
|
2358
|
+
ok: false,
|
|
2359
|
+
error: new RemoteError("subagent/attachment-invalid", "subagent continuation does not accept files", { reason: "SUBAGENT_FILE_UNSUPPORTED" })
|
|
2360
|
+
};
|
|
2361
|
+
else {
|
|
2362
|
+
const routedContent = content;
|
|
2363
|
+
const routed = await this.remote.subagents.prompt({
|
|
2364
|
+
requestId: requestId ?? randomUUID(),
|
|
2365
|
+
parentSessionId: this.address.parentSessionId,
|
|
2366
|
+
childSessionId: this.address.childSessionId,
|
|
2367
|
+
mode: "continuable",
|
|
2368
|
+
delivery: mode,
|
|
2369
|
+
content: routedContent,
|
|
2370
|
+
clientTimeZone: resolvedClientTimeZone()
|
|
2371
|
+
}, signal);
|
|
2372
|
+
result = routed.ok ? {
|
|
2373
|
+
ok: true,
|
|
2374
|
+
value: { accepted: true }
|
|
2375
|
+
} : routed;
|
|
2376
|
+
}
|
|
2377
|
+
if (!result.ok) {
|
|
2378
|
+
if (requestId !== void 0) this.retireFailedSubmission(requestId);
|
|
2379
|
+
this.promptError = {
|
|
2380
|
+
op: "send",
|
|
2381
|
+
error: result.error
|
|
2382
|
+
};
|
|
2383
|
+
this.notifier.markDirty();
|
|
2384
|
+
return result;
|
|
2385
|
+
}
|
|
2386
|
+
if (this.blankBit) {
|
|
2387
|
+
this.blankBit = false;
|
|
2388
|
+
this.notifier.markDirty();
|
|
2389
|
+
}
|
|
2390
|
+
this.options.onEngaged?.(this);
|
|
2391
|
+
return result;
|
|
2392
|
+
}
|
|
2393
|
+
/**
|
|
2394
|
+
* Resolve one image referenced by this session into browser-consumable bytes.
|
|
2395
|
+
* @param attachmentId - opaque id found in the folded session log.
|
|
2396
|
+
* @returns the authenticated reference and decoded bytes.
|
|
2397
|
+
*/
|
|
2398
|
+
async readAttachment(attachmentId) {
|
|
2399
|
+
const result = await this.remote.session.attachment({
|
|
2400
|
+
sessionId: this.sessionId,
|
|
2401
|
+
attachmentId
|
|
2402
|
+
});
|
|
2403
|
+
if (!result.ok) return result;
|
|
2404
|
+
const binary = atob(result.value.data);
|
|
2405
|
+
const data = Uint8Array.from(binary, (char) => char.charCodeAt(0));
|
|
2406
|
+
return {
|
|
2407
|
+
ok: true,
|
|
2408
|
+
value: {
|
|
2409
|
+
attachment: result.value.attachment,
|
|
2410
|
+
data
|
|
2411
|
+
}
|
|
2412
|
+
};
|
|
2413
|
+
}
|
|
2414
|
+
/** Apply one operation to a still-pending queue occurrence. */
|
|
2415
|
+
async updateQueue(itemId, action) {
|
|
2416
|
+
return this.remote.session.updateQueue({
|
|
2417
|
+
sessionId: this.sessionId,
|
|
2418
|
+
itemId,
|
|
2419
|
+
action
|
|
2420
|
+
});
|
|
2421
|
+
}
|
|
2422
|
+
/**
|
|
2423
|
+
* Stop the active turn while the Host preserves pending inbox work; failures
|
|
2424
|
+
* land in promptError (same error-strip display slot). A subagent address
|
|
2425
|
+
* routes through `subagents.interruptByParent`, whose durable parent-address
|
|
2426
|
+
* authority works without a live parent Agent.
|
|
2427
|
+
* @returns the cancel result.
|
|
2428
|
+
*/
|
|
2429
|
+
async cancel() {
|
|
2430
|
+
const address = this.address;
|
|
2431
|
+
const result = address !== void 0 ? await this.remote.subagents.interruptByParent(address.childSessionId, address.parentSessionId, "continuable") : await this.remote.session.cancel({ sessionId: this.sessionId });
|
|
2432
|
+
if (!result.ok) {
|
|
2433
|
+
this.promptError = {
|
|
2434
|
+
op: "stop",
|
|
2435
|
+
error: result.error
|
|
2436
|
+
};
|
|
2437
|
+
this.notifier.markDirty();
|
|
2438
|
+
}
|
|
2439
|
+
return result;
|
|
2440
|
+
}
|
|
2441
|
+
/**
|
|
2442
|
+
* Rename: contract session.rename 1:1. On success settle the 'title'
|
|
2443
|
+
* projection cell from the response's `{title, seq}` under the store's
|
|
2444
|
+
* higher-seq-wins rule (the push frame arriving later is a no-op replay),
|
|
2445
|
+
* so the list row and any useProjection('title') reader update without
|
|
2446
|
+
* waiting for the control-stream projection update.
|
|
2447
|
+
* @param title - raw title text (the host normalizes acceptance).
|
|
2448
|
+
* @returns the rename result (normalized accepted title + title event seq).
|
|
2449
|
+
*/
|
|
2450
|
+
async rename(title) {
|
|
2451
|
+
const result = await this.remote.session.rename({
|
|
2452
|
+
sessionId: this.sessionId,
|
|
2453
|
+
title
|
|
2454
|
+
});
|
|
2455
|
+
if (!result.ok) return result;
|
|
2456
|
+
const seq = SessionSeq(result.value.seq);
|
|
2457
|
+
this.projections.apply("title", result.value.title, seq);
|
|
2458
|
+
return {
|
|
2459
|
+
ok: true,
|
|
2460
|
+
value: {
|
|
2461
|
+
title: result.value.title,
|
|
2462
|
+
seq
|
|
2463
|
+
}
|
|
2464
|
+
};
|
|
2465
|
+
}
|
|
2466
|
+
/**
|
|
2467
|
+
* Execute one slash-command line against this session's agent — pure
|
|
2468
|
+
* admission semantics (the host executor durably logs the lifecycle;
|
|
2469
|
+
* outcomes render as flow nodes, never as a response echo).
|
|
2470
|
+
* @param line - the full command line, leading slash included.
|
|
2471
|
+
* @returns the admission result.
|
|
2472
|
+
*/
|
|
2473
|
+
async command(line) {
|
|
2474
|
+
const result = await this.remote.commands.execute(this.sessionId, line, []);
|
|
2475
|
+
if (!result.ok) return result;
|
|
2476
|
+
return {
|
|
2477
|
+
ok: true,
|
|
2478
|
+
value: { matched: result.value !== void 0 }
|
|
2479
|
+
};
|
|
2480
|
+
}
|
|
2481
|
+
/** First open: pull the tail page (idempotent — in-flight/already-open returns the existing promise). */
|
|
2482
|
+
open() {
|
|
2483
|
+
if (this.openState === "open") return Promise.resolve();
|
|
2484
|
+
if (this.openPromise !== null) return this.openPromise;
|
|
2485
|
+
const promise = this.doOpen(this.openGeneration).finally(() => {
|
|
2486
|
+
if (this.openPromise === promise) this.openPromise = null;
|
|
2487
|
+
});
|
|
2488
|
+
this.openPromise = promise;
|
|
2489
|
+
return promise;
|
|
2490
|
+
}
|
|
2491
|
+
/** Prepend one Turn-aligned page: at least 50 messages and two Turn starts, capped at 500 messages. */
|
|
2492
|
+
async loadOlder() {
|
|
2493
|
+
if (this.openState !== "open" || !this.hasMore || this.loadingOlder) return;
|
|
2494
|
+
const events = this.events;
|
|
2495
|
+
if (events === void 0) return;
|
|
2496
|
+
this.loadingOlder = true;
|
|
2497
|
+
this.notifier.markDirty();
|
|
2498
|
+
try {
|
|
2499
|
+
await events.prepend({
|
|
2500
|
+
beforeSeq: this.baseSeq,
|
|
2501
|
+
...HISTORY_PAGE_OPTIONS
|
|
2502
|
+
});
|
|
2503
|
+
} catch (error) {
|
|
2504
|
+
if (!(0, _unieai_rabi_api_gateway_client.isRemoteFailure)(error)) console.error("[session-controller] loadOlder failed:", error);
|
|
2505
|
+
} finally {
|
|
2506
|
+
this.loadingOlder = false;
|
|
2507
|
+
this.notifier.markDirty();
|
|
2508
|
+
}
|
|
2509
|
+
}
|
|
2510
|
+
/** Jump loader: page backwards until the window covers seq (see ISession.loadThrough). */
|
|
2511
|
+
loadThrough(seq) {
|
|
2512
|
+
if (this.openState !== "open" || !this.hasMore || this.baseSeq <= seq) return Promise.resolve();
|
|
2513
|
+
if (this.jumpPromise !== null) {
|
|
2514
|
+
this.jumpTargetSeq = SessionSeq(Math.min(this.jumpTargetSeq ?? seq, seq));
|
|
2515
|
+
return this.jumpPromise;
|
|
2516
|
+
}
|
|
2517
|
+
if (this.loadingOlder) return Promise.resolve();
|
|
2518
|
+
const events = this.events;
|
|
2519
|
+
if (events === void 0) return Promise.resolve();
|
|
2520
|
+
const pending = {
|
|
2521
|
+
beforeSeq: this.baseSeq,
|
|
2522
|
+
hasMore: this.hasMore,
|
|
2523
|
+
pages: []
|
|
2524
|
+
};
|
|
2525
|
+
this.pendingHistory = pending;
|
|
2526
|
+
this.jumpTargetSeq = seq;
|
|
2527
|
+
this.loadingOlder = true;
|
|
2528
|
+
this.notifier.markDirty();
|
|
2529
|
+
const generation = this.openGeneration;
|
|
2530
|
+
this.jumpPromise = (async () => {
|
|
2531
|
+
try {
|
|
2532
|
+
while (pending.hasMore && this.jumpTargetSeq !== null && pending.beforeSeq > this.jumpTargetSeq) {
|
|
2533
|
+
if (generation !== this.openGeneration) return;
|
|
2534
|
+
const before = pending.beforeSeq;
|
|
2535
|
+
await events.prepend({
|
|
2536
|
+
beforeSeq: before,
|
|
2537
|
+
...JUMP_PAGE_OPTIONS
|
|
2538
|
+
});
|
|
2539
|
+
if (pending.beforeSeq >= before) return;
|
|
2540
|
+
}
|
|
2541
|
+
} catch (error) {
|
|
2542
|
+
if (!(0, _unieai_rabi_api_gateway_client.isRemoteFailure)(error)) console.error("[session-controller] loadThrough failed:", error);
|
|
2543
|
+
} finally {
|
|
2544
|
+
this.jumpTargetSeq = null;
|
|
2545
|
+
this.jumpPromise = null;
|
|
2546
|
+
this.pendingHistory = null;
|
|
2547
|
+
this.loadingOlder = false;
|
|
2548
|
+
if (generation === this.openGeneration && pending.pages.length > 0) this.prependWindow(pending.pages.reverse().flat(), pending.hasMore);
|
|
2549
|
+
this.notifier.markDirty();
|
|
2550
|
+
}
|
|
2551
|
+
})();
|
|
2552
|
+
return this.jumpPromise;
|
|
2553
|
+
}
|
|
2554
|
+
/** Rebuild an opened history source after address replacement.
|
|
2555
|
+
* Invalidates any in-flight open first; projection state belongs to the independently
|
|
2556
|
+
* reconnecting control stream and remains untouched. */
|
|
2557
|
+
async resync() {
|
|
2558
|
+
if (this.openState === "cold") return;
|
|
2559
|
+
this.openGeneration++;
|
|
2560
|
+
const events = this.events;
|
|
2561
|
+
this.events = void 0;
|
|
2562
|
+
await events?.dispose();
|
|
2563
|
+
this.openPromise = null;
|
|
2564
|
+
this.openState = "cold";
|
|
2565
|
+
this.openError = null;
|
|
2566
|
+
this.baseSeq = SessionLogOffset(0);
|
|
2567
|
+
this.notifier.markDirty();
|
|
2568
|
+
await this.open();
|
|
2569
|
+
}
|
|
2570
|
+
/**
|
|
2571
|
+
* uSES subscription entry.
|
|
2572
|
+
* @param listener - change callback.
|
|
2573
|
+
* @returns the unsubscribe function.
|
|
2574
|
+
*/
|
|
2575
|
+
subscribe(listener) {
|
|
2576
|
+
return this.notifier.subscribe(listener);
|
|
2577
|
+
}
|
|
2578
|
+
/**
|
|
2579
|
+
* Cached Session snapshot (rebuilt lazily when dirty with no listeners).
|
|
2580
|
+
* @returns the cached reference (stable until the next flush).
|
|
2581
|
+
*/
|
|
2582
|
+
getSnapshot() {
|
|
2583
|
+
this.notifier.ensureFresh();
|
|
2584
|
+
return this.snapshotCache;
|
|
2585
|
+
}
|
|
2586
|
+
/**
|
|
2587
|
+
* Running-bit relay from the host stream (list entry and snapshot stay consistent).
|
|
2588
|
+
* @param running - the new running state.
|
|
2589
|
+
*/
|
|
2590
|
+
handleRunning(running) {
|
|
2591
|
+
if (running && this.blankBit) {
|
|
2592
|
+
this.blankBit = false;
|
|
2593
|
+
this.notifier.markDirty();
|
|
2594
|
+
}
|
|
2595
|
+
if (running) this.firstPromptPendingTurn = false;
|
|
2596
|
+
if (this.running === running) return;
|
|
2597
|
+
this.running = running;
|
|
2598
|
+
this.notifier.markDirty();
|
|
2599
|
+
}
|
|
2600
|
+
/**
|
|
2601
|
+
* Install or clear the catalog-discovered transport address. A changed
|
|
2602
|
+
* address rebuilds an already-open window through its new history route.
|
|
2603
|
+
* @param address - direct parent/child address, or undefined for ordinary transport.
|
|
2604
|
+
* @param parentAvailable - latest exact-parent availability hint, or undefined before a catalog read.
|
|
2605
|
+
*/
|
|
2606
|
+
configureSubagent(address, parentAvailable) {
|
|
2607
|
+
const same = this.address?.parentSessionId === address?.parentSessionId && this.address?.childSessionId === address?.childSessionId && this.address?.mode === address?.mode;
|
|
2608
|
+
this.address = address;
|
|
2609
|
+
this.parentAvailable = parentAvailable;
|
|
2610
|
+
if (!same && this.openState !== "cold") this.resync();
|
|
2611
|
+
else this.notifier.markDirty();
|
|
2612
|
+
}
|
|
2613
|
+
/**
|
|
2614
|
+
* Update only the parent availability hint from a catalog refresh.
|
|
2615
|
+
* @param available - whether the exact direct parent is live.
|
|
2616
|
+
*/
|
|
2617
|
+
handleSubagentParentAvailable(available) {
|
|
2618
|
+
if (this.parentAvailable === available) return;
|
|
2619
|
+
this.parentAvailable = available;
|
|
2620
|
+
this.notifier.markDirty();
|
|
2621
|
+
}
|
|
2622
|
+
/**
|
|
2623
|
+
* Apply the Manager's effective display blank, further reconciled with the
|
|
2624
|
+
* current `sessionListMetadata` projection. Local send attempts and current
|
|
2625
|
+
* running state prevent re-blanking; an earlier false summary alone does not.
|
|
2626
|
+
* The Manager retains acceptance and earlier running observations across
|
|
2627
|
+
* Session-object replacement.
|
|
2628
|
+
* @param blank - New Session display state after Manager reconciliation.
|
|
2629
|
+
*/
|
|
2630
|
+
handleBlank(blank) {
|
|
2631
|
+
blank = blank && this.projections.values().sessionListMetadata?.blank !== false;
|
|
2632
|
+
if (blank === this.blankBit) return;
|
|
2633
|
+
if (blank && (this.promptAttempted || this.running)) return;
|
|
2634
|
+
this.blankBit = blank;
|
|
2635
|
+
this.notifier.markDirty();
|
|
2636
|
+
}
|
|
2637
|
+
/** `api-session/removed` relay: flag the snapshot while retaining the resident instance. */
|
|
2638
|
+
handleRemoved() {
|
|
2639
|
+
this.removed = true;
|
|
2640
|
+
this.notifier.markDirty();
|
|
2641
|
+
}
|
|
2642
|
+
/**
|
|
2643
|
+
* `api-session/error` relay: the outlet for live failures with no turn position.
|
|
2644
|
+
* @param message - the stringified error.
|
|
2645
|
+
*/
|
|
2646
|
+
handleAgentError(message) {
|
|
2647
|
+
this.lastAgentError = message;
|
|
2648
|
+
this.notifier.markDirty();
|
|
2649
|
+
}
|
|
2650
|
+
/**
|
|
2651
|
+
* Stop the Session's live Remote source.
|
|
2652
|
+
* @returns when the Remote iterator has completed teardown.
|
|
2653
|
+
*/
|
|
2654
|
+
async dispose() {
|
|
2655
|
+
this.stopObservingInbox();
|
|
2656
|
+
for (const [requestId, settlement] of [...this.submissionSettlements]) if (settlement.admitted !== void 0) this.scheduleObservedRetirement(requestId, settlement.admitted);
|
|
2657
|
+
else this.retireFailedSubmission(requestId);
|
|
2658
|
+
this.openGeneration++;
|
|
2659
|
+
const events = this.events;
|
|
2660
|
+
this.events = void 0;
|
|
2661
|
+
await events?.dispose();
|
|
2662
|
+
}
|
|
2663
|
+
/** @param generation - openGeneration at launch; stale passes cannot publish after replacement. */
|
|
2664
|
+
async doOpen(generation) {
|
|
2665
|
+
this.openState = "loading";
|
|
2666
|
+
this.openError = null;
|
|
2667
|
+
this.notifier.markDirty();
|
|
2668
|
+
const events = new SessionEventStream(this.remote, this.sessionAddress(), {
|
|
2669
|
+
publish: (change) => {
|
|
2670
|
+
if (generation !== this.openGeneration || this.events !== events) return;
|
|
2671
|
+
this.acceptEventChange(change);
|
|
2672
|
+
},
|
|
2673
|
+
failed: (error) => {
|
|
2674
|
+
this.failEventStream(events, generation, error);
|
|
2675
|
+
}
|
|
2676
|
+
});
|
|
2677
|
+
this.events = events;
|
|
2678
|
+
try {
|
|
2679
|
+
await events.open(HISTORY_PAGE_OPTIONS);
|
|
2680
|
+
if (generation !== this.openGeneration || this.events !== events) return;
|
|
2681
|
+
this.openState = "open";
|
|
2682
|
+
} catch (error) {
|
|
2683
|
+
if (generation !== this.openGeneration || this.events !== events) return;
|
|
2684
|
+
if (!(0, _unieai_rabi_api_gateway_client.isRemoteFailure)(error)) throw error;
|
|
2685
|
+
this.events = void 0;
|
|
2686
|
+
this.openState = "error";
|
|
2687
|
+
this.openError = error;
|
|
2688
|
+
} finally {
|
|
2689
|
+
if (generation === this.openGeneration) this.notifier.markDirty();
|
|
2690
|
+
}
|
|
2691
|
+
}
|
|
2692
|
+
/** Apply one contiguous journal update already reconciled by the Remote stream. */
|
|
2693
|
+
acceptEventChange(change) {
|
|
2694
|
+
switch (change.type) {
|
|
2695
|
+
case "replace":
|
|
2696
|
+
this.installWindow(change.entries, change.hasMore, change.page.projections === void 0 ? void 0 : projectionsBaseline(change.page.projections), change.page.assistantStream);
|
|
2697
|
+
return;
|
|
2698
|
+
case "prepend":
|
|
2699
|
+
this.prependWindow(change.entries, change.hasMore);
|
|
2700
|
+
return;
|
|
2701
|
+
case "append":
|
|
2702
|
+
this.publishAssistantEntry(this.assistantStream.acceptDurable(change.entry));
|
|
2703
|
+
return;
|
|
2704
|
+
case "assistant-stream": this.publishAssistantEntry(this.assistantStream.acceptFrame(change.frame));
|
|
2705
|
+
}
|
|
2706
|
+
}
|
|
2707
|
+
/** Replace the complete contiguous window and apply page-owned projection metadata. */
|
|
2708
|
+
installWindow(entries, hasMore, projections, assistantStream) {
|
|
2709
|
+
const visible = this.assistantStream.replace(entries, assistantStream);
|
|
2710
|
+
this.baseSeq = SessionLogOffset(entries[0]?.event.seq ?? 0);
|
|
2711
|
+
this.hasMore = hasMore;
|
|
2712
|
+
if (this.pendingHistory !== null) {
|
|
2713
|
+
this.pendingHistory.beforeSeq = this.baseSeq;
|
|
2714
|
+
this.pendingHistory.hasMore = hasMore;
|
|
2715
|
+
this.pendingHistory.pages.length = 0;
|
|
2716
|
+
}
|
|
2717
|
+
if (visible.some((entry) => entry.event.type === "turn/start")) this.firstPromptPendingTurn = false;
|
|
2718
|
+
if (projections !== void 0) this.projections.seed(projections);
|
|
2719
|
+
this.eventSource.replace(visible, hasMore);
|
|
2720
|
+
if (projections !== void 0) {
|
|
2721
|
+
for (const [requestId, { receipt }] of this.submissionSettlements) if (receipt !== void 0 && receipt.seq <= projections.asOfSeq) this.scheduleObservedRetirement(requestId, receipt.attachments);
|
|
2722
|
+
}
|
|
2723
|
+
for (const entry of visible) this.observeSubmissionEvent(entry.event);
|
|
2724
|
+
if (projections !== void 0) {
|
|
2725
|
+
const inbox = projections.values.inbox;
|
|
2726
|
+
for (const target of ["next-turn", "next-step"]) this.observeSubmissionInsertions(target, inbox?.[target] ?? [], 0, projections.asOfSeq);
|
|
2727
|
+
}
|
|
2728
|
+
this.notifier.markDirty();
|
|
2729
|
+
}
|
|
2730
|
+
publishAssistantEntry(result) {
|
|
2731
|
+
if (result?.type === "rebaseline") {
|
|
2732
|
+
const events = this.events;
|
|
2733
|
+
queueMicrotask(() => {
|
|
2734
|
+
if (events !== void 0 && this.events === events) events.restart();
|
|
2735
|
+
});
|
|
2736
|
+
return;
|
|
2737
|
+
}
|
|
2738
|
+
if (result?.type === "settlement") {
|
|
2739
|
+
this.eventSource.settleAssistant(result.attemptId, result.entry);
|
|
2740
|
+
this.observeSubmissionEvent(result.entry.event);
|
|
2741
|
+
this.notifier.markDirty();
|
|
2742
|
+
return;
|
|
2743
|
+
}
|
|
2744
|
+
if (result?.type === "abandonment") {
|
|
2745
|
+
this.eventSource.settleAssistant(result.attemptId);
|
|
2746
|
+
this.notifier.markDirty();
|
|
2747
|
+
return;
|
|
2748
|
+
}
|
|
2749
|
+
if (result?.type === "publish") {
|
|
2750
|
+
const changed = this.appendLive(result.entry);
|
|
2751
|
+
if (result.retireAttemptId !== void 0) this.eventSource.settleAssistant(result.retireAttemptId);
|
|
2752
|
+
if (changed || result.retireAttemptId !== void 0) this.notifier.markDirty();
|
|
2753
|
+
} else if (result?.type === "transient") {
|
|
2754
|
+
this.eventSource.append(result.entry);
|
|
2755
|
+
this.notifier.markDirty();
|
|
2756
|
+
}
|
|
2757
|
+
}
|
|
2758
|
+
/** Prepend one stream-validated history page. */
|
|
2759
|
+
prependWindow(entries, hasMore) {
|
|
2760
|
+
if (this.pendingHistory !== null) {
|
|
2761
|
+
const pending = this.pendingHistory;
|
|
2762
|
+
pending.beforeSeq = entries[0] === void 0 ? pending.beforeSeq : SessionLogOffset(entries[0].event.seq);
|
|
2763
|
+
pending.hasMore = hasMore;
|
|
2764
|
+
pending.pages.push(entries);
|
|
2765
|
+
return;
|
|
2766
|
+
}
|
|
2767
|
+
this.baseSeq = entries[0] === void 0 ? this.baseSeq : SessionLogOffset(entries[0].event.seq);
|
|
2768
|
+
this.hasMore = hasMore;
|
|
2769
|
+
this.eventSource.prepend(entries, hasMore);
|
|
2770
|
+
}
|
|
2771
|
+
/** Append one stream-validated live event. */
|
|
2772
|
+
appendLive(entry) {
|
|
2773
|
+
const event = entry.event;
|
|
2774
|
+
const awaitingFirstTurn = this.firstPromptPendingTurn;
|
|
2775
|
+
if (event.type === "turn/start") this.firstPromptPendingTurn = false;
|
|
2776
|
+
this.eventSource.append(entry);
|
|
2777
|
+
this.observeSubmissionEvent(event);
|
|
2778
|
+
return awaitingFirstTurn !== this.firstPromptPendingTurn;
|
|
2779
|
+
}
|
|
2780
|
+
/** Observe durable acceptance even when insertion and claim share one projection notification. */
|
|
2781
|
+
observeSubmissionEvent(event) {
|
|
2782
|
+
if (this.submissionSettlements.size === 0) return;
|
|
2783
|
+
if (event.type === "agent/inbox/spliced") {
|
|
2784
|
+
const { target, start, removedCount = 0, inserted, outcome } = event.data;
|
|
2785
|
+
for (const [requestId, settlement] of this.submissionSettlements) {
|
|
2786
|
+
const receipt = settlement.receipt;
|
|
2787
|
+
if (receipt?.target !== target || receipt.index === null || receipt.seq >= event.seq) continue;
|
|
2788
|
+
const removed = receipt.index >= start && receipt.index < start + removedCount;
|
|
2789
|
+
if (removed && outcome === "canceled") this.retireFailedSubmission(requestId);
|
|
2790
|
+
else settlement.receipt = {
|
|
2791
|
+
...receipt,
|
|
2792
|
+
seq: event.seq,
|
|
2793
|
+
index: removed ? null : receipt.index < start ? receipt.index : receipt.index + inserted.length - removedCount
|
|
2794
|
+
};
|
|
2795
|
+
}
|
|
2796
|
+
this.observeSubmissionInsertions(target, inserted, start, event.seq);
|
|
2797
|
+
for (const message of inserted) this.observeSubmissionMessage(message, false);
|
|
2798
|
+
return;
|
|
2799
|
+
}
|
|
2800
|
+
if (event.type === "request/context" || event.type === "turn/end") {
|
|
2801
|
+
for (const [requestId, settlement] of this.submissionSettlements) if (settlement.admitted === void 0 && settlement.receipt?.index === null && settlement.receipt.seq < event.seq) this.retireFailedSubmission(requestId);
|
|
2802
|
+
return;
|
|
2803
|
+
}
|
|
2804
|
+
if (event.type === "user/message") this.observeSubmissionMessage(event.data, true);
|
|
2805
|
+
}
|
|
2806
|
+
observeSubmissionInsertions(target, messages, start, seq) {
|
|
2807
|
+
for (const [index, message] of messages.entries()) {
|
|
2808
|
+
const source = message.source;
|
|
2809
|
+
if (source.kind !== "user" || !("rpcId" in source)) continue;
|
|
2810
|
+
const settlement = this.submissionSettlements.get(source.rpcId);
|
|
2811
|
+
if (settlement === void 0 || settlement.placement === "queued" || settlement.retiring || (settlement.receipt?.seq ?? -1) > seq) continue;
|
|
2812
|
+
settlement.receipt = {
|
|
2813
|
+
target,
|
|
2814
|
+
seq,
|
|
2815
|
+
index: start + index,
|
|
2816
|
+
attachments: attachmentRefsIn(message.content)
|
|
2817
|
+
};
|
|
2818
|
+
}
|
|
2819
|
+
}
|
|
2820
|
+
observeSubmissionMessage(message, admitted) {
|
|
2821
|
+
const source = message.source;
|
|
2822
|
+
if (source.kind !== "user" || !("rpcId" in source)) return;
|
|
2823
|
+
const settlement = this.submissionSettlements.get(source.rpcId);
|
|
2824
|
+
if (settlement === void 0 || settlement.retiring) return;
|
|
2825
|
+
if (!admitted) {
|
|
2826
|
+
if (settlement.placement === "queued") this.scheduleObservedRetirement(source.rpcId, attachmentRefsIn(message.content));
|
|
2827
|
+
return;
|
|
2828
|
+
}
|
|
2829
|
+
settlement.admitted = attachmentRefsIn(message.content);
|
|
2830
|
+
this.retireAdmittedSubmission(source.rpcId);
|
|
2831
|
+
}
|
|
2832
|
+
/** Retire admitted Chat identities only after stale Inbox rows can no longer reappear. */
|
|
2833
|
+
retireAdmittedSubmission(requestId) {
|
|
2834
|
+
const settlement = this.submissionSettlements.get(requestId);
|
|
2835
|
+
if (settlement?.admitted === void 0) return;
|
|
2836
|
+
const receipt = settlement.receipt;
|
|
2837
|
+
if (receipt?.index === null && (this.projections.seqOf("inbox") ?? -1) < receipt.seq) return;
|
|
2838
|
+
this.scheduleObservedRetirement(requestId, settlement.admitted);
|
|
2839
|
+
}
|
|
2840
|
+
/** Inbox acceptance retires queued echoes; its watermark completes admitted Chat handoffs. */
|
|
2841
|
+
observeSubmissionInbox() {
|
|
2842
|
+
if (this.submissionSettlements.size === 0) return;
|
|
2843
|
+
const inbox = this.projections.get("inbox");
|
|
2844
|
+
if (inbox === void 0) return;
|
|
2845
|
+
const seq = this.projections.seqOf("inbox");
|
|
2846
|
+
for (const target of ["next-turn", "next-step"]) {
|
|
2847
|
+
if (seq !== void 0) this.observeSubmissionInsertions(target, inbox[target], 0, seq);
|
|
2848
|
+
for (const message of inbox[target]) this.observeSubmissionMessage(message, false);
|
|
2849
|
+
}
|
|
2850
|
+
for (const requestId of this.submissionSettlements.keys()) this.retireAdmittedSubmission(requestId);
|
|
2851
|
+
}
|
|
2852
|
+
/**
|
|
2853
|
+
* Latch one observed settlement and remove the echo an animation frame
|
|
2854
|
+
* later. The delay keeps the echo in the snapshot until the frame in which
|
|
2855
|
+
* the durable node (whose assembly frame was registered first) is
|
|
2856
|
+
* renderable; the render-time rpcId dedupe hides the one-frame overlap.
|
|
2857
|
+
*/
|
|
2858
|
+
scheduleObservedRetirement(requestId, attachments) {
|
|
2859
|
+
const settlement = this.submissionSettlements.get(requestId);
|
|
2860
|
+
if (settlement === void 0 || settlement.retiring) return;
|
|
2861
|
+
settlement.retiring = true;
|
|
2862
|
+
scheduleFrame(() => {
|
|
2863
|
+
this.finishSubmission(requestId, {
|
|
2864
|
+
reason: "observed",
|
|
2865
|
+
attachments
|
|
2866
|
+
});
|
|
2867
|
+
});
|
|
2868
|
+
}
|
|
2869
|
+
/** Remove one unsettled echo immediately (prompt rejection, abort, or disposal). */
|
|
2870
|
+
retireFailedSubmission(requestId) {
|
|
2871
|
+
const settlement = this.submissionSettlements.get(requestId);
|
|
2872
|
+
if (settlement === void 0 || settlement.retiring || settlement.admitted !== void 0) return;
|
|
2873
|
+
settlement.retiring = true;
|
|
2874
|
+
this.finishSubmission(requestId, { reason: "failed" });
|
|
2875
|
+
}
|
|
2876
|
+
/** Single removal point: drop the echo, publish, then notify the owner. */
|
|
2877
|
+
finishSubmission(requestId, retirement) {
|
|
2878
|
+
const settlement = this.submissionSettlements.get(requestId);
|
|
2879
|
+
/* v8 ignore next -- retiring latches before every schedule, so one settlement never finishes twice. */
|
|
2880
|
+
if (settlement === void 0) return;
|
|
2881
|
+
this.submissionSettlements.delete(requestId);
|
|
2882
|
+
this.pendingSubmissions = this.pendingSubmissions.filter((echo) => echo.requestId !== requestId);
|
|
2883
|
+
this.notifier.markDirty();
|
|
2884
|
+
settlement.onRetire?.(retirement);
|
|
2885
|
+
}
|
|
2886
|
+
/** Publish a terminal background failure only while this stream still owns the Session. */
|
|
2887
|
+
failEventStream(events, generation, error) {
|
|
2888
|
+
if (generation !== this.openGeneration || this.events !== events) return;
|
|
2889
|
+
if (!(0, _unieai_rabi_api_gateway_client.isRemoteFailure)(error)) throw error;
|
|
2890
|
+
this.openGeneration++;
|
|
2891
|
+
this.events = void 0;
|
|
2892
|
+
this.openPromise = null;
|
|
2893
|
+
this.openState = "error";
|
|
2894
|
+
this.openError = error;
|
|
2895
|
+
events.dispose();
|
|
2896
|
+
this.notifier.markDirty();
|
|
2897
|
+
}
|
|
2898
|
+
buildSnapshot() {
|
|
2899
|
+
const identity = this.projections.values().subagent;
|
|
2900
|
+
return {
|
|
2901
|
+
sessionId: this.sessionId,
|
|
2902
|
+
pendingSubmissions: this.pendingSubmissions,
|
|
2903
|
+
running: this.running,
|
|
2904
|
+
subagent: this.address === void 0 ? null : {
|
|
2905
|
+
address: this.address.mode === "unknown" && identity != null ? {
|
|
2906
|
+
...this.address,
|
|
2907
|
+
mode: identity.mode
|
|
2908
|
+
} : this.address,
|
|
2909
|
+
...this.parentAvailable === void 0 ? {} : { parentAvailable: this.parentAvailable }
|
|
2910
|
+
},
|
|
2911
|
+
removed: this.removed,
|
|
2912
|
+
openState: this.openState,
|
|
2913
|
+
openError: this.openError,
|
|
2914
|
+
hasMore: this.hasMore,
|
|
2915
|
+
loadingOlder: this.loadingOlder,
|
|
2916
|
+
promptError: this.promptError,
|
|
2917
|
+
blank: this.blankBit,
|
|
2918
|
+
lastAgentError: this.lastAgentError,
|
|
2919
|
+
promptAttempted: this.promptAttempted,
|
|
2920
|
+
awaitingFirstTurn: this.firstPromptPendingTurn
|
|
2921
|
+
};
|
|
2922
|
+
}
|
|
2923
|
+
sessionAddress() {
|
|
2924
|
+
return this.address === void 0 ? {
|
|
2925
|
+
kind: "session",
|
|
2926
|
+
sessionId: this.sessionId
|
|
2927
|
+
} : {
|
|
2928
|
+
kind: "subagent",
|
|
2929
|
+
...this.address
|
|
2930
|
+
};
|
|
2931
|
+
}
|
|
2932
|
+
};
|
|
2933
|
+
/** Run one callback on the next animation frame, or a macrotask where no frame clock exists. */
|
|
2934
|
+
function scheduleFrame(fn) {
|
|
2935
|
+
if (typeof requestAnimationFrame === "function") requestAnimationFrame(() => {
|
|
2936
|
+
fn();
|
|
2937
|
+
});
|
|
2938
|
+
else setTimeout(fn, 0);
|
|
2939
|
+
}
|
|
2940
|
+
/** Attachment references in one structurally-read content block list, in block order. */
|
|
2941
|
+
function attachmentRefsIn(content) {
|
|
2942
|
+
if (!Array.isArray(content)) return [];
|
|
2943
|
+
const refs = [];
|
|
2944
|
+
for (const block of content) {
|
|
2945
|
+
if (typeof block !== "object" || block === null) continue;
|
|
2946
|
+
const candidate = block;
|
|
2947
|
+
if ((candidate.type === "image" || candidate.type === "file") && typeof candidate.attachment === "object" && candidate.attachment !== null) refs.push(candidate.attachment);
|
|
2948
|
+
}
|
|
2949
|
+
return refs;
|
|
2950
|
+
}
|
|
2951
|
+
//#endregion
|
|
2952
|
+
//#region lib/types/client/sessions/manager.js
|
|
2953
|
+
/** Host catalog, durable projection caches, and explicitly retained Client instances. */
|
|
2954
|
+
function sessionSeqCursor(value) {
|
|
2955
|
+
return value === -1 ? -1 : SessionSeq(value);
|
|
2956
|
+
}
|
|
2957
|
+
/** Instance cluster + frame entry + the session list. */
|
|
2958
|
+
var SessionManager = class {
|
|
2959
|
+
remote;
|
|
2960
|
+
sessions = /* @__PURE__ */ new Map();
|
|
2961
|
+
/** In-flight Session disposals remain here after instances leave `sessions`, so manager disposal can await quiescence. */
|
|
2962
|
+
sessionDisposals = /* @__PURE__ */ new Set();
|
|
2963
|
+
/**
|
|
2964
|
+
* Accepted/running presentation must survive a later empty-history list
|
|
2965
|
+
* response. Host-asserted running is recorded even before a row, instance, or
|
|
2966
|
+
* address holds the identity — the listing that would hold it may not have
|
|
2967
|
+
* landed yet — while the client-local acceptance callback requires a current
|
|
2968
|
+
* holder, because it can arrive from a replaced or already-dropped Session.
|
|
2969
|
+
*/
|
|
2970
|
+
engagedSessions = /* @__PURE__ */ new Set();
|
|
2971
|
+
disposed = false;
|
|
2972
|
+
/** Per-session projection value stores, retained independently of instance arrival (the
|
|
2973
|
+
* title-snapshot precedent, generalized): push frames land here whether or not the Session
|
|
2974
|
+
* is instantiated (list rows read the 'title' key), and an instantiated Session adopts the
|
|
2975
|
+
* same store so history-baseline seeding and frames converge on one row set. */
|
|
2976
|
+
projectionStores = /* @__PURE__ */ new Map();
|
|
2977
|
+
summaries = [];
|
|
2978
|
+
listState = "idle";
|
|
2979
|
+
/** Arrival phase; the pending → ready edge fires on the first successful pull (see SessionListPhase). */
|
|
2980
|
+
listPhase = "pending";
|
|
2981
|
+
listError = null;
|
|
2982
|
+
listInflight = null;
|
|
2983
|
+
/** Active list request's mutation log; its identity also fences completion after reconnect. */
|
|
2984
|
+
listMutations = null;
|
|
2985
|
+
addresses = /* @__PURE__ */ new Map();
|
|
2986
|
+
projectionLoads = /* @__PURE__ */ new Map();
|
|
2987
|
+
projectionInflight = /* @__PURE__ */ new Map();
|
|
2988
|
+
listSnapshotCache;
|
|
2989
|
+
/** Entry-identity cache (reference stability): list rebuilds reuse the previous entry
|
|
2990
|
+
* object when every field matches — wire refreshes mint all-new summary objects, so identity
|
|
2991
|
+
* must be recovered by value or every SessionListItem memo misses on every refresh. */
|
|
2992
|
+
entryCache = /* @__PURE__ */ new Map();
|
|
2993
|
+
itemsCache = [];
|
|
2994
|
+
notifier = new Notifier(() => {
|
|
2995
|
+
this.listSnapshotCache = this.buildListSnapshot();
|
|
2996
|
+
});
|
|
2997
|
+
/** @param remote - generated Remote namespaces used by catalog and history readers. */
|
|
2998
|
+
constructor(remote) {
|
|
2999
|
+
this.remote = remote;
|
|
3000
|
+
this.listSnapshotCache = this.buildListSnapshot();
|
|
3001
|
+
}
|
|
3002
|
+
/**
|
|
3003
|
+
* Resolve an acquisition target without materializing a Session.
|
|
3004
|
+
* @param target - known identity or durable direct-parent address.
|
|
3005
|
+
* @returns the resolved identity with its explicit or catalog-derived history route installed.
|
|
3006
|
+
*/
|
|
3007
|
+
resolveTarget(target) {
|
|
3008
|
+
const id = typeof target === "string" ? target : target.childSessionId;
|
|
3009
|
+
const address = typeof target === "string" ? this.subagentAddress(id) : target;
|
|
3010
|
+
if (typeof target === "string" && !this.sessions.has(id) && !this.summaries.some((summary) => summary.sessionId === id) && address === void 0) throw new Error(`sessions.retain: unknown session ${id}`);
|
|
3011
|
+
if (address !== void 0) this.addresses.set(id, address);
|
|
3012
|
+
this.sessions.get(id)?.configureSubagent(address, address === void 0 ? void 0 : this.agentAvailable(address.parentSessionId));
|
|
3013
|
+
return id;
|
|
3014
|
+
}
|
|
3015
|
+
/**
|
|
3016
|
+
* Resolve an address for breadcrumb navigation without retaining transport authority.
|
|
3017
|
+
* @param sessionId - possible child id in received Session metadata.
|
|
3018
|
+
* @returns A retained address, then a catalog address, then an unknown-mode address
|
|
3019
|
+
* from a listed subagent header; undefined without that evidence.
|
|
3020
|
+
*/
|
|
3021
|
+
subagentAddress(sessionId) {
|
|
3022
|
+
const retained = this.addresses.get(sessionId);
|
|
3023
|
+
if (retained !== void 0) return retained;
|
|
3024
|
+
for (const parentSessionId of this.projectionStores.keys()) {
|
|
3025
|
+
const child = this.projectionStores.get(parentSessionId)?.values().subagentCatalog?.find((entry) => entry.id === sessionId);
|
|
3026
|
+
if (child !== void 0 && child.mode !== "external") return {
|
|
3027
|
+
parentSessionId,
|
|
3028
|
+
childSessionId: sessionId,
|
|
3029
|
+
mode: child.mode
|
|
3030
|
+
};
|
|
3031
|
+
}
|
|
3032
|
+
const summary = this.summaries.find((summary) => summary.sessionId === sessionId);
|
|
3033
|
+
if (summary?.origin !== "subagent" || summary.parentSessionId === void 0) return void 0;
|
|
3034
|
+
return {
|
|
3035
|
+
parentSessionId: summary.parentSessionId,
|
|
3036
|
+
childSessionId: sessionId,
|
|
3037
|
+
mode: "unknown"
|
|
3038
|
+
};
|
|
3039
|
+
}
|
|
3040
|
+
/**
|
|
3041
|
+
* Withdraw an exact Client instance before running its teardown callbacks.
|
|
3042
|
+
* @param sessionId - identity to withdraw.
|
|
3043
|
+
* @param expected - instance being released; a replacement is left untouched.
|
|
3044
|
+
* @returns completion of the detached instance's stream teardown.
|
|
3045
|
+
*/
|
|
3046
|
+
drop(sessionId, expected) {
|
|
3047
|
+
const session = this.sessions.get(sessionId);
|
|
3048
|
+
if (session !== expected) return Promise.resolve();
|
|
3049
|
+
this.sessions.delete(sessionId);
|
|
3050
|
+
this.addresses.delete(sessionId);
|
|
3051
|
+
this.pruneEngagement(sessionId, this.retainedIds(this.summaries));
|
|
3052
|
+
return this.startSessionDisposal(session);
|
|
3053
|
+
}
|
|
3054
|
+
/**
|
|
3055
|
+
* Stop catalog requests and dispose every resident Session.
|
|
3056
|
+
* @returns once catalog requests and every Session stream have stopped.
|
|
3057
|
+
*/
|
|
3058
|
+
async dispose() {
|
|
3059
|
+
this.disposed = true;
|
|
3060
|
+
this.listMutations = null;
|
|
3061
|
+
this.listInflight = null;
|
|
3062
|
+
this.engagedSessions.clear();
|
|
3063
|
+
const reads = [...this.projectionInflight.values()];
|
|
3064
|
+
for (const { controller } of reads) controller.abort();
|
|
3065
|
+
this.projectionInflight.clear();
|
|
3066
|
+
await Promise.all(reads.map((read) => read.promise));
|
|
3067
|
+
const sessions = [...this.sessions.values()];
|
|
3068
|
+
this.sessions.clear();
|
|
3069
|
+
this.addresses.clear();
|
|
3070
|
+
for (const session of sessions) this.startSessionDisposal(session);
|
|
3071
|
+
await this.drainSessionDisposals();
|
|
3072
|
+
}
|
|
3073
|
+
startSessionDisposal(session) {
|
|
3074
|
+
const disposal = session.dispose();
|
|
3075
|
+
this.sessionDisposals.add(disposal);
|
|
3076
|
+
disposal.then(() => {
|
|
3077
|
+
this.sessionDisposals.delete(disposal);
|
|
3078
|
+
}, () => {
|
|
3079
|
+
this.sessionDisposals.delete(disposal);
|
|
3080
|
+
});
|
|
3081
|
+
return disposal;
|
|
3082
|
+
}
|
|
3083
|
+
async drainSessionDisposals() {
|
|
3084
|
+
while (this.sessionDisposals.size > 0) await Promise.allSettled([...this.sessionDisposals]);
|
|
3085
|
+
}
|
|
3086
|
+
/**
|
|
3087
|
+
* Lazy build: return the existing instance or construct one (no auto-open —
|
|
3088
|
+
* the reference allocator opens history after binding the scope).
|
|
3089
|
+
* New instances reconcile retained metadata before returning.
|
|
3090
|
+
* @param sessionId - the session to get.
|
|
3091
|
+
* @returns the resident instance.
|
|
3092
|
+
*/
|
|
3093
|
+
get(sessionId) {
|
|
3094
|
+
let session = this.sessions.get(sessionId);
|
|
3095
|
+
if (session === void 0) {
|
|
3096
|
+
session = this.createSession(sessionId);
|
|
3097
|
+
this.sessions.set(sessionId, session);
|
|
3098
|
+
const summary = this.summaries.find((s) => s.sessionId === sessionId);
|
|
3099
|
+
if (summary !== void 0) {
|
|
3100
|
+
session.handleBlank(this.effectiveBlank(summary));
|
|
3101
|
+
session.handleRunning(summary.running);
|
|
3102
|
+
} else {
|
|
3103
|
+
const address = this.addresses.get(sessionId);
|
|
3104
|
+
const child = address === void 0 ? void 0 : this.projectionStores.get(address.parentSessionId)?.values().subagentCatalog?.find((entry) => entry.id === sessionId);
|
|
3105
|
+
if (child !== void 0 && child.mode !== "external") {
|
|
3106
|
+
session.handleBlank(false);
|
|
3107
|
+
session.handleRunning(false);
|
|
3108
|
+
} else session.handleBlank(true);
|
|
3109
|
+
}
|
|
3110
|
+
}
|
|
3111
|
+
return session;
|
|
3112
|
+
}
|
|
3113
|
+
createSession(sessionId) {
|
|
3114
|
+
const address = this.addresses.get(sessionId);
|
|
3115
|
+
const parentAvailable = address === void 0 ? void 0 : this.agentAvailable(address.parentSessionId);
|
|
3116
|
+
return new Session(sessionId, this.remote, {
|
|
3117
|
+
...address === void 0 ? {} : {
|
|
3118
|
+
address,
|
|
3119
|
+
...parentAvailable === void 0 ? {} : { parentAvailable }
|
|
3120
|
+
},
|
|
3121
|
+
onEngaged: (engaged) => {
|
|
3122
|
+
if (this.disposed || !this.retainedIds(this.summaries).has(engaged.sessionId)) return;
|
|
3123
|
+
if (!this.engagedSessions.has(engaged.sessionId)) {
|
|
3124
|
+
this.engagedSessions.add(engaged.sessionId);
|
|
3125
|
+
this.recordMutation({
|
|
3126
|
+
kind: "engaged",
|
|
3127
|
+
sessionId: engaged.sessionId
|
|
3128
|
+
});
|
|
3129
|
+
}
|
|
3130
|
+
this.sessions.get(engaged.sessionId)?.handleBlank(false);
|
|
3131
|
+
},
|
|
3132
|
+
projections: this.projectionStore(sessionId)
|
|
3133
|
+
});
|
|
3134
|
+
}
|
|
3135
|
+
effectiveBlank(summary) {
|
|
3136
|
+
return summary.blank && !this.engagedSessions.has(summary.sessionId);
|
|
3137
|
+
}
|
|
3138
|
+
/**
|
|
3139
|
+
* Identities an engagement may still belong to: the given list rows, resident
|
|
3140
|
+
* Session instances, and retained child addresses.
|
|
3141
|
+
* @param summaries - list rows of the caller's snapshot.
|
|
3142
|
+
* @returns the retained identity set.
|
|
3143
|
+
*/
|
|
3144
|
+
retainedIds(summaries) {
|
|
3145
|
+
const retained = new Set(summaries.map((summary) => summary.sessionId));
|
|
3146
|
+
for (const sessionId of this.sessions.keys()) retained.add(sessionId);
|
|
3147
|
+
for (const sessionId of this.addresses.keys()) retained.add(sessionId);
|
|
3148
|
+
return retained;
|
|
3149
|
+
}
|
|
3150
|
+
/**
|
|
3151
|
+
* Forget one engagement that no retained identity holds.
|
|
3152
|
+
* @param sessionId - identity whose engagement may be dropped.
|
|
3153
|
+
* @param retained - identities from {@link retainedIds} for the caller's snapshot.
|
|
3154
|
+
*/
|
|
3155
|
+
pruneEngagement(sessionId, retained) {
|
|
3156
|
+
if (!retained.has(sessionId)) this.engagedSessions.delete(sessionId);
|
|
3157
|
+
}
|
|
3158
|
+
/** Resident per-session projection store (create-on-demand; outlives instantiation). */
|
|
3159
|
+
projectionStore(sessionId) {
|
|
3160
|
+
let store = this.projectionStores.get(sessionId);
|
|
3161
|
+
if (store === void 0) {
|
|
3162
|
+
store = new ProjectionValueStore();
|
|
3163
|
+
const projections = store;
|
|
3164
|
+
store.subscribeAny(() => {
|
|
3165
|
+
if (projections.values().sessionListMetadata?.blank === false) this.sessions.get(sessionId)?.handleBlank(false);
|
|
3166
|
+
this.notifier.markDirty();
|
|
3167
|
+
});
|
|
3168
|
+
this.projectionStores.set(sessionId, store);
|
|
3169
|
+
}
|
|
3170
|
+
return store;
|
|
3171
|
+
}
|
|
3172
|
+
/**
|
|
3173
|
+
* Read projections without starting migration; retry failed or migration-deferred reads.
|
|
3174
|
+
* @param sessionId - Session to inspect without opening its conversation.
|
|
3175
|
+
* @returns completion of the current or newly started read.
|
|
3176
|
+
*/
|
|
3177
|
+
refreshProjections(sessionId) {
|
|
3178
|
+
const existing = this.projectionInflight.get(sessionId);
|
|
3179
|
+
if (existing !== void 0) return existing.promise;
|
|
3180
|
+
if (this.projectionLoads.get(sessionId)?.state === "ready") return Promise.resolve();
|
|
3181
|
+
const controller = new AbortController();
|
|
3182
|
+
const store = this.projectionStore(sessionId);
|
|
3183
|
+
const initialValues = store.values();
|
|
3184
|
+
this.projectionLoads.set(sessionId, {
|
|
3185
|
+
state: "loading",
|
|
3186
|
+
error: null
|
|
3187
|
+
});
|
|
3188
|
+
this.notifier.markDirty();
|
|
3189
|
+
const operation = (async () => {
|
|
3190
|
+
try {
|
|
3191
|
+
const result = await this.remote.session.projections({ sessionId }, controller.signal);
|
|
3192
|
+
if (controller.signal.aborted) return;
|
|
3193
|
+
if (result.ok) {
|
|
3194
|
+
const value = result.value;
|
|
3195
|
+
if (value !== null) switch (value.kind) {
|
|
3196
|
+
case "sequenced":
|
|
3197
|
+
store.seed({
|
|
3198
|
+
values: value.values,
|
|
3199
|
+
asOfSeq: sessionSeqCursor(value.asOfSeq)
|
|
3200
|
+
});
|
|
3201
|
+
break;
|
|
3202
|
+
case "migration-required":
|
|
3203
|
+
store.applyCached(value.values);
|
|
3204
|
+
break;
|
|
3205
|
+
default: assertNever(value, "session projections result");
|
|
3206
|
+
}
|
|
3207
|
+
else if (store.values() === initialValues) store.clear();
|
|
3208
|
+
this.projectionLoads.set(sessionId, {
|
|
3209
|
+
state: value?.kind === "migration-required" ? "migration-required" : "ready",
|
|
3210
|
+
error: null
|
|
3211
|
+
});
|
|
3212
|
+
} else this.projectionLoads.set(sessionId, {
|
|
3213
|
+
state: "error",
|
|
3214
|
+
error: result.error
|
|
3215
|
+
});
|
|
3216
|
+
} catch (error) {
|
|
3217
|
+
if (controller.signal.aborted) return;
|
|
3218
|
+
if (!(0, _unieai_rabi_api_gateway_client.isRemoteFailure)(error)) throw error;
|
|
3219
|
+
this.projectionLoads.set(sessionId, {
|
|
3220
|
+
state: "error",
|
|
3221
|
+
error
|
|
3222
|
+
});
|
|
3223
|
+
} finally {
|
|
3224
|
+
if (!controller.signal.aborted) {
|
|
3225
|
+
this.projectionInflight.delete(sessionId);
|
|
3226
|
+
this.notifier.markDirty();
|
|
3227
|
+
}
|
|
3228
|
+
}
|
|
3229
|
+
})();
|
|
3230
|
+
this.projectionInflight.set(sessionId, {
|
|
3231
|
+
promise: operation,
|
|
3232
|
+
controller
|
|
3233
|
+
});
|
|
3234
|
+
return operation;
|
|
3235
|
+
}
|
|
3236
|
+
agentAvailable(sessionId) {
|
|
3237
|
+
return this.summaries.find((summary) => summary.sessionId === sessionId)?.agentAvailable ?? (this.listPhase === "ready" ? false : void 0);
|
|
3238
|
+
}
|
|
3239
|
+
updateParentAvailability() {
|
|
3240
|
+
for (const [childId, address] of this.addresses) {
|
|
3241
|
+
const available = this.agentAvailable(address.parentSessionId);
|
|
3242
|
+
if (available !== void 0) this.sessions.get(childId)?.handleSubagentParentAvailable(available);
|
|
3243
|
+
}
|
|
3244
|
+
}
|
|
3245
|
+
/** Full refresh via session.list (single-flight within one Host generation). */
|
|
3246
|
+
refreshList() {
|
|
3247
|
+
if (this.listInflight !== null) return this.listInflight;
|
|
3248
|
+
this.listState = "loading";
|
|
3249
|
+
this.listError = null;
|
|
3250
|
+
const established = this.summaries;
|
|
3251
|
+
const mutations = [];
|
|
3252
|
+
this.listMutations = mutations;
|
|
3253
|
+
this.notifier.markDirty();
|
|
3254
|
+
this.listInflight = (async () => {
|
|
3255
|
+
try {
|
|
3256
|
+
const result = await this.remote.session.list({});
|
|
3257
|
+
if (this.listMutations !== mutations) return;
|
|
3258
|
+
if (result.ok) {
|
|
3259
|
+
const baseline = this.listPhase === "pending" ? [...result.value.items] : mergeOrderedBaseline(established, result.value.items, (summary) => summary.sessionId);
|
|
3260
|
+
const removedSincePull = /* @__PURE__ */ new Set();
|
|
3261
|
+
for (const mutation of mutations) if (mutation.kind === "remove") removedSincePull.add(mutation.sessionId);
|
|
3262
|
+
for (const s of baseline) if (s.running && !removedSincePull.has(s.sessionId)) this.engagedSessions.add(s.sessionId);
|
|
3263
|
+
const summaries = mutations.reduce(applyMutation, baseline);
|
|
3264
|
+
this.summaries = summaries;
|
|
3265
|
+
const retained = this.retainedIds(summaries);
|
|
3266
|
+
for (const sessionId of this.engagedSessions) this.pruneEngagement(sessionId, retained);
|
|
3267
|
+
this.listState = "idle";
|
|
3268
|
+
this.listPhase = "ready";
|
|
3269
|
+
this.updateParentAvailability();
|
|
3270
|
+
for (const s of this.summaries) {
|
|
3271
|
+
const session = this.sessions.get(s.sessionId);
|
|
3272
|
+
if (session === void 0) continue;
|
|
3273
|
+
session.handleBlank(this.effectiveBlank(s));
|
|
3274
|
+
session.handleRunning(s.running);
|
|
3275
|
+
}
|
|
3276
|
+
for (const s of result.value.items) if (s.projections !== void 0) this.applyListBlock(s.sessionId, s.projections);
|
|
3277
|
+
} else {
|
|
3278
|
+
this.listState = "error";
|
|
3279
|
+
this.listError = result.error;
|
|
3280
|
+
}
|
|
3281
|
+
} catch (error) {
|
|
3282
|
+
if (!(0, _unieai_rabi_api_gateway_client.isRemoteFailure)(error)) throw error;
|
|
3283
|
+
if (this.listMutations !== mutations) return;
|
|
3284
|
+
this.listState = "error";
|
|
3285
|
+
this.listError = error;
|
|
3286
|
+
} finally {
|
|
3287
|
+
if (this.listMutations === mutations) {
|
|
3288
|
+
this.listMutations = null;
|
|
3289
|
+
this.listInflight = null;
|
|
3290
|
+
this.notifier.markDirty();
|
|
3291
|
+
}
|
|
3292
|
+
}
|
|
3293
|
+
})();
|
|
3294
|
+
return this.listInflight;
|
|
3295
|
+
}
|
|
3296
|
+
/**
|
|
3297
|
+
* Search visible session message content without adding transient query
|
|
3298
|
+
* state to the list snapshot.
|
|
3299
|
+
* @param query - non-blank literal phrase.
|
|
3300
|
+
* @param signal - cancellation for superseded UI queries.
|
|
3301
|
+
* @returns the Host result or a folded transport error.
|
|
3302
|
+
*/
|
|
3303
|
+
async search(query, signal) {
|
|
3304
|
+
const result = await this.remote.session.search({ query }, signal);
|
|
3305
|
+
if (!result.ok) return result;
|
|
3306
|
+
return {
|
|
3307
|
+
ok: true,
|
|
3308
|
+
value: {
|
|
3309
|
+
items: [...result.value.items],
|
|
3310
|
+
hasMore: result.value.hasMore
|
|
3311
|
+
}
|
|
3312
|
+
};
|
|
3313
|
+
}
|
|
3314
|
+
/**
|
|
3315
|
+
* Contract session.create; on success merge into summaries immediately (no
|
|
3316
|
+
* wait for the next refresh). A created session is blank by definition
|
|
3317
|
+
* (entity birth precedes the first message).
|
|
3318
|
+
* @param opts - target workspace or working directory, an optional blank Session to reuse, and an optional Agent preset.
|
|
3319
|
+
* @returns the create result, naming the Session the Host created or reused.
|
|
3320
|
+
*/
|
|
3321
|
+
async create(opts = {}) {
|
|
3322
|
+
const shared = {
|
|
3323
|
+
...opts.sessionId === void 0 ? {} : { sessionId: opts.sessionId },
|
|
3324
|
+
...opts.agentPreset === void 0 ? {} : { agentPreset: opts.agentPreset }
|
|
3325
|
+
};
|
|
3326
|
+
const payload = opts.workspaceId !== void 0 ? {
|
|
3327
|
+
workspaceId: opts.workspaceId,
|
|
3328
|
+
...shared
|
|
3329
|
+
} : {
|
|
3330
|
+
...opts.cwd === void 0 ? {} : { cwd: opts.cwd },
|
|
3331
|
+
...shared
|
|
3332
|
+
};
|
|
3333
|
+
const result = await this.remote.session.create(payload);
|
|
3334
|
+
if (result.ok) this.recordMutation({
|
|
3335
|
+
kind: "placeholder",
|
|
3336
|
+
summary: {
|
|
3337
|
+
agentAvailable: true,
|
|
3338
|
+
sessionId: result.value.sessionId,
|
|
3339
|
+
updatedAt: Date.now(),
|
|
3340
|
+
running: false,
|
|
3341
|
+
blank: true,
|
|
3342
|
+
...opts.cwd !== void 0 ? { cwd: opts.cwd } : {}
|
|
3343
|
+
}
|
|
3344
|
+
});
|
|
3345
|
+
else {
|
|
3346
|
+
const publishedSessionId = workspaceAttachSessionId(result.error);
|
|
3347
|
+
if (publishedSessionId !== void 0) this.recordMutation({
|
|
3348
|
+
kind: "placeholder",
|
|
3349
|
+
summary: {
|
|
3350
|
+
agentAvailable: true,
|
|
3351
|
+
sessionId: publishedSessionId,
|
|
3352
|
+
updatedAt: Date.now(),
|
|
3353
|
+
running: false,
|
|
3354
|
+
blank: true
|
|
3355
|
+
}
|
|
3356
|
+
});
|
|
3357
|
+
}
|
|
3358
|
+
return result;
|
|
3359
|
+
}
|
|
3360
|
+
/**
|
|
3361
|
+
* Contract session.fork; on success merge the child into summaries
|
|
3362
|
+
* immediately (same synchronous-addressability guarantee as create).
|
|
3363
|
+
* Blankness starts provisionally true so the authoritative Host summary can
|
|
3364
|
+
* preserve it or lower it after an exact cut before the first `turn/start`;
|
|
3365
|
+
* lineage rides parentSessionId. A child published before Workspace
|
|
3366
|
+
* attachment fails is also reconciled into the list.
|
|
3367
|
+
* @param opts - source session, optional exact inclusive boundary seq, and permission to start migration.
|
|
3368
|
+
* @returns the fork result (the child session id).
|
|
3369
|
+
*/
|
|
3370
|
+
async fork(opts) {
|
|
3371
|
+
const source = this.summaries.find((s) => s.sessionId === opts.sessionId);
|
|
3372
|
+
const result = await this.remote.session.fork({
|
|
3373
|
+
sessionId: opts.sessionId,
|
|
3374
|
+
...opts.atSeq === void 0 ? {} : { atSeq: opts.atSeq },
|
|
3375
|
+
...opts.allowMigration === void 0 ? {} : { allowMigration: opts.allowMigration }
|
|
3376
|
+
});
|
|
3377
|
+
const childId = result.ok ? result.value.sessionId : workspaceAttachSessionId(result.error);
|
|
3378
|
+
if (childId !== void 0) this.recordMutation({
|
|
3379
|
+
kind: "placeholder",
|
|
3380
|
+
summary: {
|
|
3381
|
+
agentAvailable: true,
|
|
3382
|
+
sessionId: childId,
|
|
3383
|
+
updatedAt: Date.now(),
|
|
3384
|
+
running: false,
|
|
3385
|
+
blank: true,
|
|
3386
|
+
parentSessionId: opts.sessionId,
|
|
3387
|
+
...source?.cwd !== void 0 ? { cwd: source.cwd } : {}
|
|
3388
|
+
}
|
|
3389
|
+
});
|
|
3390
|
+
return result;
|
|
3391
|
+
}
|
|
3392
|
+
/**
|
|
3393
|
+
* Rename a Session and update its title projection without opening its history.
|
|
3394
|
+
* @param sessionId - Session to rename.
|
|
3395
|
+
* @param title - raw title text for Host normalization.
|
|
3396
|
+
* @returns the accepted title and event position, or the Remote failure.
|
|
3397
|
+
*/
|
|
3398
|
+
async rename(sessionId, title) {
|
|
3399
|
+
const result = await this.remote.session.rename({
|
|
3400
|
+
sessionId,
|
|
3401
|
+
title
|
|
3402
|
+
});
|
|
3403
|
+
if (result.ok) this.projectionStore(sessionId).apply("title", result.value.title, SessionSeq(result.value.seq));
|
|
3404
|
+
return result;
|
|
3405
|
+
}
|
|
3406
|
+
/**
|
|
3407
|
+
* Merge a Host summary, replacing live state and filling missing metadata.
|
|
3408
|
+
* Local create/fork placeholders only fill metadata on an existing row.
|
|
3409
|
+
*/
|
|
3410
|
+
mergeSummary(summary) {
|
|
3411
|
+
this.recordMutation({
|
|
3412
|
+
kind: "upsert",
|
|
3413
|
+
summary
|
|
3414
|
+
});
|
|
3415
|
+
this.updateParentAvailability();
|
|
3416
|
+
}
|
|
3417
|
+
/** Apply immediately and retain for replay when a list response is in flight. */
|
|
3418
|
+
recordMutation(mutation) {
|
|
3419
|
+
if (this.disposed) return;
|
|
3420
|
+
this.listMutations?.push(mutation);
|
|
3421
|
+
this.summaries = applyMutation(this.summaries, mutation);
|
|
3422
|
+
this.notifier.markDirty();
|
|
3423
|
+
}
|
|
3424
|
+
/**
|
|
3425
|
+
* uSES subscription entry for useSessionList.
|
|
3426
|
+
* @param listener - change callback.
|
|
3427
|
+
* @returns the unsubscribe function.
|
|
3428
|
+
*/
|
|
3429
|
+
subscribe(listener) {
|
|
3430
|
+
return this.notifier.subscribe(listener);
|
|
3431
|
+
}
|
|
3432
|
+
/**
|
|
3433
|
+
* Cached list snapshot (rebuilt lazily when dirty with no listeners).
|
|
3434
|
+
* @returns the cached reference (stable until the next flush).
|
|
3435
|
+
*/
|
|
3436
|
+
getListSnapshot() {
|
|
3437
|
+
this.notifier.ensureFresh();
|
|
3438
|
+
return this.listSnapshotCache;
|
|
3439
|
+
}
|
|
3440
|
+
/**
|
|
3441
|
+
* Read cached projection values for a Session that may exist only in a loaded subagent catalog.
|
|
3442
|
+
* @param sessionId - Session whose control or history baseline supplied projections.
|
|
3443
|
+
* @returns current values, or undefined before any projection store exists.
|
|
3444
|
+
*/
|
|
3445
|
+
projectionValues(sessionId) {
|
|
3446
|
+
return this.projectionStores.get(sessionId)?.values();
|
|
3447
|
+
}
|
|
3448
|
+
/**
|
|
3449
|
+
* Apply a complete control baseline or one later replacement frame.
|
|
3450
|
+
* @param frame - baseline or live control replacement from Session Controller.
|
|
3451
|
+
*/
|
|
3452
|
+
handleControlFrame(frame) {
|
|
3453
|
+
if (frame.type === "baseline") {
|
|
3454
|
+
this.replaceControlBaseline(frame.value);
|
|
3455
|
+
return;
|
|
3456
|
+
}
|
|
3457
|
+
this.projectionStore(frame.sessionId).apply(frame.key, frame.value, SessionSeq(frame.seq));
|
|
3458
|
+
this.notifier.markDirty();
|
|
3459
|
+
}
|
|
3460
|
+
replaceControlBaseline(baseline) {
|
|
3461
|
+
for (const [sessionId, block] of Object.entries(baseline.projections)) {
|
|
3462
|
+
const store = this.projectionStore(sessionId);
|
|
3463
|
+
const asOfSeq = sessionSeqCursor(block.asOfSeq);
|
|
3464
|
+
store.seed({
|
|
3465
|
+
...block,
|
|
3466
|
+
asOfSeq
|
|
3467
|
+
});
|
|
3468
|
+
}
|
|
3469
|
+
this.notifier.markDirty();
|
|
3470
|
+
}
|
|
3471
|
+
/**
|
|
3472
|
+
* Apply one Session-list addition forwarded through `ctx.remote.$on`.
|
|
3473
|
+
* @param summary - current Host summary for the added Session.
|
|
3474
|
+
*/
|
|
3475
|
+
handleSessionAdded(summary) {
|
|
3476
|
+
this.mergeSummary(summary);
|
|
3477
|
+
if (!this.disposed && summary.running) this.engagedSessions.add(summary.sessionId);
|
|
3478
|
+
this.sessions.get(summary.sessionId)?.handleBlank(this.effectiveBlank(summary));
|
|
3479
|
+
if (summary.projections !== void 0) this.applyListBlock(summary.sessionId, summary.projections);
|
|
3480
|
+
}
|
|
3481
|
+
/**
|
|
3482
|
+
* Merge one list-surface projection block by the sequence space it declares.
|
|
3483
|
+
* A `sequenced` block came from the Host's live registry for an attached
|
|
3484
|
+
* Session, so each key lands under higher-seq-wins against that Session's
|
|
3485
|
+
* baselines and frames. A `cached` block was viewed from the persisted
|
|
3486
|
+
* checkpoint by a header-only listing: its watermark is not comparable with
|
|
3487
|
+
* this connection's seqs, so it only fills keys no sequenced row holds.
|
|
3488
|
+
*/
|
|
3489
|
+
applyListBlock(sessionId, block) {
|
|
3490
|
+
const store = this.projectionStore(sessionId);
|
|
3491
|
+
switch (block.kind) {
|
|
3492
|
+
case "sequenced": {
|
|
3493
|
+
const seq = sessionSeqCursor(block.asOfSeq);
|
|
3494
|
+
for (const [key, value] of Object.entries(block.values)) store.apply(key, value, seq);
|
|
3495
|
+
return;
|
|
3496
|
+
}
|
|
3497
|
+
case "cached":
|
|
3498
|
+
store.applyCached(block.values);
|
|
3499
|
+
return;
|
|
3500
|
+
default: assertNever(block.kind, "session list projection block kind");
|
|
3501
|
+
}
|
|
3502
|
+
}
|
|
3503
|
+
/**
|
|
3504
|
+
* Apply one Session removal forwarded through `ctx.remote.$on`.
|
|
3505
|
+
* @param sessionId - removed Session identity.
|
|
3506
|
+
*/
|
|
3507
|
+
handleSessionRemoved(sessionId) {
|
|
3508
|
+
const durableSubagent = this.subagentAddress(sessionId) !== void 0 || this.summaries.some((summary) => summary.sessionId === sessionId && summary.origin === "subagent");
|
|
3509
|
+
this.recordMutation(durableSubagent ? {
|
|
3510
|
+
kind: "status",
|
|
3511
|
+
sessionId,
|
|
3512
|
+
running: false,
|
|
3513
|
+
agentAvailable: false
|
|
3514
|
+
} : {
|
|
3515
|
+
kind: "remove",
|
|
3516
|
+
sessionId
|
|
3517
|
+
});
|
|
3518
|
+
if (durableSubagent) this.sessions.get(sessionId)?.handleRunning(false);
|
|
3519
|
+
else this.sessions.get(sessionId)?.handleRemoved();
|
|
3520
|
+
const catalog = this.projectionStores.get(sessionId)?.values().subagentCatalog;
|
|
3521
|
+
if (!durableSubagent && (catalog === void 0 || catalog.length === 0)) this.projectionStores.delete(sessionId);
|
|
3522
|
+
this.pruneEngagement(sessionId, this.retainedIds(this.summaries));
|
|
3523
|
+
this.projectionInflight.get(sessionId)?.controller.abort();
|
|
3524
|
+
this.projectionInflight.delete(sessionId);
|
|
3525
|
+
this.projectionLoads.delete(sessionId);
|
|
3526
|
+
for (const [childId, address] of this.addresses) if (address.parentSessionId === sessionId) this.sessions.get(childId)?.handleSubagentParentAvailable(false);
|
|
3527
|
+
}
|
|
3528
|
+
/**
|
|
3529
|
+
* Apply one live Agent running-state change.
|
|
3530
|
+
* @param sessionId - Session whose Agent state changed.
|
|
3531
|
+
* @param running - current Agent running state.
|
|
3532
|
+
*/
|
|
3533
|
+
handleSessionStatus(sessionId, running) {
|
|
3534
|
+
if (!this.disposed && running) this.engagedSessions.add(sessionId);
|
|
3535
|
+
this.recordMutation({
|
|
3536
|
+
kind: "status",
|
|
3537
|
+
sessionId,
|
|
3538
|
+
running,
|
|
3539
|
+
agentAvailable: true
|
|
3540
|
+
});
|
|
3541
|
+
this.updateParentAvailability();
|
|
3542
|
+
this.sessions.get(sessionId)?.handleRunning(running);
|
|
3543
|
+
}
|
|
3544
|
+
/**
|
|
3545
|
+
* Advance Session-list activity from one user-authored durable message.
|
|
3546
|
+
* @param sessionId - Session whose activity changed.
|
|
3547
|
+
* @param updatedAt - durable message timestamp.
|
|
3548
|
+
*/
|
|
3549
|
+
handleSessionActivity(sessionId, updatedAt) {
|
|
3550
|
+
this.recordMutation({
|
|
3551
|
+
kind: "activity",
|
|
3552
|
+
sessionId,
|
|
3553
|
+
updatedAt
|
|
3554
|
+
});
|
|
3555
|
+
}
|
|
3556
|
+
/**
|
|
3557
|
+
* Surface one live Agent failure on an already-materialized Session.
|
|
3558
|
+
* @param sessionId - Session whose Agent failed.
|
|
3559
|
+
* @param message - caller-visible failure description.
|
|
3560
|
+
*/
|
|
3561
|
+
handleSessionError(sessionId, message) {
|
|
3562
|
+
this.sessions.get(sessionId)?.handleAgentError(message);
|
|
3563
|
+
}
|
|
3564
|
+
/**
|
|
3565
|
+
* Repair one re-established Host-event generation with queryable baselines.
|
|
3566
|
+
* Discard old projection cuts before new queries, including cold Sessions
|
|
3567
|
+
* absent from the process-local control baseline.
|
|
3568
|
+
* Opened Session follow streams resume independently through API Gateway.
|
|
3569
|
+
*/
|
|
3570
|
+
handleConnected() {
|
|
3571
|
+
for (const store of this.projectionStores.values()) store.clear();
|
|
3572
|
+
this.listMutations = null;
|
|
3573
|
+
this.listInflight = null;
|
|
3574
|
+
this.refreshList();
|
|
3575
|
+
const parents = new Set(this.projectionLoads.keys());
|
|
3576
|
+
for (const id of this.sessions.keys()) {
|
|
3577
|
+
const address = this.addresses.get(id);
|
|
3578
|
+
if (address !== void 0) parents.add(address.parentSessionId);
|
|
3579
|
+
}
|
|
3580
|
+
for (const { controller } of this.projectionInflight.values()) controller.abort();
|
|
3581
|
+
this.projectionInflight.clear();
|
|
3582
|
+
this.projectionLoads.clear();
|
|
3583
|
+
for (const parentSessionId of parents) this.refreshProjections(parentSessionId);
|
|
3584
|
+
}
|
|
3585
|
+
buildListSnapshot() {
|
|
3586
|
+
const items = flattenLineage(this.summaries.map((summary) => {
|
|
3587
|
+
const projectionStore = this.projectionStores.get(summary.sessionId);
|
|
3588
|
+
const title = projectionStore?.get("title");
|
|
3589
|
+
const projectionValues = projectionStore?.values();
|
|
3590
|
+
const metadata = projectionValues?.sessionListMetadata;
|
|
3591
|
+
return {
|
|
3592
|
+
...summary,
|
|
3593
|
+
blank: this.effectiveBlank(summary) && metadata?.blank !== false,
|
|
3594
|
+
updatedAt: Math.max(summary.updatedAt, metadata?.lastPromptAt ?? 0),
|
|
3595
|
+
...typeof title === "string" && title !== "" ? { title } : {},
|
|
3596
|
+
...projectionValues === void 0 ? {} : { projectionValues }
|
|
3597
|
+
};
|
|
3598
|
+
})).map((entry) => {
|
|
3599
|
+
const prev = this.entryCache.get(entry.sessionId);
|
|
3600
|
+
if (prev !== void 0 && prev.updatedAt === entry.updatedAt && prev.running === entry.running && prev.blank === entry.blank && prev.parentSessionId === entry.parentSessionId && prev.cwd === entry.cwd && prev.origin === entry.origin && prev.title === entry.title && prev.depth === entry.depth && prev.formatStatus === entry.formatStatus && prev.projectionValues === entry.projectionValues) return prev;
|
|
3601
|
+
this.entryCache.set(entry.sessionId, entry);
|
|
3602
|
+
return entry;
|
|
3603
|
+
});
|
|
3604
|
+
const itemIds = new Set(items.map((entry) => entry.sessionId));
|
|
3605
|
+
for (const id of this.entryCache.keys()) if (!itemIds.has(id)) this.entryCache.delete(id);
|
|
3606
|
+
if (!(items.length === this.itemsCache.length && items.every((e, i) => e === this.itemsCache[i]))) this.itemsCache = items;
|
|
3607
|
+
return {
|
|
3608
|
+
items: this.itemsCache,
|
|
3609
|
+
state: this.listState,
|
|
3610
|
+
phase: this.listPhase,
|
|
3611
|
+
error: this.listError,
|
|
3612
|
+
projectionsBySession: Object.fromEntries([...this.projectionStores].map(([sessionId, store]) => [sessionId, {
|
|
3613
|
+
values: store.values(),
|
|
3614
|
+
state: "idle",
|
|
3615
|
+
error: null,
|
|
3616
|
+
...this.projectionLoads.get(sessionId)
|
|
3617
|
+
}]))
|
|
3618
|
+
};
|
|
3619
|
+
}
|
|
3620
|
+
};
|
|
3621
|
+
/** Apply one list mutation without deriving display order. */
|
|
3622
|
+
function applyMutation(summaries, mutation) {
|
|
3623
|
+
switch (mutation.kind) {
|
|
3624
|
+
case "upsert":
|
|
3625
|
+
case "placeholder": {
|
|
3626
|
+
const existing = summaries.find((summary) => summary.sessionId === mutation.summary.sessionId);
|
|
3627
|
+
if (existing === void 0) return [mutation.summary, ...summaries];
|
|
3628
|
+
const filled = {
|
|
3629
|
+
...existing,
|
|
3630
|
+
blank: existing.blank && mutation.summary.blank,
|
|
3631
|
+
...mutation.kind === "upsert" ? {
|
|
3632
|
+
agentAvailable: mutation.summary.agentAvailable,
|
|
3633
|
+
running: mutation.summary.running,
|
|
3634
|
+
...mutation.summary.formatStatus === void 0 ? {} : { formatStatus: mutation.summary.formatStatus }
|
|
3635
|
+
} : {},
|
|
3636
|
+
...existing.cwd === void 0 && mutation.summary.cwd !== void 0 ? { cwd: mutation.summary.cwd } : {},
|
|
3637
|
+
...existing.parentSessionId === void 0 && mutation.summary.parentSessionId !== void 0 ? { parentSessionId: mutation.summary.parentSessionId } : {},
|
|
3638
|
+
...existing.origin === void 0 && mutation.summary.origin !== void 0 ? { origin: mutation.summary.origin } : {}
|
|
3639
|
+
};
|
|
3640
|
+
if (filled.cwd === existing.cwd && filled.parentSessionId === existing.parentSessionId && filled.origin === existing.origin && filled.blank === existing.blank && filled.agentAvailable === existing.agentAvailable && filled.running === existing.running && filled.formatStatus === existing.formatStatus) return [...summaries];
|
|
3641
|
+
return summaries.map((summary) => summary.sessionId === mutation.summary.sessionId ? filled : summary);
|
|
3642
|
+
}
|
|
3643
|
+
case "remove": return summaries.filter((summary) => summary.sessionId !== mutation.sessionId);
|
|
3644
|
+
case "status": return summaries.map((summary) => summary.sessionId === mutation.sessionId && (summary.running !== mutation.running || summary.agentAvailable !== mutation.agentAvailable || mutation.running && summary.blank) ? {
|
|
3645
|
+
...summary,
|
|
3646
|
+
running: mutation.running,
|
|
3647
|
+
agentAvailable: mutation.agentAvailable,
|
|
3648
|
+
blank: summary.blank && !mutation.running
|
|
3649
|
+
} : summary);
|
|
3650
|
+
case "activity": return summaries.map((summary) => summary.sessionId === mutation.sessionId && mutation.updatedAt > summary.updatedAt ? {
|
|
3651
|
+
...summary,
|
|
3652
|
+
updatedAt: mutation.updatedAt
|
|
3653
|
+
} : summary);
|
|
3654
|
+
case "engaged": return summaries.map((summary) => summary.sessionId === mutation.sessionId && summary.blank ? {
|
|
3655
|
+
...summary,
|
|
3656
|
+
blank: false
|
|
3657
|
+
} : summary);
|
|
3658
|
+
}
|
|
3659
|
+
}
|
|
3660
|
+
/** Temporary source-plane bridge while the Host contract and client project build independently. */
|
|
3661
|
+
function workspaceAttachSessionId(error) {
|
|
3662
|
+
return error.code === "session/workspace-attach-failed" ? error.details.sessionId : void 0;
|
|
3663
|
+
}
|
|
3664
|
+
//#endregion
|
|
3665
|
+
//#region lib/types/client/sessions/service.js
|
|
3666
|
+
/** Structured session-create failure. */
|
|
3667
|
+
var SessionCreateError = class extends Error {
|
|
3668
|
+
rpcError;
|
|
3669
|
+
requestedSessionId;
|
|
3670
|
+
name = "SessionCreateError";
|
|
3671
|
+
/**
|
|
3672
|
+
* @param rpcError - Host business or folded transport error.
|
|
3673
|
+
* @param requestedSessionId - caller-preallocated id used for later stream/list reconciliation.
|
|
3674
|
+
*/
|
|
3675
|
+
constructor(rpcError, requestedSessionId) {
|
|
3676
|
+
super(`session create failed: ${rpcError.code}: ${rpcError.message}`);
|
|
3677
|
+
this.rpcError = rpcError;
|
|
3678
|
+
this.requestedSessionId = requestedSessionId;
|
|
3679
|
+
}
|
|
3680
|
+
};
|
|
3681
|
+
/** Structured session-fork failure. */
|
|
3682
|
+
var SessionForkError = class extends Error {
|
|
3683
|
+
rpcError;
|
|
3684
|
+
sourceSessionId;
|
|
3685
|
+
name = "SessionForkError";
|
|
3686
|
+
/**
|
|
3687
|
+
* @param rpcError - Host business or folded transport error.
|
|
3688
|
+
* @param sourceSessionId - the session the fork was cut from.
|
|
3689
|
+
*/
|
|
3690
|
+
constructor(rpcError, sourceSessionId) {
|
|
3691
|
+
super(`session fork failed: ${rpcError.code}: ${rpcError.message}`);
|
|
3692
|
+
this.rpcError = rpcError;
|
|
3693
|
+
this.sourceSessionId = sourceSessionId;
|
|
3694
|
+
}
|
|
3695
|
+
};
|
|
3696
|
+
/**
|
|
3697
|
+
* Display title projection: durable title, project directory basename, then
|
|
3698
|
+
* the raw id.
|
|
3699
|
+
*/
|
|
3700
|
+
function displayTitleOf(title, cwd, id) {
|
|
3701
|
+
if (title !== void 0) return title;
|
|
3702
|
+
if (cwd !== void 0 && cwd !== "") {
|
|
3703
|
+
const base = workspaceTitleOf(cwd);
|
|
3704
|
+
if (base !== "") return base;
|
|
3705
|
+
}
|
|
3706
|
+
return id;
|
|
3707
|
+
}
|
|
3708
|
+
/**
|
|
3709
|
+
* Increment a trailing fork number while preserving its half-width or
|
|
3710
|
+
* full-width parentheses; an unnumbered title starts with ` (1)`.
|
|
3711
|
+
* @param title - source session's durable title.
|
|
3712
|
+
* @returns the title assigned to the fork child.
|
|
3713
|
+
*/
|
|
3714
|
+
function increasedForkTitle(title) {
|
|
3715
|
+
const ascii = /^(.*?)\((\d+)\)$/u.exec(title);
|
|
3716
|
+
if (ascii?.[1] !== void 0 && ascii[2] !== void 0) return `${ascii[1]}(${BigInt(ascii[2]) + 1n})`;
|
|
3717
|
+
const fullWidth = /^(.*?)((\d+))$/u.exec(title);
|
|
3718
|
+
if (fullWidth?.[1] !== void 0 && fullWidth[2] !== void 0) return `${fullWidth[1]}(${BigInt(fullWidth[2]) + 1n})`;
|
|
3719
|
+
return `${title} (1)`;
|
|
3720
|
+
}
|
|
3721
|
+
/** Source labels are dictionary keys, including names also present on Object.prototype. */
|
|
3722
|
+
function freezeRetainedBy(counts) {
|
|
3723
|
+
Object.setPrototypeOf(counts, null);
|
|
3724
|
+
return Object.freeze(counts);
|
|
3725
|
+
}
|
|
3726
|
+
const EMPTY_RETAIN_INFO = Object.freeze({
|
|
3727
|
+
referenceCount: 0,
|
|
3728
|
+
retainedBy: freezeRetainedBy({})
|
|
3729
|
+
});
|
|
3730
|
+
/** A cancelled waiter releases only its own reference, not the shared opening. */
|
|
3731
|
+
async function waitForOpen(opening, signal) {
|
|
3732
|
+
if (signal === void 0) return opening;
|
|
3733
|
+
const aborted = Promise.withResolvers();
|
|
3734
|
+
const onAbort = () => {
|
|
3735
|
+
aborted.reject(signal.reason);
|
|
3736
|
+
};
|
|
3737
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
3738
|
+
try {
|
|
3739
|
+
if (signal.aborted) onAbort();
|
|
3740
|
+
await Promise.race([opening, aborted.promise]);
|
|
3741
|
+
} finally {
|
|
3742
|
+
signal.removeEventListener("abort", onAbort);
|
|
3743
|
+
}
|
|
3744
|
+
}
|
|
3745
|
+
var ClientSessionReference = class {
|
|
3746
|
+
sessionId;
|
|
3747
|
+
record;
|
|
3748
|
+
releaseReference;
|
|
3749
|
+
released = new AbortController();
|
|
3750
|
+
readiness = Promise.withResolvers();
|
|
3751
|
+
ready = this.readiness.promise;
|
|
3752
|
+
constructor(sessionId, record, releaseReference) {
|
|
3753
|
+
this.sessionId = sessionId;
|
|
3754
|
+
this.record = record;
|
|
3755
|
+
this.releaseReference = releaseReference;
|
|
3756
|
+
this.ready.catch(() => {});
|
|
3757
|
+
}
|
|
3758
|
+
get binding() {
|
|
3759
|
+
if (this.record === void 0 || !this.record.live) throw new Error(`Session reference "${this.sessionId}" is released`);
|
|
3760
|
+
return this.record.binding;
|
|
3761
|
+
}
|
|
3762
|
+
attachOpening(opening, signal) {
|
|
3763
|
+
const waitSignal = signal === void 0 ? this.released.signal : AbortSignal.any([this.released.signal, signal]);
|
|
3764
|
+
waitForOpen(opening, waitSignal).then(() => {
|
|
3765
|
+
try {
|
|
3766
|
+
waitSignal.throwIfAborted();
|
|
3767
|
+
this.readiness.resolve(this.binding);
|
|
3768
|
+
} catch (error) {
|
|
3769
|
+
this.readiness.reject(error);
|
|
3770
|
+
}
|
|
3771
|
+
}, (error) => {
|
|
3772
|
+
this.readiness.reject(error);
|
|
3773
|
+
});
|
|
3774
|
+
}
|
|
3775
|
+
release() {
|
|
3776
|
+
const reason = /* @__PURE__ */ new Error(`Session reference "${this.sessionId}" is released`);
|
|
3777
|
+
const release = this.releaseReference;
|
|
3778
|
+
this.released.abort(reason);
|
|
3779
|
+
this.readiness.reject(reason);
|
|
3780
|
+
this.record = void 0;
|
|
3781
|
+
this.releaseReference = void 0;
|
|
3782
|
+
release?.();
|
|
3783
|
+
}
|
|
3784
|
+
[Symbol.dispose]() {
|
|
3785
|
+
this.release();
|
|
3786
|
+
}
|
|
3787
|
+
};
|
|
3788
|
+
/** Host catalog and local reference allocator; view selection remains outside the Controller. */
|
|
3789
|
+
var ClientSessions = class {
|
|
3790
|
+
rootCtx;
|
|
3791
|
+
/**
|
|
3792
|
+
* The wire schema's own result bound, re-exposed for presentation plugins as
|
|
3793
|
+
* injected data. Not per-connection state: the `session.search` response
|
|
3794
|
+
* schema caps `items` at this constant, so every transport (fixture included)
|
|
3795
|
+
* reports the same number.
|
|
3796
|
+
*/
|
|
3797
|
+
searchResultLimit = 20;
|
|
3798
|
+
/** Catalog metadata and local reference-source projection. */
|
|
3799
|
+
list;
|
|
3800
|
+
/** The object-layer instance cluster and frame dispatch entry. */
|
|
3801
|
+
manager;
|
|
3802
|
+
scopes = /* @__PURE__ */ new Map();
|
|
3803
|
+
/** Stable per-id sources retained for the Client root lifetime, including across generation replacement. */
|
|
3804
|
+
retainObservers = /* @__PURE__ */ new Map();
|
|
3805
|
+
scopeDrops = /* @__PURE__ */ new Set();
|
|
3806
|
+
closed = false;
|
|
3807
|
+
/**
|
|
3808
|
+
* @param ctx - client root context (scope fibers mount under it).
|
|
3809
|
+
* @param remote - generated Remote namespaces shared with every Session.
|
|
3810
|
+
*/
|
|
3811
|
+
constructor(rootCtx, remote) {
|
|
3812
|
+
this.rootCtx = rootCtx;
|
|
3813
|
+
this.manager = new SessionManager(remote);
|
|
3814
|
+
this.list = (0, _unieai_rabi_client_store.createSnapshotStore)({
|
|
3815
|
+
ids: [],
|
|
3816
|
+
byId: {},
|
|
3817
|
+
phase: "pending",
|
|
3818
|
+
projectionsBySession: {}
|
|
3819
|
+
});
|
|
3820
|
+
const disposeManagerProjection = this.manager.subscribe(() => {
|
|
3821
|
+
this.projectList();
|
|
3822
|
+
});
|
|
3823
|
+
rootCtx.effect(() => async () => {
|
|
3824
|
+
this.closed = true;
|
|
3825
|
+
disposeManagerProjection();
|
|
3826
|
+
const scopes = [...this.scopes];
|
|
3827
|
+
this.scopes.clear();
|
|
3828
|
+
for (const [, record] of scopes) {
|
|
3829
|
+
record.live = false;
|
|
3830
|
+
record.session.unbindScope();
|
|
3831
|
+
}
|
|
3832
|
+
const managerDisposal = this.manager.dispose();
|
|
3833
|
+
for (const [id, record] of scopes) {
|
|
3834
|
+
this.startScopeDrop(id, record);
|
|
3835
|
+
this.publishRetention(id);
|
|
3836
|
+
}
|
|
3837
|
+
await this.drainScopeDrops();
|
|
3838
|
+
await managerDisposal;
|
|
3839
|
+
}, "session-controller.client.sessions");
|
|
3840
|
+
rootCtx.reflect.provide("sessions", this, void 0);
|
|
3841
|
+
}
|
|
3842
|
+
retain(target, options) {
|
|
3843
|
+
const { source, signal } = options;
|
|
3844
|
+
signal?.throwIfAborted();
|
|
3845
|
+
if (this.closed) throw new Error("Session Controller is disposed");
|
|
3846
|
+
const id = this.manager.resolveTarget(target);
|
|
3847
|
+
const reference = this.retainScope(id, source);
|
|
3848
|
+
try {
|
|
3849
|
+
reference.attachOpening(this.manager.get(id).open(), signal);
|
|
3850
|
+
return reference;
|
|
3851
|
+
} catch (error) {
|
|
3852
|
+
reference.release();
|
|
3853
|
+
throw error;
|
|
3854
|
+
}
|
|
3855
|
+
}
|
|
3856
|
+
async using(target, options, operation) {
|
|
3857
|
+
const reference = this.retain(target, options);
|
|
3858
|
+
try {
|
|
3859
|
+
await reference.ready;
|
|
3860
|
+
return await operation(reference);
|
|
3861
|
+
} finally {
|
|
3862
|
+
reference.release();
|
|
3863
|
+
}
|
|
3864
|
+
}
|
|
3865
|
+
retainInfo(id) {
|
|
3866
|
+
let observer = this.retainObservers.get(id);
|
|
3867
|
+
if (observer === void 0) {
|
|
3868
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
3869
|
+
observer = {
|
|
3870
|
+
listeners,
|
|
3871
|
+
published: this.retentionSnapshot(id),
|
|
3872
|
+
source: {
|
|
3873
|
+
getSnapshot: () => this.retentionSnapshot(id),
|
|
3874
|
+
subscribe: (listener) => {
|
|
3875
|
+
listeners.add(listener);
|
|
3876
|
+
return () => {
|
|
3877
|
+
listeners.delete(listener);
|
|
3878
|
+
};
|
|
3879
|
+
}
|
|
3880
|
+
}
|
|
3881
|
+
};
|
|
3882
|
+
this.retainObservers.set(id, observer);
|
|
3883
|
+
}
|
|
3884
|
+
return observer.source;
|
|
3885
|
+
}
|
|
3886
|
+
/**
|
|
3887
|
+
* Resolve an already discovered direct-parent address without opening it.
|
|
3888
|
+
* Feature plugins use this to avoid Agent-bound RPCs in persisted child views.
|
|
3889
|
+
* @param id - possible addressed child id.
|
|
3890
|
+
* @returns A retained, catalog-derived, or unknown-mode listed address, without retaining a new selection or scope.
|
|
3891
|
+
*/
|
|
3892
|
+
subagentAddress(id) {
|
|
3893
|
+
return this.manager.subagentAddress(id);
|
|
3894
|
+
}
|
|
3895
|
+
/**
|
|
3896
|
+
* Read projections without starting migration; retry failed or migration-deferred reads.
|
|
3897
|
+
* @param sessionId - Session to inspect without opening its conversation.
|
|
3898
|
+
*/
|
|
3899
|
+
refreshProjections(sessionId) {
|
|
3900
|
+
return this.manager.refreshProjections(sessionId);
|
|
3901
|
+
}
|
|
3902
|
+
/**
|
|
3903
|
+
* Refresh the real Session baseline, reusing an in-flight pull.
|
|
3904
|
+
* @returns completion of the current or newly started baseline pull.
|
|
3905
|
+
*/
|
|
3906
|
+
refresh() {
|
|
3907
|
+
return this.manager.refreshList();
|
|
3908
|
+
}
|
|
3909
|
+
/**
|
|
3910
|
+
* Search the Host's visible message-content index. Results stay
|
|
3911
|
+
* request-local; the list snapshot remains the metadata authority.
|
|
3912
|
+
* @param query - non-blank literal phrase.
|
|
3913
|
+
* @param signal - cancellation for a superseded search.
|
|
3914
|
+
* @returns bounded results or a business/transport error.
|
|
3915
|
+
*/
|
|
3916
|
+
search(query, signal) {
|
|
3917
|
+
return this.manager.search(query, signal);
|
|
3918
|
+
}
|
|
3919
|
+
/**
|
|
3920
|
+
* Apply one Session Controller live-control frame.
|
|
3921
|
+
* @param frame - baseline or live control replacement.
|
|
3922
|
+
*/
|
|
3923
|
+
handleControlFrame(frame) {
|
|
3924
|
+
this.manager.handleControlFrame(frame);
|
|
3925
|
+
}
|
|
3926
|
+
/**
|
|
3927
|
+
* Apply one remotely forwarded Session-list addition.
|
|
3928
|
+
* @param summary - current Host summary for the added Session.
|
|
3929
|
+
*/
|
|
3930
|
+
handleSessionAdded(summary) {
|
|
3931
|
+
this.manager.handleSessionAdded(summary);
|
|
3932
|
+
}
|
|
3933
|
+
/**
|
|
3934
|
+
* Apply one remotely forwarded Session removal.
|
|
3935
|
+
* @param sessionId - removed Session identity.
|
|
3936
|
+
*/
|
|
3937
|
+
handleSessionRemoved(sessionId) {
|
|
3938
|
+
this.manager.handleSessionRemoved(sessionId);
|
|
3939
|
+
}
|
|
3940
|
+
/**
|
|
3941
|
+
* Apply one remotely forwarded running-state change.
|
|
3942
|
+
* @param args - Session identity and current Agent running state.
|
|
3943
|
+
*/
|
|
3944
|
+
handleSessionStatus(...args) {
|
|
3945
|
+
this.manager.handleSessionStatus(...args);
|
|
3946
|
+
}
|
|
3947
|
+
/**
|
|
3948
|
+
* Apply one remotely forwarded list-activity change.
|
|
3949
|
+
* @param args - Session identity and durable activity timestamp.
|
|
3950
|
+
*/
|
|
3951
|
+
handleSessionActivity(...args) {
|
|
3952
|
+
this.manager.handleSessionActivity(...args);
|
|
3953
|
+
}
|
|
3954
|
+
/**
|
|
3955
|
+
* Apply one remotely forwarded Agent failure.
|
|
3956
|
+
* @param args - Session identity and caller-visible failure description.
|
|
3957
|
+
*/
|
|
3958
|
+
handleSessionError(...args) {
|
|
3959
|
+
this.manager.handleSessionError(...args);
|
|
3960
|
+
}
|
|
3961
|
+
/** Rebuild the Session baseline and every opened window after connection. */
|
|
3962
|
+
handleConnected() {
|
|
3963
|
+
this.manager.handleConnected();
|
|
3964
|
+
}
|
|
3965
|
+
/**
|
|
3966
|
+
* Create a Host Session and publish its catalog row before resolving.
|
|
3967
|
+
* Callers retain the returned identity before borrowing its binding.
|
|
3968
|
+
* @param opts - target workspace or directory, an optional blank Session to reuse, and an optional Agent preset.
|
|
3969
|
+
* @returns the created or reused session id.
|
|
3970
|
+
* @throws {SessionCreateError} with the requested id.
|
|
3971
|
+
*/
|
|
3972
|
+
async create(opts = {}) {
|
|
3973
|
+
const result = await this.manager.create(opts);
|
|
3974
|
+
if (!result.ok) throw new SessionCreateError(result.error, opts.sessionId);
|
|
3975
|
+
this.projectList();
|
|
3976
|
+
return result.value.sessionId;
|
|
3977
|
+
}
|
|
3978
|
+
/**
|
|
3979
|
+
* Fork a session from an exact inclusive prefix of the source (same
|
|
3980
|
+
* synchronous-addressability guarantee as {@link ClientSessions.create}:
|
|
3981
|
+
* on resolution the child is catalogued and may be explicitly retained).
|
|
3982
|
+
* @param opts - source session id, the optional exact inclusive boundary
|
|
3983
|
+
* seq (a real event seq the caller already knows; a cut inside an open
|
|
3984
|
+
* turn is balanced Host-side with synthetic closers, and omission selects
|
|
3985
|
+
* the latest completed-turn prefix), and whether to increment an
|
|
3986
|
+
* inherited durable title before resolving, plus permission to start source migration.
|
|
3987
|
+
* @returns the child session id.
|
|
3988
|
+
* @throws {SessionForkError} with the source id.
|
|
3989
|
+
* @throws {Error} when a requested child-title rename fails after creation.
|
|
3990
|
+
*/
|
|
3991
|
+
async fork(opts) {
|
|
3992
|
+
const sourceTitle = opts.increaseTitle ? this.list.getSnapshot().byId[opts.sessionId]?.title : void 0;
|
|
3993
|
+
const result = await this.manager.fork({
|
|
3994
|
+
sessionId: opts.sessionId,
|
|
3995
|
+
...opts.atSeq === void 0 ? {} : { atSeq: SessionSeq(opts.atSeq) },
|
|
3996
|
+
...opts.allowMigration === void 0 ? {} : { allowMigration: opts.allowMigration }
|
|
3997
|
+
});
|
|
3998
|
+
if (!result.ok) throw new SessionForkError(result.error, opts.sessionId);
|
|
3999
|
+
this.projectList();
|
|
4000
|
+
const childId = result.value.sessionId;
|
|
4001
|
+
opts.onCreated?.(childId);
|
|
4002
|
+
if (sourceTitle !== void 0) {
|
|
4003
|
+
const renamed = await this.manager.rename(childId, increasedForkTitle(sourceTitle));
|
|
4004
|
+
if (!renamed.ok) throw new Error(`fork child rename failed: ${renamed.error.code}: ${renamed.error.message}`);
|
|
4005
|
+
}
|
|
4006
|
+
return childId;
|
|
4007
|
+
}
|
|
4008
|
+
/**
|
|
4009
|
+
* Borrow an already-retained Agent-scoped Context.
|
|
4010
|
+
* @param id - session id (the agent identity — 1:1 same axis).
|
|
4011
|
+
* @returns the scoped Context, or undefined without a retained generation.
|
|
4012
|
+
*/
|
|
4013
|
+
scope(id) {
|
|
4014
|
+
return this.scopes.get(id)?.ctx;
|
|
4015
|
+
}
|
|
4016
|
+
/**
|
|
4017
|
+
* Retain a validated Gateway identity synchronously, without history or catalog I/O.
|
|
4018
|
+
* @param id - Host-projected Session identity, possibly not yet catalogued.
|
|
4019
|
+
* @returns a Gateway-source reference owned by the invocation.
|
|
4020
|
+
*/
|
|
4021
|
+
retainAgentScope(id) {
|
|
4022
|
+
if (this.closed) throw new Error("Session Controller is disposed");
|
|
4023
|
+
return this.retainScope(id, "gateway");
|
|
4024
|
+
}
|
|
4025
|
+
/**
|
|
4026
|
+
* Read the Agent scope tag off a context. Service-method boundary: fetch
|
|
4027
|
+
* bundles must reach scope resolution through ctx.sessions — a cross-bundle
|
|
4028
|
+
* value import of the standalone helper would inline a second module
|
|
4029
|
+
* instance whose private tag Symbol never matches.
|
|
4030
|
+
* @param ctx - any client context.
|
|
4031
|
+
* @returns the session id, or undefined on root contexts.
|
|
4032
|
+
*/
|
|
4033
|
+
scopeOf(ctx) {
|
|
4034
|
+
return scopeOf(ctx);
|
|
4035
|
+
}
|
|
4036
|
+
/**
|
|
4037
|
+
* Resolve the business Session behind an Agent-scoped context — the one
|
|
4038
|
+
* hop every scoped consumer (event listeners, per-session controllers)
|
|
4039
|
+
* takes from ctx-space into object-space (the client mirror of host
|
|
4040
|
+
* `agent.session`). Same service-method boundary as
|
|
4041
|
+
* {@link ClientSessions.scopeOf}.
|
|
4042
|
+
* @param ctx - an Agent-scoped context.
|
|
4043
|
+
* @returns the matching live Session, or undefined for an untagged or ended generation.
|
|
4044
|
+
*/
|
|
4045
|
+
sessionOf(ctx) {
|
|
4046
|
+
const id = scopeOf(ctx);
|
|
4047
|
+
if (id === void 0) return void 0;
|
|
4048
|
+
const record = this.scopes.get(id);
|
|
4049
|
+
return record !== void 0 && scopeIdentityOf(record.ctx) === scopeIdentityOf(ctx) ? record.binding.session : void 0;
|
|
4050
|
+
}
|
|
4051
|
+
/**
|
|
4052
|
+
* Borrow an already-retained binding without extending its lifetime.
|
|
4053
|
+
* @param id - Session identity.
|
|
4054
|
+
* @returns the live binding, or undefined without a retained generation.
|
|
4055
|
+
*/
|
|
4056
|
+
binding(id) {
|
|
4057
|
+
return this.scopes.get(id)?.binding;
|
|
4058
|
+
}
|
|
4059
|
+
retainScope(id, source) {
|
|
4060
|
+
const record = this.scopes.get(id) ?? this.materializeScope(id);
|
|
4061
|
+
const previous = record.retention;
|
|
4062
|
+
record.retention = Object.freeze({
|
|
4063
|
+
referenceCount: previous.referenceCount + 1,
|
|
4064
|
+
retainedBy: freezeRetainedBy({
|
|
4065
|
+
...previous.retainedBy,
|
|
4066
|
+
[source]: (previous.retainedBy[source] ?? 0) + 1
|
|
4067
|
+
})
|
|
4068
|
+
});
|
|
4069
|
+
const reference = new ClientSessionReference(id, record, () => {
|
|
4070
|
+
if (!record.live) return;
|
|
4071
|
+
const count = record.retention.referenceCount - 1;
|
|
4072
|
+
const { [source]: sourceCount = 0, ...otherSources } = record.retention.retainedBy;
|
|
4073
|
+
const retainedBy = sourceCount > 1 ? {
|
|
4074
|
+
...otherSources,
|
|
4075
|
+
[source]: sourceCount - 1
|
|
4076
|
+
} : otherSources;
|
|
4077
|
+
record.retention = count === 0 ? EMPTY_RETAIN_INFO : Object.freeze({
|
|
4078
|
+
referenceCount: count,
|
|
4079
|
+
retainedBy: freezeRetainedBy(retainedBy)
|
|
4080
|
+
});
|
|
4081
|
+
if (count === 0) this.retireScope(id, record);
|
|
4082
|
+
else this.publishRetention(id);
|
|
4083
|
+
});
|
|
4084
|
+
if (this.list.getSnapshot().byId[id] === void 0 && this.manager.subagentAddress(id) !== void 0) this.projectList();
|
|
4085
|
+
this.publishRetention(id);
|
|
4086
|
+
return reference;
|
|
4087
|
+
}
|
|
4088
|
+
retentionSnapshot(id) {
|
|
4089
|
+
return this.scopes.get(id)?.retention ?? EMPTY_RETAIN_INFO;
|
|
4090
|
+
}
|
|
4091
|
+
publishRetention(id) {
|
|
4092
|
+
const state = this.list.getSnapshot();
|
|
4093
|
+
const row = state.byId[id];
|
|
4094
|
+
const retainedBy = this.retentionSnapshot(id).retainedBy;
|
|
4095
|
+
if (row !== void 0 && row.retainedBy !== retainedBy) this.list.set({
|
|
4096
|
+
...state,
|
|
4097
|
+
byId: {
|
|
4098
|
+
...state.byId,
|
|
4099
|
+
[id]: {
|
|
4100
|
+
...row,
|
|
4101
|
+
retainedBy
|
|
4102
|
+
}
|
|
4103
|
+
}
|
|
4104
|
+
});
|
|
4105
|
+
const observer = this.retainObservers.get(id);
|
|
4106
|
+
const snapshot = this.retentionSnapshot(id);
|
|
4107
|
+
if (observer === void 0 || observer.published === snapshot) return;
|
|
4108
|
+
observer.published = snapshot;
|
|
4109
|
+
(0, _unieai_rabi_client_store.notifySubscribers)(observer.listeners, "[session-controller] reference sources");
|
|
4110
|
+
}
|
|
4111
|
+
retireScope(id, record, disposeFiber = true) {
|
|
4112
|
+
if (!record.live) return;
|
|
4113
|
+
record.live = false;
|
|
4114
|
+
if (this.scopes.get(id) === record) this.scopes.delete(id);
|
|
4115
|
+
record.session.unbindScope();
|
|
4116
|
+
const sessionDisposal = this.manager.drop(id, record.session);
|
|
4117
|
+
this.projectList();
|
|
4118
|
+
this.publishRetention(id);
|
|
4119
|
+
this.startScopeDrop(id, record, disposeFiber, sessionDisposal);
|
|
4120
|
+
}
|
|
4121
|
+
/** Materialize one scope after its caller establishes that the id may be addressed. */
|
|
4122
|
+
materializeScope(id) {
|
|
4123
|
+
const { fiber, ctx } = createScope(this.rootCtx, id);
|
|
4124
|
+
const session = this.manager.get(id);
|
|
4125
|
+
session.bindScope(ctx);
|
|
4126
|
+
const record = {
|
|
4127
|
+
fiber,
|
|
4128
|
+
ctx,
|
|
4129
|
+
binding: {
|
|
4130
|
+
sessionId: id,
|
|
4131
|
+
session,
|
|
4132
|
+
eventSource: session.eventSource,
|
|
4133
|
+
ctx
|
|
4134
|
+
},
|
|
4135
|
+
session,
|
|
4136
|
+
retention: EMPTY_RETAIN_INFO,
|
|
4137
|
+
live: true
|
|
4138
|
+
};
|
|
4139
|
+
this.scopes.set(id, record);
|
|
4140
|
+
ctx.effect(() => () => {
|
|
4141
|
+
this.retireScope(id, record, false);
|
|
4142
|
+
}, "session-controller: exact generation");
|
|
4143
|
+
return record;
|
|
4144
|
+
}
|
|
4145
|
+
/** Project the manager's list snapshot into the store (title derivation is display-only). */
|
|
4146
|
+
projectList() {
|
|
4147
|
+
const previousById = this.list.getSnapshot().byId;
|
|
4148
|
+
const { items, phase, projectionsBySession } = this.manager.getListSnapshot();
|
|
4149
|
+
const ids = [];
|
|
4150
|
+
const byId = {};
|
|
4151
|
+
for (const entry of items) {
|
|
4152
|
+
ids.push(entry.sessionId);
|
|
4153
|
+
byId[entry.sessionId] = {
|
|
4154
|
+
id: entry.sessionId,
|
|
4155
|
+
displayTitle: displayTitleOf(entry.title, entry.cwd, entry.sessionId),
|
|
4156
|
+
running: entry.running,
|
|
4157
|
+
retainedBy: this.retentionSnapshot(entry.sessionId).retainedBy,
|
|
4158
|
+
blank: entry.blank,
|
|
4159
|
+
updatedAt: entry.updatedAt,
|
|
4160
|
+
formatStatus: entry.formatStatus,
|
|
4161
|
+
...entry.projectionValues === void 0 ? {} : { projectionValues: entry.projectionValues },
|
|
4162
|
+
...entry.title !== void 0 ? { title: entry.title } : {},
|
|
4163
|
+
...entry.cwd !== void 0 ? { cwd: entry.cwd } : {},
|
|
4164
|
+
...entry.parentSessionId !== void 0 ? { parentId: entry.parentSessionId } : {},
|
|
4165
|
+
...entry.origin !== void 0 ? { origin: entry.origin } : {}
|
|
4166
|
+
};
|
|
4167
|
+
}
|
|
4168
|
+
for (const [parentId, projection] of Object.entries(projectionsBySession)) for (const child of projection.values.subagentCatalog ?? []) {
|
|
4169
|
+
if (child.mode === "external") continue;
|
|
4170
|
+
const childId = child.id;
|
|
4171
|
+
const summary = byId[childId];
|
|
4172
|
+
const projectionValues = summary?.projectionValues ?? this.manager.projectionValues(childId);
|
|
4173
|
+
const projectedTitle = projectionValues?.title;
|
|
4174
|
+
const title = typeof projectedTitle === "string" && projectedTitle !== "" ? projectedTitle : void 0;
|
|
4175
|
+
const displayTitle = title ?? child.label ?? childId;
|
|
4176
|
+
if (summary === void 0) byId[childId] = {
|
|
4177
|
+
id: childId,
|
|
4178
|
+
displayTitle,
|
|
4179
|
+
parentId,
|
|
4180
|
+
origin: "subagent",
|
|
4181
|
+
running: this.scopes.get(childId)?.session.getSnapshot().running ?? false,
|
|
4182
|
+
blank: false,
|
|
4183
|
+
updatedAt: 0,
|
|
4184
|
+
retainedBy: this.retentionSnapshot(childId).retainedBy,
|
|
4185
|
+
...projectionValues === void 0 ? {} : { projectionValues },
|
|
4186
|
+
...title === void 0 ? {} : { title }
|
|
4187
|
+
};
|
|
4188
|
+
else if (summary.displayTitle !== displayTitle || summary.projectionValues !== projectionValues) byId[childId] = {
|
|
4189
|
+
...summary,
|
|
4190
|
+
displayTitle,
|
|
4191
|
+
...projectionValues === void 0 ? {} : { projectionValues }
|
|
4192
|
+
};
|
|
4193
|
+
}
|
|
4194
|
+
for (const [id, record] of this.scopes) {
|
|
4195
|
+
if (byId[id] !== void 0) continue;
|
|
4196
|
+
const address = this.manager.subagentAddress(id);
|
|
4197
|
+
if (address === void 0) continue;
|
|
4198
|
+
const previous = previousById[id];
|
|
4199
|
+
const snapshot = record.session.getSnapshot();
|
|
4200
|
+
const projectionValues = this.manager.projectionValues(id);
|
|
4201
|
+
const projectedTitle = projectionValues?.title;
|
|
4202
|
+
const title = typeof projectedTitle === "string" && projectedTitle !== "" ? projectedTitle : previous?.title;
|
|
4203
|
+
byId[id] = {
|
|
4204
|
+
...previous ?? {
|
|
4205
|
+
id,
|
|
4206
|
+
displayTitle: id,
|
|
4207
|
+
updatedAt: 0
|
|
4208
|
+
},
|
|
4209
|
+
running: snapshot.running,
|
|
4210
|
+
retainedBy: record.retention.retainedBy,
|
|
4211
|
+
blank: snapshot.blank,
|
|
4212
|
+
parentId: address.parentSessionId,
|
|
4213
|
+
origin: "subagent",
|
|
4214
|
+
...projectionValues === void 0 ? {} : { projectionValues },
|
|
4215
|
+
...title === void 0 ? {} : {
|
|
4216
|
+
title,
|
|
4217
|
+
displayTitle: title
|
|
4218
|
+
}
|
|
4219
|
+
};
|
|
4220
|
+
}
|
|
4221
|
+
this.list.set({
|
|
4222
|
+
ids,
|
|
4223
|
+
byId,
|
|
4224
|
+
phase,
|
|
4225
|
+
projectionsBySession
|
|
4226
|
+
});
|
|
4227
|
+
}
|
|
4228
|
+
startScopeDrop(id, record, disposeFiber = true, sessionDisposal = this.manager.drop(id, record.session)) {
|
|
4229
|
+
const drop = this.dropScope(record, disposeFiber, sessionDisposal);
|
|
4230
|
+
this.scopeDrops.add(drop);
|
|
4231
|
+
drop.then(() => {
|
|
4232
|
+
this.scopeDrops.delete(drop);
|
|
4233
|
+
}, () => {
|
|
4234
|
+
this.scopeDrops.delete(drop);
|
|
4235
|
+
});
|
|
4236
|
+
}
|
|
4237
|
+
async drainScopeDrops() {
|
|
4238
|
+
while (this.scopeDrops.size > 0) await Promise.allSettled([...this.scopeDrops]);
|
|
4239
|
+
}
|
|
4240
|
+
/** Await the already-withdrawn Session and scoped cleanup to quiescence. */
|
|
4241
|
+
async dropScope(record, disposeFiber, sessionDisposal) {
|
|
4242
|
+
await Promise.allSettled([sessionDisposal, ...disposeFiber ? [record.fiber.dispose()] : []]);
|
|
4243
|
+
}
|
|
4244
|
+
};
|
|
4245
|
+
//#endregion
|
|
4246
|
+
//#region lib/types/client/index.js
|
|
4247
|
+
/** Client Session object layer, Agent scopes, and Remote lifecycle wiring. */
|
|
4248
|
+
/** Required Remote and Context projection services. */
|
|
4249
|
+
const inject = [
|
|
4250
|
+
"connection",
|
|
4251
|
+
"fileUpload",
|
|
4252
|
+
"typert",
|
|
4253
|
+
"remote",
|
|
4254
|
+
"remote.commands",
|
|
4255
|
+
"remote.session",
|
|
4256
|
+
"remote.subagents"
|
|
4257
|
+
];
|
|
4258
|
+
/**
|
|
4259
|
+
* Install Client Session state and its reconnecting control stream.
|
|
4260
|
+
* @param ctx - Client Cordis context.
|
|
4261
|
+
*/
|
|
4262
|
+
function apply(ctx) {
|
|
4263
|
+
const remotes = ctx.remote;
|
|
4264
|
+
const connection = ctx.get("connection");
|
|
4265
|
+
const sessions = new ClientSessions(ctx, remotes);
|
|
4266
|
+
ctx.remote.$on("api-session/added", (summary) => {
|
|
4267
|
+
sessions.handleSessionAdded(summary);
|
|
4268
|
+
});
|
|
4269
|
+
ctx.remote.$on("api-session/removed", (sessionId) => {
|
|
4270
|
+
sessions.handleSessionRemoved(sessionId);
|
|
4271
|
+
});
|
|
4272
|
+
ctx.remote.$on("api-session/status", (sessionId, running) => {
|
|
4273
|
+
sessions.handleSessionStatus(sessionId, running);
|
|
4274
|
+
});
|
|
4275
|
+
ctx.remote.$on("api-session/activity", (sessionId, updatedAt) => {
|
|
4276
|
+
sessions.handleSessionActivity(sessionId, updatedAt);
|
|
4277
|
+
});
|
|
4278
|
+
ctx.remote.$on("api-session/error", (sessionId, message) => {
|
|
4279
|
+
sessions.handleSessionError(sessionId, message);
|
|
4280
|
+
});
|
|
4281
|
+
const control = createSessionControlStream(remotes, {
|
|
4282
|
+
accept: (frame) => {
|
|
4283
|
+
sessions.handleControlFrame(frame);
|
|
4284
|
+
},
|
|
4285
|
+
failed: (error) => {
|
|
4286
|
+
console.error("[session-controller] control stream failed:", error);
|
|
4287
|
+
}
|
|
4288
|
+
});
|
|
4289
|
+
const connected = () => {
|
|
4290
|
+
if (connection.generation.getSnapshot() === void 0) return;
|
|
4291
|
+
sessions.handleConnected();
|
|
4292
|
+
control.restart();
|
|
4293
|
+
control.start();
|
|
4294
|
+
};
|
|
4295
|
+
ctx.effect(() => connection.generation.subscribe(connected), "session-controller.client.generation");
|
|
4296
|
+
connected();
|
|
4297
|
+
ctx.typert.contexts.registerClient("agent", {
|
|
4298
|
+
identity: (candidate) => sessions.sessionOf(candidate)?.sessionId,
|
|
4299
|
+
resolve: (sessionId) => {
|
|
4300
|
+
const reference = sessions.retainAgentScope(sessionId);
|
|
4301
|
+
return typertOwnedValue(reference.binding.ctx, () => {
|
|
4302
|
+
reference.release();
|
|
4303
|
+
});
|
|
4304
|
+
}
|
|
4305
|
+
});
|
|
4306
|
+
ctx.effect(() => async () => {
|
|
4307
|
+
await control.dispose();
|
|
4308
|
+
}, "session-controller.client.control");
|
|
4309
|
+
}
|
|
4310
|
+
//#endregion
|
|
4311
|
+
exports.MutableSessionEventSource = MutableSessionEventSource;
|
|
4312
|
+
exports.SESSION_SEARCH_RESULT_LIMIT = SESSION_SEARCH_RESULT_LIMIT;
|
|
4313
|
+
exports.SESSION_SEARCH_SNIPPET_MAX_CODE_POINTS = SESSION_SEARCH_SNIPPET_MAX_CODE_POINTS;
|
|
4314
|
+
exports.SessionCreateError = SessionCreateError;
|
|
4315
|
+
exports.SessionEventStream = SessionEventStream;
|
|
4316
|
+
exports.SessionForkError = SessionForkError;
|
|
4317
|
+
exports.apply = apply;
|
|
4318
|
+
exports.createScope = createScope;
|
|
4319
|
+
exports.createSessionControlStream = createSessionControlStream;
|
|
4320
|
+
exports.inject = inject;
|
|
4321
|
+
exports.scopeOf = scopeOf;
|
|
4322
|
+
return module.exports;
|
|
4323
|
+
}
|
|
4324
|
+
});
|
|
4325
|
+
|