@unieai/rabi-api-session-controller 0.0.0-stage → 0.2.2-rc.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +7 -2
  3. package/lib/client.js +4 -0
  4. package/lib/index.js +4300 -0
  5. package/lib/typert.host.d.ts +3 -0
  6. package/lib/typert.host.js +5013 -0
  7. package/lib/typert.remote-client.d.ts +115 -0
  8. package/lib/typert.remote-client.js +2714 -0
  9. package/lib/types/agent.d.ts +164 -0
  10. package/lib/types/agent.js +484 -0
  11. package/lib/types/archived-session-gate.d.ts +33 -0
  12. package/lib/types/archived-session-gate.js +54 -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 +107 -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 +178 -0
  20. package/lib/types/client/contract/session.js +1 -0
  21. package/lib/types/client/contract/sessions.d.ts +162 -0
  22. package/lib/types/client/contract/sessions.js +1 -0
  23. package/lib/types/client/contract/snapshot.d.ts +84 -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 +48 -0
  38. package/lib/types/client/sessions/lineage.js +55 -0
  39. package/lib/types/client/sessions/manager.d.ts +272 -0
  40. package/lib/types/client/sessions/manager.js +774 -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 +263 -0
  48. package/lib/types/client/sessions/service.js +597 -0
  49. package/lib/types/client/sessions/session.d.ts +303 -0
  50. package/lib/types/client/sessions/session.js +991 -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 +130 -0
  55. package/lib/types/commands.d.ts +92 -0
  56. package/lib/types/commands.js +575 -0
  57. package/lib/types/continuation.d.ts +35 -0
  58. package/lib/types/continuation.js +47 -0
  59. package/lib/types/control.d.ts +20 -0
  60. package/lib/types/control.js +106 -0
  61. package/lib/types/file-references.d.ts +27 -0
  62. package/lib/types/file-references.js +68 -0
  63. package/lib/types/history/assistant-stream.d.ts +43 -0
  64. package/lib/types/history/assistant-stream.js +79 -0
  65. package/lib/types/history/controller.d.ts +104 -0
  66. package/lib/types/history/controller.js +293 -0
  67. package/lib/types/history/listener.d.ts +105 -0
  68. package/lib/types/history/listener.js +296 -0
  69. package/lib/types/history.d.ts +58 -0
  70. package/lib/types/history.js +152 -0
  71. package/lib/types/index.d.ts +262 -0
  72. package/lib/types/index.js +693 -0
  73. package/lib/types/list.d.ts +62 -0
  74. package/lib/types/list.js +343 -0
  75. package/lib/types/media-references.d.ts +18 -0
  76. package/lib/types/media-references.js +84 -0
  77. package/lib/types/remote-events.d.ts +8 -0
  78. package/lib/types/remote-events.js +1 -0
  79. package/lib/types/skill-catalog.d.ts +28 -0
  80. package/lib/types/skill-catalog.js +203 -0
  81. package/lib/types/state/controller.d.ts +45 -0
  82. package/lib/types/state/controller.js +288 -0
  83. package/lib/types/state/listener.d.ts +40 -0
  84. package/lib/types/state/listener.js +111 -0
  85. package/lib/types/types.d.ts +687 -0
  86. package/lib/types/types.js +5 -0
  87. package/lib/types/web/controller.d.ts +25 -0
  88. package/lib/types/web/controller.js +138 -0
  89. package/locale/de.json +6 -0
  90. package/locale/en.json +5 -0
  91. package/locale/es.json +6 -0
  92. package/locale/fr.json +6 -0
  93. package/locale/ja.json +6 -0
  94. package/locale/pt.json +6 -0
  95. package/locale/ru.json +6 -0
  96. package/locale/zh.json +6 -0
  97. package/package.json +119 -4
  98. package/src/agent.ts +474 -0
  99. package/src/archived-session-gate.ts +59 -0
  100. package/src/assistant-stream.ts +102 -0
  101. package/src/catalog.ts +117 -0
  102. package/src/client/contract/events.ts +205 -0
  103. package/src/client/contract/session.ts +174 -0
  104. package/src/client/contract/sessions.ts +169 -0
  105. package/src/client/contract/snapshot.ts +94 -0
  106. package/src/client/index.ts +149 -0
  107. package/src/client/ordered-baseline.ts +43 -0
  108. package/src/client/scope.ts +76 -0
  109. package/src/client/session-wire-event.ts +46 -0
  110. package/src/client/sessions/assistant-stream.ts +229 -0
  111. package/src/client/sessions/history-records.ts +35 -0
  112. package/src/client/sessions/lineage.ts +96 -0
  113. package/src/client/sessions/manager.ts +857 -0
  114. package/src/client/sessions/notifier.ts +97 -0
  115. package/src/client/sessions/projection-store.ts +244 -0
  116. package/src/client/sessions/remotes.ts +44 -0
  117. package/src/client/sessions/service.ts +741 -0
  118. package/src/client/sessions/session.ts +1055 -0
  119. package/src/client/time-zone.ts +14 -0
  120. package/src/client/transport.ts +247 -0
  121. package/src/commands.ts +602 -0
  122. package/src/continuation.ts +58 -0
  123. package/src/control.ts +121 -0
  124. package/src/file-references.ts +42 -0
  125. package/src/history/assistant-stream.ts +102 -0
  126. package/src/history/controller.ts +256 -0
  127. package/src/history/listener.ts +302 -0
  128. package/src/history.ts +189 -0
  129. package/src/index.ts +651 -0
  130. package/src/list.ts +382 -0
  131. package/src/media-references.ts +84 -0
  132. package/src/remote-events.ts +14 -0
  133. package/src/skill-catalog.ts +108 -0
  134. package/src/state/controller.ts +221 -0
  135. package/src/state/listener.ts +116 -0
  136. package/src/types.ts +720 -0
  137. package/src/web/controller.ts +78 -0
