@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
|
@@ -0,0 +1,582 @@
|
|
|
1
|
+
import { SessionSeq } from '@unieai/rabi-session/types';
|
|
2
|
+
import { workspaceTitleOf } from '@unieai/rabi-util-workspace-path';
|
|
3
|
+
import { SESSION_SEARCH_RESULT_LIMIT } from "../../types.js";
|
|
4
|
+
import { createSnapshotStore, notifySubscribers, } from '@unieai/rabi-client-store';
|
|
5
|
+
import { createScope, scopeIdentityOf, scopeOf as scopeTagOf } from "../scope.js";
|
|
6
|
+
import { SessionManager } from "./manager.js";
|
|
7
|
+
/** Structured session-create failure. */
|
|
8
|
+
export class SessionCreateError extends Error {
|
|
9
|
+
rpcError;
|
|
10
|
+
requestedSessionId;
|
|
11
|
+
name = 'SessionCreateError';
|
|
12
|
+
/**
|
|
13
|
+
* @param rpcError - Host business or folded transport error.
|
|
14
|
+
* @param requestedSessionId - caller-preallocated id used for later stream/list reconciliation.
|
|
15
|
+
*/
|
|
16
|
+
constructor(rpcError, requestedSessionId) {
|
|
17
|
+
super(`session create failed: ${rpcError.code}: ${rpcError.message}`);
|
|
18
|
+
this.rpcError = rpcError;
|
|
19
|
+
this.requestedSessionId = requestedSessionId;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
/** Structured session-fork failure. */
|
|
23
|
+
export class SessionForkError extends Error {
|
|
24
|
+
rpcError;
|
|
25
|
+
sourceSessionId;
|
|
26
|
+
name = 'SessionForkError';
|
|
27
|
+
/**
|
|
28
|
+
* @param rpcError - Host business or folded transport error.
|
|
29
|
+
* @param sourceSessionId - the session the fork was cut from.
|
|
30
|
+
*/
|
|
31
|
+
constructor(rpcError, sourceSessionId) {
|
|
32
|
+
super(`session fork failed: ${rpcError.code}: ${rpcError.message}`);
|
|
33
|
+
this.rpcError = rpcError;
|
|
34
|
+
this.sourceSessionId = sourceSessionId;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
// Scope primitives live in ../scope.ts (the client mirror of host
|
|
38
|
+
// rabi-scope, keyed by Agent identity); re-exported here so existing
|
|
39
|
+
// consumers keep their import site.
|
|
40
|
+
export { scopeOf } from "../scope.js";
|
|
41
|
+
/**
|
|
42
|
+
* Display title projection: durable title, project directory basename, then
|
|
43
|
+
* the raw id.
|
|
44
|
+
*/
|
|
45
|
+
function displayTitleOf(title, cwd, id) {
|
|
46
|
+
if (title !== undefined)
|
|
47
|
+
return title;
|
|
48
|
+
if (cwd !== undefined && cwd !== '') {
|
|
49
|
+
const base = workspaceTitleOf(cwd);
|
|
50
|
+
if (base !== '')
|
|
51
|
+
return base;
|
|
52
|
+
}
|
|
53
|
+
return id;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Increment a trailing fork number while preserving its half-width or
|
|
57
|
+
* full-width parentheses; an unnumbered title starts with ` (1)`.
|
|
58
|
+
* @param title - source session's durable title.
|
|
59
|
+
* @returns the title assigned to the fork child.
|
|
60
|
+
*/
|
|
61
|
+
function increasedForkTitle(title) {
|
|
62
|
+
const ascii = /^(.*?)\((\d+)\)$/u.exec(title);
|
|
63
|
+
if (ascii?.[1] !== undefined && ascii[2] !== undefined) {
|
|
64
|
+
return `${ascii[1]}(${BigInt(ascii[2]) + 1n})`;
|
|
65
|
+
}
|
|
66
|
+
const fullWidth = /^(.*?)((\d+))$/u.exec(title);
|
|
67
|
+
if (fullWidth?.[1] !== undefined && fullWidth[2] !== undefined) {
|
|
68
|
+
return `${fullWidth[1]}(${BigInt(fullWidth[2]) + 1n})`;
|
|
69
|
+
}
|
|
70
|
+
return `${title} (1)`;
|
|
71
|
+
}
|
|
72
|
+
/** Source labels are dictionary keys, including names also present on Object.prototype. */
|
|
73
|
+
function freezeRetainedBy(counts) {
|
|
74
|
+
Object.setPrototypeOf(counts, null);
|
|
75
|
+
return Object.freeze(counts);
|
|
76
|
+
}
|
|
77
|
+
const EMPTY_RETAIN_INFO = Object.freeze({ referenceCount: 0, retainedBy: freezeRetainedBy({}) });
|
|
78
|
+
/** A cancelled waiter releases only its own reference, not the shared opening. */
|
|
79
|
+
async function waitForOpen(opening, signal) {
|
|
80
|
+
if (signal === undefined)
|
|
81
|
+
return opening;
|
|
82
|
+
const aborted = Promise.withResolvers();
|
|
83
|
+
const onAbort = () => { aborted.reject(signal.reason); };
|
|
84
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
85
|
+
try {
|
|
86
|
+
if (signal.aborted)
|
|
87
|
+
onAbort();
|
|
88
|
+
await Promise.race([opening, aborted.promise]);
|
|
89
|
+
}
|
|
90
|
+
finally {
|
|
91
|
+
signal.removeEventListener('abort', onAbort);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
class ClientSessionReference {
|
|
95
|
+
sessionId;
|
|
96
|
+
record;
|
|
97
|
+
releaseReference;
|
|
98
|
+
released = new AbortController();
|
|
99
|
+
readiness = Promise.withResolvers();
|
|
100
|
+
ready = this.readiness.promise;
|
|
101
|
+
constructor(sessionId, record, releaseReference) {
|
|
102
|
+
this.sessionId = sessionId;
|
|
103
|
+
this.record = record;
|
|
104
|
+
this.releaseReference = releaseReference;
|
|
105
|
+
void this.ready.catch(() => { });
|
|
106
|
+
}
|
|
107
|
+
get binding() {
|
|
108
|
+
if (this.record === undefined || !this.record.live)
|
|
109
|
+
throw new Error(`Session reference "${this.sessionId}" is released`);
|
|
110
|
+
return this.record.binding;
|
|
111
|
+
}
|
|
112
|
+
attachOpening(opening, signal) {
|
|
113
|
+
const waitSignal = signal === undefined
|
|
114
|
+
? this.released.signal
|
|
115
|
+
: AbortSignal.any([this.released.signal, signal]);
|
|
116
|
+
void waitForOpen(opening, waitSignal).then(() => {
|
|
117
|
+
try {
|
|
118
|
+
waitSignal.throwIfAborted();
|
|
119
|
+
this.readiness.resolve(this.binding);
|
|
120
|
+
}
|
|
121
|
+
catch (error) {
|
|
122
|
+
this.readiness.reject(error);
|
|
123
|
+
}
|
|
124
|
+
}, (error) => { this.readiness.reject(error); });
|
|
125
|
+
}
|
|
126
|
+
release() {
|
|
127
|
+
const reason = new Error(`Session reference "${this.sessionId}" is released`);
|
|
128
|
+
const release = this.releaseReference;
|
|
129
|
+
this.released.abort(reason);
|
|
130
|
+
this.readiness.reject(reason);
|
|
131
|
+
this.record = undefined;
|
|
132
|
+
this.releaseReference = undefined;
|
|
133
|
+
release?.();
|
|
134
|
+
}
|
|
135
|
+
[Symbol.dispose]() {
|
|
136
|
+
this.release();
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
/** Host catalog and local reference allocator; view selection remains outside the Controller. */
|
|
140
|
+
export class ClientSessions {
|
|
141
|
+
rootCtx;
|
|
142
|
+
/**
|
|
143
|
+
* The wire schema's own result bound, re-exposed for presentation plugins as
|
|
144
|
+
* injected data. Not per-connection state: the `session.search` response
|
|
145
|
+
* schema caps `items` at this constant, so every transport (fixture included)
|
|
146
|
+
* reports the same number.
|
|
147
|
+
*/
|
|
148
|
+
searchResultLimit = SESSION_SEARCH_RESULT_LIMIT;
|
|
149
|
+
/** Catalog metadata and local reference-source projection. */
|
|
150
|
+
list;
|
|
151
|
+
/** The object-layer instance cluster and frame dispatch entry. */
|
|
152
|
+
manager;
|
|
153
|
+
scopes = new Map();
|
|
154
|
+
/** Stable per-id sources retained for the Client root lifetime, including across generation replacement. */
|
|
155
|
+
retainObservers = new Map();
|
|
156
|
+
scopeDrops = new Set();
|
|
157
|
+
closed = false;
|
|
158
|
+
/**
|
|
159
|
+
* @param ctx - client root context (scope fibers mount under it).
|
|
160
|
+
* @param remote - generated Remote namespaces shared with every Session.
|
|
161
|
+
*/
|
|
162
|
+
constructor(rootCtx, remote) {
|
|
163
|
+
this.rootCtx = rootCtx;
|
|
164
|
+
this.manager = new SessionManager(remote);
|
|
165
|
+
this.list = createSnapshotStore({
|
|
166
|
+
ids: [], byId: {}, phase: 'pending', projectionsBySession: {},
|
|
167
|
+
});
|
|
168
|
+
const disposeManagerProjection = this.manager.subscribe(() => { this.projectList(); });
|
|
169
|
+
rootCtx.effect(() => async () => {
|
|
170
|
+
this.closed = true;
|
|
171
|
+
disposeManagerProjection();
|
|
172
|
+
const scopes = [...this.scopes];
|
|
173
|
+
this.scopes.clear();
|
|
174
|
+
for (const [, record] of scopes) {
|
|
175
|
+
record.live = false;
|
|
176
|
+
record.session.unbindScope();
|
|
177
|
+
}
|
|
178
|
+
const managerDisposal = this.manager.dispose();
|
|
179
|
+
for (const [id, record] of scopes) {
|
|
180
|
+
this.startScopeDrop(id, record);
|
|
181
|
+
this.publishRetention(id);
|
|
182
|
+
}
|
|
183
|
+
await this.drainScopeDrops();
|
|
184
|
+
await managerDisposal;
|
|
185
|
+
}, 'session-controller.client.sessions');
|
|
186
|
+
rootCtx.reflect.provide('sessions', this, undefined);
|
|
187
|
+
}
|
|
188
|
+
retain(target, options) {
|
|
189
|
+
const { source, signal } = options;
|
|
190
|
+
signal?.throwIfAborted();
|
|
191
|
+
if (this.closed)
|
|
192
|
+
throw new Error('Session Controller is disposed');
|
|
193
|
+
const id = this.manager.resolveTarget(target);
|
|
194
|
+
const reference = this.retainScope(id, source);
|
|
195
|
+
try {
|
|
196
|
+
reference.attachOpening(this.manager.get(id).open(), signal);
|
|
197
|
+
return reference;
|
|
198
|
+
}
|
|
199
|
+
catch (error) {
|
|
200
|
+
reference.release();
|
|
201
|
+
throw error;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
async using(target, options, operation) {
|
|
205
|
+
const reference = this.retain(target, options);
|
|
206
|
+
try {
|
|
207
|
+
await reference.ready;
|
|
208
|
+
return await operation(reference);
|
|
209
|
+
}
|
|
210
|
+
finally {
|
|
211
|
+
reference.release();
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
retainInfo(id) {
|
|
215
|
+
let observer = this.retainObservers.get(id);
|
|
216
|
+
if (observer === undefined) {
|
|
217
|
+
const listeners = new Set();
|
|
218
|
+
observer = {
|
|
219
|
+
listeners,
|
|
220
|
+
published: this.retentionSnapshot(id),
|
|
221
|
+
source: {
|
|
222
|
+
getSnapshot: () => this.retentionSnapshot(id),
|
|
223
|
+
subscribe: (listener) => {
|
|
224
|
+
listeners.add(listener);
|
|
225
|
+
return () => { listeners.delete(listener); };
|
|
226
|
+
},
|
|
227
|
+
},
|
|
228
|
+
};
|
|
229
|
+
this.retainObservers.set(id, observer);
|
|
230
|
+
}
|
|
231
|
+
return observer.source;
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* Resolve an already discovered direct-parent address without opening it.
|
|
235
|
+
* Feature plugins use this to avoid Agent-bound RPCs in persisted child views.
|
|
236
|
+
* @param id - possible addressed child id.
|
|
237
|
+
* @returns A retained, catalog-derived, or unknown-mode listed address, without retaining a new selection or scope.
|
|
238
|
+
*/
|
|
239
|
+
subagentAddress(id) {
|
|
240
|
+
return this.manager.subagentAddress(id);
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* Read projections without starting migration; retry failed or migration-deferred reads.
|
|
244
|
+
* @param sessionId - Session to inspect without opening its conversation.
|
|
245
|
+
*/
|
|
246
|
+
refreshProjections(sessionId) {
|
|
247
|
+
return this.manager.refreshProjections(sessionId);
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* Refresh the real Session baseline, reusing an in-flight pull.
|
|
251
|
+
* @returns completion of the current or newly started baseline pull.
|
|
252
|
+
*/
|
|
253
|
+
refresh() {
|
|
254
|
+
return this.manager.refreshList();
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Search the Host's visible message-content index. Results stay
|
|
258
|
+
* request-local; the list snapshot remains the metadata authority.
|
|
259
|
+
* @param query - non-blank literal phrase.
|
|
260
|
+
* @param signal - cancellation for a superseded search.
|
|
261
|
+
* @returns bounded results or a business/transport error.
|
|
262
|
+
*/
|
|
263
|
+
search(query, signal) {
|
|
264
|
+
return this.manager.search(query, signal);
|
|
265
|
+
}
|
|
266
|
+
/**
|
|
267
|
+
* Apply one Session Controller live-control frame.
|
|
268
|
+
* @param frame - baseline or live control replacement.
|
|
269
|
+
*/
|
|
270
|
+
handleControlFrame(frame) {
|
|
271
|
+
this.manager.handleControlFrame(frame);
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Apply one remotely forwarded Session-list addition.
|
|
275
|
+
* @param summary - current Host summary for the added Session.
|
|
276
|
+
*/
|
|
277
|
+
handleSessionAdded(summary) {
|
|
278
|
+
this.manager.handleSessionAdded(summary);
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* Apply one remotely forwarded Session removal.
|
|
282
|
+
* @param sessionId - removed Session identity.
|
|
283
|
+
*/
|
|
284
|
+
handleSessionRemoved(sessionId) {
|
|
285
|
+
this.manager.handleSessionRemoved(sessionId);
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* Apply one remotely forwarded running-state change.
|
|
289
|
+
* @param args - Session identity and current Agent running state.
|
|
290
|
+
*/
|
|
291
|
+
handleSessionStatus(...args) {
|
|
292
|
+
this.manager.handleSessionStatus(...args);
|
|
293
|
+
}
|
|
294
|
+
/**
|
|
295
|
+
* Apply one remotely forwarded list-activity change.
|
|
296
|
+
* @param args - Session identity and durable activity timestamp.
|
|
297
|
+
*/
|
|
298
|
+
handleSessionActivity(...args) {
|
|
299
|
+
this.manager.handleSessionActivity(...args);
|
|
300
|
+
}
|
|
301
|
+
/**
|
|
302
|
+
* Apply one remotely forwarded Agent failure.
|
|
303
|
+
* @param args - Session identity and caller-visible failure description.
|
|
304
|
+
*/
|
|
305
|
+
handleSessionError(...args) {
|
|
306
|
+
this.manager.handleSessionError(...args);
|
|
307
|
+
}
|
|
308
|
+
/** Rebuild the Session baseline and every opened window after connection. */
|
|
309
|
+
handleConnected() {
|
|
310
|
+
this.manager.handleConnected();
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* Create a Host Session and publish its catalog row before resolving.
|
|
314
|
+
* Callers retain the returned identity before borrowing its binding.
|
|
315
|
+
* @param opts - target workspace or directory, an optional blank Session to reuse, and an optional Agent preset.
|
|
316
|
+
* @returns the created or reused session id.
|
|
317
|
+
* @throws {SessionCreateError} with the requested id.
|
|
318
|
+
*/
|
|
319
|
+
async create(opts = {}) {
|
|
320
|
+
const result = await this.manager.create(opts);
|
|
321
|
+
if (!result.ok)
|
|
322
|
+
throw new SessionCreateError(result.error, opts.sessionId);
|
|
323
|
+
this.projectList();
|
|
324
|
+
return result.value.sessionId;
|
|
325
|
+
}
|
|
326
|
+
/**
|
|
327
|
+
* Fork a session from an exact inclusive prefix of the source (same
|
|
328
|
+
* synchronous-addressability guarantee as {@link ClientSessions.create}:
|
|
329
|
+
* on resolution the child is catalogued and may be explicitly retained).
|
|
330
|
+
* @param opts - source session id, the optional exact inclusive boundary
|
|
331
|
+
* seq (a real event seq the caller already knows; a cut inside an open
|
|
332
|
+
* turn is balanced Host-side with synthetic closers, and omission selects
|
|
333
|
+
* the latest completed-turn prefix), and whether to increment an
|
|
334
|
+
* inherited durable title before resolving, plus permission to start source migration.
|
|
335
|
+
* @returns the child session id.
|
|
336
|
+
* @throws {SessionForkError} with the source id.
|
|
337
|
+
* @throws {Error} when a requested child-title rename fails after creation.
|
|
338
|
+
*/
|
|
339
|
+
async fork(opts) {
|
|
340
|
+
const sourceTitle = opts.increaseTitle
|
|
341
|
+
? this.list.getSnapshot().byId[opts.sessionId]?.title
|
|
342
|
+
: undefined;
|
|
343
|
+
const result = await this.manager.fork({
|
|
344
|
+
sessionId: opts.sessionId,
|
|
345
|
+
...(opts.atSeq === undefined ? {} : { atSeq: SessionSeq(opts.atSeq) }),
|
|
346
|
+
...(opts.allowMigration === undefined ? {} : { allowMigration: opts.allowMigration }),
|
|
347
|
+
});
|
|
348
|
+
if (!result.ok)
|
|
349
|
+
throw new SessionForkError(result.error, opts.sessionId);
|
|
350
|
+
this.projectList();
|
|
351
|
+
const childId = result.value.sessionId;
|
|
352
|
+
opts.onCreated?.(childId);
|
|
353
|
+
if (sourceTitle !== undefined) {
|
|
354
|
+
const renamed = await this.manager.rename(childId, increasedForkTitle(sourceTitle));
|
|
355
|
+
if (!renamed.ok)
|
|
356
|
+
throw new Error(`fork child rename failed: ${renamed.error.code}: ${renamed.error.message}`);
|
|
357
|
+
}
|
|
358
|
+
return childId;
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* Borrow an already-retained Agent-scoped Context.
|
|
362
|
+
* @param id - session id (the agent identity — 1:1 same axis).
|
|
363
|
+
* @returns the scoped Context, or undefined without a retained generation.
|
|
364
|
+
*/
|
|
365
|
+
scope(id) {
|
|
366
|
+
return this.scopes.get(id)?.ctx;
|
|
367
|
+
}
|
|
368
|
+
/**
|
|
369
|
+
* Retain a validated Gateway identity synchronously, without history or catalog I/O.
|
|
370
|
+
* @param id - Host-projected Session identity, possibly not yet catalogued.
|
|
371
|
+
* @returns a Gateway-source reference owned by the invocation.
|
|
372
|
+
*/
|
|
373
|
+
retainAgentScope(id) {
|
|
374
|
+
if (this.closed)
|
|
375
|
+
throw new Error('Session Controller is disposed');
|
|
376
|
+
return this.retainScope(id, 'gateway');
|
|
377
|
+
}
|
|
378
|
+
/**
|
|
379
|
+
* Read the Agent scope tag off a context. Service-method boundary: fetch
|
|
380
|
+
* bundles must reach scope resolution through ctx.sessions — a cross-bundle
|
|
381
|
+
* value import of the standalone helper would inline a second module
|
|
382
|
+
* instance whose private tag Symbol never matches.
|
|
383
|
+
* @param ctx - any client context.
|
|
384
|
+
* @returns the session id, or undefined on root contexts.
|
|
385
|
+
*/
|
|
386
|
+
scopeOf(ctx) {
|
|
387
|
+
return scopeTagOf(ctx);
|
|
388
|
+
}
|
|
389
|
+
/**
|
|
390
|
+
* Resolve the business Session behind an Agent-scoped context — the one
|
|
391
|
+
* hop every scoped consumer (event listeners, per-session controllers)
|
|
392
|
+
* takes from ctx-space into object-space (the client mirror of host
|
|
393
|
+
* `agent.session`). Same service-method boundary as
|
|
394
|
+
* {@link ClientSessions.scopeOf}.
|
|
395
|
+
* @param ctx - an Agent-scoped context.
|
|
396
|
+
* @returns the matching live Session, or undefined for an untagged or ended generation.
|
|
397
|
+
*/
|
|
398
|
+
sessionOf(ctx) {
|
|
399
|
+
const id = scopeTagOf(ctx);
|
|
400
|
+
if (id === undefined)
|
|
401
|
+
return undefined;
|
|
402
|
+
const record = this.scopes.get(id);
|
|
403
|
+
return record !== undefined && scopeIdentityOf(record.ctx) === scopeIdentityOf(ctx)
|
|
404
|
+
? record.binding.session
|
|
405
|
+
: undefined;
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* Borrow an already-retained binding without extending its lifetime.
|
|
409
|
+
* @param id - Session identity.
|
|
410
|
+
* @returns the live binding, or undefined without a retained generation.
|
|
411
|
+
*/
|
|
412
|
+
binding(id) {
|
|
413
|
+
return this.scopes.get(id)?.binding;
|
|
414
|
+
}
|
|
415
|
+
retainScope(id, source) {
|
|
416
|
+
const record = this.scopes.get(id) ?? this.materializeScope(id);
|
|
417
|
+
const previous = record.retention;
|
|
418
|
+
record.retention = Object.freeze({
|
|
419
|
+
referenceCount: previous.referenceCount + 1,
|
|
420
|
+
retainedBy: freezeRetainedBy({ ...previous.retainedBy, [source]: (previous.retainedBy[source] ?? 0) + 1 }),
|
|
421
|
+
});
|
|
422
|
+
const reference = new ClientSessionReference(id, record, () => {
|
|
423
|
+
if (!record.live)
|
|
424
|
+
return;
|
|
425
|
+
const count = record.retention.referenceCount - 1;
|
|
426
|
+
const { [source]: sourceCount = 0, ...otherSources } = record.retention.retainedBy;
|
|
427
|
+
const retainedBy = sourceCount > 1 ? { ...otherSources, [source]: sourceCount - 1 } : otherSources;
|
|
428
|
+
record.retention = count === 0
|
|
429
|
+
? EMPTY_RETAIN_INFO
|
|
430
|
+
: Object.freeze({ referenceCount: count, retainedBy: freezeRetainedBy(retainedBy) });
|
|
431
|
+
if (count === 0)
|
|
432
|
+
this.retireScope(id, record);
|
|
433
|
+
else
|
|
434
|
+
this.publishRetention(id);
|
|
435
|
+
});
|
|
436
|
+
if (this.list.getSnapshot().byId[id] === undefined && this.manager.subagentAddress(id) !== undefined) {
|
|
437
|
+
this.projectList();
|
|
438
|
+
}
|
|
439
|
+
this.publishRetention(id);
|
|
440
|
+
return reference;
|
|
441
|
+
}
|
|
442
|
+
retentionSnapshot(id) {
|
|
443
|
+
return this.scopes.get(id)?.retention ?? EMPTY_RETAIN_INFO;
|
|
444
|
+
}
|
|
445
|
+
publishRetention(id) {
|
|
446
|
+
const state = this.list.getSnapshot();
|
|
447
|
+
const row = state.byId[id];
|
|
448
|
+
const retainedBy = this.retentionSnapshot(id).retainedBy;
|
|
449
|
+
if (row !== undefined && row.retainedBy !== retainedBy) {
|
|
450
|
+
this.list.set({ ...state, byId: { ...state.byId, [id]: { ...row, retainedBy } } });
|
|
451
|
+
}
|
|
452
|
+
const observer = this.retainObservers.get(id);
|
|
453
|
+
const snapshot = this.retentionSnapshot(id);
|
|
454
|
+
if (observer === undefined || observer.published === snapshot)
|
|
455
|
+
return;
|
|
456
|
+
observer.published = snapshot;
|
|
457
|
+
notifySubscribers(observer.listeners, '[session-controller] reference sources');
|
|
458
|
+
}
|
|
459
|
+
retireScope(id, record, disposeFiber = true) {
|
|
460
|
+
if (!record.live)
|
|
461
|
+
return;
|
|
462
|
+
record.live = false;
|
|
463
|
+
if (this.scopes.get(id) === record)
|
|
464
|
+
this.scopes.delete(id);
|
|
465
|
+
record.session.unbindScope();
|
|
466
|
+
const sessionDisposal = this.manager.drop(id, record.session);
|
|
467
|
+
this.projectList();
|
|
468
|
+
this.publishRetention(id);
|
|
469
|
+
this.startScopeDrop(id, record, disposeFiber, sessionDisposal);
|
|
470
|
+
}
|
|
471
|
+
/** Materialize one scope after its caller establishes that the id may be addressed. */
|
|
472
|
+
materializeScope(id) {
|
|
473
|
+
const { fiber, ctx } = createScope(this.rootCtx, id);
|
|
474
|
+
const session = this.manager.get(id);
|
|
475
|
+
// The Session owns its scoped dispatch point (host Agent.loopCtx mirror);
|
|
476
|
+
// mint and bind are one step so a live scope record implies a bound actx.
|
|
477
|
+
session.bindScope(ctx);
|
|
478
|
+
const binding = { sessionId: id, session, eventSource: session.eventSource, ctx };
|
|
479
|
+
const record = {
|
|
480
|
+
fiber,
|
|
481
|
+
ctx,
|
|
482
|
+
binding,
|
|
483
|
+
session,
|
|
484
|
+
retention: EMPTY_RETAIN_INFO,
|
|
485
|
+
live: true,
|
|
486
|
+
};
|
|
487
|
+
this.scopes.set(id, record);
|
|
488
|
+
ctx.effect(() => () => { this.retireScope(id, record, false); }, 'session-controller: exact generation');
|
|
489
|
+
return record;
|
|
490
|
+
}
|
|
491
|
+
/** Project the manager's list snapshot into the store (title derivation is display-only). */
|
|
492
|
+
projectList() {
|
|
493
|
+
const previousById = this.list.getSnapshot().byId;
|
|
494
|
+
const { items, phase, projectionsBySession, } = this.manager.getListSnapshot();
|
|
495
|
+
const ids = [];
|
|
496
|
+
const byId = {};
|
|
497
|
+
for (const entry of items) {
|
|
498
|
+
ids.push(entry.sessionId);
|
|
499
|
+
byId[entry.sessionId] = {
|
|
500
|
+
id: entry.sessionId,
|
|
501
|
+
displayTitle: displayTitleOf(entry.title, entry.cwd, entry.sessionId),
|
|
502
|
+
running: entry.running,
|
|
503
|
+
retainedBy: this.retentionSnapshot(entry.sessionId).retainedBy,
|
|
504
|
+
blank: entry.blank,
|
|
505
|
+
updatedAt: entry.updatedAt,
|
|
506
|
+
formatStatus: entry.formatStatus,
|
|
507
|
+
...(entry.projectionValues === undefined
|
|
508
|
+
? {}
|
|
509
|
+
: { projectionValues: entry.projectionValues }),
|
|
510
|
+
...(entry.title !== undefined ? { title: entry.title } : {}),
|
|
511
|
+
...(entry.cwd !== undefined ? { cwd: entry.cwd } : {}),
|
|
512
|
+
...(entry.parentSessionId !== undefined ? { parentId: entry.parentSessionId } : {}),
|
|
513
|
+
...(entry.origin !== undefined ? { origin: entry.origin } : {}),
|
|
514
|
+
};
|
|
515
|
+
}
|
|
516
|
+
for (const [parentId, projection] of Object.entries(projectionsBySession)) {
|
|
517
|
+
for (const child of projection.values.subagentCatalog ?? []) {
|
|
518
|
+
if (child.mode === 'external')
|
|
519
|
+
continue;
|
|
520
|
+
const childId = child.id;
|
|
521
|
+
const summary = byId[childId];
|
|
522
|
+
const projectionValues = summary?.projectionValues ?? this.manager.projectionValues(childId);
|
|
523
|
+
const projectedTitle = projectionValues?.title;
|
|
524
|
+
const title = typeof projectedTitle === 'string' && projectedTitle !== '' ? projectedTitle : undefined;
|
|
525
|
+
const displayTitle = title ?? child.label ?? childId;
|
|
526
|
+
if (summary === undefined) {
|
|
527
|
+
byId[childId] = {
|
|
528
|
+
id: childId, displayTitle, parentId: parentId,
|
|
529
|
+
origin: 'subagent', running: this.scopes.get(childId)?.session.getSnapshot().running ?? false, blank: false, updatedAt: 0,
|
|
530
|
+
retainedBy: this.retentionSnapshot(childId).retainedBy,
|
|
531
|
+
...(projectionValues === undefined ? {} : { projectionValues }),
|
|
532
|
+
...(title === undefined ? {} : { title }),
|
|
533
|
+
};
|
|
534
|
+
}
|
|
535
|
+
else if (summary.displayTitle !== displayTitle || summary.projectionValues !== projectionValues) {
|
|
536
|
+
byId[childId] = {
|
|
537
|
+
...summary,
|
|
538
|
+
displayTitle,
|
|
539
|
+
...(projectionValues === undefined ? {} : { projectionValues }),
|
|
540
|
+
};
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
for (const [id, record] of this.scopes) {
|
|
545
|
+
if (byId[id] !== undefined)
|
|
546
|
+
continue;
|
|
547
|
+
const address = this.manager.subagentAddress(id);
|
|
548
|
+
if (address === undefined)
|
|
549
|
+
continue;
|
|
550
|
+
const previous = previousById[id];
|
|
551
|
+
const snapshot = record.session.getSnapshot();
|
|
552
|
+
const projectionValues = this.manager.projectionValues(id);
|
|
553
|
+
const projectedTitle = projectionValues?.title;
|
|
554
|
+
const title = typeof projectedTitle === 'string' && projectedTitle !== '' ? projectedTitle : previous?.title;
|
|
555
|
+
byId[id] = {
|
|
556
|
+
...(previous ?? { id, displayTitle: id, updatedAt: 0 }),
|
|
557
|
+
running: snapshot.running,
|
|
558
|
+
retainedBy: record.retention.retainedBy,
|
|
559
|
+
blank: snapshot.blank,
|
|
560
|
+
parentId: address.parentSessionId,
|
|
561
|
+
origin: 'subagent',
|
|
562
|
+
...(projectionValues === undefined ? {} : { projectionValues }),
|
|
563
|
+
...(title === undefined ? {} : { title, displayTitle: title }),
|
|
564
|
+
};
|
|
565
|
+
}
|
|
566
|
+
this.list.set({ ids, byId, phase, projectionsBySession });
|
|
567
|
+
}
|
|
568
|
+
startScopeDrop(id, record, disposeFiber = true, sessionDisposal = this.manager.drop(id, record.session)) {
|
|
569
|
+
const drop = this.dropScope(record, disposeFiber, sessionDisposal);
|
|
570
|
+
this.scopeDrops.add(drop);
|
|
571
|
+
void drop.then(() => { this.scopeDrops.delete(drop); }, () => { this.scopeDrops.delete(drop); });
|
|
572
|
+
}
|
|
573
|
+
async drainScopeDrops() {
|
|
574
|
+
while (this.scopeDrops.size > 0) {
|
|
575
|
+
await Promise.allSettled([...this.scopeDrops]);
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
/** Await the already-withdrawn Session and scoped cleanup to quiescence. */
|
|
579
|
+
async dropScope(record, disposeFiber, sessionDisposal) {
|
|
580
|
+
await Promise.allSettled([sessionDisposal, ...disposeFiber ? [record.fiber.dispose()] : []]);
|
|
581
|
+
}
|
|
582
|
+
}
|