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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +7 -2
  3. package/lib/client.js +4325 -0
  4. package/lib/index.js +3367 -0
  5. package/lib/typert.host.d.ts +3 -0
  6. package/lib/typert.host.js +4053 -0
  7. package/lib/typert.remote-client.d.ts +97 -0
  8. package/lib/typert.remote-client.js +2013 -0
  9. package/lib/types/agent.d.ts +198 -0
  10. package/lib/types/agent.js +609 -0
  11. package/lib/types/archived-session-gate.d.ts +30 -0
  12. package/lib/types/archived-session-gate.js +51 -0
  13. package/lib/types/assistant-stream.d.ts +26 -0
  14. package/lib/types/assistant-stream.js +82 -0
  15. package/lib/types/catalog.d.ts +24 -0
  16. package/lib/types/catalog.js +106 -0
  17. package/lib/types/client/contract/events.d.ts +102 -0
  18. package/lib/types/client/contract/events.js +111 -0
  19. package/lib/types/client/contract/session.d.ts +157 -0
  20. package/lib/types/client/contract/session.js +1 -0
  21. package/lib/types/client/contract/sessions.d.ts +161 -0
  22. package/lib/types/client/contract/sessions.js +1 -0
  23. package/lib/types/client/contract/snapshot.d.ts +81 -0
  24. package/lib/types/client/contract/snapshot.js +1 -0
  25. package/lib/types/client/index.d.ts +39 -0
  26. package/lib/types/client/index.js +60 -0
  27. package/lib/types/client/ordered-baseline.d.ts +12 -0
  28. package/lib/types/client/ordered-baseline.js +40 -0
  29. package/lib/types/client/scope.d.ts +46 -0
  30. package/lib/types/client/scope.js +46 -0
  31. package/lib/types/client/session-wire-event.d.ts +11 -0
  32. package/lib/types/client/session-wire-event.js +42 -0
  33. package/lib/types/client/sessions/assistant-stream.d.ts +56 -0
  34. package/lib/types/client/sessions/assistant-stream.js +182 -0
  35. package/lib/types/client/sessions/history-records.d.ts +22 -0
  36. package/lib/types/client/sessions/history-records.js +25 -0
  37. package/lib/types/client/sessions/lineage.d.ts +40 -0
  38. package/lib/types/client/sessions/lineage.js +54 -0
  39. package/lib/types/client/sessions/manager.d.ts +269 -0
  40. package/lib/types/client/sessions/manager.js +799 -0
  41. package/lib/types/client/sessions/notifier.d.ts +39 -0
  42. package/lib/types/client/sessions/notifier.js +97 -0
  43. package/lib/types/client/sessions/projection-store.d.ts +128 -0
  44. package/lib/types/client/sessions/projection-store.js +161 -0
  45. package/lib/types/client/sessions/remotes.d.ts +29 -0
  46. package/lib/types/client/sessions/remotes.js +7 -0
  47. package/lib/types/client/sessions/service.d.ts +258 -0
  48. package/lib/types/client/sessions/service.js +582 -0
  49. package/lib/types/client/sessions/session.d.ts +287 -0
  50. package/lib/types/client/sessions/session.js +866 -0
  51. package/lib/types/client/time-zone.d.ts +8 -0
  52. package/lib/types/client/time-zone.js +13 -0
  53. package/lib/types/client/transport.d.ts +77 -0
  54. package/lib/types/client/transport.js +129 -0
  55. package/lib/types/commands.d.ts +86 -0
  56. package/lib/types/commands.js +624 -0
  57. package/lib/types/control.d.ts +20 -0
  58. package/lib/types/control.js +106 -0
  59. package/lib/types/file-references.d.ts +27 -0
  60. package/lib/types/file-references.js +68 -0
  61. package/lib/types/history.d.ts +32 -0
  62. package/lib/types/history.js +441 -0
  63. package/lib/types/index.d.ts +222 -0
  64. package/lib/types/index.js +658 -0
  65. package/lib/types/list.d.ts +50 -0
  66. package/lib/types/list.js +325 -0
  67. package/lib/types/media-references.d.ts +16 -0
  68. package/lib/types/media-references.js +76 -0
  69. package/lib/types/model-selection-projection.d.ts +8 -0
  70. package/lib/types/model-selection-projection.js +65 -0
  71. package/lib/types/remote-events.d.ts +8 -0
  72. package/lib/types/remote-events.js +1 -0
  73. package/lib/types/skill-catalog.d.ts +28 -0
  74. package/lib/types/skill-catalog.js +203 -0
  75. package/lib/types/types.d.ts +611 -0
  76. package/lib/types/types.js +4 -0
  77. package/locale/en.json +5 -0
  78. package/locale/zh.json +6 -0
  79. package/package.json +114 -4