@@ -0,0 +1,164 @@
1
+ /** Agent activation, composition, and initial model route owned by API Session. */
2
+ import type { Context } from '@unieai/cordis';
3
+ import type { Agent, AgentSetup } from '@unieai/rabi-agent';
4
+ import type { Session, SessionId } from '@unieai/rabi-session';
5
+ import { type SessionObservation } from '@unieai/rabi-session-query';
6
+ import { RemoteError } from '@unieai/rabi-typert-protocol';
7
+ /** Cold Session identity absent from persistence. */
8
+ export declare class ApiSessionNotFound extends Error {
9
+ }
10
+ /** Session identity whose lifecycle belongs to subagent routing. */
11
+ export declare class ApiSessionSubagentOwnership extends Error {
12
+ readonly sessionId: SessionId;
13
+ /** @param sessionId - identity reserved to subagent routing. */
14
+ constructor(sessionId: SessionId);
15
+ }
16
+ /** Explicit-id creation attempted to adopt a Session under another cwd. */
17
+ export declare class ApiSessionCwdConflict extends Error {
18
+ readonly sessionId: SessionId;
19
+ readonly requestedCwd: string;
20
+ readonly existingCwd: string | undefined;
21
+ constructor(sessionId: SessionId, requestedCwd: string, existingCwd: string | undefined);
22
+ }
23
+ /** Reuse of a Session named an Agent preset while the deployment composes no preset roster. */
24
+ export declare class ApiSessionPresetConflict extends Error {
25
+ readonly sessionId: SessionId;
26
+ readonly requestedPreset: string;
27
+ constructor(sessionId: SessionId, requestedPreset: string);
28
+ }
29
+ /** Placement and Agent preset for one Session created for a new conversation. */
30
+ export interface ApiSessionCreateRequest {
31
+ /** Blank Session to reuse, or the identity of a new Session when none is stored under it. */
32
+ readonly sessionId?: SessionId;
33
+ /** Directory the Session owns. */
34
+ readonly cwd: string;
35
+ /** Preset the Session runs; the configured default when omitted. */
36
+ readonly agentPreset?: string;
37
+ /**
38
+ * Placement rule the caller owns, such as Workspace membership and archive state.
39
+ * @param sessionId - existing Session named by the request.
40
+ * @returns whether that Session may be reused.
41
+ */
42
+ readonly reusable: (sessionId: SessionId) => boolean;
43
+ }
44
+ /** The Session one creation request created or reused. */
45
+ export interface ApiSessionCreated {
46
+ /** Live Agent of the Session. */
47
+ readonly agent: Agent;
48
+ /** Preset the Session ran when the request finished, before a later request for the same identity; absent without a roster. */
49
+ readonly agentPreset: string | undefined;
50
+ }
51
+ /** Resolved preset and pre-publication Agent setup for one create or resume. */
52
+ interface ApiSessionComposition {
53
+ readonly agentPreset?: string;
54
+ readonly setup: AgentSetup;
55
+ }
56
+ /** Failures produced while resolving one ordinary Session identity to its live Agent. */
57
+ export type ApiSessionAgentError = RemoteError<'session/not-found' | 'session/agent-busy' | 'session/writer-held' | 'gateway/internal'>;
58
+ /** Result of resolving one ordinary Session identity to its live Agent. */
59
+ export type ApiSessionAgentResult = {
60
+ readonly agent: Agent;
61
+ } | {
62
+ readonly error: ApiSessionAgentError;
63
+ };
64
+ /**
65
+ * Test whether generic Session routing must leave an identity to subagent routing.
66
+ * @param session - Attached or live Session whose origin is tested.
67
+ * @returns whether subagent routing owns the Session identity.
68
+ */
69
+ export declare function hasApiSessionSubagentOwner(session: Pick<Session, 'header'>): boolean;
70
+ /**
71
+ * Build the stable caller-facing subagent ownership rejection.
72
+ * @param sessionId - Session identity owned by subagent routing.
73
+ * @returns a stable Session-domain failure.
74
+ */
75
+ export declare function apiSessionSubagentOwnershipError(sessionId: SessionId): ApiSessionAgentError;
76
+ /** Owns every operation that may create, resume, or configure a Web Agent. */
77
+ export declare class ApiSessionAgentController {
78
+ private readonly ctx;
79
+ private readonly resumes;
80
+ private readonly claims;
81
+ private readonly imageAdmissionChains;
82
+ /** @param ctx - Host context carrying Agent, model, persistence, and Typert services. */
83
+ constructor(ctx: Context);
84
+ /**
85
+ * Configure Session and Agent lookups for Typert.
86
+ */
87
+ initialize(): void;
88
+ /**
89
+ * Resolve or resume one ordinary Session, deduplicating concurrent resumes.
90
+ * @param sessionId - ordinary Session identity.
91
+ * @returns the live Agent or a stable Session-domain failure.
92
+ */
93
+ resolveAgent(sessionId: SessionId): Promise<ApiSessionAgentResult>;
94
+ /**
95
+ * Resolve one ordinary Session from an already-retained exact observation.
96
+ * @param observation - Host-owned observation whose preparation stays pinned through setup.
97
+ * @returns the live Agent or a stable Session-domain failure.
98
+ */
99
+ resolveObservedAgent(observation: SessionObservation): Promise<ApiSessionAgentResult>;
100
+ private resolve;
101
+ /**
102
+ * Create a Session for a new conversation, reusing the named blank Session
103
+ * while it is still reusable. A reused Session runs the requested preset, or
104
+ * the configured default when the request names none; the preset it recorded
105
+ * is not resolved, and a change is logged as `agent-preset/selected` before
106
+ * the Agent is published. A named Session that has started a turn, fails the
107
+ * caller's placement rule, or is written by another owner stays unchanged,
108
+ * and a new Session is created instead. Requests naming one identity run in
109
+ * arrival order, including their preset resolution, and check the named
110
+ * Session's directory and ownership before resolving the preset.
111
+ * @param request - optional Session to reuse, directory, preset, and placement rule.
112
+ * @returns the reused or created Session and the preset it ran when this request finished.
113
+ * @throws ApiSessionCwdConflict when the named Session belongs to another directory.
114
+ * @throws ApiSessionSubagentOwnership when subagent routing owns the named Session.
115
+ * @throws RemoteError `agent-preset/not-found` or `agent-preset/invalid` for the requested or default preset.
116
+ * @throws ApiSessionPresetConflict when no roster is composed and the request names a preset for a reused Session.
117
+ */
118
+ createSession(request: ApiSessionCreateRequest): Promise<ApiSessionCreated>;
119
+ /**
120
+ * Read the current Agent preset from the Session projection.
121
+ * @param session - live Session whose projection state is available.
122
+ * @returns the current preset, or undefined without a preset service or recorded selection.
123
+ */
124
+ presetForSession(session: Session): string | undefined;
125
+ /**
126
+ * Serialize image admission and model selection for one Agent.
127
+ * @param agent - live Agent that owns the serialization chain.
128
+ * @param operation - asynchronous operation admitted after prior work settles.
129
+ * @returns the operation result or rejection.
130
+ */
131
+ serializeImageAdmission<Value>(agent: Agent, operation: () => Promise<Value>): Promise<Value>;
132
+ /**
133
+ * Resolve the preset id and pre-publication Agent setup for a create or resume.
134
+ * @param presetId - requested preset or the configured default when omitted.
135
+ * @returns the resolved preset identity and Agent setup callback.
136
+ */
137
+ composeAgent(presetId: string | undefined): Promise<ApiSessionComposition>;
138
+ private liveAgent;
139
+ private resume;
140
+ private resumeObserved;
141
+ private inOrder;
142
+ /** @returns the reused Session, a new Session under `sessionId` when none is stored, or a new Session under a minted identity. */
143
+ private claim;
144
+ /** @returns the live blank Session under the requested preset, or undefined when it cannot be reused. */
145
+ private reuseLive;
146
+ /** Setup that re-checks blankness under the acquired writer, then records a preset change before publication. */
147
+ private reuseSetup;
148
+ /** Whether no turn has started, by the predicate the preset registry's `select` enforces. */
149
+ private isBlank;
150
+ /** Without a roster, reuse cannot apply a named preset. */
151
+ private assertPresetApplicable;
152
+ private created;
153
+ private createMinted;
154
+ private createAgent;
155
+ private agentOptions;
156
+ /**
157
+ * Read the current Agent preset from an all-projections observation.
158
+ * @param observation - exact Session observation carrying its projection snapshot.
159
+ * @returns the current preset, or undefined when the capability is absent.
160
+ */
161
+ presetForObservation(observation: SessionObservation): string | undefined;
162
+ }
163
+ export {};
164
+ //# sourceMappingURL=agent.d.ts.map
@@ -0,0 +1,484 @@
1
+ /** Agent activation, composition, and initial model route 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 { SessionQueryError } from '@unieai/rabi-session-query';
59
+ import { RemoteError, remoteErrorOf } from '@unieai/rabi-typert-protocol';
60
+ /** Cold Session identity absent from persistence. */
61
+ export class ApiSessionNotFound extends Error {
62
+ }
63
+ /** Session identity whose lifecycle belongs to subagent routing. */
64
+ export class ApiSessionSubagentOwnership extends Error {
65
+ sessionId;
66
+ /** @param sessionId - identity reserved to subagent routing. */
67
+ constructor(sessionId) {
68
+ super(`session "${sessionId}" is a subagent session; use subagent delivery`);
69
+ this.sessionId = sessionId;
70
+ }
71
+ }
72
+ /** Explicit-id creation attempted to adopt a Session under another cwd. */
73
+ export class ApiSessionCwdConflict extends Error {
74
+ sessionId;
75
+ requestedCwd;
76
+ existingCwd;
77
+ constructor(sessionId, requestedCwd, existingCwd) {
78
+ super(existingCwd === undefined
79
+ ? `session "${sessionId}" records no cwd and cannot be adopted for "${requestedCwd}"`
80
+ : `session "${sessionId}" belongs to "${existingCwd}", not "${requestedCwd}"`);
81
+ this.sessionId = sessionId;
82
+ this.requestedCwd = requestedCwd;
83
+ this.existingCwd = existingCwd;
84
+ }
85
+ }
86
+ /** Reuse of a Session named an Agent preset while the deployment composes no preset roster. */
87
+ export class ApiSessionPresetConflict extends Error {
88
+ sessionId;
89
+ requestedPreset;
90
+ constructor(sessionId, requestedPreset) {
91
+ super(`the deployment composes no agent preset roster, so session "${sessionId}" cannot run preset "${requestedPreset}"`);
92
+ this.sessionId = sessionId;
93
+ this.requestedPreset = requestedPreset;
94
+ }
95
+ }
96
+ /** A blank Session chosen for reuse started a turn before this Host acquired its writer. */
97
+ class ApiSessionStartedSinceObserved extends Error {
98
+ }
99
+ /**
100
+ * Test whether generic Session routing must leave an identity to subagent routing.
101
+ * @param session - Attached or live Session whose origin is tested.
102
+ * @returns whether subagent routing owns the Session identity.
103
+ */
104
+ export function hasApiSessionSubagentOwner(session) {
105
+ return session.header.origin === 'subagent';
106
+ }
107
+ /**
108
+ * Build the stable caller-facing subagent ownership rejection.
109
+ * @param sessionId - Session identity owned by subagent routing.
110
+ * @returns a stable Session-domain failure.
111
+ */
112
+ export function apiSessionSubagentOwnershipError(sessionId) {
113
+ return new RemoteError('session/agent-busy', `session "${sessionId}" is owned by subagent routing`, { reason: 'use subagent delivery for this child session' });
114
+ }
115
+ /** Owns every operation that may create, resume, or configure a Web Agent. */
116
+ export class ApiSessionAgentController {
117
+ ctx;
118
+ resumes = new Map();
119
+ claims = new Map();
120
+ imageAdmissionChains = new WeakMap();
121
+ /** @param ctx - Host context carrying Agent, model, persistence, and Typert services. */
122
+ constructor(ctx) {
123
+ this.ctx = ctx;
124
+ }
125
+ /**
126
+ * Configure Session and Agent lookups for Typert.
127
+ */
128
+ initialize() {
129
+ const ctx = this.ctx;
130
+ ctx.typert.lookups.configure('agent', async (sessionId) => {
131
+ const found = await this.resolveAgent(sessionId);
132
+ if ('error' in found)
133
+ throw found.error;
134
+ return found.agent;
135
+ });
136
+ ctx.typert.lookups.configure('session', async (sessionId) => {
137
+ const found = await this.resolveAgent(sessionId);
138
+ if ('error' in found)
139
+ throw found.error;
140
+ return found.agent.session;
141
+ });
142
+ ctx.typert.contexts.configureHost('agent', async (sessionId) => {
143
+ const found = await this.resolveAgent(sessionId);
144
+ if ('error' in found)
145
+ throw found.error;
146
+ return found.agent.ctx;
147
+ });
148
+ }
149
+ /**
150
+ * Resolve or resume one ordinary Session, deduplicating concurrent resumes.
151
+ * @param sessionId - ordinary Session identity.
152
+ * @returns the live Agent or a stable Session-domain failure.
153
+ */
154
+ async resolveAgent(sessionId) {
155
+ return this.resolve(sessionId);
156
+ }
157
+ /**
158
+ * Resolve one ordinary Session from an already-retained exact observation.
159
+ * @param observation - Host-owned observation whose preparation stays pinned through setup.
160
+ * @returns the live Agent or a stable Session-domain failure.
161
+ */
162
+ async resolveObservedAgent(observation) {
163
+ return this.resolve(observation.header.id, observation);
164
+ }
165
+ async resolve(sessionId, observation) {
166
+ const live = this.liveAgent(sessionId);
167
+ if (live !== undefined)
168
+ return live;
169
+ const attached = this.ctx.sessions.get(sessionId);
170
+ if (attached !== undefined && hasApiSessionSubagentOwner(attached)) {
171
+ return { error: apiSessionSubagentOwnershipError(sessionId) };
172
+ }
173
+ let resume = this.resumes.get(sessionId);
174
+ if (resume === undefined) {
175
+ resume = this.resume(sessionId, observation).finally(() => { this.resumes.delete(sessionId); });
176
+ this.resumes.set(sessionId, resume);
177
+ }
178
+ try {
179
+ const agent = await resume;
180
+ // A shared resume can publish an identity that subagent routing adopts
181
+ // before every waiter observes it; apply the live ownership policy again.
182
+ const published = this.liveAgent(sessionId);
183
+ return published ?? { agent };
184
+ }
185
+ catch (error) {
186
+ if (error instanceof ApiSessionNotFound) {
187
+ return { error: new RemoteError('session/not-found', error.message, { sessionId }) };
188
+ }
189
+ if (error instanceof ApiSessionSubagentOwnership) {
190
+ return { error: apiSessionSubagentOwnershipError(error.sessionId) };
191
+ }
192
+ const raced = this.liveAgent(sessionId);
193
+ if (raced !== undefined)
194
+ return raced;
195
+ const racedSession = this.ctx.sessions.get(sessionId);
196
+ if (racedSession !== undefined && hasApiSessionSubagentOwner(racedSession)) {
197
+ return { error: apiSessionSubagentOwnershipError(sessionId) };
198
+ }
199
+ if (error instanceof Error && error.name === 'SessionAlreadyOwnedError') {
200
+ return { error: new RemoteError('session/writer-held', error.message, { sessionId }) };
201
+ }
202
+ return {
203
+ error: new RemoteError('gateway/internal', `resume failed for session "${sessionId}": ${String(error)}`, {}),
204
+ };
205
+ }
206
+ }
207
+ /**
208
+ * Create a Session for a new conversation, reusing the named blank Session
209
+ * while it is still reusable. A reused Session runs the requested preset, or
210
+ * the configured default when the request names none; the preset it recorded
211
+ * is not resolved, and a change is logged as `agent-preset/selected` before
212
+ * the Agent is published. A named Session that has started a turn, fails the
213
+ * caller's placement rule, or is written by another owner stays unchanged,
214
+ * and a new Session is created instead. Requests naming one identity run in
215
+ * arrival order, including their preset resolution, and check the named
216
+ * Session's directory and ownership before resolving the preset.
217
+ * @param request - optional Session to reuse, directory, preset, and placement rule.
218
+ * @returns the reused or created Session and the preset it ran when this request finished.
219
+ * @throws ApiSessionCwdConflict when the named Session belongs to another directory.
220
+ * @throws ApiSessionSubagentOwnership when subagent routing owns the named Session.
221
+ * @throws RemoteError `agent-preset/not-found` or `agent-preset/invalid` for the requested or default preset.
222
+ * @throws ApiSessionPresetConflict when no roster is composed and the request names a preset for a reused Session.
223
+ */
224
+ async createSession(request) {
225
+ const named = request.sessionId;
226
+ if (named === undefined)
227
+ return this.created(await this.createMinted(request.cwd, await this.composeAgent(request.agentPreset)));
228
+ return this.inOrder(named, async () => this.created(await this.claim(named, request)));
229
+ }
230
+ /**
231
+ * Read the current Agent preset from the Session projection.
232
+ * @param session - live Session whose projection state is available.
233
+ * @returns the current preset, or undefined without a preset service or recorded selection.
234
+ */
235
+ presetForSession(session) {
236
+ return this.ctx.get('agentPresets')?.presetForSession(session) ?? undefined;
237
+ }
238
+ /**
239
+ * Serialize image admission and model selection for one Agent.
240
+ * @param agent - live Agent that owns the serialization chain.
241
+ * @param operation - asynchronous operation admitted after prior work settles.
242
+ * @returns the operation result or rejection.
243
+ */
244
+ serializeImageAdmission(agent, operation) {
245
+ const result = (this.imageAdmissionChains.get(agent) ?? Promise.resolve()).then(operation);
246
+ this.imageAdmissionChains.set(agent, result.then(() => undefined, () => undefined));
247
+ return result;
248
+ }
249
+ /**
250
+ * Resolve the preset id and pre-publication Agent setup for a create or resume.
251
+ * @param presetId - requested preset or the configured default when omitted.
252
+ * @returns the resolved preset identity and Agent setup callback.
253
+ */
254
+ async composeAgent(presetId) {
255
+ const presets = this.ctx.get('agentPresets');
256
+ if (presets === undefined) {
257
+ return { setup: (agentCtx) => { installModelSelection(agentCtx); } };
258
+ }
259
+ const resolvedId = (await presets.resolve(presetId)).id;
260
+ return {
261
+ agentPreset: resolvedId,
262
+ setup: async (agentCtx) => {
263
+ installModelSelection(agentCtx);
264
+ await presets.mount(agentCtx, resolvedId);
265
+ },
266
+ };
267
+ }
268
+ liveAgent(sessionId) {
269
+ const agent = this.ctx.agents.get(sessionId);
270
+ if (agent === undefined)
271
+ return undefined;
272
+ return hasApiSessionSubagentOwner(agent.session)
273
+ ? { error: apiSessionSubagentOwnershipError(sessionId) }
274
+ : { agent };
275
+ }
276
+ async resume(sessionId, supplied) {
277
+ if (supplied !== undefined)
278
+ return this.resumeObserved(sessionId, supplied);
279
+ try {
280
+ const env_1 = { stack: [], error: void 0, hasError: false };
281
+ try {
282
+ const observation = __addDisposableResource(env_1, await this.ctx.sessionQuery.observeSession(sessionId), false);
283
+ return await this.resumeObserved(sessionId, observation);
284
+ }
285
+ catch (e_1) {
286
+ env_1.error = e_1;
287
+ env_1.hasError = true;
288
+ }
289
+ finally {
290
+ __disposeResources(env_1);
291
+ }
292
+ }
293
+ catch (error) {
294
+ if (error instanceof SessionQueryError
295
+ && error.code === 'SESSION_QUERY_SESSION_NOT_FOUND') {
296
+ throw new ApiSessionNotFound(`session "${sessionId}" not found`);
297
+ }
298
+ throw error;
299
+ }
300
+ }
301
+ async resumeObserved(sessionId, observation) {
302
+ if (observation.header.id !== sessionId || observation.header.cwd === undefined) {
303
+ throw new ApiSessionNotFound(`session "${sessionId}" not found`);
304
+ }
305
+ if (hasApiSessionSubagentOwner({ header: observation.header })) {
306
+ throw new ApiSessionSubagentOwnership(sessionId);
307
+ }
308
+ const composition = await this.composeAgent(this.presetForObservation(observation));
309
+ const published = this.ctx.sessions.get(sessionId);
310
+ if (published !== undefined && hasApiSessionSubagentOwner(published)) {
311
+ throw new ApiSessionSubagentOwnership(sessionId);
312
+ }
313
+ return (await this.ctx.agents.resume({
314
+ resumeSessionId: sessionId,
315
+ agentOptions: this.agentOptions(),
316
+ setup: composition.setup,
317
+ })).agent;
318
+ }
319
+ async inOrder(sessionId, operation) {
320
+ const result = (this.claims.get(sessionId) ?? Promise.resolve()).then(operation);
321
+ const settled = result.then(() => undefined, () => undefined);
322
+ this.claims.set(sessionId, settled);
323
+ try {
324
+ return await result;
325
+ }
326
+ finally {
327
+ if (this.claims.get(sessionId) === settled)
328
+ this.claims.delete(sessionId);
329
+ }
330
+ }
331
+ /** @returns the reused Session, a new Session under `sessionId` when none is stored, or a new Session under a minted identity. */
332
+ async claim(sessionId, request) {
333
+ const attached = this.ctx.sessions.get(sessionId);
334
+ const live = this.ctx.agents.get(sessionId);
335
+ if (attached !== undefined && hasApiSessionSubagentOwner(attached)) {
336
+ throw new ApiSessionSubagentOwnership(sessionId);
337
+ }
338
+ if (live !== undefined) {
339
+ if (live.session.header.cwd !== request.cwd) {
340
+ throw new ApiSessionCwdConflict(live.id, request.cwd, live.session.header.cwd);
341
+ }
342
+ const composition = await this.composeAgent(request.agentPreset);
343
+ return await this.reuseLive(live, request, composition) ?? this.createMinted(request.cwd, composition);
344
+ }
345
+ let observation;
346
+ try {
347
+ observation = await this.ctx.sessionQuery.observeSession(sessionId);
348
+ }
349
+ catch (error) {
350
+ if (!(error instanceof SessionQueryError) || error.code !== 'SESSION_QUERY_SESSION_NOT_FOUND')
351
+ throw error;
352
+ return this.createAgent(sessionId, request.cwd, await this.composeAgent(request.agentPreset));
353
+ }
354
+ let reusable;
355
+ {
356
+ const env_2 = { stack: [], error: void 0, hasError: false };
357
+ try {
358
+ const observed = __addDisposableResource(env_2, observation, false);
359
+ if (hasApiSessionSubagentOwner({ header: observed.header })) {
360
+ throw new ApiSessionSubagentOwnership(sessionId);
361
+ }
362
+ if (observed.header.cwd !== request.cwd) {
363
+ throw new ApiSessionCwdConflict(sessionId, request.cwd, observed.header.cwd);
364
+ }
365
+ reusable = request.reusable(sessionId) && !observed.events.some(event => event.type === 'turn/start');
366
+ }
367
+ catch (e_2) {
368
+ env_2.error = e_2;
369
+ env_2.hasError = true;
370
+ }
371
+ finally {
372
+ __disposeResources(env_2);
373
+ }
374
+ }
375
+ const composition = await this.composeAgent(request.agentPreset);
376
+ if (!reusable)
377
+ return this.createMinted(request.cwd, composition);
378
+ this.assertPresetApplicable(sessionId, request.agentPreset);
379
+ try {
380
+ return (await this.ctx.agents.resume({
381
+ resumeSessionId: sessionId,
382
+ agentOptions: this.agentOptions(),
383
+ setup: this.reuseSetup(composition),
384
+ })).agent;
385
+ }
386
+ catch (error) {
387
+ if (error instanceof ApiSessionStartedSinceObserved)
388
+ return this.createMinted(request.cwd, composition);
389
+ if (!(error instanceof Error) || error.name !== 'SessionAlreadyOwnedError')
390
+ throw error;
391
+ // Another resume in this process may hold the writer for the Agent it published.
392
+ return this.ctx.agents.get(sessionId) === undefined
393
+ ? this.createMinted(request.cwd, composition)
394
+ : this.claim(sessionId, request);
395
+ }
396
+ }
397
+ /** @returns the live blank Session under the requested preset, or undefined when it cannot be reused. */
398
+ async reuseLive(live, request, composition) {
399
+ if (!request.reusable(live.id) || !this.isBlank(live.session))
400
+ return undefined;
401
+ this.assertPresetApplicable(live.id, request.agentPreset);
402
+ const current = this.presetForSession(live.session);
403
+ const presets = this.ctx.get('agentPresets');
404
+ const target = composition.agentPreset;
405
+ if (presets === undefined || target === undefined || target === current)
406
+ return live;
407
+ try {
408
+ await presets.select(live, target);
409
+ }
410
+ catch (error) {
411
+ if (remoteErrorOf(error)?.code !== 'agent-preset/locked')
412
+ throw error;
413
+ return undefined;
414
+ }
415
+ return live;
416
+ }
417
+ /** Setup that re-checks blankness under the acquired writer, then records a preset change before publication. */
418
+ reuseSetup(composition) {
419
+ return async (agentCtx, agent) => {
420
+ if (!this.isBlank(agent.session))
421
+ throw new ApiSessionStartedSinceObserved();
422
+ const commit = await composition.setup(agentCtx, agent);
423
+ const target = composition.agentPreset;
424
+ if (target !== undefined && this.presetForSession(agent.session) !== target) {
425
+ agent.session.append('agent-preset/selected', { agentPreset: target });
426
+ }
427
+ return commit;
428
+ };
429
+ }
430
+ /** Whether no turn has started, by the predicate the preset registry's `select` enforces. */
431
+ isBlank(session) {
432
+ const boundary = this.ctx.agents.turnBoundaryOf(session);
433
+ return boundary.openTurnStartSeq === null && boundary.lastTurn === 0;
434
+ }
435
+ /** Without a roster, reuse cannot apply a named preset. */
436
+ assertPresetApplicable(sessionId, requested) {
437
+ if (requested === undefined || this.ctx.get('agentPresets') !== undefined)
438
+ return;
439
+ throw new ApiSessionPresetConflict(sessionId, requested);
440
+ }
441
+ created(agent) {
442
+ return { agent, agentPreset: this.presetForSession(agent.session) };
443
+ }
444
+ createMinted(cwd, composition) {
445
+ return this.createAgent(brandString(`session-${randomUUID()}`), cwd, composition);
446
+ }
447
+ async createAgent(sessionId, cwd, composition) {
448
+ try {
449
+ await mkdir(cwd, { recursive: true });
450
+ }
451
+ catch (error) {
452
+ throw new Error(`failed to ensure project directory "${cwd}": ${String(error)}`, { cause: error });
453
+ }
454
+ return (await this.ctx.agents.create({
455
+ sessionId,
456
+ agentOptions: this.agentOptions(),
457
+ meta: {
458
+ cwd,
459
+ ...(composition.agentPreset === undefined ? {} : { agentPreset: composition.agentPreset }),
460
+ },
461
+ setup: composition.setup,
462
+ })).agent;
463
+ }
464
+ agentOptions() {
465
+ const defaults = this.ctx.agentDefaultModel;
466
+ // A Session that records no selection or request follows default changes.
467
+ return {
468
+ get provider() { return defaults.currentSelection().provider; },
469
+ get model() { return defaults.currentSelection().model; },
470
+ get reasoningEffort() { return defaults.currentSelection().reasoningEffort; },
471
+ };
472
+ }
473
+ /**
474
+ * Read the current Agent preset from an all-projections observation.
475
+ * @param observation - exact Session observation carrying its projection snapshot.
476
+ * @returns the current preset, or undefined when the capability is absent.
477
+ */
478
+ presetForObservation(observation) {
479
+ if (observation.projections === undefined) {
480
+ throw new Error('api-session: Agent activation requires a projected Session observation');
481
+ }
482
+ return observation.projections.values.agentPreset ?? undefined;
483
+ }
484
+ }
@@ -0,0 +1,33 @@
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. The Subagent
8
+ * runtime also checks its retained ancestry before each step, so a released
9
+ * intermediate Session cannot hide an archived ancestor.
10
+ */
11
+ import type { Context, Plugin } from '@unieai/cordis';
12
+ import type { Agent } from '@unieai/rabi-agent';
13
+ /**
14
+ * The gate as a plugin for `ctx.plugin(...)`: it loads once the Agent
15
+ * registry, Session store, and Workspace registry are available and unwinds
16
+ * with the plugin's fiber. A late waking delivery to an archived Session — a
17
+ * subagent settlement, a queued follow-up — proposes a step the gate rejects,
18
+ * which the loop ends as `blocked` without a request; unarchiving lifts the
19
+ * gate for the whole lineage.
20
+ */
21
+ export declare const ArchivedSessionGate: Plugin.Object<void>;
22
+ /**
23
+ * Whether the Agent's Session, or a Session above it in its subagent lineage,
24
+ * is archived. This header-only check follows the durable fields through
25
+ * subagent-origin Sessions only: a fork of an archived Session is an
26
+ * independent conversation. The Subagent runtime separately checks managed
27
+ * ancestry when an intermediate Session is unavailable here.
28
+ * @param ctx - Host context.
29
+ * @param agent - the Agent proposing a step.
30
+ * @returns whether an archived Session owns the step.
31
+ */
32
+ export declare function underArchivedSession(ctx: Context, agent: Agent): boolean;
33
+ //# sourceMappingURL=archived-session-gate.d.ts.map