@@ -0,0 +1,609 @@
1
+ /** Agent activation, composition, and model-selection policy owned by API Session. */
2
+ var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {
3
+ if (value !== null && value !== void 0) {
4
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
5
+ var dispose, inner;
6
+ if (async) {
7
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
8
+ dispose = value[Symbol.asyncDispose];
9
+ }
10
+ if (dispose === void 0) {
11
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
12
+ dispose = value[Symbol.dispose];
13
+ if (async) inner = dispose;
14
+ }
15
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
16
+ if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
17
+ env.stack.push({ value: value, dispose: dispose, async: async });
18
+ }
19
+ else if (async) {
20
+ env.stack.push({ async: true });
21
+ }
22
+ return value;
23
+ };
24
+ var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {
25
+ return function (env) {
26
+ function fail(e) {
27
+ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
28
+ env.hasError = true;
29
+ }
30
+ var r, s = 0;
31
+ function next() {
32
+ while (r = env.stack.pop()) {
33
+ try {
34
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
35
+ if (r.dispose) {
36
+ var result = r.dispose.call(r.value);
37
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
38
+ }
39
+ else s |= 1;
40
+ }
41
+ catch (e) {
42
+ fail(e);
43
+ }
44
+ }
45
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
46
+ if (env.hasError) throw env.error;
47
+ }
48
+ return next();
49
+ };
50
+ })(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
51
+ var e = new Error(message);
52
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
53
+ });
54
+ import { randomUUID } from 'node:crypto';
55
+ import { mkdir } from 'node:fs/promises';
56
+ import { installModelSelection } from '@unieai/rabi-agent';
57
+ import { brandString } from '@unieai/rabi-brand';
58
+ import { ReasoningEffortId } from '@unieai/rabi-llm';
59
+ import { SessionQueryError } from '@unieai/rabi-session-query';
60
+ import { RemoteError, remoteErrorOf } from '@unieai/rabi-typert-protocol';
61
+ /** Cold Session identity absent from persistence. */
62
+ export class ApiSessionNotFound extends Error {
63
+ }
64
+ /** Session identity whose lifecycle belongs to subagent routing. */
65
+ export class ApiSessionSubagentOwnership extends Error {
66
+ sessionId;
67
+ /** @param sessionId - identity reserved to subagent routing. */
68
+ constructor(sessionId) {
69
+ super(`session "${sessionId}" is a subagent session; use subagent delivery`);
70
+ this.sessionId = sessionId;
71
+ }
72
+ }
73
+ /** Explicit-id creation attempted to adopt a Session under another cwd. */
74
+ export class ApiSessionCwdConflict extends Error {
75
+ sessionId;
76
+ requestedCwd;
77
+ existingCwd;
78
+ constructor(sessionId, requestedCwd, existingCwd) {
79
+ super(existingCwd === undefined
80
+ ? `session "${sessionId}" records no cwd and cannot be adopted for "${requestedCwd}"`
81
+ : `session "${sessionId}" belongs to "${existingCwd}", not "${requestedCwd}"`);
82
+ this.sessionId = sessionId;
83
+ this.requestedCwd = requestedCwd;
84
+ this.existingCwd = existingCwd;
85
+ }
86
+ }
87
+ /** Reuse of a Session named an Agent preset while the deployment composes no preset roster. */
88
+ export class ApiSessionPresetConflict extends Error {
89
+ sessionId;
90
+ requestedPreset;
91
+ constructor(sessionId, requestedPreset) {
92
+ super(`the deployment composes no agent preset roster, so session "${sessionId}" cannot run preset "${requestedPreset}"`);
93
+ this.sessionId = sessionId;
94
+ this.requestedPreset = requestedPreset;
95
+ }
96
+ }
97
+ /** A blank Session chosen for reuse started a turn before this Host acquired its writer. */
98
+ class ApiSessionStartedSinceObserved extends Error {
99
+ }
100
+ /**
101
+ * Test whether generic Session routing must leave an identity to subagent routing.
102
+ * @param ctx - Host context carrying the Agent ownership registry.
103
+ * @param session - attached or live Session whose ownership is tested.
104
+ * @param agent - live Agent when one exists for the Session.
105
+ * @returns whether subagent routing owns the Session identity.
106
+ */
107
+ export function hasApiSessionSubagentOwner(ctx, session, agent) {
108
+ if (session.header.origin === 'subagent')
109
+ return true;
110
+ const parentId = session.header.parentSession;
111
+ if (parentId === undefined || agent === undefined)
112
+ return false;
113
+ const parent = ctx.agents.get(parentId);
114
+ return parent !== undefined && ctx.agents.isOwnedBy(agent.id, parent);
115
+ }
116
+ /**
117
+ * Build the stable caller-facing subagent ownership rejection.
118
+ * @param sessionId - Session identity owned by subagent routing.
119
+ * @returns a stable Session-domain failure.
120
+ */
121
+ export function apiSessionSubagentOwnershipError(sessionId) {
122
+ return new RemoteError('session/agent-busy', `session "${sessionId}" is owned by subagent routing`, { reason: 'use subagent delivery for this child session' });
123
+ }
124
+ /**
125
+ * Inspect one cold Session without repairing, resuming, or publishing it.
126
+ * @param ctx - Host context carrying Session persistence.
127
+ * @param sessionId - durable Session identity.
128
+ * @param signal - optional cancellation for persistence reads.
129
+ * @returns the persisted header and complete event prefix.
130
+ */
131
+ export async function inspectApiSession(ctx, sessionId, signal) {
132
+ try {
133
+ const env_1 = { stack: [], error: void 0, hasError: false };
134
+ try {
135
+ const observation = __addDisposableResource(env_1, await ctx.sessionQuery.observeSession(sessionId, {
136
+ ...(signal === undefined ? {} : { signal }),
137
+ projectionMode: 'none',
138
+ }), false);
139
+ if (observation.header.cwd === undefined) {
140
+ throw new ApiSessionNotFound(`session "${sessionId}" not found`);
141
+ }
142
+ return {
143
+ meta: observation.header,
144
+ inheritedEventCount: observation.inheritedEventCount,
145
+ events: [...observation.events],
146
+ };
147
+ }
148
+ catch (e_1) {
149
+ env_1.error = e_1;
150
+ env_1.hasError = true;
151
+ }
152
+ finally {
153
+ __disposeResources(env_1);
154
+ }
155
+ }
156
+ catch (error) {
157
+ if (error instanceof SessionQueryError
158
+ && error.code === 'SESSION_QUERY_SESSION_NOT_FOUND') {
159
+ throw new ApiSessionNotFound(`session "${sessionId}" not found`);
160
+ }
161
+ throw error;
162
+ }
163
+ }
164
+ /** Owns every operation that may create, resume, or configure a Web Agent. */
165
+ export class ApiSessionAgentController {
166
+ ctx;
167
+ resumes = new Map();
168
+ claims = new Map();
169
+ selections = new WeakMap();
170
+ imageAdmissionChains = new WeakMap();
171
+ /** @param ctx - Host context carrying Agent, model, persistence, and Typert services. */
172
+ constructor(ctx) {
173
+ this.ctx = ctx;
174
+ ctx.typert.lookups.configure('agent', async (sessionId) => {
175
+ const found = await this.resolveAgent(sessionId);
176
+ if ('error' in found)
177
+ throw found.error;
178
+ return found.agent;
179
+ });
180
+ ctx.typert.lookups.configure('session', async (sessionId) => {
181
+ const found = await this.resolveAgent(sessionId);
182
+ if ('error' in found)
183
+ throw found.error;
184
+ return found.agent.session;
185
+ });
186
+ ctx.typert.contexts.configureHost('agent', async (sessionId) => {
187
+ const found = await this.resolveAgent(sessionId);
188
+ if ('error' in found)
189
+ throw found.error;
190
+ return found.agent.ctx;
191
+ });
192
+ }
193
+ /**
194
+ * Resolve or resume one ordinary Session, deduplicating concurrent resumes.
195
+ * @param sessionId - ordinary Session identity.
196
+ * @returns the live Agent or a stable Session-domain failure.
197
+ */
198
+ async resolveAgent(sessionId) {
199
+ return this.resolve(sessionId);
200
+ }
201
+ /**
202
+ * Resolve one ordinary Session from an already-retained exact observation.
203
+ * @param observation - Host-owned observation whose preparation stays pinned through setup.
204
+ * @returns the live Agent or a stable Session-domain failure.
205
+ */
206
+ async resolveObservedAgent(observation) {
207
+ return this.resolve(observation.header.id, observation);
208
+ }
209
+ async resolve(sessionId, observation) {
210
+ const live = this.liveAgent(sessionId);
211
+ if (live !== undefined)
212
+ return live;
213
+ const attached = this.ctx.sessions.get(sessionId);
214
+ if (attached !== undefined && hasApiSessionSubagentOwner(this.ctx, attached, undefined)) {
215
+ return { error: apiSessionSubagentOwnershipError(sessionId) };
216
+ }
217
+ let resume = this.resumes.get(sessionId);
218
+ if (resume === undefined) {
219
+ resume = this.resume(sessionId, observation).finally(() => { this.resumes.delete(sessionId); });
220
+ this.resumes.set(sessionId, resume);
221
+ }
222
+ try {
223
+ const agent = await resume;
224
+ // A shared resume can publish an identity that subagent routing adopts
225
+ // before every waiter observes it; apply the live ownership policy again.
226
+ const published = this.liveAgent(sessionId);
227
+ return published ?? { agent };
228
+ }
229
+ catch (error) {
230
+ if (error instanceof ApiSessionNotFound) {
231
+ return { error: new RemoteError('session/not-found', error.message, { sessionId }) };
232
+ }
233
+ if (error instanceof ApiSessionSubagentOwnership) {
234
+ return { error: apiSessionSubagentOwnershipError(error.sessionId) };
235
+ }
236
+ const raced = this.liveAgent(sessionId);
237
+ if (raced !== undefined)
238
+ return raced;
239
+ const racedSession = this.ctx.sessions.get(sessionId);
240
+ if (racedSession !== undefined && hasApiSessionSubagentOwner(this.ctx, racedSession, undefined)) {
241
+ return { error: apiSessionSubagentOwnershipError(sessionId) };
242
+ }
243
+ if (error instanceof Error && error.name === 'SessionAlreadyOwnedError') {
244
+ return { error: new RemoteError('session/writer-held', error.message, { sessionId }) };
245
+ }
246
+ return {
247
+ error: new RemoteError('gateway/internal', `resume failed for session "${sessionId}": ${String(error)}`, {}),
248
+ };
249
+ }
250
+ }
251
+ /**
252
+ * Create a Session for a new conversation, reusing the named blank Session
253
+ * while it is still reusable. A reused Session runs the requested preset, or
254
+ * the configured default when the request names none; the preset it recorded
255
+ * is not resolved, and a change is logged as `agent-preset/selected` before
256
+ * the Agent is published. A named Session that has started a turn, fails the
257
+ * caller's placement rule, or is written by another owner stays unchanged,
258
+ * and a new Session is created instead. Requests naming one identity run in
259
+ * arrival order, including their preset resolution, and check the named
260
+ * Session's directory and ownership before resolving the preset.
261
+ * @param request - optional Session to reuse, directory, preset, and placement rule.
262
+ * @returns the reused or created Session and the preset it ran when this request finished.
263
+ * @throws ApiSessionCwdConflict when the named Session belongs to another directory.
264
+ * @throws ApiSessionSubagentOwnership when subagent routing owns the named Session.
265
+ * @throws RemoteError `agent-preset/not-found` or `agent-preset/invalid` for the requested or default preset.
266
+ * @throws ApiSessionPresetConflict when no roster is composed and the request names a preset for a reused Session.
267
+ */
268
+ async createSession(request) {
269
+ const named = request.sessionId;
270
+ if (named === undefined)
271
+ return this.created(await this.createMinted(request.cwd, await this.composeAgent(request.agentPreset)));
272
+ return this.inOrder(named, async () => this.created(await this.claim(named, request)));
273
+ }
274
+ /**
275
+ * Install or return the Session-local model selection used by prompt assembly.
276
+ * @param agent - live Agent that owns the selection.
277
+ * @returns the installed mutable selection reference.
278
+ */
279
+ selectionFor(agent) {
280
+ const installed = this.selections.get(agent);
281
+ if (installed !== undefined)
282
+ return installed;
283
+ const projectionState = this.ctx.sessionProjections.stateOf(agent.session, 'modelSelection');
284
+ if (projectionState === undefined) {
285
+ throw new Error('api-session: required modelSelection projection is not registered');
286
+ }
287
+ let picked = projectionState.pending === null
288
+ ? undefined
289
+ : agentModelSelection(projectionState.pending);
290
+ const defaultModel = this.ctx.agentDefaultModel;
291
+ const selection = {
292
+ get current() {
293
+ if (picked !== undefined)
294
+ return picked;
295
+ const loggedHeader = agent.session.requestHeader();
296
+ if (loggedHeader === undefined)
297
+ return defaultModel.currentSelection();
298
+ const logged = loggedHeader.config;
299
+ return {
300
+ provider: logged.provider,
301
+ model: logged.model,
302
+ // An effort the adapter defaulted is not a conversation choice: restoring
303
+ // it as one would make an unchanged default read as a request change.
304
+ ...(logged.reasoningEffort === undefined
305
+ || loggedHeader.adapterDefaults?.reasoningEffort === true
306
+ ? {}
307
+ : { reasoningEffort: logged.reasoningEffort }),
308
+ };
309
+ },
310
+ set current(next) {
311
+ picked = next;
312
+ },
313
+ consume(provider, model, reasoningEffort) {
314
+ if (picked?.provider !== provider
315
+ || picked.model !== model
316
+ || picked.reasoningEffort !== reasoningEffort)
317
+ return false;
318
+ picked = undefined;
319
+ return true;
320
+ },
321
+ assembled: undefined,
322
+ };
323
+ installModelSelection(agent.ctx, selection);
324
+ this.selections.set(agent, selection);
325
+ return selection;
326
+ }
327
+ /**
328
+ * Commit and cache one validated selection for the next prompt assembly.
329
+ * @param agent - live Agent that owns the selection.
330
+ * @param selection - validated selection to record and apply.
331
+ */
332
+ selectForNextRequest(agent, selection) {
333
+ agent.session.append('model/selection', selection);
334
+ this.selectionFor(agent).current = selection;
335
+ }
336
+ /**
337
+ * Let a matching durable request header retire the execution cache.
338
+ * @param agent - live Agent whose request was recorded.
339
+ * @param provider - provider route used by the request.
340
+ * @param model - provider-owned model used by the request.
341
+ * @param reasoningEffort - adapter-owned effort used by the request.
342
+ * @returns whether the pending selection was consumed.
343
+ */
344
+ consumeSelection(agent, provider, model, reasoningEffort) {
345
+ return this.selections.get(agent)?.consume(provider, model, reasoningEffort) ?? false;
346
+ }
347
+ /**
348
+ * Read the current Agent preset from the Session projection.
349
+ * @param session - live Session whose projection state is available.
350
+ * @returns the current preset, or undefined when the capability is absent.
351
+ */
352
+ presetForSession(session) {
353
+ return this.ctx.sessionProjections.stateOf(session, 'agentPreset') ?? undefined;
354
+ }
355
+ /**
356
+ * Serialize image admission and model selection for one Agent.
357
+ * @param agent - live Agent that owns the serialization chain.
358
+ * @param operation - asynchronous operation admitted after prior work settles.
359
+ * @returns the operation result or rejection.
360
+ */
361
+ serializeImageAdmission(agent, operation) {
362
+ const result = (this.imageAdmissionChains.get(agent) ?? Promise.resolve()).then(operation);
363
+ this.imageAdmissionChains.set(agent, result.then(() => undefined, () => undefined));
364
+ return result;
365
+ }
366
+ /**
367
+ * Resolve the preset id and pre-publication Agent setup for a create or resume.
368
+ * @param presetId - requested preset or the configured default when omitted.
369
+ * @returns the resolved preset identity and Agent setup callback.
370
+ */
371
+ async composeAgent(presetId) {
372
+ const presets = this.ctx.get('agentPresets');
373
+ if (presets === undefined) {
374
+ return { setup: (_agentCtx, agent) => { this.installSelection(agent); } };
375
+ }
376
+ const resolvedId = (await presets.resolve(presetId)).id;
377
+ return {
378
+ agentPreset: resolvedId,
379
+ setup: async (agentCtx, agent) => {
380
+ this.installSelection(agent);
381
+ await presets.mount(agentCtx, resolvedId);
382
+ },
383
+ };
384
+ }
385
+ liveAgent(sessionId) {
386
+ const agent = this.ctx.agents.get(sessionId);
387
+ if (agent === undefined)
388
+ return undefined;
389
+ return hasApiSessionSubagentOwner(this.ctx, agent.session, agent)
390
+ ? { error: apiSessionSubagentOwnershipError(sessionId) }
391
+ : { agent };
392
+ }
393
+ async resume(sessionId, supplied) {
394
+ if (supplied !== undefined)
395
+ return this.resumeObserved(sessionId, supplied);
396
+ try {
397
+ const env_2 = { stack: [], error: void 0, hasError: false };
398
+ try {
399
+ const observation = __addDisposableResource(env_2, await this.ctx.sessionQuery.observeSession(sessionId), false);
400
+ return await this.resumeObserved(sessionId, observation);
401
+ }
402
+ catch (e_2) {
403
+ env_2.error = e_2;
404
+ env_2.hasError = true;
405
+ }
406
+ finally {
407
+ __disposeResources(env_2);
408
+ }
409
+ }
410
+ catch (error) {
411
+ if (error instanceof SessionQueryError
412
+ && error.code === 'SESSION_QUERY_SESSION_NOT_FOUND') {
413
+ throw new ApiSessionNotFound(`session "${sessionId}" not found`);
414
+ }
415
+ throw error;
416
+ }
417
+ }
418
+ async resumeObserved(sessionId, observation) {
419
+ if (observation.header.id !== sessionId || observation.header.cwd === undefined) {
420
+ throw new ApiSessionNotFound(`session "${sessionId}" not found`);
421
+ }
422
+ if (hasApiSessionSubagentOwner(this.ctx, { header: observation.header }, undefined)) {
423
+ throw new ApiSessionSubagentOwnership(sessionId);
424
+ }
425
+ const composition = await this.composeAgent(this.presetForObservation(observation));
426
+ const published = this.ctx.sessions.get(sessionId);
427
+ const live = this.ctx.agents.get(sessionId);
428
+ if (published !== undefined && hasApiSessionSubagentOwner(this.ctx, published, live)) {
429
+ throw new ApiSessionSubagentOwnership(sessionId);
430
+ }
431
+ return (await this.ctx.agents.resume({
432
+ resumeSessionId: sessionId,
433
+ agentOptions: this.agentOptions(),
434
+ setup: composition.setup,
435
+ })).agent;
436
+ }
437
+ async inOrder(sessionId, operation) {
438
+ const result = (this.claims.get(sessionId) ?? Promise.resolve()).then(operation);
439
+ const settled = result.then(() => undefined, () => undefined);
440
+ this.claims.set(sessionId, settled);
441
+ try {
442
+ return await result;
443
+ }
444
+ finally {
445
+ if (this.claims.get(sessionId) === settled)
446
+ this.claims.delete(sessionId);
447
+ }
448
+ }
449
+ /** @returns the reused Session, a new Session under `sessionId` when none is stored, or a new Session under a minted identity. */
450
+ async claim(sessionId, request) {
451
+ const attached = this.ctx.sessions.get(sessionId);
452
+ const live = this.ctx.agents.get(sessionId);
453
+ if (attached !== undefined && hasApiSessionSubagentOwner(this.ctx, attached, live)) {
454
+ throw new ApiSessionSubagentOwnership(sessionId);
455
+ }
456
+ if (live !== undefined) {
457
+ if (live.session.header.cwd !== request.cwd) {
458
+ throw new ApiSessionCwdConflict(live.id, request.cwd, live.session.header.cwd);
459
+ }
460
+ const composition = await this.composeAgent(request.agentPreset);
461
+ return await this.reuseLive(live, request, composition) ?? this.createMinted(request.cwd, composition);
462
+ }
463
+ let observation;
464
+ try {
465
+ observation = await this.ctx.sessionQuery.observeSession(sessionId);
466
+ }
467
+ catch (error) {
468
+ if (!(error instanceof SessionQueryError) || error.code !== 'SESSION_QUERY_SESSION_NOT_FOUND')
469
+ throw error;
470
+ return this.createAgent(sessionId, request.cwd, await this.composeAgent(request.agentPreset));
471
+ }
472
+ let reusable;
473
+ {
474
+ const env_3 = { stack: [], error: void 0, hasError: false };
475
+ try {
476
+ const observed = __addDisposableResource(env_3, observation, false);
477
+ if (hasApiSessionSubagentOwner(this.ctx, { header: observed.header }, undefined)) {
478
+ throw new ApiSessionSubagentOwnership(sessionId);
479
+ }
480
+ if (observed.header.cwd !== request.cwd) {
481
+ throw new ApiSessionCwdConflict(sessionId, request.cwd, observed.header.cwd);
482
+ }
483
+ reusable = request.reusable(sessionId) && !observed.events.some(event => event.type === 'turn/start');
484
+ }
485
+ catch (e_3) {
486
+ env_3.error = e_3;
487
+ env_3.hasError = true;
488
+ }
489
+ finally {
490
+ __disposeResources(env_3);
491
+ }
492
+ }
493
+ const composition = await this.composeAgent(request.agentPreset);
494
+ if (!reusable)
495
+ return this.createMinted(request.cwd, composition);
496
+ this.assertPresetApplicable(sessionId, request.agentPreset);
497
+ try {
498
+ return (await this.ctx.agents.resume({
499
+ resumeSessionId: sessionId,
500
+ agentOptions: this.agentOptions(),
501
+ setup: this.reuseSetup(composition),
502
+ })).agent;
503
+ }
504
+ catch (error) {
505
+ if (error instanceof ApiSessionStartedSinceObserved)
506
+ return this.createMinted(request.cwd, composition);
507
+ if (!(error instanceof Error) || error.name !== 'SessionAlreadyOwnedError')
508
+ throw error;
509
+ // Another resume in this process may hold the writer for the Agent it published.
510
+ return this.ctx.agents.get(sessionId) === undefined
511
+ ? this.createMinted(request.cwd, composition)
512
+ : this.claim(sessionId, request);
513
+ }
514
+ }
515
+ /** @returns the live blank Session under the requested preset, or undefined when it cannot be reused. */
516
+ async reuseLive(live, request, composition) {
517
+ if (!request.reusable(live.id) || !this.isBlank(live.session))
518
+ return undefined;
519
+ this.assertPresetApplicable(live.id, request.agentPreset);
520
+ const current = this.presetForSession(live.session);
521
+ const presets = this.ctx.get('agentPresets');
522
+ const target = composition.agentPreset;
523
+ if (presets === undefined || target === undefined || target === current)
524
+ return live;
525
+ try {
526
+ await presets.select(live, target);
527
+ }
528
+ catch (error) {
529
+ if (remoteErrorOf(error)?.code !== 'agent-preset/locked')
530
+ throw error;
531
+ return undefined;
532
+ }
533
+ return live;
534
+ }
535
+ /** Setup that re-checks blankness under the acquired writer, then records a preset change before publication. */
536
+ reuseSetup(composition) {
537
+ return async (agentCtx, agent) => {
538
+ if (!this.isBlank(agent.session))
539
+ throw new ApiSessionStartedSinceObserved();
540
+ const commit = await composition.setup(agentCtx, agent);
541
+ const target = composition.agentPreset;
542
+ if (target !== undefined && this.presetForSession(agent.session) !== target) {
543
+ agent.session.append('agent-preset/selected', { agentPreset: target });
544
+ }
545
+ return commit;
546
+ };
547
+ }
548
+ /** Whether no turn has started, by the predicate the preset registry's `select` enforces. */
549
+ isBlank(session) {
550
+ const boundary = this.ctx.sessionProjections.stateOf(session, 'turnBoundary');
551
+ return boundary === undefined || (boundary.openTurnStartSeq === null && boundary.lastTurn === 0);
552
+ }
553
+ /** Without a roster, reuse cannot apply a named preset. */
554
+ assertPresetApplicable(sessionId, requested) {
555
+ if (requested === undefined || this.ctx.get('agentPresets') !== undefined)
556
+ return;
557
+ throw new ApiSessionPresetConflict(sessionId, requested);
558
+ }
559
+ created(agent) {
560
+ return { agent, agentPreset: this.presetForSession(agent.session) };
561
+ }
562
+ createMinted(cwd, composition) {
563
+ return this.createAgent(brandString(`session-${randomUUID()}`), cwd, composition);
564
+ }
565
+ async createAgent(sessionId, cwd, composition) {
566
+ try {
567
+ await mkdir(cwd, { recursive: true });
568
+ }
569
+ catch (error) {
570
+ throw new Error(`failed to ensure project directory "${cwd}": ${String(error)}`, { cause: error });
571
+ }
572
+ return (await this.ctx.agents.create({
573
+ sessionId,
574
+ agentOptions: this.agentOptions(),
575
+ meta: {
576
+ cwd,
577
+ ...(composition.agentPreset === undefined ? {} : { agentPreset: composition.agentPreset }),
578
+ },
579
+ setup: composition.setup,
580
+ })).agent;
581
+ }
582
+ agentOptions() {
583
+ const { provider, model } = this.ctx.agentDefaultModel.currentSelection();
584
+ return { provider, model };
585
+ }
586
+ installSelection(agent) {
587
+ this.selectionFor(agent);
588
+ }
589
+ /**
590
+ * Read the current Agent preset from an all-projections observation.
591
+ * @param observation - exact Session observation carrying its projection snapshot.
592
+ * @returns the current preset, or undefined when the capability is absent.
593
+ */
594
+ presetForObservation(observation) {
595
+ if (observation.projections === undefined) {
596
+ throw new Error('api-session: Agent activation requires a projected Session observation');
597
+ }
598
+ return observation.projections.values.agentPreset ?? undefined;
599
+ }
600
+ }
601
+ function agentModelSelection(selection) {
602
+ return {
603
+ provider: selection.provider,
604
+ model: selection.model,
605
+ ...(selection.reasoningEffort === undefined
606
+ ? {}
607
+ : { reasoningEffort: ReasoningEffortId(selection.reasoningEffort) }),
608
+ };
609
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * The controller's admission gate for archived Sessions: an archived
3
+ * Session, or a subagent descendant of one, must not run a model step until
4
+ * it is restored. The work a Session still runs is reported and stopped by
5
+ * its owners — the Agent registry (`turn`), the job registry seam (`job`),
6
+ * the Subagent runtime (`subagent`), and the Schedule plugin (`schedule`) —
7
+ * through the Workspace registry's archive-admission events.
8
+ */
9
+ import type { Context, Plugin } from '@unieai/cordis';
10
+ import type { Agent } from '@unieai/rabi-agent';
11
+ /**
12
+ * The gate as a plugin for `ctx.plugin(...)`: it loads once the Agent
13
+ * registry, Session store, and Workspace registry are available and unwinds
14
+ * with the plugin's fiber. A late waking delivery to an archived Session — a
15
+ * subagent settlement, a queued follow-up — proposes a step the gate rejects,
16
+ * which the loop ends as `blocked` without a request; unarchiving lifts the
17
+ * gate for the whole lineage.
18
+ */
19
+ export declare const ArchivedSessionGate: Plugin.Object<void>;
20
+ /**
21
+ * Whether the Agent's Session, or a Session above it in its subagent lineage,
22
+ * is archived. Lineage follows the durable header fields through
23
+ * subagent-origin Sessions only: a fork of an archived Session is an
24
+ * independent conversation.
25
+ * @param ctx - Host context.
26
+ * @param agent - the Agent proposing a step.
27
+ * @returns whether an archived Session owns the step.
28
+ */
29
+ export declare function underArchivedSession(ctx: Context, agent: Agent): boolean;
30
+ //# sourceMappingURL=archived-session-gate.d.ts.map
@@ -0,0 +1,51 @@
1
+ /**
2
+ * The controller's admission gate for archived Sessions: an archived
3
+ * Session, or a subagent descendant of one, must not run a model step until
4
+ * it is restored. The work a Session still runs is reported and stopped by
5
+ * its owners — the Agent registry (`turn`), the job registry seam (`job`),
6
+ * the Subagent runtime (`subagent`), and the Schedule plugin (`schedule`) —
7
+ * through the Workspace registry's archive-admission events.
8
+ */
9
+ /**
10
+ * The gate as a plugin for `ctx.plugin(...)`: it loads once the Agent
11
+ * registry, Session store, and Workspace registry are available and unwinds
12
+ * with the plugin's fiber. A late waking delivery to an archived Session — a
13
+ * subagent settlement, a queued follow-up — proposes a step the gate rejects,
14
+ * which the loop ends as `blocked` without a request; unarchiving lifts the
15
+ * gate for the whole lineage.
16
+ */
17
+ export const ArchivedSessionGate = {
18
+ name: 'archived-session-gate',
19
+ inject: ['agents', 'sessions', 'workspaceRegistry'],
20
+ apply(ctx) {
21
+ ctx.on('agent/pre-step', (payload, next) => underArchivedSession(ctx, payload.agent)
22
+ ? Promise.resolve({ kind: 'reject' })
23
+ : next());
24
+ },
25
+ };
26
+ /**
27
+ * Whether the Agent's Session, or a Session above it in its subagent lineage,
28
+ * is archived. Lineage follows the durable header fields through
29
+ * subagent-origin Sessions only: a fork of an archived Session is an
30
+ * independent conversation.
31
+ * @param ctx - Host context.
32
+ * @param agent - the Agent proposing a step.
33
+ * @returns whether an archived Session owns the step.
34
+ */
35
+ export function underArchivedSession(ctx, agent) {
36
+ const archived = ctx.workspaceRegistry.archivedSessionIds;
37
+ let header = agent.session.header;
38
+ const visited = new Set();
39
+ while (!visited.has(header.id)) {
40
+ if (archived.includes(header.id))
41
+ return true;
42
+ visited.add(header.id);
43
+ if (header.origin !== 'subagent' || header.parentSession === undefined)
44
+ return false;
45
+ const parent = ctx.sessions.get(header.parentSession);
46
+ if (parent === undefined)
47
+ return archived.includes(header.parentSession);
48
+ header = parent.header;
49
+ }
50
+ return false;
51
+ }