@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
package/lib/index.js ADDED
@@ -0,0 +1,4300 @@
1
+ import { hostname } from "node:os";
2
+ import { isAbsolute, resolve } from "node:path";
3
+ import { Service } from "@unieai/cordis";
4
+ import z from "@unieai/schemastery";
5
+ import { AssistantStreamAccumulator, ReasoningEffortId, createUserMessage, errorChain, freezeMessage } from "@unieai/rabi-llm";
6
+ import { canOpenNativePath, nativeFileApplications, nativeFileManager, openNativeAssociatedPath, openNativeFileApplication, revealNativePath } from "@unieai/rabi-native-command";
7
+ import { Remote, RemoteError, TypertRemoteService, principalOf, remoteErrorOf } from "@unieai/rabi-typert-protocol";
8
+ import { canonicalClientTimeZone } from "@unieai/rabi-util-time";
9
+ import { assertNever } from "@unieai/rabi-util-values";
10
+ import { randomUUID } from "node:crypto";
11
+ import { mkdir } from "node:fs/promises";
12
+ import { installModelSelection } from "@unieai/rabi-agent";
13
+ import { brandNumber, brandString } from "@unieai/rabi-brand";
14
+ import { SessionQueryError } from "@unieai/rabi-session-query";
15
+ import { z as z$1 } from "zod";
16
+ import { credentialRef } from "@unieai/rabi-credentials";
17
+ import { AttachmentError } from "@unieai/rabi-attachment";
18
+ import { buildForkSeed } from "@unieai/rabi-session/fork";
19
+ import { SessionLogOffset, SessionSeq, isAppendSurfaceEvent } from "@unieai/rabi-session";
20
+ import { SessionTitleInvalidError } from "@unieai/rabi-session-title";
21
+ import { Deque } from "@unieai/rabi-deque";
22
+ import { MAX_TIMER_DELAY_MS, deadline, timeoutOf } from "@unieai/rabi-timeout";
23
+ import { performance } from "node:perf_hooks";
24
+ import { scheduler } from "node:timers/promises";
25
+ import { isUserInvocable } from "@unieai/rabi-skill";
26
+ import { FsError } from "@unieai/rabi-fs";
27
+ import mime from "mime-types";
28
+ //#region lib/types/agent.js
29
+ /** Agent activation, composition, and initial model route owned by API Session. */
30
+ var __addDisposableResource$6 = function(env, value, async) {
31
+ if (value !== null && value !== void 0) {
32
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
33
+ var dispose, inner;
34
+ if (async) {
35
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
36
+ dispose = value[Symbol.asyncDispose];
37
+ }
38
+ if (dispose === void 0) {
39
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
40
+ dispose = value[Symbol.dispose];
41
+ if (async) inner = dispose;
42
+ }
43
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
44
+ if (inner) dispose = function() {
45
+ try {
46
+ inner.call(this);
47
+ } catch (e) {
48
+ return Promise.reject(e);
49
+ }
50
+ };
51
+ env.stack.push({
52
+ value,
53
+ dispose,
54
+ async
55
+ });
56
+ } else if (async) env.stack.push({ async: true });
57
+ return value;
58
+ };
59
+ var __disposeResources$6 = (function(SuppressedError) {
60
+ return function(env) {
61
+ function fail(e) {
62
+ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
63
+ env.hasError = true;
64
+ }
65
+ var r, s = 0;
66
+ function next() {
67
+ while (r = env.stack.pop()) try {
68
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
69
+ if (r.dispose) {
70
+ var result = r.dispose.call(r.value);
71
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
72
+ fail(e);
73
+ return next();
74
+ });
75
+ } else s |= 1;
76
+ } catch (e) {
77
+ fail(e);
78
+ }
79
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
80
+ if (env.hasError) throw env.error;
81
+ }
82
+ return next();
83
+ };
84
+ })(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
85
+ var e = new Error(message);
86
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
87
+ });
88
+ /** Cold Session identity absent from persistence. */
89
+ var ApiSessionNotFound = class extends Error {};
90
+ /** Session identity whose lifecycle belongs to subagent routing. */
91
+ var ApiSessionSubagentOwnership = class extends Error {
92
+ sessionId;
93
+ /** @param sessionId - identity reserved to subagent routing. */
94
+ constructor(sessionId) {
95
+ super(`session "${sessionId}" is a subagent session; use subagent delivery`);
96
+ this.sessionId = sessionId;
97
+ }
98
+ };
99
+ /** Explicit-id creation attempted to adopt a Session under another cwd. */
100
+ var ApiSessionCwdConflict = class extends Error {
101
+ sessionId;
102
+ requestedCwd;
103
+ existingCwd;
104
+ constructor(sessionId, requestedCwd, existingCwd) {
105
+ super(existingCwd === void 0 ? `session "${sessionId}" records no cwd and cannot be adopted for "${requestedCwd}"` : `session "${sessionId}" belongs to "${existingCwd}", not "${requestedCwd}"`);
106
+ this.sessionId = sessionId;
107
+ this.requestedCwd = requestedCwd;
108
+ this.existingCwd = existingCwd;
109
+ }
110
+ };
111
+ /** Reuse of a Session named an Agent preset while the deployment composes no preset roster. */
112
+ var ApiSessionPresetConflict = class extends Error {
113
+ sessionId;
114
+ requestedPreset;
115
+ constructor(sessionId, requestedPreset) {
116
+ super(`the deployment composes no agent preset roster, so session "${sessionId}" cannot run preset "${requestedPreset}"`);
117
+ this.sessionId = sessionId;
118
+ this.requestedPreset = requestedPreset;
119
+ }
120
+ };
121
+ /** A blank Session chosen for reuse started a turn before this Host acquired its writer. */
122
+ var ApiSessionStartedSinceObserved = class extends Error {};
123
+ /**
124
+ * Test whether generic Session routing must leave an identity to subagent routing.
125
+ * @param session - Attached or live Session whose origin is tested.
126
+ * @returns whether subagent routing owns the Session identity.
127
+ */
128
+ function hasApiSessionSubagentOwner(session) {
129
+ return session.header.origin === "subagent";
130
+ }
131
+ /**
132
+ * Build the stable caller-facing subagent ownership rejection.
133
+ * @param sessionId - Session identity owned by subagent routing.
134
+ * @returns a stable Session-domain failure.
135
+ */
136
+ function apiSessionSubagentOwnershipError(sessionId) {
137
+ return new RemoteError("session/agent-busy", `session "${sessionId}" is owned by subagent routing`, { reason: "use subagent delivery for this child session" });
138
+ }
139
+ /** Owns every operation that may create, resume, or configure a Web Agent. */
140
+ var ApiSessionAgentController = class {
141
+ ctx;
142
+ resumes = /* @__PURE__ */ new Map();
143
+ claims = /* @__PURE__ */ new Map();
144
+ imageAdmissionChains = /* @__PURE__ */ new WeakMap();
145
+ /** @param ctx - Host context carrying Agent, model, persistence, and Typert services. */
146
+ constructor(ctx) {
147
+ this.ctx = ctx;
148
+ }
149
+ /**
150
+ * Configure Session and Agent lookups for Typert.
151
+ */
152
+ initialize() {
153
+ const ctx = this.ctx;
154
+ ctx.typert.lookups.configure("agent", async (sessionId) => {
155
+ const found = await this.resolveAgent(sessionId);
156
+ if ("error" in found) throw found.error;
157
+ return found.agent;
158
+ });
159
+ ctx.typert.lookups.configure("session", async (sessionId) => {
160
+ const found = await this.resolveAgent(sessionId);
161
+ if ("error" in found) throw found.error;
162
+ return found.agent.session;
163
+ });
164
+ ctx.typert.contexts.configureHost("agent", async (sessionId) => {
165
+ const found = await this.resolveAgent(sessionId);
166
+ if ("error" in found) throw found.error;
167
+ return found.agent.ctx;
168
+ });
169
+ }
170
+ /**
171
+ * Resolve or resume one ordinary Session, deduplicating concurrent resumes.
172
+ * @param sessionId - ordinary Session identity.
173
+ * @returns the live Agent or a stable Session-domain failure.
174
+ */
175
+ async resolveAgent(sessionId) {
176
+ return this.resolve(sessionId);
177
+ }
178
+ /**
179
+ * Resolve one ordinary Session from an already-retained exact observation.
180
+ * @param observation - Host-owned observation whose preparation stays pinned through setup.
181
+ * @returns the live Agent or a stable Session-domain failure.
182
+ */
183
+ async resolveObservedAgent(observation) {
184
+ return this.resolve(observation.header.id, observation);
185
+ }
186
+ async resolve(sessionId, observation) {
187
+ const live = this.liveAgent(sessionId);
188
+ if (live !== void 0) return live;
189
+ const attached = this.ctx.sessions.get(sessionId);
190
+ if (attached !== void 0 && hasApiSessionSubagentOwner(attached)) return { error: apiSessionSubagentOwnershipError(sessionId) };
191
+ let resume = this.resumes.get(sessionId);
192
+ if (resume === void 0) {
193
+ resume = this.resume(sessionId, observation).finally(() => {
194
+ this.resumes.delete(sessionId);
195
+ });
196
+ this.resumes.set(sessionId, resume);
197
+ }
198
+ try {
199
+ const agent = await resume;
200
+ return this.liveAgent(sessionId) ?? { agent };
201
+ } catch (error) {
202
+ if (error instanceof ApiSessionNotFound) return { error: new RemoteError("session/not-found", error.message, { sessionId }) };
203
+ if (error instanceof ApiSessionSubagentOwnership) return { error: apiSessionSubagentOwnershipError(error.sessionId) };
204
+ const raced = this.liveAgent(sessionId);
205
+ if (raced !== void 0) return raced;
206
+ const racedSession = this.ctx.sessions.get(sessionId);
207
+ if (racedSession !== void 0 && hasApiSessionSubagentOwner(racedSession)) return { error: apiSessionSubagentOwnershipError(sessionId) };
208
+ if (error instanceof Error && error.name === "SessionAlreadyOwnedError") return { error: new RemoteError("session/writer-held", error.message, { sessionId }) };
209
+ return { error: new RemoteError("gateway/internal", `resume failed for session "${sessionId}": ${String(error)}`, {}) };
210
+ }
211
+ }
212
+ /**
213
+ * Create a Session for a new conversation, reusing the named blank Session
214
+ * while it is still reusable. A reused Session runs the requested preset, or
215
+ * the configured default when the request names none; the preset it recorded
216
+ * is not resolved, and a change is logged as `agent-preset/selected` before
217
+ * the Agent is published. A named Session that has started a turn, fails the
218
+ * caller's placement rule, or is written by another owner stays unchanged,
219
+ * and a new Session is created instead. Requests naming one identity run in
220
+ * arrival order, including their preset resolution, and check the named
221
+ * Session's directory and ownership before resolving the preset.
222
+ * @param request - optional Session to reuse, directory, preset, and placement rule.
223
+ * @returns the reused or created Session and the preset it ran when this request finished.
224
+ * @throws ApiSessionCwdConflict when the named Session belongs to another directory.
225
+ * @throws ApiSessionSubagentOwnership when subagent routing owns the named Session.
226
+ * @throws RemoteError `agent-preset/not-found` or `agent-preset/invalid` for the requested or default preset.
227
+ * @throws ApiSessionPresetConflict when no roster is composed and the request names a preset for a reused Session.
228
+ */
229
+ async createSession(request) {
230
+ const named = request.sessionId;
231
+ if (named === void 0) return this.created(await this.createMinted(request.cwd, await this.composeAgent(request.agentPreset)));
232
+ return this.inOrder(named, async () => this.created(await this.claim(named, request)));
233
+ }
234
+ /**
235
+ * Read the current Agent preset from the Session projection.
236
+ * @param session - live Session whose projection state is available.
237
+ * @returns the current preset, or undefined without a preset service or recorded selection.
238
+ */
239
+ presetForSession(session) {
240
+ return this.ctx.get("agentPresets")?.presetForSession(session) ?? void 0;
241
+ }
242
+ /**
243
+ * Serialize image admission and model selection for one Agent.
244
+ * @param agent - live Agent that owns the serialization chain.
245
+ * @param operation - asynchronous operation admitted after prior work settles.
246
+ * @returns the operation result or rejection.
247
+ */
248
+ serializeImageAdmission(agent, operation) {
249
+ const result = (this.imageAdmissionChains.get(agent) ?? Promise.resolve()).then(operation);
250
+ this.imageAdmissionChains.set(agent, result.then(() => void 0, () => void 0));
251
+ return result;
252
+ }
253
+ /**
254
+ * Resolve the preset id and pre-publication Agent setup for a create or resume.
255
+ * @param presetId - requested preset or the configured default when omitted.
256
+ * @returns the resolved preset identity and Agent setup callback.
257
+ */
258
+ async composeAgent(presetId) {
259
+ const presets = this.ctx.get("agentPresets");
260
+ if (presets === void 0) return { setup: (agentCtx) => {
261
+ installModelSelection(agentCtx);
262
+ } };
263
+ const resolvedId = (await presets.resolve(presetId)).id;
264
+ return {
265
+ agentPreset: resolvedId,
266
+ setup: async (agentCtx) => {
267
+ installModelSelection(agentCtx);
268
+ await presets.mount(agentCtx, resolvedId);
269
+ }
270
+ };
271
+ }
272
+ liveAgent(sessionId) {
273
+ const agent = this.ctx.agents.get(sessionId);
274
+ if (agent === void 0) return void 0;
275
+ return hasApiSessionSubagentOwner(agent.session) ? { error: apiSessionSubagentOwnershipError(sessionId) } : { agent };
276
+ }
277
+ async resume(sessionId, supplied) {
278
+ if (supplied !== void 0) return this.resumeObserved(sessionId, supplied);
279
+ try {
280
+ const env_1 = {
281
+ stack: [],
282
+ error: void 0,
283
+ hasError: false
284
+ };
285
+ try {
286
+ const observation = __addDisposableResource$6(env_1, await this.ctx.sessionQuery.observeSession(sessionId), false);
287
+ return await this.resumeObserved(sessionId, observation);
288
+ } catch (e_1) {
289
+ env_1.error = e_1;
290
+ env_1.hasError = true;
291
+ } finally {
292
+ __disposeResources$6(env_1);
293
+ }
294
+ } catch (error) {
295
+ if (error instanceof SessionQueryError && error.code === "SESSION_QUERY_SESSION_NOT_FOUND") throw new ApiSessionNotFound(`session "${sessionId}" not found`);
296
+ throw error;
297
+ }
298
+ }
299
+ async resumeObserved(sessionId, observation) {
300
+ if (observation.header.id !== sessionId || observation.header.cwd === void 0) throw new ApiSessionNotFound(`session "${sessionId}" not found`);
301
+ if (hasApiSessionSubagentOwner({ header: observation.header })) throw new ApiSessionSubagentOwnership(sessionId);
302
+ const composition = await this.composeAgent(this.presetForObservation(observation));
303
+ const published = this.ctx.sessions.get(sessionId);
304
+ if (published !== void 0 && hasApiSessionSubagentOwner(published)) throw new ApiSessionSubagentOwnership(sessionId);
305
+ return (await this.ctx.agents.resume({
306
+ resumeSessionId: sessionId,
307
+ agentOptions: this.agentOptions(),
308
+ setup: composition.setup
309
+ })).agent;
310
+ }
311
+ async inOrder(sessionId, operation) {
312
+ const result = (this.claims.get(sessionId) ?? Promise.resolve()).then(operation);
313
+ const settled = result.then(() => void 0, () => void 0);
314
+ this.claims.set(sessionId, settled);
315
+ try {
316
+ return await result;
317
+ } finally {
318
+ if (this.claims.get(sessionId) === settled) this.claims.delete(sessionId);
319
+ }
320
+ }
321
+ /** @returns the reused Session, a new Session under `sessionId` when none is stored, or a new Session under a minted identity. */
322
+ async claim(sessionId, request) {
323
+ const attached = this.ctx.sessions.get(sessionId);
324
+ const live = this.ctx.agents.get(sessionId);
325
+ if (attached !== void 0 && hasApiSessionSubagentOwner(attached)) throw new ApiSessionSubagentOwnership(sessionId);
326
+ if (live !== void 0) {
327
+ if (live.session.header.cwd !== request.cwd) throw new ApiSessionCwdConflict(live.id, request.cwd, live.session.header.cwd);
328
+ const composition = await this.composeAgent(request.agentPreset);
329
+ return await this.reuseLive(live, request, composition) ?? this.createMinted(request.cwd, composition);
330
+ }
331
+ let observation;
332
+ try {
333
+ observation = await this.ctx.sessionQuery.observeSession(sessionId);
334
+ } catch (error) {
335
+ if (!(error instanceof SessionQueryError) || error.code !== "SESSION_QUERY_SESSION_NOT_FOUND") throw error;
336
+ return this.createAgent(sessionId, request.cwd, await this.composeAgent(request.agentPreset));
337
+ }
338
+ let reusable;
339
+ {
340
+ const env_2 = {
341
+ stack: [],
342
+ error: void 0,
343
+ hasError: false
344
+ };
345
+ try {
346
+ const observed = __addDisposableResource$6(env_2, observation, false);
347
+ if (hasApiSessionSubagentOwner({ header: observed.header })) throw new ApiSessionSubagentOwnership(sessionId);
348
+ if (observed.header.cwd !== request.cwd) throw new ApiSessionCwdConflict(sessionId, request.cwd, observed.header.cwd);
349
+ reusable = request.reusable(sessionId) && !observed.events.some((event) => event.type === "turn/start");
350
+ } catch (e_2) {
351
+ env_2.error = e_2;
352
+ env_2.hasError = true;
353
+ } finally {
354
+ __disposeResources$6(env_2);
355
+ }
356
+ }
357
+ const composition = await this.composeAgent(request.agentPreset);
358
+ if (!reusable) return this.createMinted(request.cwd, composition);
359
+ this.assertPresetApplicable(sessionId, request.agentPreset);
360
+ try {
361
+ return (await this.ctx.agents.resume({
362
+ resumeSessionId: sessionId,
363
+ agentOptions: this.agentOptions(),
364
+ setup: this.reuseSetup(composition)
365
+ })).agent;
366
+ } catch (error) {
367
+ if (error instanceof ApiSessionStartedSinceObserved) return this.createMinted(request.cwd, composition);
368
+ if (!(error instanceof Error) || error.name !== "SessionAlreadyOwnedError") throw error;
369
+ return this.ctx.agents.get(sessionId) === void 0 ? this.createMinted(request.cwd, composition) : this.claim(sessionId, request);
370
+ }
371
+ }
372
+ /** @returns the live blank Session under the requested preset, or undefined when it cannot be reused. */
373
+ async reuseLive(live, request, composition) {
374
+ if (!request.reusable(live.id) || !this.isBlank(live.session)) return void 0;
375
+ this.assertPresetApplicable(live.id, request.agentPreset);
376
+ const current = this.presetForSession(live.session);
377
+ const presets = this.ctx.get("agentPresets");
378
+ const target = composition.agentPreset;
379
+ if (presets === void 0 || target === void 0 || target === current) return live;
380
+ try {
381
+ await presets.select(live, target);
382
+ } catch (error) {
383
+ if (remoteErrorOf(error)?.code !== "agent-preset/locked") throw error;
384
+ return;
385
+ }
386
+ return live;
387
+ }
388
+ /** Setup that re-checks blankness under the acquired writer, then records a preset change before publication. */
389
+ reuseSetup(composition) {
390
+ return async (agentCtx, agent) => {
391
+ if (!this.isBlank(agent.session)) throw new ApiSessionStartedSinceObserved();
392
+ const commit = await composition.setup(agentCtx, agent);
393
+ const target = composition.agentPreset;
394
+ if (target !== void 0 && this.presetForSession(agent.session) !== target) agent.session.append("agent-preset/selected", { agentPreset: target });
395
+ return commit;
396
+ };
397
+ }
398
+ /** Whether no turn has started, by the predicate the preset registry's `select` enforces. */
399
+ isBlank(session) {
400
+ const boundary = this.ctx.agents.turnBoundaryOf(session);
401
+ return boundary.openTurnStartSeq === null && boundary.lastTurn === 0;
402
+ }
403
+ /** Without a roster, reuse cannot apply a named preset. */
404
+ assertPresetApplicable(sessionId, requested) {
405
+ if (requested === void 0 || this.ctx.get("agentPresets") !== void 0) return;
406
+ throw new ApiSessionPresetConflict(sessionId, requested);
407
+ }
408
+ created(agent) {
409
+ return {
410
+ agent,
411
+ agentPreset: this.presetForSession(agent.session)
412
+ };
413
+ }
414
+ createMinted(cwd, composition) {
415
+ return this.createAgent(brandString(`session-${randomUUID()}`), cwd, composition);
416
+ }
417
+ async createAgent(sessionId, cwd, composition) {
418
+ try {
419
+ await mkdir(cwd, { recursive: true });
420
+ } catch (error) {
421
+ throw new Error(`failed to ensure project directory "${cwd}": ${String(error)}`, { cause: error });
422
+ }
423
+ return (await this.ctx.agents.create({
424
+ sessionId,
425
+ agentOptions: this.agentOptions(),
426
+ meta: {
427
+ cwd,
428
+ ...composition.agentPreset === void 0 ? {} : { agentPreset: composition.agentPreset }
429
+ },
430
+ setup: composition.setup
431
+ })).agent;
432
+ }
433
+ agentOptions() {
434
+ const defaults = this.ctx.agentDefaultModel;
435
+ return {
436
+ get provider() {
437
+ return defaults.currentSelection().provider;
438
+ },
439
+ get model() {
440
+ return defaults.currentSelection().model;
441
+ },
442
+ get reasoningEffort() {
443
+ return defaults.currentSelection().reasoningEffort;
444
+ }
445
+ };
446
+ }
447
+ /**
448
+ * Read the current Agent preset from an all-projections observation.
449
+ * @param observation - exact Session observation carrying its projection snapshot.
450
+ * @returns the current preset, or undefined when the capability is absent.
451
+ */
452
+ presetForObservation(observation) {
453
+ if (observation.projections === void 0) throw new Error("api-session: Agent activation requires a projected Session observation");
454
+ return observation.projections.values.agentPreset ?? void 0;
455
+ }
456
+ };
457
+ //#endregion
458
+ //#region lib/types/continuation.js
459
+ const CONTINUABLE_FAILURES = new Set([
460
+ "RATE_LIMIT",
461
+ "SERVER",
462
+ "TIMEOUT",
463
+ "TRANSPORT",
464
+ "EMPTY_RESPONSE",
465
+ "STREAM_CLOSED"
466
+ ]);
467
+ const endingSchema = z$1.number().int().nonnegative().transform(brandNumber).nullable();
468
+ const stateSchema = z$1.object({
469
+ admitted: z$1.boolean(),
470
+ failedAttempt: z$1.boolean(),
471
+ ending: endingSchema
472
+ });
473
+ const EMPTY = {
474
+ admitted: false,
475
+ failedAttempt: false,
476
+ ending: null
477
+ };
478
+ /** Eligibility requires admitted human work and a failed settlement in the last request step. */
479
+ const continuationProjectionDefinition = {
480
+ key: "conversationContinuation",
481
+ stateVersion: 4,
482
+ stateSchema,
483
+ init: () => EMPTY,
484
+ apply: (state, event) => {
485
+ switch (event.type) {
486
+ case "turn/start": return EMPTY;
487
+ case "step/start":
488
+ case "assistant/message": return state.failedAttempt ? {
489
+ ...state,
490
+ failedAttempt: false
491
+ } : state;
492
+ case "user/message": return !state.admitted && event.surfaceOp === "append" && (event.data.source.kind === "user" && event.data.content.length > 0 || event.data.source.kind === "retry" && event.data.content.length === 0) ? {
493
+ ...state,
494
+ admitted: true
495
+ } : state;
496
+ case "assistant/attempt": return state.failedAttempt ? state : {
497
+ ...state,
498
+ failedAttempt: true
499
+ };
500
+ case "turn/end": {
501
+ const ending = event.data.reason.kind === "error" && CONTINUABLE_FAILURES.has(event.data.reason.error.code) && state.admitted && state.failedAttempt ? event.seq : null;
502
+ return ending === null ? EMPTY : {
503
+ ...EMPTY,
504
+ ending
505
+ };
506
+ }
507
+ default: return state;
508
+ }
509
+ },
510
+ wire: {
511
+ viewSchema: endingSchema,
512
+ view: (state) => state.ending
513
+ }
514
+ };
515
+ //#endregion
516
+ //#region lib/types/catalog.js
517
+ /** Shared projection of the live LLM registry into the browser model catalog. */
518
+ /**
519
+ * Build the browser model catalog without requiring a Session.
520
+ * @param ctx - Host context carrying the live LLM registry.
521
+ * @param defaultSelection - deployment default used before a Session selects a model.
522
+ * @returns successful non-empty provider groups and isolated provider failures.
523
+ */
524
+ async function buildModelCatalog(ctx, defaultSelection = ctx.agentDefaultModel.currentSelection()) {
525
+ const providers = ctx.llm.listProviders();
526
+ const catalog = await Promise.all(providers.map(async (provider) => {
527
+ try {
528
+ const models = await ctx.llm.listModels(provider.id);
529
+ const entries = await Promise.all(models.map(async (model) => {
530
+ const resolved = await ctx.llm.resolveModelInfo(provider.id, model.id);
531
+ const reasoning = resolved.reasoning === void 0 ? void 0 : {
532
+ efforts: resolved.reasoning.efforts.map((effort) => ({
533
+ id: effort.id,
534
+ name: effort.name,
535
+ ...effort.description === void 0 ? {} : { description: effort.description }
536
+ })),
537
+ ...resolved.reasoning.defaultEffort === void 0 ? {} : { defaultEffort: resolved.reasoning.defaultEffort }
538
+ };
539
+ return {
540
+ id: model.id,
541
+ name: model.name,
542
+ ...model.description === void 0 ? {} : { description: model.description },
543
+ ...reasoning === void 0 ? {} : { reasoning },
544
+ ...model.badge === void 0 ? {} : { badge: model.badge }
545
+ };
546
+ }));
547
+ return {
548
+ kind: "group",
549
+ group: {
550
+ id: provider.id,
551
+ name: provider.name,
552
+ models: entries
553
+ }
554
+ };
555
+ } catch (error) {
556
+ return {
557
+ kind: "failure",
558
+ failure: {
559
+ id: provider.id,
560
+ name: provider.name,
561
+ message: error instanceof Error ? error.message : String(error)
562
+ }
563
+ };
564
+ }
565
+ }));
566
+ const groups = catalog.flatMap((item) => item.kind === "group" ? [item.group] : []).filter((group) => group.models.length > 0);
567
+ return {
568
+ default: { ...defaultSelection },
569
+ routableProviders: groups.map((group) => group.id),
570
+ groups,
571
+ failures: catalog.flatMap((item) => item.kind === "failure" ? [item.failure] : [])
572
+ };
573
+ }
574
+ /**
575
+ * Check a GUI selection against the current available provider catalog.
576
+ * @param ctx - Host LLM registry.
577
+ * @param selection - stored or explicitly requested selection.
578
+ * @returns whether the exact model is currently advertised as available.
579
+ */
580
+ async function modelAvailable(ctx, selection) {
581
+ if (!ctx.llm.listProviders().some((provider) => provider.id === selection.provider)) return false;
582
+ let models;
583
+ try {
584
+ models = await ctx.llm.listModels(selection.provider);
585
+ } catch (error) {
586
+ throw new RemoteError("session/model-unavailable", error instanceof Error ? error.message : String(error), {
587
+ provider: selection.provider,
588
+ model: selection.model
589
+ });
590
+ }
591
+ return models.some((model) => model.id === selection.model);
592
+ }
593
+ /**
594
+ * Check configured provider API-key references independently of model availability.
595
+ * @param ctx - Host registry, settings, and credential services.
596
+ * @returns whether any API-key provider has a configured credential.
597
+ */
598
+ async function hasProviderApiKey(ctx) {
599
+ const settings = ctx.get("settings");
600
+ const credentials = ctx.get("credentials");
601
+ if (settings === void 0 || credentials === void 0) throw new RemoteError("session/provider-credentials-unavailable", "provider credentials are unavailable", {});
602
+ const namespaces = settings.describe({ redactSecrets: true });
603
+ for (const provider of ctx.llm.listConfigurableProviders()) {
604
+ if (provider.provider === "deepseek-account") continue;
605
+ let profile = namespaces.find((namespace) => namespace.ns === provider.settingsNs)?.value;
606
+ for (const key of provider.settingsPath) profile = typeof profile === "object" && profile !== null ? Reflect.get(profile, key) : void 0;
607
+ if (typeof profile !== "object" || profile === null) continue;
608
+ const ref = Reflect.get(profile, "apiKeyEnv");
609
+ if (typeof ref === "string" && ref.length > 0 && (await credentials.describe(credentialRef(ref))).configured) return true;
610
+ }
611
+ return false;
612
+ }
613
+ //#endregion
614
+ //#region lib/types/commands.js
615
+ /** Session commands whose activation policy is explicit at each Remote method. */
616
+ var __addDisposableResource$5 = function(env, value, async) {
617
+ if (value !== null && value !== void 0) {
618
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
619
+ var dispose, inner;
620
+ if (async) {
621
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
622
+ dispose = value[Symbol.asyncDispose];
623
+ }
624
+ if (dispose === void 0) {
625
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
626
+ dispose = value[Symbol.dispose];
627
+ if (async) inner = dispose;
628
+ }
629
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
630
+ if (inner) dispose = function() {
631
+ try {
632
+ inner.call(this);
633
+ } catch (e) {
634
+ return Promise.reject(e);
635
+ }
636
+ };
637
+ env.stack.push({
638
+ value,
639
+ dispose,
640
+ async
641
+ });
642
+ } else if (async) env.stack.push({ async: true });
643
+ return value;
644
+ };
645
+ var __disposeResources$5 = (function(SuppressedError) {
646
+ return function(env) {
647
+ function fail(e) {
648
+ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
649
+ env.hasError = true;
650
+ }
651
+ var r, s = 0;
652
+ function next() {
653
+ while (r = env.stack.pop()) try {
654
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
655
+ if (r.dispose) {
656
+ var result = r.dispose.call(r.value);
657
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
658
+ fail(e);
659
+ return next();
660
+ });
661
+ } else s |= 1;
662
+ } catch (e) {
663
+ fail(e);
664
+ }
665
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
666
+ if (env.hasError) throw env.error;
667
+ }
668
+ return next();
669
+ };
670
+ })(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
671
+ var e = new Error(message);
672
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
673
+ });
674
+ /**
675
+ * Whether prompt content carries non-whitespace text or an attachment.
676
+ * @param content - submitted or edited prompt parts.
677
+ * @returns whether any part supplies ordinary prompt content.
678
+ */
679
+ function hasPromptContent(content) {
680
+ return content.some((part) => part.type !== "text" || part.text.trim().length > 0);
681
+ }
682
+ /**
683
+ * Resolve the omitted-`atSeq` default to the latest completed-turn prefix,
684
+ * including standalone events before the next turn begins.
685
+ */
686
+ function latestCompletedPrefixBoundary(events) {
687
+ const lastTurnEnd = events.findLast((event) => event.type === "turn/end");
688
+ if (lastTurnEnd === void 0) return void 0;
689
+ let boundary = lastTurnEnd.seq;
690
+ for (const next of events.slice(boundary + 1)) {
691
+ if (next.type === "turn/start" || next.type === "user/message" && next.surfaceOp === "append" || next.type === "agent/inbox/spliced") break;
692
+ boundary = next.seq;
693
+ }
694
+ return boundary;
695
+ }
696
+ /** Implements Session business commands delegated by the Session Controller Remote service. */
697
+ var SessionCommandController = class {
698
+ ctx;
699
+ agents;
700
+ defaultCwd;
701
+ /** First-insertion facts cached per exact Session; the log remains the recovery source. */
702
+ promptReceipts = /* @__PURE__ */ new WeakMap();
703
+ continuation;
704
+ /** Register complete-history empty-prompt eligibility. @returns when command admission is ready. */
705
+ async initialize() {
706
+ this.continuation = await this.ctx.sessionProjections.register(continuationProjectionDefinition);
707
+ }
708
+ /**
709
+ * @param ctx - Host context carrying Agent, model, attachment, title, and Workspace services.
710
+ * @param agents - sole owner of create, resume, and Agent composition.
711
+ * @param defaultCwd - project directory used when create names neither a Workspace nor a cwd.
712
+ */
713
+ constructor(ctx, agents, defaultCwd) {
714
+ this.ctx = ctx;
715
+ this.agents = agents;
716
+ this.defaultCwd = defaultCwd;
717
+ }
718
+ /**
719
+ * Create one ordinary Session for a new conversation, reusing the named
720
+ * blank Session while it is an unarchived member of the requested Workspace.
721
+ * @param request - optional blank Session to reuse, location, and Agent preset.
722
+ * @returns the created or reused Session identity and its preset when configured.
723
+ */
724
+ async create(request) {
725
+ if (request.workspaceId !== void 0 && request.cwd !== void 0) throw new RemoteError("gateway/bad-request", "session.create accepts workspaceId or cwd, not both", {});
726
+ let workspace;
727
+ if (request.workspaceId !== void 0) {
728
+ workspace = this.ctx.workspaceRegistry.get(request.workspaceId);
729
+ if (workspace === void 0) throw new RemoteError("workspace/not-found", `workspace "${request.workspaceId}" not found`, { workspaceId: request.workspaceId });
730
+ }
731
+ const cwd = workspace?.path ?? request.cwd ?? this.defaultCwd;
732
+ let created;
733
+ try {
734
+ created = await this.agents.createSession({
735
+ ...request.sessionId === void 0 ? {} : { sessionId: request.sessionId },
736
+ cwd,
737
+ ...request.agentPreset === void 0 ? {} : { agentPreset: request.agentPreset },
738
+ reusable: (sessionId) => !this.ctx.workspaceRegistry.archivedSessionIds.includes(sessionId) && (workspace === void 0 || workspace.sessionIds.includes(sessionId))
739
+ });
740
+ } catch (error) {
741
+ this.rejectCreation(error);
742
+ }
743
+ const sessionId = created.agent.id;
744
+ if (workspace !== void 0) try {
745
+ await workspace.attachSession(sessionId);
746
+ } catch (error) {
747
+ throw new RemoteError("session/workspace-attach-failed", `session "${sessionId}" was created but could not attach to workspace "${workspace.id}": ${String(error)}`, {
748
+ sessionId,
749
+ workspaceId: workspace.id
750
+ });
751
+ }
752
+ return {
753
+ sessionId,
754
+ ...created.agentPreset === void 0 ? {} : { agentPreset: created.agentPreset }
755
+ };
756
+ }
757
+ /**
758
+ * Validate and record one Session model selection; save the default in the background.
759
+ * @param request - Session identity and requested model selection.
760
+ * @returns the normalized selection recorded for the Session, without waiting for default persistence.
761
+ */
762
+ async selectModel(request) {
763
+ const agent = await this.resolveAgent(request.sessionId);
764
+ return this.agents.serializeImageAdmission(agent, async () => {
765
+ try {
766
+ await this.requireModel(request);
767
+ const selected = {
768
+ provider: request.provider,
769
+ model: request.model,
770
+ ...request.reasoningEffort === void 0 ? {} : { reasoningEffort: ReasoningEffortId(request.reasoningEffort) }
771
+ };
772
+ await this.ctx.llm.resolveCallConfig(selected);
773
+ agent.model.select(selected);
774
+ this.ctx.agentDefaultModel.saveSelection(selected).catch((error) => {
775
+ this.ctx.logger.warn(`session-controller: model selection changed for the Session but the default was not saved: ${String(error)}`);
776
+ });
777
+ return { selected: { ...selected } };
778
+ } catch (error) {
779
+ if (remoteErrorOf(error) !== void 0) throw error;
780
+ throw new RemoteError("session/model-unavailable", error instanceof Error ? error.message : String(error), {
781
+ provider: request.provider,
782
+ model: request.model
783
+ });
784
+ }
785
+ });
786
+ }
787
+ /**
788
+ * Normalize and append a user-owned Session title.
789
+ * @param request - Session identity and proposed title.
790
+ * @returns the accepted title and durable event sequence.
791
+ */
792
+ async rename(request) {
793
+ const agent = await this.resolveAgent(request.sessionId);
794
+ const titles = this.ctx.get("sessionTitle");
795
+ if (titles === void 0) throw new RemoteError("gateway/internal", "renaming is unavailable: this deployment mounts no session-title service", {});
796
+ try {
797
+ const accepted = titles.rename(agent.session, request.title);
798
+ return {
799
+ title: accepted.title,
800
+ seq: accepted.eventSeq
801
+ };
802
+ } catch (error) {
803
+ if (error instanceof SessionTitleInvalidError) throw new RemoteError("session/title-invalid", error.message, { sessionId: request.sessionId });
804
+ throw new RemoteError("gateway/internal", `failed to rename session "${request.sessionId}": ${String(error)}`, {});
805
+ }
806
+ }
807
+ /**
808
+ * Create a new ordinary Session from an exact event prefix. An explicit
809
+ * `atSeq` is the inclusive cut; an omitted value selects the latest
810
+ * completed-turn prefix. An open cut receives synthetic fork closers.
811
+ * @param request - source Session and optional exact event boundary.
812
+ * @returns the new Session identity.
813
+ */
814
+ async fork(request) {
815
+ const env_1 = {
816
+ stack: [],
817
+ error: void 0,
818
+ hasError: false
819
+ };
820
+ try {
821
+ let atSeq;
822
+ try {
823
+ atSeq = request.atSeq === void 0 ? void 0 : SessionSeq(request.atSeq);
824
+ } catch {
825
+ throw new RemoteError("gateway/bad-request", "atSeq must be a non-negative safe integer", {});
826
+ }
827
+ let observed;
828
+ try {
829
+ observed = await this.ctx.sessionQuery.observeSession(request.sessionId);
830
+ } catch (error) {
831
+ if (error instanceof SessionQueryError && error.code === "SESSION_QUERY_SESSION_NOT_FOUND") throw new RemoteError("session/not-found", `session "${request.sessionId}" not found`, { sessionId: request.sessionId });
832
+ throw new RemoteError("gateway/internal", `fork source unavailable for session "${request.sessionId}": ${String(error)}`, {});
833
+ }
834
+ const source = __addDisposableResource$5(env_1, observed, false);
835
+ const boundary = atSeq ?? latestCompletedPrefixBoundary(source.events);
836
+ if (boundary === void 0 || source.events[boundary]?.seq !== boundary) throw new RemoteError("session/fork-unavailable", request.atSeq === void 0 ? `session "${request.sessionId}" has no completed turn to fork from` : `event ${String(request.atSeq)} does not exist in session "${request.sessionId}" (last seq: ${String(source.events.at(-1)?.seq ?? "none")})`, { sessionId: request.sessionId });
837
+ const seed = buildForkSeed(source.events, boundary);
838
+ let workspace;
839
+ try {
840
+ workspace = await this.forkWorkspace(source.header);
841
+ } catch (error) {
842
+ throw new RemoteError("gateway/internal", `failed to resolve fork workspace for session "${request.sessionId}": ${String(error)}`, {});
843
+ }
844
+ const childId = brandString(`session-${randomUUID()}`);
845
+ const composition = await this.agents.composeAgent(this.agents.presetForObservation(source));
846
+ try {
847
+ const { provider, model } = this.ctx.agentDefaultModel.currentSelection();
848
+ await this.ctx.agents.create({
849
+ sessionId: childId,
850
+ seed,
851
+ inheritedEventCount: SessionLogOffset(boundary + 1),
852
+ meta: {
853
+ ...source.header.cwd === void 0 ? {} : { cwd: source.header.cwd },
854
+ isSeeded: true,
855
+ ...composition.agentPreset === void 0 ? {} : { agentPreset: composition.agentPreset }
856
+ },
857
+ agentOptions: {
858
+ provider,
859
+ model
860
+ },
861
+ setup: composition.setup
862
+ });
863
+ } catch (error) {
864
+ throw new RemoteError("gateway/internal", `failed to fork session "${request.sessionId}": ${String(error)}`, {});
865
+ }
866
+ if (workspace !== void 0) try {
867
+ await workspace.attachSession(childId);
868
+ } catch (error) {
869
+ throw new RemoteError("session/workspace-attach-failed", `session "${childId}" was forked but could not attach to workspace "${workspace.id}": ${String(error)}`, {
870
+ sessionId: childId,
871
+ workspaceId: workspace.id
872
+ });
873
+ }
874
+ return { sessionId: childId };
875
+ } catch (e_1) {
876
+ env_1.error = e_1;
877
+ env_1.hasError = true;
878
+ } finally {
879
+ __disposeResources$5(env_1);
880
+ }
881
+ }
882
+ /**
883
+ * Admit one prompt after Agent and attachment validation; the Remote method
884
+ * has already validated the content and built the durable message source.
885
+ * @param request - Session identity, prompt content, and delivery mode.
886
+ * @param source - caller metadata recorded on the accepted ordinary or retry user message.
887
+ * @returns acknowledgement that the Agent accepted the prompt.
888
+ */
889
+ async prompt(request, source) {
890
+ const agent = await this.resolveAgent(request.sessionId);
891
+ if (this.hasPromptRequest(agent.session, request.requestId)) return { accepted: true };
892
+ if (request.content.length === 0) try {
893
+ return await agent.runMaintenance(() => {
894
+ const inbox = agent.inbox;
895
+ if (request.mode !== "queue" || this.continuation.stateOf(agent.session).ending === null || inbox.nextTurn.length > 0 || inbox.nextStep.some((message) => message.source.kind === "user")) throw new RemoteError("session/agent-busy", "generation continuation is unavailable", { reason: "NO_CONTINUABLE_FAILURE_OR_PENDING_INPUT" });
896
+ agent.followup(createUserMessage({
897
+ content: [],
898
+ source
899
+ }));
900
+ return Promise.resolve({ accepted: true });
901
+ });
902
+ } catch (error) {
903
+ if (remoteErrorOf(error) !== void 0) throw error;
904
+ throw new RemoteError("session/agent-busy", "generation continuation was not accepted", { reason: String(error) });
905
+ }
906
+ const admission = resolvePromptFileReceipts(request.content, (receiptId) => this.ctx.fileUploads.resolve(agent, receiptId));
907
+ const hasImage = admission.content.some((part) => part.type === "image");
908
+ const admit = async () => {
909
+ try {
910
+ const env_2 = {
911
+ stack: [],
912
+ error: void 0,
913
+ hasError: false
914
+ };
915
+ try {
916
+ if (this.hasPromptRequest(agent.session, request.requestId)) return { accepted: true };
917
+ if (hasImage) {
918
+ const current = agent.model.current();
919
+ if (current !== void 0) {
920
+ const model = await this.ctx.llm.resolveModelInfo(current.provider, current.model);
921
+ if (model.inputModalities !== void 0 && !model.inputModalities.includes("image")) throw new RemoteError("session/attachment-invalid", `Model "${current.model}" does not support image input.`, { reason: "MODEL_DOES_NOT_SUPPORT_IMAGES" });
922
+ }
923
+ }
924
+ const content = await this.ctx.attachments.admitPromptContent(admission.content);
925
+ if (this.hasPromptRequest(agent.session, request.requestId)) return { accepted: true };
926
+ const message = createUserMessage({
927
+ content,
928
+ source
929
+ });
930
+ if (this.ctx.agents.get(agent.id) !== agent) throw new RemoteError("session/not-found", `session "${agent.id}" was disposed during prompt admission`, { sessionId: agent.id });
931
+ const binding = __addDisposableResource$5(env_2, this.ctx.fileUploads.bindPrompt(agent, admission.receiptIds, request.requestId), false);
932
+ if (request.mode === "steer") agent.steer(message);
933
+ else agent.followup(message);
934
+ binding.commit();
935
+ } catch (e_2) {
936
+ env_2.error = e_2;
937
+ env_2.hasError = true;
938
+ } finally {
939
+ __disposeResources$5(env_2);
940
+ }
941
+ } catch (error) {
942
+ if (this.hasPromptRequest(agent.session, request.requestId)) return { accepted: true };
943
+ if (remoteErrorOf(error) !== void 0) throw error;
944
+ if (error instanceof AttachmentError) throw new RemoteError("session/attachment-invalid", error.message, { reason: error.code });
945
+ throw new RemoteError("session/agent-busy", "prompt rejected", { reason: String(error) });
946
+ }
947
+ return { accepted: true };
948
+ };
949
+ return hasImage ? this.agents.serializeImageAdmission(agent, admit) : admit();
950
+ }
951
+ /** Recover first input acceptance, including claimed or removed messages, from unseen log entries. */
952
+ hasPromptRequest(session, requestId) {
953
+ let receipts = this.promptReceipts.get(session);
954
+ if (receipts === void 0) {
955
+ receipts = {
956
+ offset: SessionLogOffset(0),
957
+ messages: /* @__PURE__ */ new Set(),
958
+ requests: /* @__PURE__ */ new Set()
959
+ };
960
+ this.promptReceipts.set(session, receipts);
961
+ }
962
+ if (receipts.offset !== session.seq) {
963
+ for (const event of session.snapshotEvents(receipts.offset)) {
964
+ if (event.type !== "agent/inbox/spliced" && event.type !== "user/message") continue;
965
+ const messages = event.type === "agent/inbox/spliced" ? event.data.inserted : [event.data];
966
+ for (const message of messages) {
967
+ if (receipts.messages.has(message.id)) continue;
968
+ receipts.messages.add(message.id);
969
+ if (event.seq < session.inheritedEventCount) continue;
970
+ const source = message.source;
971
+ if ((source.kind === "user" || source.kind === "retry") && "rpcId" in source) receipts.requests.add(source.rpcId);
972
+ }
973
+ }
974
+ receipts.offset = session.seq;
975
+ }
976
+ return receipts.requests.has(requestId);
977
+ }
978
+ async requireModel(selection) {
979
+ if (!await modelAvailable(this.ctx, selection)) throw new RemoteError("session/model-unavailable", "Select an available model before sending a message.", {
980
+ provider: selection.provider,
981
+ model: selection.model
982
+ });
983
+ }
984
+ /**
985
+ * Read one durable image using the supplied reference without consulting Session history.
986
+ * @param request - image reference and gateway permission scope; Session existence is not checked.
987
+ * @returns the durable attachment reference and base64-encoded bytes.
988
+ */
989
+ async attachment(request) {
990
+ try {
991
+ const stored = await this.ctx.attachments.readImage(request.attachment);
992
+ return {
993
+ attachment: stored.ref,
994
+ data: Buffer.from(stored.data).toString("base64")
995
+ };
996
+ } catch (error) {
997
+ if (error instanceof AttachmentError) throw new RemoteError("session/attachment-invalid", error.message, { reason: error.code });
998
+ throw new RemoteError("gateway/internal", "Unable to read image attachment.", {});
999
+ }
1000
+ }
1001
+ /**
1002
+ * Mutate one pending Inbox occurrence, restoring an ordinary cold Agent when needed.
1003
+ * @param request - Session, queue item, and requested mutation.
1004
+ * @returns acknowledgement that the queue mutation was applied.
1005
+ */
1006
+ async updateQueue(request) {
1007
+ if (request.action.kind === "edit") {
1008
+ if (request.action.content.some((block) => block.type !== "text")) throw new RemoteError("session/attachment-invalid", "queue edits accept text content only", { reason: "QUEUE_EDIT_NON_TEXT" });
1009
+ if (!hasPromptContent(request.action.content)) throw new RemoteError("gateway/bad-request", "queue edit content must include non-whitespace text", {});
1010
+ }
1011
+ let agent = this.ctx.agents.get(request.sessionId);
1012
+ if (agent === void 0) {
1013
+ const found = await this.agents.resolveAgent(request.sessionId);
1014
+ if ("error" in found) {
1015
+ if (found.error.code !== "session/not-found") throw found.error;
1016
+ throw new RemoteError("session/queue-item-not-found", "queued item is no longer pending", { itemId: request.itemId });
1017
+ }
1018
+ agent = found.agent;
1019
+ }
1020
+ if (hasApiSessionSubagentOwner(agent.session)) {
1021
+ const identity = this.ctx.sessionProjections.snapshot(agent.session, ["subagent"]).values.subagent;
1022
+ if (identity?.mode !== "continuable" || !agent.session.isOwnSeq(identity.seq)) throw apiSessionSubagentOwnershipError(request.sessionId);
1023
+ }
1024
+ const nextTurn = agent.inbox.nextTurn.find((message) => message.id === request.itemId);
1025
+ const nextStep = agent.inbox.nextStep.find((message) => message.id === request.itemId);
1026
+ const located = nextTurn === void 0 ? nextStep === void 0 ? void 0 : {
1027
+ target: "next-step",
1028
+ message: nextStep
1029
+ } : {
1030
+ target: "next-turn",
1031
+ message: nextTurn
1032
+ };
1033
+ if (located === void 0) throw new RemoteError("session/queue-item-not-found", "queued item is no longer pending", { itemId: request.itemId });
1034
+ const { target, message } = located;
1035
+ if (request.action.kind === "steer" && (target !== "next-turn" || agent.status !== "running")) throw new RemoteError("session/steer-unavailable", "current turn no longer accepts steering", { itemId: request.itemId });
1036
+ switch (request.action.kind) {
1037
+ case "edit":
1038
+ agent.inbox.replace(request.itemId, freezeMessage({
1039
+ ...message,
1040
+ content: [...request.action.content]
1041
+ }));
1042
+ break;
1043
+ case "remove": {
1044
+ agent.inbox.remove(request.itemId);
1045
+ const source = message.source;
1046
+ if (source.kind === "user" && "rpcId" in source) this.ctx.fileUploads.retirePrompt(agent, source.rpcId);
1047
+ break;
1048
+ }
1049
+ case "steer":
1050
+ agent.inbox.remove(request.itemId);
1051
+ agent.steer(message);
1052
+ break;
1053
+ /* v8 ignore next 2 -- closed-union exhaustiveness guard */
1054
+ default: assertNever(request.action, "queue action");
1055
+ }
1056
+ return { accepted: true };
1057
+ }
1058
+ /**
1059
+ * Cancel one live ordinary Agent while retaining pending inbox work.
1060
+ * @param request - Session whose active Agent turn is cancelled.
1061
+ * @returns acknowledgement that cancellation was requested.
1062
+ */
1063
+ cancel(request) {
1064
+ const agent = this.ctx.agents.get(request.sessionId);
1065
+ if (agent === void 0) throw new RemoteError("session/not-found", `session "${request.sessionId}" not found (not attached)`, { sessionId: request.sessionId });
1066
+ if (hasApiSessionSubagentOwner(agent.session)) throw apiSessionSubagentOwnershipError(request.sessionId);
1067
+ agent.cancel({ kind: "user" }, { keepInbox: true });
1068
+ return { accepted: true };
1069
+ }
1070
+ async resolveAgent(sessionId) {
1071
+ const found = await this.agents.resolveAgent(sessionId);
1072
+ if ("error" in found) throw found.error;
1073
+ return found.agent;
1074
+ }
1075
+ rejectCreation(error) {
1076
+ if (remoteErrorOf(error) !== void 0) throw error;
1077
+ if (error instanceof ApiSessionPresetConflict) throw new RemoteError("agent-preset/conflict", error.message, {
1078
+ sessionId: error.sessionId,
1079
+ requestedPreset: error.requestedPreset
1080
+ });
1081
+ if (error instanceof ApiSessionCwdConflict) throw new RemoteError("session/conflict", error.message, {
1082
+ sessionId: error.sessionId,
1083
+ requestedCwd: error.requestedCwd,
1084
+ ...error.existingCwd === void 0 ? {} : { existingCwd: error.existingCwd }
1085
+ });
1086
+ if (error instanceof ApiSessionSubagentOwnership) throw apiSessionSubagentOwnershipError(error.sessionId);
1087
+ throw new RemoteError("gateway/internal", `failed to create session: ${String(error)}`, {});
1088
+ }
1089
+ async forkWorkspace(source) {
1090
+ const workspaces = this.ctx.workspaceRegistry.list();
1091
+ const direct = workspaces.find((workspace) => workspace.sessionIds.includes(source.id));
1092
+ if (direct !== void 0 || source.origin !== "subagent") return direct;
1093
+ const lineage = await this.ctx.sessionQuery.traceSession(source.id);
1094
+ for (const ancestor of lineage.ancestors) {
1095
+ const workspace = workspaces.find((candidate) => candidate.sessionIds.includes(ancestor.header.id));
1096
+ if (workspace !== void 0) return workspace;
1097
+ }
1098
+ }
1099
+ };
1100
+ /** Replace each file part with the file or image its staged receipt names. */
1101
+ function resolvePromptFileReceipts(content, staged) {
1102
+ const receiptIds = /* @__PURE__ */ new Set();
1103
+ return {
1104
+ content: content.map((part) => {
1105
+ if (part.type !== "file") return part;
1106
+ const attachment = staged(part.receiptId);
1107
+ if (attachment === void 0) throw new RemoteError("session/attachment-invalid", "File was not uploaded for this session.", { reason: "FILE_NOT_STAGED" });
1108
+ receiptIds.add(part.receiptId);
1109
+ return attachment;
1110
+ }),
1111
+ receiptIds: [...receiptIds]
1112
+ };
1113
+ }
1114
+ //#endregion
1115
+ //#region lib/types/control.js
1116
+ /** Live Session projection state with reconnect baselines. */
1117
+ /** Owns the Host-wide Session control stream. */
1118
+ var SessionControlController = class {
1119
+ ctx;
1120
+ streams = /* @__PURE__ */ new Set();
1121
+ /** @param ctx - Host context carrying live Agent and projection services. */
1122
+ constructor(ctx) {
1123
+ this.ctx = ctx;
1124
+ ctx.sessionProjections.onEventChanged((session, changes, seq) => {
1125
+ this.broadcast({
1126
+ type: "projection",
1127
+ sessionId: session.id,
1128
+ seq,
1129
+ changes
1130
+ });
1131
+ });
1132
+ ctx.effect(() => () => {
1133
+ for (const stream of this.streams) stream.end();
1134
+ this.streams.clear();
1135
+ }, "session-controller.control");
1136
+ }
1137
+ /**
1138
+ * Open one generation of Host-wide live control state.
1139
+ * @param signal - Remote stream cancellation.
1140
+ * @returns one complete baseline followed by live replacement frames.
1141
+ */
1142
+ async *control(signal) {
1143
+ signal.throwIfAborted();
1144
+ const queue = new ControlQueue();
1145
+ this.streams.add(queue);
1146
+ try {
1147
+ yield {
1148
+ type: "baseline",
1149
+ value: this.baseline()
1150
+ };
1151
+ yield* queue.iterate(signal);
1152
+ } finally {
1153
+ this.streams.delete(queue);
1154
+ queue.end();
1155
+ }
1156
+ }
1157
+ baseline() {
1158
+ const sessions = this.ctx.sessions.list();
1159
+ return { projections: this.projectionBaseline(sessions) };
1160
+ }
1161
+ projectionBaseline(sessions) {
1162
+ const blocks = Object.create(null);
1163
+ for (const session of sessions) {
1164
+ const snapshot = this.ctx.sessionProjections.snapshot(session);
1165
+ blocks[session.id] = {
1166
+ asOfSeq: snapshot.asOfSeq,
1167
+ values: snapshot.values
1168
+ };
1169
+ }
1170
+ return blocks;
1171
+ }
1172
+ broadcast(frame) {
1173
+ for (const stream of this.streams) stream.push(frame);
1174
+ }
1175
+ };
1176
+ var ControlQueue = class {
1177
+ buffer = new Deque();
1178
+ wake;
1179
+ done = false;
1180
+ push(frame) {
1181
+ if (this.done) return;
1182
+ this.buffer.pushBack(frame);
1183
+ const wake = this.wake;
1184
+ this.wake = void 0;
1185
+ wake?.();
1186
+ }
1187
+ end() {
1188
+ if (this.done) return;
1189
+ this.done = true;
1190
+ const wake = this.wake;
1191
+ this.wake = void 0;
1192
+ wake?.();
1193
+ }
1194
+ async *iterate(signal) {
1195
+ const onAbort = () => {
1196
+ this.end();
1197
+ };
1198
+ signal.addEventListener("abort", onAbort, { once: true });
1199
+ try {
1200
+ while (!this.done && !signal.aborted) {
1201
+ const frame = this.buffer.popFront();
1202
+ if (frame !== void 0) {
1203
+ yield frame;
1204
+ continue;
1205
+ }
1206
+ await new Promise((resolve) => {
1207
+ this.wake = resolve;
1208
+ });
1209
+ }
1210
+ while (this.buffer.size > 0 && !signal.aborted) yield this.buffer.popFront();
1211
+ } finally {
1212
+ signal.removeEventListener("abort", onAbort);
1213
+ this.end();
1214
+ }
1215
+ }
1216
+ };
1217
+ const MESSAGE_TYPES$1 = new Set(["user/message", "assistant/message"]);
1218
+ /**
1219
+ * Reject an invalid message budget or turn window.
1220
+ * @param request - history window fields.
1221
+ */
1222
+ function validateHistoryWindow(request) {
1223
+ if (request.maxMessages !== void 0 && (!Number.isSafeInteger(request.maxMessages) || request.maxMessages <= 0)) throw new RemoteError("gateway/bad-request", "maxMessages must be a positive safe integer", {});
1224
+ const window = request.turnWindow;
1225
+ if (window !== void 0) {
1226
+ if (!Number.isSafeInteger(window.minMessages) || window.minMessages <= 0 || window.minMessages > (request.maxMessages ?? 50)) throw new RemoteError("gateway/bad-request", "turnWindow.minMessages must be a positive safe integer no greater than maxMessages", {});
1227
+ if (!Number.isSafeInteger(window.minTurns) || window.minTurns <= 0) throw new RemoteError("gateway/bad-request", "turnWindow.minTurns must be a positive safe integer", {});
1228
+ }
1229
+ }
1230
+ /**
1231
+ * Select the Session whose log an address names.
1232
+ * @param address - ordinary Session or direct-subagent address.
1233
+ * @returns the Session whose log the address reads.
1234
+ */
1235
+ function addressId(address) {
1236
+ return address.kind === "session" ? address.sessionId : address.childSessionId;
1237
+ }
1238
+ /**
1239
+ * Reject an address that does not match the observed Session.
1240
+ * @param address - ordinary Session or direct-subagent address.
1241
+ * @param header - observed Session header.
1242
+ * @param inheritedEventCount - observed fork-inherited event count.
1243
+ * @param projections - observed projections; subagent addresses require them.
1244
+ */
1245
+ function validateAddress(address, header, inheritedEventCount, projections) {
1246
+ if (address.kind === "session") {
1247
+ if (header.origin === "subagent") throw new RemoteError("session/agent-busy", "subagent Sessions require their durable parent address", { reason: "use subagent delivery for this child session" });
1248
+ return;
1249
+ }
1250
+ if (header.origin !== "subagent" || header.parentSession !== address.parentSessionId) throw new RemoteError("subagent/unauthorized", "subagent does not belong to the supplied parent", { childSessionId: address.childSessionId });
1251
+ const identity = projections?.values.subagent;
1252
+ if (identity === null) throw new RemoteError("subagent/catalog-diagnostic", "subagent descriptor is corrupt", {
1253
+ parentSessionId: address.parentSessionId,
1254
+ childSessionId: address.childSessionId,
1255
+ reason: "corrupt"
1256
+ });
1257
+ if (identity === void 0 || identity.seq < inheritedEventCount) throw new RemoteError("subagent/catalog-diagnostic", "subagent descriptor is unavailable", {
1258
+ parentSessionId: address.parentSessionId,
1259
+ childSessionId: address.childSessionId,
1260
+ reason: "unsupported"
1261
+ });
1262
+ if (address.mode !== "unknown" && identity.mode !== address.mode) throw new RemoteError("subagent/unauthorized", "subagent mode does not match the supplied address", { childSessionId: address.childSessionId });
1263
+ }
1264
+ /**
1265
+ * Reject a missing Session using its address-specific error.
1266
+ * @param address - ordinary Session or direct-subagent address.
1267
+ * @returns never; this operation always throws.
1268
+ * @throws RemoteError `session/not-found` or `subagent/not-found`.
1269
+ */
1270
+ function rejectNotFound(address) {
1271
+ if (address.kind === "session") throw new RemoteError("session/not-found", `session "${address.sessionId}" not found`, { sessionId: address.sessionId });
1272
+ throw new RemoteError("subagent/not-found", "subagent is unavailable", {
1273
+ parentSessionId: address.parentSessionId,
1274
+ childSessionId: address.childSessionId
1275
+ });
1276
+ }
1277
+ /**
1278
+ * Cut one message-aligned backwards page from a contiguous event prefix.
1279
+ * @param events - contiguous events starting at seq 0.
1280
+ * @param beforeSeq - exclusive upper offset of an older page.
1281
+ * @param maxMessages - message budget.
1282
+ * @param throughSeq - inclusive log cut.
1283
+ * @param turnWindow - optional turn-boundary stop rule.
1284
+ * @returns the page events and whether older events remain.
1285
+ */
1286
+ function paginate(events, beforeSeq, maxMessages, throughSeq, turnWindow) {
1287
+ const end = SessionLogOffset(Math.min(throughSeq + 1, beforeSeq ?? throughSeq + 1));
1288
+ let count = 0;
1289
+ let turns = 0;
1290
+ let cut = SessionLogOffset(0);
1291
+ for (let index = end - 1; index >= 0; index--) {
1292
+ const event = events[index];
1293
+ if (turnWindow !== void 0 && event.type === "turn/start") {
1294
+ turns++;
1295
+ if (count >= turnWindow.minMessages && turns >= turnWindow.minTurns) {
1296
+ cut = SessionLogOffset(index);
1297
+ break;
1298
+ }
1299
+ }
1300
+ if (!MESSAGE_TYPES$1.has(event.type) || !isAppendSurfaceEvent(event)) continue;
1301
+ count++;
1302
+ const sources = event.sourceEventSeqs;
1303
+ let groupStart = event.seq;
1304
+ if (sources !== void 0) {
1305
+ for (const source of sources) if (source < groupStart) groupStart = source;
1306
+ }
1307
+ if (count >= maxMessages) {
1308
+ cut = SessionLogOffset(groupStart);
1309
+ break;
1310
+ }
1311
+ }
1312
+ return {
1313
+ events: events.slice(cut, end),
1314
+ hasMore: cut > 0
1315
+ };
1316
+ }
1317
+ /**
1318
+ * Convert a committed event to its wire entry.
1319
+ * @param event - committed Session event.
1320
+ * @returns the wire event entry.
1321
+ */
1322
+ function entryFor(event) {
1323
+ return {
1324
+ type: "event",
1325
+ event
1326
+ };
1327
+ }
1328
+ /**
1329
+ * Encode one bounded logical page without changing its pagination cut.
1330
+ * @param events - page events.
1331
+ * @returns the wire records.
1332
+ */
1333
+ function pageRecords(events) {
1334
+ return events.map(entryFor);
1335
+ }
1336
+ //#endregion
1337
+ //#region lib/types/history/listener.js
1338
+ /** Passive per-Session streams; subscriptions never acquire Session observations. */
1339
+ /** A single subscription buffers before either consumption mode starts. */
1340
+ var EventListener = class {
1341
+ buffer;
1342
+ disposes = [];
1343
+ firstReceivedSeq;
1344
+ nextExpectedSeq;
1345
+ /**
1346
+ * @param ctx - context owning the event registrations.
1347
+ * @param sessionId - Session whose notifications are emitted.
1348
+ * @param signal - cancellation that wakes consumers.
1349
+ * @param queue - optional caller-owned buffer; only an internally created buffer is disposed here.
1350
+ */
1351
+ constructor(ctx, sessionId, signal, queue) {
1352
+ signal.throwIfAborted();
1353
+ const buffer = queue ?? new ListenerBuffer(ctx, signal);
1354
+ this.buffer = queue === void 0 ? buffer : void 0;
1355
+ const input = buffer.createInput((item) => this.transform(item));
1356
+ const target = sessionId;
1357
+ try {
1358
+ this.disposes.push(ctx.on("session/event", (session, event) => {
1359
+ if (session.id !== target) return;
1360
+ buffer.capture(() => {
1361
+ this.recordFirst(event.seq);
1362
+ input.append({
1363
+ type: "event",
1364
+ session,
1365
+ event
1366
+ });
1367
+ });
1368
+ }, { global: true }));
1369
+ this.disposes.push(ctx.on("session/created", (session) => {
1370
+ if (session.id !== target) return;
1371
+ buffer.capture(() => {
1372
+ if (session.firstLiveSeq < session.seq) this.recordFirst(session.firstLiveSeq);
1373
+ input.prepend({
1374
+ type: "created",
1375
+ session,
1376
+ end: session.seq
1377
+ });
1378
+ });
1379
+ }, { global: true }));
1380
+ this.buffer?.own(() => {
1381
+ this[Symbol.dispose]();
1382
+ });
1383
+ } catch (error) {
1384
+ this[Symbol.dispose]();
1385
+ throw error;
1386
+ }
1387
+ }
1388
+ /** Consume notifications without reading history.
1389
+ * @returns event frames from the first received event, without loading a baseline. */
1390
+ events() {
1391
+ return this.iterate();
1392
+ }
1393
+ /** Set the inclusive opening cut for buffered history notifications.
1394
+ * @param cursor - snapshot cut set before consuming the queue. */
1395
+ setCursor(cursor) {
1396
+ this.nextExpectedSeq = cursor + 1;
1397
+ }
1398
+ *transform(item) {
1399
+ if (this.disposes.length === 0) return;
1400
+ this.nextExpectedSeq ??= this.firstReceivedSeq;
1401
+ const result = eventItem(item, this.nextExpectedSeq);
1402
+ this.nextExpectedSeq = result.next;
1403
+ for (const event of result.events) {
1404
+ if (this.disposes.length === 0) return;
1405
+ yield entryFor(event);
1406
+ }
1407
+ }
1408
+ async *iterate() {
1409
+ if (this.buffer === void 0) throw new Error("Consume the externally owned history buffer directly");
1410
+ try {
1411
+ yield* this.buffer.items();
1412
+ } finally {
1413
+ this[Symbol.dispose]();
1414
+ }
1415
+ }
1416
+ recordFirst(seq) {
1417
+ this.firstReceivedSeq = this.firstReceivedSeq === void 0 ? seq : Math.min(this.firstReceivedSeq, seq);
1418
+ }
1419
+ [Symbol.dispose]() {
1420
+ for (const dispose of this.disposes.splice(0).reverse()) dispose();
1421
+ this.buffer?.[Symbol.dispose]();
1422
+ }
1423
+ };
1424
+ /**
1425
+ * Select the uncovered events represented by one notification.
1426
+ * @param item - one buffered notification.
1427
+ * @param next - next required seq, or undefined before the first event.
1428
+ * @returns uncovered events and the next required seq without acquiring an observation.
1429
+ */
1430
+ function eventItem(item, next) {
1431
+ if (item.type === "event") {
1432
+ if (next !== void 0 && item.event.seq < next) return {
1433
+ events: [],
1434
+ next
1435
+ };
1436
+ if (next !== void 0 && item.event.seq !== next) throw new RemoteError("gateway/internal", `session event stream skipped seq ${String(next)}`, {});
1437
+ return {
1438
+ events: [item.event],
1439
+ next: item.event.seq + 1
1440
+ };
1441
+ }
1442
+ const start = next ?? item.session.firstLiveSeq;
1443
+ if (start >= item.end) return {
1444
+ events: [],
1445
+ next
1446
+ };
1447
+ const events = item.session.snapshotEvents(SessionLogOffset(start), SessionLogOffset(item.end));
1448
+ for (const event of events) {
1449
+ if (next !== void 0 && event.seq !== next) throw new RemoteError("gateway/internal", `session event stream skipped seq ${String(next)}`, {});
1450
+ next = event.seq + 1;
1451
+ }
1452
+ return {
1453
+ events,
1454
+ next
1455
+ };
1456
+ }
1457
+ /** Projection changes of one Session, one change per committed event that changed a projection. */
1458
+ var ProjectionListener = class {
1459
+ buffer;
1460
+ /**
1461
+ * @param ctx - context owning projection notifications.
1462
+ * @param sessionId - Session whose notifications are emitted.
1463
+ * @param signal - cancellation that removes registrations and wakes consumers.
1464
+ */
1465
+ constructor(ctx, sessionId, signal) {
1466
+ this.buffer = new ListenerBuffer(ctx, signal);
1467
+ const input = this.buffer.createInput((item) => [item]);
1468
+ const target = sessionId;
1469
+ try {
1470
+ this.buffer.own(ctx.sessionProjections.onEventChanged((session, changes, seq) => {
1471
+ if (session.id !== target) return;
1472
+ this.buffer.capture(() => {
1473
+ const change = {
1474
+ type: "projection",
1475
+ seq,
1476
+ changes
1477
+ };
1478
+ input.append({
1479
+ session,
1480
+ change
1481
+ });
1482
+ });
1483
+ }));
1484
+ } catch (error) {
1485
+ this.buffer[Symbol.dispose]();
1486
+ throw error;
1487
+ }
1488
+ }
1489
+ /** Consume per-event projection changes.
1490
+ * @returns validated change frames, one per committed event; projection seqs need not be contiguous. */
1491
+ async *changes() {
1492
+ try {
1493
+ for await (const { change } of this.buffer.items()) yield change;
1494
+ } finally {
1495
+ this[Symbol.dispose]();
1496
+ }
1497
+ }
1498
+ [Symbol.dispose]() {
1499
+ this.buffer[Symbol.dispose]();
1500
+ }
1501
+ };
1502
+ /** Owns buffering, callback failure and registration cleanup for one consumer. */
1503
+ var ListenerBuffer = class {
1504
+ values = new Deque();
1505
+ transformIds = new Deque();
1506
+ transforms = [];
1507
+ cleanup = [];
1508
+ wake;
1509
+ closed = false;
1510
+ failure;
1511
+ consumed = false;
1512
+ constructor(ctx, signal) {
1513
+ signal.throwIfAborted();
1514
+ const close = () => {
1515
+ this[Symbol.dispose]();
1516
+ };
1517
+ signal.addEventListener("abort", close, { once: true });
1518
+ this.own(() => {
1519
+ signal.removeEventListener("abort", close);
1520
+ });
1521
+ try {
1522
+ const dispose = ctx.effect(() => close, "session-controller.listener-buffer");
1523
+ this.own(() => {
1524
+ dispose();
1525
+ });
1526
+ } catch (error) {
1527
+ this[Symbol.dispose]();
1528
+ throw error;
1529
+ }
1530
+ }
1531
+ /**
1532
+ * Register cleanup, or run it immediately when already closed.
1533
+ * @param dispose - synchronous cleanup.
1534
+ */
1535
+ own(dispose) {
1536
+ if (this.closed) dispose();
1537
+ else this.cleanup.push(dispose);
1538
+ }
1539
+ /**
1540
+ * Contain producer failure and wake the consumer with that failure.
1541
+ * @param action - synchronous producer operation.
1542
+ */
1543
+ capture(action) {
1544
+ if (this.closed) return;
1545
+ try {
1546
+ action();
1547
+ } catch (error) {
1548
+ this.failure = { error };
1549
+ this[Symbol.dispose]();
1550
+ }
1551
+ }
1552
+ /**
1553
+ * Register a dequeue transform and obtain its write-only input.
1554
+ * @param transform - conversion bound once and evaluated when each input is dequeued.
1555
+ * @returns a write-only input sharing this buffer's storage and lifetime.
1556
+ * @throws when this buffer is already closed.
1557
+ */
1558
+ createInput(transform) {
1559
+ if (this.closed) throw new Error("Cannot register a transform on a closed listener buffer");
1560
+ const transformId = this.transforms.length;
1561
+ this.transforms.push((value) => transform(value));
1562
+ return {
1563
+ append: (item) => {
1564
+ if (this.closed) return;
1565
+ this.values.pushBack(item);
1566
+ this.transformIds.pushBack(transformId);
1567
+ this.notify();
1568
+ },
1569
+ prepend: (item) => {
1570
+ if (this.closed) return;
1571
+ this.values.pushFront(item);
1572
+ this.transformIds.pushFront(transformId);
1573
+ this.notify();
1574
+ }
1575
+ };
1576
+ }
1577
+ /**
1578
+ * Consume queued values once, releasing the buffer when iteration ends.
1579
+ * @returns transformed output values.
1580
+ */
1581
+ async *items() {
1582
+ if (this.consumed) throw new RemoteError("gateway/internal", "Session listener already has a consumer", {});
1583
+ this.consumed = true;
1584
+ try {
1585
+ for (;;) {
1586
+ if (this.failure !== void 0) throw this.failure.error;
1587
+ if (this.closed) return;
1588
+ if (this.transformIds.size === 0) {
1589
+ await new Promise((resolve) => {
1590
+ this.wake = resolve;
1591
+ });
1592
+ continue;
1593
+ }
1594
+ const transformId = this.transformIds.popFront();
1595
+ const value = this.values.popFront();
1596
+ for (const item of this.transforms[transformId](value)) {
1597
+ this.throwIfFailed();
1598
+ if (this.isClosed()) return;
1599
+ yield item;
1600
+ }
1601
+ }
1602
+ } finally {
1603
+ this[Symbol.dispose]();
1604
+ }
1605
+ }
1606
+ throwIfFailed() {
1607
+ if (this.failure !== void 0) throw this.failure.error;
1608
+ }
1609
+ /** @returns whether disposal ended this buffer while a transform was yielding. */
1610
+ isClosed() {
1611
+ return this.closed;
1612
+ }
1613
+ notify() {
1614
+ const wake = this.wake;
1615
+ this.wake = void 0;
1616
+ wake?.();
1617
+ }
1618
+ [Symbol.dispose]() {
1619
+ if (this.closed) return;
1620
+ this.closed = true;
1621
+ this.values.clear();
1622
+ this.transformIds.clear();
1623
+ this.transforms.length = 0;
1624
+ this.notify();
1625
+ for (const dispose of this.cleanup.splice(0).reverse()) dispose();
1626
+ }
1627
+ };
1628
+ //#endregion
1629
+ //#region lib/types/assistant-stream.js
1630
+ /** Process-local assistant state retained for reconnecting Web followers. */
1631
+ const EMPTY_BASELINE = { revision: 0 };
1632
+ /**
1633
+ * Folds dense Agent frames and materializes one shared immutable reconnect
1634
+ * baseline per accepted revision.
1635
+ */
1636
+ var SessionAssistantStreamAccumulator = class {
1637
+ activeAttempt;
1638
+ revision = 0;
1639
+ snapshotValue = EMPTY_BASELINE;
1640
+ dirty = false;
1641
+ /**
1642
+ * Fold one trusted frame from the current attached Agent lifecycle.
1643
+ * @param frame - next dense process-local Assistant frame.
1644
+ * @param durableCursor - last committed Session seq when this frame was observed.
1645
+ */
1646
+ accept(frame, durableCursor) {
1647
+ if (frame.type === "start" && frame.revision === 1 && this.revision !== 0) {
1648
+ this.activeAttempt = void 0;
1649
+ this.revision = 0;
1650
+ }
1651
+ if (frame.revision !== this.revision + 1) {
1652
+ this.activeAttempt = void 0;
1653
+ this.revision = frame.revision;
1654
+ this.dirty = true;
1655
+ return;
1656
+ }
1657
+ this.revision = frame.revision;
1658
+ switch (frame.type) {
1659
+ case "start":
1660
+ this.activeAttempt = {
1661
+ attemptId: frame.attemptId,
1662
+ startedAfterSeq: durableCursor,
1663
+ turn: frame.turn,
1664
+ step: frame.step,
1665
+ stream: new AssistantStreamAccumulator(),
1666
+ nextIndex: 0
1667
+ };
1668
+ break;
1669
+ case "chunk": {
1670
+ const attempt = this.activeAttempt;
1671
+ if (attempt === void 0 || attempt.attemptId !== frame.attemptId || frame.index !== attempt.nextIndex) {
1672
+ this.activeAttempt = void 0;
1673
+ break;
1674
+ }
1675
+ attempt.stream.push({
1676
+ time: frame.time,
1677
+ chunk: frame.chunk
1678
+ });
1679
+ attempt.nextIndex += 1;
1680
+ break;
1681
+ }
1682
+ case "end":
1683
+ this.activeAttempt = void 0;
1684
+ break;
1685
+ }
1686
+ this.dirty = true;
1687
+ }
1688
+ /**
1689
+ * Read the cached reconnect baseline, materializing it after a state change.
1690
+ * @returns the identity-stable baseline for the latest accepted revision.
1691
+ */
1692
+ snapshot() {
1693
+ if (!this.dirty) return this.snapshotValue;
1694
+ this.snapshotValue = {
1695
+ revision: this.revision,
1696
+ ...this.activeAttempt === void 0 ? {} : { activeAttempt: {
1697
+ attemptId: this.activeAttempt.attemptId,
1698
+ startedAfterSeq: this.activeAttempt.startedAfterSeq,
1699
+ turn: this.activeAttempt.turn,
1700
+ step: this.activeAttempt.step,
1701
+ nextIndex: this.activeAttempt.nextIndex,
1702
+ stream: this.activeAttempt.stream.snapshot()
1703
+ } }
1704
+ };
1705
+ this.dirty = false;
1706
+ return this.snapshotValue;
1707
+ }
1708
+ };
1709
+ //#endregion
1710
+ //#region lib/types/history/assistant-stream.js
1711
+ /** Assistant stream baselines and per-connection subscriptions. */
1712
+ /** One accumulator per live Session, shared by every subscription bound to it. */
1713
+ var SessionAssistantStreamsListener = class {
1714
+ ctx;
1715
+ streams = /* @__PURE__ */ new Map();
1716
+ /** @param ctx - service context owning the accumulator listeners. */
1717
+ constructor(ctx) {
1718
+ this.ctx = ctx;
1719
+ ctx.on("agent/assistant-stream", ({ agent, frame }) => {
1720
+ let stream = this.streams.get(agent.session.id);
1721
+ if (stream === void 0) {
1722
+ stream = new SessionAssistantStreamAccumulator();
1723
+ this.streams.set(agent.session.id, stream);
1724
+ }
1725
+ stream.accept(frame, agent.session.seq === 0 ? -1 : SessionSeq(agent.session.seq - 1));
1726
+ }, { global: true });
1727
+ ctx.on("agent/disposed", ({ agent }) => {
1728
+ this.streams.delete(agent.session.id);
1729
+ }, { global: true });
1730
+ ctx.effect(() => () => {
1731
+ this.streams.clear();
1732
+ }, "session-controller.assistant-streams");
1733
+ }
1734
+ /**
1735
+ * Bind one connection to a Session assistant stream.
1736
+ * @param sessionId - Session to subscribe.
1737
+ * @param signal - cancellation owned by the caller.
1738
+ * @param queue - caller-owned raw notification buffer.
1739
+ * @returns a listener the caller disposes.
1740
+ */
1741
+ bind(sessionId, signal, queue) {
1742
+ return new AssistantStreamListener(this.ctx, sessionId, signal, () => {
1743
+ return this.streams.get(sessionId)?.snapshot() ?? { revision: 0 };
1744
+ }, queue);
1745
+ }
1746
+ };
1747
+ /** Writes assistant notifications into the connection's shared queue. */
1748
+ var AssistantStreamListener = class {
1749
+ _snapshot;
1750
+ disposes = [];
1751
+ ordinal = 0;
1752
+ cut = 0;
1753
+ constructor(ctx, sessionId, signal, _snapshot, output) {
1754
+ this._snapshot = _snapshot;
1755
+ signal.throwIfAborted();
1756
+ const input = output.createInput((item) => this.transform(item));
1757
+ try {
1758
+ this.disposes.push(ctx.on("agent/assistant-stream", ({ agent, frame }) => {
1759
+ if (agent.session.id !== sessionId) return;
1760
+ output.capture(() => {
1761
+ const wire = frame.type === "start" ? {
1762
+ ...frame,
1763
+ startedAfterSeq: agent.session.seq === 0 ? -1 : SessionSeq(agent.session.seq - 1)
1764
+ } : frame.type === "chunk" ? {
1765
+ ...frame,
1766
+ chunk: frame.chunk
1767
+ } : frame;
1768
+ input.append({
1769
+ type: "assistant-stream",
1770
+ session: agent.session,
1771
+ frame: wire,
1772
+ ordinal: ++this.ordinal
1773
+ });
1774
+ });
1775
+ }, { global: true }));
1776
+ } catch (error) {
1777
+ this[Symbol.dispose]();
1778
+ throw error;
1779
+ }
1780
+ }
1781
+ /** @returns the baseline and local arrival cut captured synchronously together. */
1782
+ snapshot() {
1783
+ return {
1784
+ baseline: this._snapshot(),
1785
+ ordinal: this.ordinal
1786
+ };
1787
+ }
1788
+ /** @param ordinal - local snapshot cut set before queue consumption. */
1789
+ setOrdinalCut(ordinal) {
1790
+ this.cut = ordinal;
1791
+ }
1792
+ *transform(item) {
1793
+ if (this.disposes.length === 0 || item.ordinal <= this.cut) return;
1794
+ yield {
1795
+ type: "assistant-stream",
1796
+ frame: item.frame
1797
+ };
1798
+ }
1799
+ [Symbol.dispose]() {
1800
+ for (const dispose of this.disposes.splice(0).reverse()) dispose();
1801
+ }
1802
+ };
1803
+ //#endregion
1804
+ //#region lib/types/history/controller.js
1805
+ /** Independent Session snapshots and passive event subscriptions. */
1806
+ var __addDisposableResource$4 = function(env, value, async) {
1807
+ if (value !== null && value !== void 0) {
1808
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
1809
+ var dispose, inner;
1810
+ if (async) {
1811
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
1812
+ dispose = value[Symbol.asyncDispose];
1813
+ }
1814
+ if (dispose === void 0) {
1815
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
1816
+ dispose = value[Symbol.dispose];
1817
+ if (async) inner = dispose;
1818
+ }
1819
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
1820
+ if (inner) dispose = function() {
1821
+ try {
1822
+ inner.call(this);
1823
+ } catch (e) {
1824
+ return Promise.reject(e);
1825
+ }
1826
+ };
1827
+ env.stack.push({
1828
+ value,
1829
+ dispose,
1830
+ async
1831
+ });
1832
+ } else if (async) env.stack.push({ async: true });
1833
+ return value;
1834
+ };
1835
+ var __disposeResources$4 = (function(SuppressedError) {
1836
+ return function(env) {
1837
+ function fail(e) {
1838
+ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
1839
+ env.hasError = true;
1840
+ }
1841
+ var r, s = 0;
1842
+ function next() {
1843
+ while (r = env.stack.pop()) try {
1844
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
1845
+ if (r.dispose) {
1846
+ var result = r.dispose.call(r.value);
1847
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
1848
+ fail(e);
1849
+ return next();
1850
+ });
1851
+ } else s |= 1;
1852
+ } catch (e) {
1853
+ fail(e);
1854
+ }
1855
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
1856
+ if (env.hasError) throw env.error;
1857
+ }
1858
+ return next();
1859
+ };
1860
+ })(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
1861
+ var e = new Error(message);
1862
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
1863
+ });
1864
+ /** Session snapshots do not share lifetime with passive subscriptions. */
1865
+ var HistoryController = class {
1866
+ ctx;
1867
+ /** Reconnect state for this controller's assistant subscriptions. */
1868
+ streamsListener;
1869
+ /** @param ctx - Host context carrying Session reads and projections. */
1870
+ constructor(ctx) {
1871
+ this.ctx = ctx;
1872
+ this.streamsListener = new SessionAssistantStreamsListener(this.ctx);
1873
+ }
1874
+ /**
1875
+ * Read a passive page of Session events at an exact cut.
1876
+ * @param request - Session identity and optional cut and page window.
1877
+ * @param signal - read cancellation.
1878
+ * @returns a page at the supplied cut, or the observed log end when omitted.
1879
+ */
1880
+ async events(request, signal) {
1881
+ const spec = resolveHistoryRequest(request);
1882
+ try {
1883
+ return await this.usingObservation({
1884
+ sessionId: addressId(request.address),
1885
+ projection: request.address.kind === "subagent"
1886
+ }, signal, (observation) => {
1887
+ validateObservationAddress(request.address, observation);
1888
+ return history(observation, spec);
1889
+ });
1890
+ } catch (error) {
1891
+ if (remoteErrorOf(error)?.code === "session/not-found") rejectNotFound(request.address);
1892
+ throw error;
1893
+ }
1894
+ }
1895
+ /**
1896
+ * Subscribe to Session events without reading or activating the Session.
1897
+ * @param request - Session address to subscribe.
1898
+ * @param signal - stream cancellation.
1899
+ * @returns subscription readiness followed by event frames; readiness does not establish existence.
1900
+ */
1901
+ async *observeEvent(request, signal) {
1902
+ const env_1 = {
1903
+ stack: [],
1904
+ error: void 0,
1905
+ hasError: false
1906
+ };
1907
+ try {
1908
+ const listener = __addDisposableResource$4(env_1, new EventListener(this.ctx, addressId(request.address), signal), false);
1909
+ yield { type: "ready" };
1910
+ yield* listener.events();
1911
+ } catch (e_1) {
1912
+ env_1.error = e_1;
1913
+ env_1.hasError = true;
1914
+ } finally {
1915
+ __disposeResources$4(env_1);
1916
+ }
1917
+ }
1918
+ /**
1919
+ * Read exact projections or migration cache hints without activating the Session.
1920
+ * @param request - Session identity whose exact projection baseline is required.
1921
+ * @param signal - read cancellation.
1922
+ * @returns exact sequenced values, migration cache hints, or null when absent.
1923
+ */
1924
+ async projections(request, signal) {
1925
+ const { sessionId } = request;
1926
+ if (sessionId.length === 0) throw new RemoteError("gateway/bad-request", "sessionId must not be empty", {});
1927
+ try {
1928
+ signal.throwIfAborted();
1929
+ const live = this.ctx.sessions.get(sessionId);
1930
+ if (live !== void 0) {
1931
+ const snapshot = this.ctx.sessionProjections.snapshot(live);
1932
+ return {
1933
+ kind: "sequenced",
1934
+ asOfSeq: snapshot.asOfSeq,
1935
+ values: snapshot.values
1936
+ };
1937
+ } else {
1938
+ const stored = await this.ctx.get("sessionPersistence")?.stat(sessionId, { signal });
1939
+ signal.throwIfAborted();
1940
+ if (stored?.formatStatus === "migration-required") return {
1941
+ kind: "migration-required",
1942
+ values: { ...(this.ctx.get("sessionProjectionCache")?.cachedSnapshot(stored.header))?.values }
1943
+ };
1944
+ return await this.usingObservation({
1945
+ sessionId: request.sessionId,
1946
+ projection: true
1947
+ }, signal, (observation) => ({
1948
+ kind: "sequenced",
1949
+ ...projections(observation)
1950
+ }));
1951
+ }
1952
+ } catch (error) {
1953
+ const code = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
1954
+ if (code === "SESSION_QUERY_SESSION_NOT_FOUND" || code === "session/not-found") return null;
1955
+ if (signal.aborted || code === "SESSION_QUERY_ABORTED") throw new RemoteError("gateway/cancelled", "Session projection read was cancelled", {}, { cause: error });
1956
+ if (remoteErrorOf(error) !== void 0) throw error;
1957
+ throw new RemoteError("gateway/internal", "Session projection read failed", {}, { cause: error });
1958
+ }
1959
+ }
1960
+ /**
1961
+ * Subscribe to projection changes without reading a baseline.
1962
+ * @param request - Session identity to subscribe without reading a baseline.
1963
+ * @param signal - stream cancellation.
1964
+ * @returns readiness followed by one change frame per committed event, listing every key it changed.
1965
+ */
1966
+ async *observeProjections(request, signal) {
1967
+ const env_2 = {
1968
+ stack: [],
1969
+ error: void 0,
1970
+ hasError: false
1971
+ };
1972
+ try {
1973
+ const listener = __addDisposableResource$4(env_2, new ProjectionListener(this.ctx, request.sessionId, signal), false);
1974
+ yield { type: "ready" };
1975
+ yield* listener.changes();
1976
+ } catch (e_2) {
1977
+ env_2.error = e_2;
1978
+ env_2.hasError = true;
1979
+ } finally {
1980
+ __disposeResources$4(env_2);
1981
+ }
1982
+ }
1983
+ /**
1984
+ * Read bounded committed assistant messages through a stopping cursor.
1985
+ * @param sessionId - Session whose committed assistant messages are requested.
1986
+ * @param afterSeq - exclusive lower bound.
1987
+ * @param throughSeq - inclusive stopping-state cursor.
1988
+ * @param maxMessages - positive assistant record limit.
1989
+ * @param signal - caller cancellation, independent of a completed wait deadline.
1990
+ * @returns newest-first assistant messages and whether further matching records were omitted.
1991
+ */
1992
+ async assistantOutput(sessionId, afterSeq, throughSeq, maxMessages, signal) {
1993
+ return this.usingObservation({
1994
+ sessionId,
1995
+ projection: false
1996
+ }, signal, (observation) => {
1997
+ if (throughSeq > observation.cursor) throw new RemoteError("gateway/internal", "Session history no longer covers the wait cursor", {});
1998
+ const records = [];
1999
+ const events = observation.events;
2000
+ for (let index = throughSeq; index > afterSeq; index--) {
2001
+ const event = events[index];
2002
+ if (event.type !== "assistant/message" || !isAppendSurfaceEvent(event)) continue;
2003
+ if (records.length === maxMessages) return {
2004
+ records,
2005
+ truncated: true
2006
+ };
2007
+ records.push(entryFor(event));
2008
+ }
2009
+ return {
2010
+ records,
2011
+ truncated: false
2012
+ };
2013
+ });
2014
+ }
2015
+ async usingObservation({ sessionId, projection }, signal, callback) {
2016
+ const env_3 = {
2017
+ stack: [],
2018
+ error: void 0,
2019
+ hasError: false
2020
+ };
2021
+ try {
2022
+ let observation;
2023
+ try {
2024
+ observation = await this.ctx.sessionQuery.observeSession(sessionId, {
2025
+ signal,
2026
+ projectionMode: projection ? "all" : "none"
2027
+ });
2028
+ } catch (error) {
2029
+ const code = error?.code;
2030
+ if (code === "SESSION_QUERY_SESSION_NOT_FOUND") throw new RemoteError("session/not-found", `session "${sessionId}" not found`, { sessionId });
2031
+ if (code === "SESSION_QUERY_ABORTED") throw new RemoteError("gateway/cancelled", error instanceof Error ? error.message : "Session read was cancelled", {}, { cause: error });
2032
+ throw error;
2033
+ }
2034
+ try {
2035
+ signal.throwIfAborted();
2036
+ } catch (error) {
2037
+ observation[Symbol.dispose]();
2038
+ throw error;
2039
+ }
2040
+ if (callback === void 0) return observation;
2041
+ return await callback(__addDisposableResource$4(env_3, observation, false));
2042
+ } catch (e_3) {
2043
+ env_3.error = e_3;
2044
+ env_3.hasError = true;
2045
+ } finally {
2046
+ __disposeResources$4(env_3);
2047
+ }
2048
+ }
2049
+ };
2050
+ /**
2051
+ * Validate an Address against the exact read used by a Controller.
2052
+ * @param address - caller-supplied Session address.
2053
+ * @param observation - borrowed read; subagent addresses require projections.
2054
+ */
2055
+ function validateObservationAddress(address, observation) {
2056
+ if (observation.header.cwd === void 0) rejectNotFound(address);
2057
+ validateAddress(address, observation.header, observation.inheritedEventCount, observation.projections);
2058
+ }
2059
+ /**
2060
+ * Convert a borrowed observation to one page without acquiring or retaining it.
2061
+ * @param observation - exact read cut owned by the caller.
2062
+ * @param request - validated page window and optional inclusive cut.
2063
+ * @returns a chronological page at the requested cut.
2064
+ */
2065
+ function history(observation, request) {
2066
+ const cursor = request.throughSeq === void 0 ? observation.cursor : request.throughSeq === -1 ? -1 : SessionSeq(request.throughSeq);
2067
+ if (cursor > observation.cursor) throw new RemoteError("gateway/bad-request", `session history cut ${String(cursor)} exceeds ${String(observation.cursor)}`, {});
2068
+ const page = paginate(observation.events, request.beforeSeq === void 0 ? void 0 : SessionLogOffset(request.beforeSeq), request.maxMessages, cursor, request.turnWindow);
2069
+ return {
2070
+ cursor,
2071
+ records: pageRecords(page.events),
2072
+ hasMore: page.hasMore
2073
+ };
2074
+ }
2075
+ /**
2076
+ * Convert the projection baseline without acquiring or retaining its observation.
2077
+ * @param observation - projected read cut owned by the caller.
2078
+ * @returns the exact baseline; missing projection support fails explicitly.
2079
+ */
2080
+ function projections(observation) {
2081
+ const snapshot = observation.projections;
2082
+ if (snapshot === void 0) throw new RemoteError("session/projections-unavailable", "Session projections are unavailable", {});
2083
+ return {
2084
+ asOfSeq: snapshot.asOfSeq,
2085
+ values: snapshot.values
2086
+ };
2087
+ }
2088
+ /**
2089
+ * Validate and resolve the history page window.
2090
+ * @param request - external history window.
2091
+ * @returns the validated request with an explicit message budget.
2092
+ */
2093
+ function resolveHistoryRequest(request) {
2094
+ if (request.throughSeq !== void 0 && (!Number.isSafeInteger(request.throughSeq) || request.throughSeq < -1 || Object.is(request.throughSeq, -0))) throw new RemoteError("gateway/bad-request", "throughSeq must be an integer greater than or equal to -1", {});
2095
+ if (request.beforeSeq !== void 0 && (!Number.isSafeInteger(request.beforeSeq) || request.beforeSeq < 0 || Object.is(request.beforeSeq, -0))) throw new RemoteError("gateway/bad-request", "beforeSeq must be a non-negative safe integer", {});
2096
+ validateHistoryWindow(request);
2097
+ return {
2098
+ ...request,
2099
+ maxMessages: request.maxMessages ?? 50
2100
+ };
2101
+ }
2102
+ //#endregion
2103
+ //#region lib/types/state/listener.js
2104
+ /** Coalesced Session state observations with Host-local revisions. */
2105
+ /** Coalesces Session/Agent invalidations with local revisions; pending events are sampled on reads. */
2106
+ var StateListener = class {
2107
+ readState;
2108
+ disposes = [];
2109
+ cancellation = new AbortController();
2110
+ signal;
2111
+ revision = 0;
2112
+ resolver = createDeferredSignal();
2113
+ closed = false;
2114
+ /**
2115
+ * @param ctx - lifecycle notification owner.
2116
+ * @param target - Session to observe.
2117
+ * @param signal - caller cancellation.
2118
+ * @param readState - passive complete-state reader.
2119
+ */
2120
+ constructor(ctx, target, signal, readState) {
2121
+ this.readState = readState;
2122
+ signal.throwIfAborted();
2123
+ this.signal = AbortSignal.any([signal, this.cancellation.signal]);
2124
+ const notify = (id) => {
2125
+ if (id !== target || this.closed) return;
2126
+ this.revision++;
2127
+ const resolver = this.resolver;
2128
+ this.resolver = createDeferredSignal();
2129
+ resolver.resolve();
2130
+ };
2131
+ const close = () => {
2132
+ this[Symbol.dispose]();
2133
+ };
2134
+ signal.addEventListener("abort", close, { once: true });
2135
+ this.disposes.push(() => {
2136
+ signal.removeEventListener("abort", close);
2137
+ });
2138
+ try {
2139
+ this.disposes.push(ctx.on("session/event", (session) => {
2140
+ notify(session.id);
2141
+ }, { global: true }));
2142
+ this.disposes.push(ctx.on("session/created", (session) => {
2143
+ notify(session.id);
2144
+ }, { global: true }));
2145
+ this.disposes.push(ctx.on("session/disposed", (session) => {
2146
+ notify(session.id);
2147
+ }, { global: true }));
2148
+ this.disposes.push(ctx.on("agent/status", ({ agent }) => {
2149
+ notify(agent.id);
2150
+ }, { global: true }));
2151
+ this.disposes.push(ctx.on("agent/created", ({ agent }) => {
2152
+ notify(agent.id);
2153
+ }, { global: true }));
2154
+ this.disposes.push(ctx.on("agent/disposed", ({ agent }) => {
2155
+ notify(agent.id);
2156
+ }, { global: true }));
2157
+ const dispose = ctx.effect(() => close, "session-controller.state-listener");
2158
+ this.disposes.push(() => {
2159
+ dispose();
2160
+ });
2161
+ } catch (error) {
2162
+ this[Symbol.dispose]();
2163
+ throw error;
2164
+ }
2165
+ }
2166
+ /**
2167
+ * Check whether a completed read still represents the latest invalidation.
2168
+ * @param revision - revision captured with a completed read.
2169
+ * @returns whether no intervening invalidation occurred.
2170
+ */
2171
+ isCurrent(revision) {
2172
+ return !this.closed && revision === this.revision;
2173
+ }
2174
+ /**
2175
+ * Read coalesced state replacements with optional periodic refresh.
2176
+ * @param refreshMs - optional idle recheck interval; omitted for event-only observation.
2177
+ * @returns complete state replacements with internal consistency revisions.
2178
+ */
2179
+ async *observeStates(refreshMs) {
2180
+ let lastRevision = -1;
2181
+ try {
2182
+ while (!this.closed) {
2183
+ if (lastRevision === this.revision) if (refreshMs === void 0) await this.resolver.promise;
2184
+ else {
2185
+ let timer;
2186
+ try {
2187
+ await Promise.race([this.resolver.promise, new Promise((resolve) => {
2188
+ timer = setTimeout(resolve, refreshMs);
2189
+ })]);
2190
+ } finally {
2191
+ clearTimeout(timer);
2192
+ }
2193
+ if (this.isCurrent(lastRevision)) {
2194
+ this.revision++;
2195
+ const resolver = this.resolver;
2196
+ this.resolver = createDeferredSignal();
2197
+ resolver.resolve();
2198
+ }
2199
+ }
2200
+ if (!this.isCurrent(this.revision)) return;
2201
+ lastRevision = this.revision;
2202
+ const state = await this.readState(this.signal);
2203
+ if (this.isCurrent(lastRevision)) yield {
2204
+ state,
2205
+ revision: lastRevision
2206
+ };
2207
+ }
2208
+ } finally {
2209
+ this[Symbol.dispose]();
2210
+ }
2211
+ }
2212
+ [Symbol.dispose]() {
2213
+ if (this.closed) return;
2214
+ this.closed = true;
2215
+ this.cancellation.abort();
2216
+ this.resolver.resolve();
2217
+ for (const dispose of this.disposes.splice(0).reverse()) dispose();
2218
+ }
2219
+ };
2220
+ function createDeferredSignal() {
2221
+ let resolve;
2222
+ return {
2223
+ promise: new Promise((settle) => {
2224
+ resolve = settle;
2225
+ }),
2226
+ resolve
2227
+ };
2228
+ }
2229
+ //#endregion
2230
+ //#region lib/types/state/controller.js
2231
+ /** Passive Session state, coalesced observations and quiescence waits. */
2232
+ var __addDisposableResource$3 = function(env, value, async) {
2233
+ if (value !== null && value !== void 0) {
2234
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
2235
+ var dispose, inner;
2236
+ if (async) {
2237
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
2238
+ dispose = value[Symbol.asyncDispose];
2239
+ }
2240
+ if (dispose === void 0) {
2241
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
2242
+ dispose = value[Symbol.dispose];
2243
+ if (async) inner = dispose;
2244
+ }
2245
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
2246
+ if (inner) dispose = function() {
2247
+ try {
2248
+ inner.call(this);
2249
+ } catch (e) {
2250
+ return Promise.reject(e);
2251
+ }
2252
+ };
2253
+ env.stack.push({
2254
+ value,
2255
+ dispose,
2256
+ async
2257
+ });
2258
+ } else if (async) env.stack.push({ async: true });
2259
+ return value;
2260
+ };
2261
+ var __disposeResources$3 = (function(SuppressedError) {
2262
+ return function(env) {
2263
+ function fail(e) {
2264
+ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
2265
+ env.hasError = true;
2266
+ }
2267
+ var r, s = 0;
2268
+ function next() {
2269
+ while (r = env.stack.pop()) try {
2270
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
2271
+ if (r.dispose) {
2272
+ var result = r.dispose.call(r.value);
2273
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
2274
+ fail(e);
2275
+ return next();
2276
+ });
2277
+ } else s |= 1;
2278
+ } catch (e) {
2279
+ fail(e);
2280
+ }
2281
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
2282
+ if (env.hasError) throw env.error;
2283
+ }
2284
+ return next();
2285
+ };
2286
+ })(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
2287
+ var e = new Error(message);
2288
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
2289
+ });
2290
+ const DEFAULT_WAIT_TIMEOUT_MS = 3e4;
2291
+ /** Reads and waits without activating or cancelling Session execution. */
2292
+ var StateController = class {
2293
+ ctx;
2294
+ historyController;
2295
+ /**
2296
+ * @param ctx - live Session and pending Remote event services.
2297
+ * @param historyController - passive read entry used for cold state and its bounded output.
2298
+ */
2299
+ constructor(ctx, historyController) {
2300
+ this.ctx = ctx;
2301
+ this.historyController = historyController;
2302
+ }
2303
+ /**
2304
+ * Read passive execution and pending-input state.
2305
+ * @param request - Session identity.
2306
+ * @param signal - read cancellation.
2307
+ * @returns current passive state.
2308
+ */
2309
+ async state(request, signal) {
2310
+ return this.readState(request.sessionId, signal);
2311
+ }
2312
+ /**
2313
+ * Observe complete passive state replacements.
2314
+ * @param request - Session identity.
2315
+ * @param signal - observation cancellation.
2316
+ * @returns complete state replacements, starting with the current state.
2317
+ */
2318
+ async *observeState(request, signal) {
2319
+ const env_1 = {
2320
+ stack: [],
2321
+ error: void 0,
2322
+ hasError: false
2323
+ };
2324
+ try {
2325
+ const listener = __addDisposableResource$3(env_1, this.listen(request.sessionId, signal), false);
2326
+ for await (const { state } of listener.observeStates()) yield state;
2327
+ } catch (e_1) {
2328
+ env_1.error = e_1;
2329
+ env_1.hasError = true;
2330
+ } finally {
2331
+ __disposeResources$3(env_1);
2332
+ }
2333
+ }
2334
+ /**
2335
+ * Wait for quiescence, pending input, or the deadline without cancelling execution.
2336
+ * @param request - Session identity, timeout and assistant output window.
2337
+ * @param signal - cancellation of this wait only, never of Agent execution.
2338
+ * @returns the stopping reason and last complete state; no state before timeout is an error.
2339
+ */
2340
+ async wait(request, signal) {
2341
+ const env_2 = {
2342
+ stack: [],
2343
+ error: void 0,
2344
+ hasError: false
2345
+ };
2346
+ try {
2347
+ const timeoutMs = request.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS;
2348
+ const afterSeq = request.afterSeq ?? -1;
2349
+ const maxMessages = request.maxMessages ?? 50;
2350
+ if (!Number.isSafeInteger(afterSeq) || afterSeq < -1 || Object.is(afterSeq, -0)) throw new RemoteError("gateway/bad-request", "afterSeq must be an integer greater than or equal to -1", {});
2351
+ if (!Number.isSafeInteger(maxMessages) || maxMessages <= 0) throw new RemoteError("gateway/bad-request", "maxMessages must be a positive safe integer", {});
2352
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > MAX_TIMER_DELAY_MS) throw new RemoteError("gateway/bad-request", "timeoutMs must be a positive supported timer delay", {});
2353
+ const timer = __addDisposableResource$3(env_2, deadline(signal, timeoutMs, "session/wait-timeout"), false);
2354
+ const listener = __addDisposableResource$3(env_2, this.listen(request.sessionId, timer.signal), false);
2355
+ const sessionId = request.sessionId;
2356
+ const statesGenerator = listener.observeStates(1e3);
2357
+ let nextStatePromise = statesGenerator.next();
2358
+ let currentState;
2359
+ let reason = "timeout";
2360
+ try {
2361
+ for (;;) {
2362
+ const observedState = await nextStatePromise;
2363
+ if (observedState.done) {
2364
+ timer.signal.throwIfAborted();
2365
+ throw new RemoteError("session/observation-ended", "Session observation ended before a stopping state", {});
2366
+ }
2367
+ nextStatePromise = statesGenerator.next();
2368
+ nextStatePromise.catch(() => void 0);
2369
+ if (!listener.isCurrent(observedState.value.revision)) continue;
2370
+ currentState = observedState.value.state;
2371
+ const action = computeWaitAction(currentState);
2372
+ if (action === "continue") continue;
2373
+ if (action === "input-required" || action === "idle") {
2374
+ reason = action;
2375
+ break;
2376
+ }
2377
+ const agent = this.ctx.agents.get(sessionId);
2378
+ if (agent === void 0 || this.ctx.sessions.get(sessionId) !== agent.session) continue;
2379
+ if (await waitForIdleOrStateChange(agent, nextStatePromise) === "state-changed") continue;
2380
+ if (!listener.isCurrent(observedState.value.revision) || this.ctx.agents.get(sessionId) !== agent || this.ctx.sessions.get(sessionId) !== agent.session) continue;
2381
+ reason = "idle";
2382
+ break;
2383
+ }
2384
+ } catch (error) {
2385
+ if (signal.aborted) throw signal.reason;
2386
+ if (!expired(timer.signal, error)) throw error;
2387
+ } finally {
2388
+ listener[Symbol.dispose]();
2389
+ await nextStatePromise.catch(() => void 0);
2390
+ await statesGenerator.return(void 0);
2391
+ }
2392
+ signal.throwIfAborted();
2393
+ if (currentState === void 0) throw new RemoteError("session/wait-timeout", "No Session state arrived before the wait deadline", {});
2394
+ const output = await this.historyController.assistantOutput(sessionId, afterSeq, currentState.cursor, maxMessages, signal);
2395
+ return {
2396
+ reason,
2397
+ state: currentState,
2398
+ output
2399
+ };
2400
+ } catch (e_2) {
2401
+ env_2.error = e_2;
2402
+ env_2.hasError = true;
2403
+ } finally {
2404
+ __disposeResources$3(env_2);
2405
+ }
2406
+ }
2407
+ listen(sessionId, signal) {
2408
+ return new StateListener(this.ctx, sessionId, signal, (readSignal) => this.readState(sessionId, readSignal));
2409
+ }
2410
+ /**
2411
+ * @param sessionId - Session to sample.
2412
+ * @param signal - read cancellation.
2413
+ * @param retried - whether a live source already redirected this read once.
2414
+ * @returns one passive state sample.
2415
+ */
2416
+ async readState(sessionId, signal, retried = false) {
2417
+ signal.throwIfAborted();
2418
+ const agent = this.ctx.agents.get(sessionId);
2419
+ if (agent !== void 0) {
2420
+ if (agent.session.header.cwd === void 0) rejectNotFound({
2421
+ kind: "session",
2422
+ sessionId
2423
+ });
2424
+ return {
2425
+ cursor: agent.session.seq - 1,
2426
+ active: true,
2427
+ running: agent.status === "running",
2428
+ queue: queueItems(agent),
2429
+ pendingInput: this.pendingInput(agent.session.id)
2430
+ };
2431
+ }
2432
+ const state = await this.historyController.usingObservation({
2433
+ sessionId,
2434
+ projection: false
2435
+ }, signal, (observation) => {
2436
+ if (!retried && observation.source === "live") return void 0;
2437
+ if (observation.header.cwd === void 0) rejectNotFound({
2438
+ kind: "session",
2439
+ sessionId
2440
+ });
2441
+ return {
2442
+ cursor: observation.cursor,
2443
+ active: false,
2444
+ running: false,
2445
+ queue: null,
2446
+ pendingInput: this.pendingInput(observation.header.id)
2447
+ };
2448
+ });
2449
+ signal.throwIfAborted();
2450
+ return state ?? this.readState(sessionId, signal, true);
2451
+ }
2452
+ pendingInput(sessionId) {
2453
+ const kinds = /* @__PURE__ */ new Set();
2454
+ for (const { event, agentId } of this.ctx.typertGateway.getPendingRemoteEvents()) {
2455
+ if (String(agentId) !== sessionId) continue;
2456
+ kinds.add(event === "approval/request" ? "approval" : event === "user-questions/request" ? "question" : "other");
2457
+ }
2458
+ return [...kinds];
2459
+ }
2460
+ };
2461
+ /**
2462
+ * @param signal - wait deadline signal.
2463
+ * @param error - failure raised by the in-flight read.
2464
+ * @returns whether the deadline expired and cancelled that read.
2465
+ */
2466
+ function expired(signal, error) {
2467
+ const reason = timeoutOf(signal, "session/wait-timeout");
2468
+ if (reason === void 0) return false;
2469
+ let current = error;
2470
+ for (let depth = 0; depth < 4 && current instanceof Error; depth++) {
2471
+ if (current === reason || current.cause === reason) return true;
2472
+ current = current.cause;
2473
+ }
2474
+ return error === reason;
2475
+ }
2476
+ /** Choose the next wait action; check-idle requires the caller's whenIdle and identity checks. */
2477
+ function computeWaitAction(state) {
2478
+ if (state.pendingInput.length > 0) return "input-required";
2479
+ if (state.running) return "continue";
2480
+ if (!state.active) return "idle";
2481
+ return "check-idle";
2482
+ }
2483
+ /** Wait for either driver quiescence or the already-armed next state; preserve rejections from both. */
2484
+ function waitForIdleOrStateChange(agent, nextStatePromise) {
2485
+ return Promise.race([agent.whenIdle().then(() => "idle"), nextStatePromise.then(() => "state-changed")]);
2486
+ }
2487
+ function queueItems(agent) {
2488
+ const item = (message, placement) => ({
2489
+ id: message.id,
2490
+ placement,
2491
+ ...message.source.kind === "user" && "rpcId" in message.source ? { rpcId: message.source.rpcId } : {},
2492
+ content: message.content
2493
+ });
2494
+ return [...agent.inbox.nextTurn.map((message) => item(message, "queued")), ...agent.inbox.nextStep.map((message) => item(message, message.source.kind === "user" ? "steering" : "context"))];
2495
+ }
2496
+ //#endregion
2497
+ //#region lib/types/web/controller.js
2498
+ /** Web opening aggregation over one observation and a shared transforming buffer. */
2499
+ var __addDisposableResource$2 = function(env, value, async) {
2500
+ if (value !== null && value !== void 0) {
2501
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
2502
+ var dispose, inner;
2503
+ if (async) {
2504
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
2505
+ dispose = value[Symbol.asyncDispose];
2506
+ }
2507
+ if (dispose === void 0) {
2508
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
2509
+ dispose = value[Symbol.dispose];
2510
+ if (async) inner = dispose;
2511
+ }
2512
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
2513
+ if (inner) dispose = function() {
2514
+ try {
2515
+ inner.call(this);
2516
+ } catch (e) {
2517
+ return Promise.reject(e);
2518
+ }
2519
+ };
2520
+ env.stack.push({
2521
+ value,
2522
+ dispose,
2523
+ async
2524
+ });
2525
+ } else if (async) env.stack.push({ async: true });
2526
+ return value;
2527
+ };
2528
+ var __disposeResources$2 = (function(SuppressedError) {
2529
+ return function(env) {
2530
+ function fail(e) {
2531
+ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
2532
+ env.hasError = true;
2533
+ }
2534
+ var r, s = 0;
2535
+ function next() {
2536
+ while (r = env.stack.pop()) try {
2537
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
2538
+ if (r.dispose) {
2539
+ var result = r.dispose.call(r.value);
2540
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
2541
+ fail(e);
2542
+ return next();
2543
+ });
2544
+ } else s |= 1;
2545
+ } catch (e) {
2546
+ fail(e);
2547
+ }
2548
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
2549
+ if (env.hasError) throw env.error;
2550
+ }
2551
+ return next();
2552
+ };
2553
+ })(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
2554
+ var e = new Error(message);
2555
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
2556
+ });
2557
+ /** Combines opening data and consumes transformed listener output from one queue. */
2558
+ var WebController = class {
2559
+ ctx;
2560
+ historyController;
2561
+ promote;
2562
+ /**
2563
+ * @param ctx - Host context carrying Session queries and identity projections.
2564
+ * @param historyController - passive reading and listener construction.
2565
+ * @param promote - background activation requested before an opening snapshot is delivered.
2566
+ */
2567
+ constructor(ctx, historyController, promote) {
2568
+ this.ctx = ctx;
2569
+ this.historyController = historyController;
2570
+ this.promote = promote;
2571
+ }
2572
+ /**
2573
+ * Open a history snapshot and follow uncovered history and assistant notifications.
2574
+ * @param request - Session identity, page budget, assistant output and optional activation (default false).
2575
+ * @param signal - cancellation for opening and streaming.
2576
+ * @returns an opening snapshot followed by uncovered queued increments.
2577
+ */
2578
+ async *follow(request, signal) {
2579
+ const env_1 = {
2580
+ stack: [],
2581
+ error: void 0,
2582
+ hasError: false
2583
+ };
2584
+ try {
2585
+ const sessionId = addressId(request.address);
2586
+ const spec = resolveHistoryRequest(request);
2587
+ const queue = __addDisposableResource$2(env_1, new ListenerBuffer(this.ctx, signal), false);
2588
+ const listener = __addDisposableResource$2(env_1, new EventListener(this.ctx, sessionId, signal, queue), false);
2589
+ const streams = this.historyController.streamsListener;
2590
+ const assistantListener = __addDisposableResource$2(env_1, request.assistantStream === true ? streams.bind(sessionId, signal, queue) : void 0, false);
2591
+ const observation = __addDisposableResource$2(env_1, await this.historyController.usingObservation({
2592
+ sessionId,
2593
+ projection: true
2594
+ }, signal).catch((error) => {
2595
+ if (remoteErrorOf(error)?.code === "session/not-found") rejectNotFound(request.address);
2596
+ throw error;
2597
+ }), false);
2598
+ validateObservationAddress(request.address, observation);
2599
+ let opening = {
2600
+ type: "snapshot",
2601
+ header: { ...observation.header },
2602
+ projections: projections(observation),
2603
+ ...history(observation, spec)
2604
+ };
2605
+ listener.setCursor(opening.cursor);
2606
+ if (assistantListener !== void 0) {
2607
+ const { baseline: assistantStream, ordinal } = assistantListener.snapshot();
2608
+ opening = {
2609
+ ...opening,
2610
+ assistantStream
2611
+ };
2612
+ assistantListener.setOrdinalCut(ordinal);
2613
+ }
2614
+ if (request.activate === true && !signal.aborted && observation.header.origin !== "subagent" && observation.source === "prepared") {
2615
+ const promotion = observation.retain();
2616
+ observation[Symbol.dispose]();
2617
+ try {
2618
+ this.promote(promotion);
2619
+ } catch (error) {
2620
+ promotion[Symbol.dispose]();
2621
+ throw error;
2622
+ }
2623
+ } else observation[Symbol.dispose]();
2624
+ yield opening;
2625
+ yield* queue.items();
2626
+ } catch (e_1) {
2627
+ env_1.error = e_1;
2628
+ env_1.hasError = true;
2629
+ } finally {
2630
+ __disposeResources$2(env_1);
2631
+ }
2632
+ }
2633
+ };
2634
+ //#endregion
2635
+ //#region lib/types/file-references.js
2636
+ /** Session Controller adapter for Agent-scoped file-reference discovery. */
2637
+ var __runInitializers$2 = function(thisArg, initializers, value) {
2638
+ var useValue = arguments.length > 2;
2639
+ for (var i = 0; i < initializers.length; i++) value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
2640
+ return useValue ? value : void 0;
2641
+ };
2642
+ var __esDecorate$2 = function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
2643
+ function accept(f) {
2644
+ if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
2645
+ return f;
2646
+ }
2647
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
2648
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
2649
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
2650
+ var _, done = false;
2651
+ for (var i = decorators.length - 1; i >= 0; i--) {
2652
+ var context = {};
2653
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
2654
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
2655
+ context.addInitializer = function(f) {
2656
+ if (done) throw new TypeError("Cannot add initializers after decoration has completed");
2657
+ extraInitializers.push(accept(f || null));
2658
+ };
2659
+ var result = (0, decorators[i])(kind === "accessor" ? {
2660
+ get: descriptor.get,
2661
+ set: descriptor.set
2662
+ } : descriptor[key], context);
2663
+ if (kind === "accessor") {
2664
+ if (result === void 0) continue;
2665
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
2666
+ if (_ = accept(result.get)) descriptor.get = _;
2667
+ if (_ = accept(result.set)) descriptor.set = _;
2668
+ if (_ = accept(result.init)) initializers.unshift(_);
2669
+ } else if (_ = accept(result)) if (kind === "field") initializers.unshift(_);
2670
+ else descriptor[key] = _;
2671
+ }
2672
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
2673
+ done = true;
2674
+ };
2675
+ /** Host Remote adapter over the composed file-reference provider. */
2676
+ let SessionFileReferences = (() => {
2677
+ let _classSuper = TypertRemoteService;
2678
+ let _instanceExtraInitializers = [];
2679
+ let _list_decorators;
2680
+ return class SessionFileReferences extends _classSuper {
2681
+ static {
2682
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
2683
+ _list_decorators = [Remote];
2684
+ __esDecorate$2(this, null, _list_decorators, {
2685
+ kind: "method",
2686
+ name: "list",
2687
+ static: false,
2688
+ private: false,
2689
+ access: {
2690
+ has: (obj) => "list" in obj,
2691
+ get: (obj) => obj.list
2692
+ },
2693
+ metadata: _metadata
2694
+ }, null, _instanceExtraInitializers);
2695
+ if (_metadata) Object.defineProperty(this, Symbol.metadata, {
2696
+ enumerable: true,
2697
+ configurable: true,
2698
+ writable: true,
2699
+ value: _metadata
2700
+ });
2701
+ }
2702
+ static inject = ["fileReferences", "typert"];
2703
+ /** @param ctx - Host context carrying the selected file-reference provider. */
2704
+ constructor(ctx) {
2705
+ super(ctx, "sessionFileReferences", { namespace: "fileReferences" });
2706
+ __runInitializers$2(this, _instanceExtraInitializers);
2707
+ }
2708
+ /**
2709
+ * List file and directory candidates for one Agent's working directory.
2710
+ * @param agent - target Agent resolved from the Session identity on the wire.
2711
+ * @param query - path text following `@` or `@"`.
2712
+ * @param signal - caller cancellation.
2713
+ * @returns deterministic path-only candidates from the composed provider.
2714
+ */
2715
+ list(agent, query, signal) {
2716
+ return this.ctx.fileReferences.list(agent, query, signal);
2717
+ }
2718
+ };
2719
+ })();
2720
+ //#endregion
2721
+ //#region lib/types/list.js
2722
+ /** Cold-safe Session list and search projection. */
2723
+ const SEARCH_PROVIDER_CALL_LIMIT = 100;
2724
+ const SESSION_SEARCH_QUERY_MAX_CHARS = 500;
2725
+ const MESSAGE_TYPES = new Set(["user/message", "assistant/message"]);
2726
+ const sessionListMetadataSchema = z$1.object({
2727
+ blank: z$1.boolean(),
2728
+ lastPromptAt: z$1.number().nullable()
2729
+ });
2730
+ const imageLimitsSchema = z$1.object({
2731
+ maxImageBytes: z$1.number().int().positive(),
2732
+ maxImagesPerMessage: z$1.number().int().positive(),
2733
+ maxMessageImageBytes: z$1.number().int().positive(),
2734
+ maxImagePixels: z$1.number().int().positive(),
2735
+ maxImageDimension: z$1.number().int().positive(),
2736
+ mediaTypes: z$1.array(z$1.string())
2737
+ });
2738
+ /**
2739
+ * Advance the Session-list metadata projection by one committed event.
2740
+ * @param state - metadata before the event.
2741
+ * @param event - next committed Session event.
2742
+ * @returns the original or advanced metadata value.
2743
+ */
2744
+ function applySessionListMetadata(state, event) {
2745
+ const blank = state.blank && event.type !== "turn/start";
2746
+ const lastPromptAt = event.type === "user/message" && event.data.source.kind === "user" ? event.time : state.lastPromptAt;
2747
+ return blank === state.blank && lastPromptAt === state.lastPromptAt ? state : {
2748
+ blank,
2749
+ lastPromptAt
2750
+ };
2751
+ }
2752
+ /**
2753
+ * Return the longest prefix containing at most `maximum` Unicode code points.
2754
+ * @param value - source text.
2755
+ * @param maximum - maximum number of Unicode code points.
2756
+ * @returns the source text or its longest allowed prefix.
2757
+ */
2758
+ function truncateUnicodeCodePoints(value, maximum) {
2759
+ let count = 0;
2760
+ let end = 0;
2761
+ for (const codePoint of value) {
2762
+ if (count === maximum) return value.slice(0, end);
2763
+ count++;
2764
+ end += codePoint.length;
2765
+ }
2766
+ return value;
2767
+ }
2768
+ /** Owns list projection registration, bounded cold summaries, and authorized search. */
2769
+ var ApiSessionList = class {
2770
+ ctx;
2771
+ workSliceMs;
2772
+ listMetadata;
2773
+ /**
2774
+ * @param ctx - Host context carrying Session, query, persistence, and projection services.
2775
+ * @param workSliceMs - Resolved positive integral list-work budget in milliseconds.
2776
+ */
2777
+ constructor(ctx, workSliceMs) {
2778
+ this.ctx = ctx;
2779
+ this.workSliceMs = workSliceMs;
2780
+ }
2781
+ /**
2782
+ * Acquire projection readers before exposing dependent operations.
2783
+ * @returns when all required registrations are ready.
2784
+ */
2785
+ async initialize() {
2786
+ this.listMetadata = await this.ctx.sessionProjections.register({
2787
+ key: "sessionListMetadata",
2788
+ stateSchema: sessionListMetadataSchema,
2789
+ init: () => ({
2790
+ blank: true,
2791
+ lastPromptAt: null
2792
+ }),
2793
+ apply: applySessionListMetadata,
2794
+ wire: {
2795
+ viewSchema: sessionListMetadataSchema,
2796
+ view: (state) => state
2797
+ },
2798
+ stateVersion: 1
2799
+ });
2800
+ await this.ctx.sessionProjections.register({
2801
+ key: "imageLimits",
2802
+ stateSchema: z$1.null(),
2803
+ init: () => null,
2804
+ apply: (state) => state,
2805
+ wire: {
2806
+ viewSchema: imageLimitsSchema,
2807
+ view: () => this.ctx.attachments.imageLimits,
2808
+ summary: false
2809
+ },
2810
+ stateVersion: 1
2811
+ });
2812
+ }
2813
+ /**
2814
+ * Build one current attached-Session summary.
2815
+ * Blankness and recency come from the `sessionListMetadata` handle; projection
2816
+ * hints carry every summary key computed through `snapshot`. The first call
2817
+ * for a Session computes these projections over its whole in-memory log, and
2818
+ * later calls advance them incrementally. The handle read and the hint with
2819
+ * the same key come from one cell; the handle read does not depend on any
2820
+ * other unit's view.
2821
+ * @param session - attached Session to summarize.
2822
+ * @returns current list metadata and available projections.
2823
+ */
2824
+ summaryFor(session) {
2825
+ const metadata = this.listMetadata.stateOf(session);
2826
+ const projections = this.projectionsFor(session.header, session);
2827
+ return {
2828
+ sessionId: session.id,
2829
+ updatedAt: updatedAt(session.header, metadata),
2830
+ agentAvailable: this.ctx.agents.get(session.id)?.session === session,
2831
+ formatStatus: "current",
2832
+ running: this.ctx.agents.get(session.id)?.status === "running",
2833
+ blank: metadata.blank,
2834
+ ...listFields(session.header),
2835
+ ...projections === void 0 ? {} : { projections }
2836
+ };
2837
+ }
2838
+ /**
2839
+ * Read every visible attached and persisted Session without activating an Agent.
2840
+ * @param signal - optional cancellation for persistence reads and summary generation.
2841
+ * @returns visible Session summaries ordered by activity.
2842
+ */
2843
+ async list(signal) {
2844
+ signal?.throwIfAborted();
2845
+ const records = await this.ctx.sessionQuery.listSessions(signal);
2846
+ signal?.throwIfAborted();
2847
+ const items = [];
2848
+ const cold = [];
2849
+ let yieldDeadline = performance.now() + this.workSliceMs;
2850
+ for (const record of records) {
2851
+ signal?.throwIfAborted();
2852
+ const live = this.ctx.sessions.get(record.header.id);
2853
+ if (live !== void 0) items.push(this.summaryFor(live));
2854
+ else if (record.header.cwd !== void 0) cold.push(record);
2855
+ if (performance.now() >= yieldDeadline) {
2856
+ await scheduler.yield();
2857
+ signal?.throwIfAborted();
2858
+ yieldDeadline = performance.now() + this.workSliceMs;
2859
+ }
2860
+ }
2861
+ for (const record of cold) {
2862
+ signal?.throwIfAborted();
2863
+ items.push(this.summarizeCold(record));
2864
+ if (performance.now() >= yieldDeadline) {
2865
+ await scheduler.yield();
2866
+ signal?.throwIfAborted();
2867
+ yieldDeadline = performance.now() + this.workSliceMs;
2868
+ }
2869
+ }
2870
+ signal?.throwIfAborted();
2871
+ items.sort((left, right) => right.updatedAt - left.updatedAt);
2872
+ return items;
2873
+ }
2874
+ summarizeCold({ header, formatStatus }) {
2875
+ const projections = this.projectionsFor(header, void 0);
2876
+ const metadata = projections?.values.sessionListMetadata;
2877
+ return {
2878
+ sessionId: header.id,
2879
+ updatedAt: updatedAt(header, metadata),
2880
+ agentAvailable: false,
2881
+ ...formatStatus === void 0 ? {} : { formatStatus },
2882
+ running: false,
2883
+ blank: metadata?.blank ?? false,
2884
+ ...listFields(header),
2885
+ ...projections === void 0 ? {} : { projections }
2886
+ };
2887
+ }
2888
+ /**
2889
+ * Search current visible message content without activating any matching Session.
2890
+ * @param query - literal message-content query.
2891
+ * @param signal - cancellation for list and search reads.
2892
+ * @returns authorized bounded Session search results.
2893
+ */
2894
+ async search(query, signal) {
2895
+ const normalizedQuery = normalizeSearchQuery(query);
2896
+ signal.throwIfAborted();
2897
+ const provider = this.ctx.get("sessionQuery");
2898
+ if (provider === void 0) throw new RemoteError("gateway/internal", "session search is unavailable: this deployment does not mount @unieai/rabi-session-query", {});
2899
+ try {
2900
+ const visible = await provider.listSessions(signal);
2901
+ signal.throwIfAborted();
2902
+ const visibleIds = new Set(visible.filter((record) => record.header.cwd !== void 0).map((record) => record.header.id));
2903
+ if (visibleIds.size === 0) return {
2904
+ items: [],
2905
+ hasMore: false
2906
+ };
2907
+ const authorized = [];
2908
+ const acceptedIds = /* @__PURE__ */ new Set();
2909
+ const seenCursors = /* @__PURE__ */ new Set();
2910
+ let cursor;
2911
+ let providerCalls = 0;
2912
+ let pageLimit = 20;
2913
+ while (authorized.length <= 20) {
2914
+ signal.throwIfAborted();
2915
+ if (providerCalls >= SEARCH_PROVIDER_CALL_LIMIT) throw new Error(`session search provider exceeded the ${SEARCH_PROVIDER_CALL_LIMIT}-call work budget`);
2916
+ providerCalls++;
2917
+ const requestedCursor = cursor;
2918
+ const requestedLimit = pageLimit;
2919
+ let page;
2920
+ try {
2921
+ page = await provider.searchSessions({
2922
+ query: normalizedQuery,
2923
+ eventFilters: [{
2924
+ kind: "type",
2925
+ values: ["user/message", "assistant/message"]
2926
+ }, {
2927
+ kind: "surface",
2928
+ values: ["current"]
2929
+ }],
2930
+ limit: requestedLimit,
2931
+ ...requestedCursor === void 0 ? {} : { cursor: requestedCursor }
2932
+ }, { signal });
2933
+ signal.throwIfAborted();
2934
+ } catch (error) {
2935
+ signal.throwIfAborted();
2936
+ if (requestedCursor === void 0 && error instanceof SessionQueryError && error.code === "SESSION_QUERY_INVALID_LIMIT" && requestedLimit > 1) {
2937
+ pageLimit = Math.max(1, Math.floor(requestedLimit / 2));
2938
+ continue;
2939
+ }
2940
+ if (requestedCursor !== void 0 && error instanceof SessionQueryError && error.code === "SESSION_QUERY_STALE_CURSOR") {
2941
+ authorized.length = 0;
2942
+ acceptedIds.clear();
2943
+ seenCursors.clear();
2944
+ cursor = void 0;
2945
+ continue;
2946
+ }
2947
+ throw error;
2948
+ }
2949
+ if (page.items.length > requestedLimit) throw new Error(`session search provider returned ${String(page.items.length)} items; maximum is ${String(requestedLimit)}`);
2950
+ for (const hit of page.items) {
2951
+ if (authorized.length > 20) continue;
2952
+ if (!visibleIds.has(hit.header.id) || hit.bestMatch.sessionId !== hit.header.id || hit.bestMatch.surface !== "current" || !MESSAGE_TYPES.has(hit.bestMatch.type) || acceptedIds.has(hit.header.id)) continue;
2953
+ acceptedIds.add(hit.header.id);
2954
+ authorized.push({
2955
+ sessionId: hit.header.id,
2956
+ snippet: truncateUnicodeCodePoints(hit.bestMatch.snippet, 240)
2957
+ });
2958
+ }
2959
+ if (page.nextCursor !== void 0) {
2960
+ if (seenCursors.has(page.nextCursor)) throw new Error("session search provider repeated a continuation cursor");
2961
+ seenCursors.add(page.nextCursor);
2962
+ }
2963
+ if (authorized.length > 20 || page.nextCursor === void 0) break;
2964
+ cursor = page.nextCursor;
2965
+ }
2966
+ return {
2967
+ items: authorized.slice(0, 20),
2968
+ hasMore: authorized.length > 20
2969
+ };
2970
+ } catch (error) {
2971
+ signal.throwIfAborted();
2972
+ if (error instanceof SessionQueryError && error.code === "SESSION_QUERY_ABORTED") throw new RemoteError("gateway/cancelled", "session search was aborted", {});
2973
+ throw new RemoteError("gateway/internal", `session search failed: ${String(error)}`, {});
2974
+ }
2975
+ }
2976
+ projectionsFor(header, session) {
2977
+ try {
2978
+ const keys = this.ctx.sessionProjections.summaryKeys();
2979
+ if (session !== void 0) return hintsOf("sequenced", this.ctx.sessionProjections.snapshot(session, keys));
2980
+ const cache = this.ctx.get("sessionProjectionCache");
2981
+ return hintsOf("cached", cache?.cachedSnapshot(header, keys) ?? cache?.cachedPredecessorTitle(header));
2982
+ } catch (error) {
2983
+ this.ctx.logger.warn(`api-session.list: projection column for "${header.id}" failed; serving the row without it: ${String(error)}`);
2984
+ return;
2985
+ }
2986
+ }
2987
+ };
2988
+ /**
2989
+ * Wrap one summary projection block as Session-list hints of the named sequence space.
2990
+ * The block is the summary key set's values, not every value the source holds.
2991
+ * @param kind - which sequence space the block's watermark belongs to.
2992
+ * @param block - the block, or `undefined` when no source served one.
2993
+ * @returns the hints, or `undefined` when the block is absent or carries no value.
2994
+ */
2995
+ function hintsOf(kind, block) {
2996
+ if (block === void 0 || Object.keys(block.values).length === 0) return void 0;
2997
+ return {
2998
+ kind,
2999
+ asOfSeq: block.asOfSeq,
3000
+ values: block.values
3001
+ };
3002
+ }
3003
+ function normalizeSearchQuery(query) {
3004
+ const normalized = query.trim();
3005
+ if (normalized.length === 0) throw new RemoteError("gateway/bad-request", "session search query must not be empty", {});
3006
+ if (normalized.length > SESSION_SEARCH_QUERY_MAX_CHARS) throw new RemoteError("gateway/bad-request", `session search query must contain at most ${SESSION_SEARCH_QUERY_MAX_CHARS} UTF-16 code units`, {});
3007
+ if (normalized.includes("\0")) throw new RemoteError("gateway/bad-request", "session search query must not contain NUL", {});
3008
+ return normalized;
3009
+ }
3010
+ function updatedAt(header, metadata) {
3011
+ return Math.max(header.createdAt, metadata?.lastPromptAt ?? 0);
3012
+ }
3013
+ function listFields(header) {
3014
+ return {
3015
+ ...header.parentSession === void 0 ? {} : { parentSessionId: header.parentSession },
3016
+ ...header.origin === void 0 ? {} : { origin: header.origin },
3017
+ ...header.cwd === void 0 ? {} : { cwd: header.cwd }
3018
+ };
3019
+ }
3020
+ //#endregion
3021
+ //#region lib/types/skill-catalog.js
3022
+ /** Session-addressed, cold-readable skill catalog Remote. */
3023
+ var __runInitializers$1 = function(thisArg, initializers, value) {
3024
+ var useValue = arguments.length > 2;
3025
+ for (var i = 0; i < initializers.length; i++) value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
3026
+ return useValue ? value : void 0;
3027
+ };
3028
+ var __esDecorate$1 = function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
3029
+ function accept(f) {
3030
+ if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
3031
+ return f;
3032
+ }
3033
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
3034
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
3035
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
3036
+ var _, done = false;
3037
+ for (var i = decorators.length - 1; i >= 0; i--) {
3038
+ var context = {};
3039
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
3040
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
3041
+ context.addInitializer = function(f) {
3042
+ if (done) throw new TypeError("Cannot add initializers after decoration has completed");
3043
+ extraInitializers.push(accept(f || null));
3044
+ };
3045
+ var result = (0, decorators[i])(kind === "accessor" ? {
3046
+ get: descriptor.get,
3047
+ set: descriptor.set
3048
+ } : descriptor[key], context);
3049
+ if (kind === "accessor") {
3050
+ if (result === void 0) continue;
3051
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
3052
+ if (_ = accept(result.get)) descriptor.get = _;
3053
+ if (_ = accept(result.set)) descriptor.set = _;
3054
+ if (_ = accept(result.init)) initializers.unshift(_);
3055
+ } else if (_ = accept(result)) if (kind === "field") initializers.unshift(_);
3056
+ else descriptor[key] = _;
3057
+ }
3058
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
3059
+ done = true;
3060
+ };
3061
+ var __addDisposableResource$1 = function(env, value, async) {
3062
+ if (value !== null && value !== void 0) {
3063
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
3064
+ var dispose, inner;
3065
+ if (async) {
3066
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
3067
+ dispose = value[Symbol.asyncDispose];
3068
+ }
3069
+ if (dispose === void 0) {
3070
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
3071
+ dispose = value[Symbol.dispose];
3072
+ if (async) inner = dispose;
3073
+ }
3074
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
3075
+ if (inner) dispose = function() {
3076
+ try {
3077
+ inner.call(this);
3078
+ } catch (e) {
3079
+ return Promise.reject(e);
3080
+ }
3081
+ };
3082
+ env.stack.push({
3083
+ value,
3084
+ dispose,
3085
+ async
3086
+ });
3087
+ } else if (async) env.stack.push({ async: true });
3088
+ return value;
3089
+ };
3090
+ var __disposeResources$1 = (function(SuppressedError) {
3091
+ return function(env) {
3092
+ function fail(e) {
3093
+ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
3094
+ env.hasError = true;
3095
+ }
3096
+ var r, s = 0;
3097
+ function next() {
3098
+ while (r = env.stack.pop()) try {
3099
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
3100
+ if (r.dispose) {
3101
+ var result = r.dispose.call(r.value);
3102
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
3103
+ fail(e);
3104
+ return next();
3105
+ });
3106
+ } else s |= 1;
3107
+ } catch (e) {
3108
+ fail(e);
3109
+ }
3110
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
3111
+ if (env.hasError) throw env.error;
3112
+ }
3113
+ return next();
3114
+ };
3115
+ })(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
3116
+ var e = new Error(message);
3117
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
3118
+ });
3119
+ /** Host service backing `ctx.remote.skills` without activating a cold Agent. */
3120
+ let SessionSkillCatalog = (() => {
3121
+ let _classSuper = TypertRemoteService;
3122
+ let _instanceExtraInitializers = [];
3123
+ let _list_decorators;
3124
+ return class SessionSkillCatalog extends _classSuper {
3125
+ static {
3126
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
3127
+ _list_decorators = [Remote];
3128
+ __esDecorate$1(this, null, _list_decorators, {
3129
+ kind: "method",
3130
+ name: "list",
3131
+ static: false,
3132
+ private: false,
3133
+ access: {
3134
+ has: (obj) => "list" in obj,
3135
+ get: (obj) => obj.list
3136
+ },
3137
+ metadata: _metadata
3138
+ }, null, _instanceExtraInitializers);
3139
+ if (_metadata) Object.defineProperty(this, Symbol.metadata, {
3140
+ enumerable: true,
3141
+ configurable: true,
3142
+ writable: true,
3143
+ value: _metadata
3144
+ });
3145
+ }
3146
+ static inject = [
3147
+ "agents",
3148
+ "sessionQuery",
3149
+ "typert",
3150
+ "workingDirectory"
3151
+ ];
3152
+ /** @param ctx - Host context carrying Session reads and optional skill/preset services. */
3153
+ constructor(ctx) {
3154
+ super(ctx, "sessionSkillCatalog", { namespace: "skills" });
3155
+ __runInitializers$1(this, _instanceExtraInitializers);
3156
+ }
3157
+ /**
3158
+ * List the user-invocable skills visible to one Session composition.
3159
+ * @param request - Session identity whose cwd and preset select the catalog view.
3160
+ * @param signal - caller lifetime carried by the Remote transport; admitted catalog reads retain their existing completion semantics.
3161
+ * @returns user-invocable skill metadata without loading skill bodies.
3162
+ * @throws RemoteError when the Session cannot be inspected or no registry can serve it.
3163
+ */
3164
+ async list(request, signal) {
3165
+ const env_1 = {
3166
+ stack: [],
3167
+ error: void 0,
3168
+ hasError: false
3169
+ };
3170
+ try {
3171
+ const { sessionId } = request;
3172
+ let cwd;
3173
+ let agentPreset;
3174
+ try {
3175
+ const env_2 = {
3176
+ stack: [],
3177
+ error: void 0,
3178
+ hasError: false
3179
+ };
3180
+ try {
3181
+ const observation = __addDisposableResource$1(env_2, await this.ctx.sessionQuery.observeSession(sessionId), false);
3182
+ if (observation.projections === void 0) throw new Error("skill catalog requires a projected Session observation");
3183
+ cwd = observation.projections.values.workingDirectory ?? observation.header.cwd ?? this.ctx.workingDirectory.defaultDirectory;
3184
+ agentPreset = observation.projections.values.agentPreset ?? void 0;
3185
+ const live = this.ctx.agents.get(sessionId);
3186
+ if (live !== void 0) cwd = await this.ctx.workingDirectory.ensure(live, signal);
3187
+ } catch (e_1) {
3188
+ env_2.error = e_1;
3189
+ env_2.hasError = true;
3190
+ } finally {
3191
+ __disposeResources$1(env_2);
3192
+ }
3193
+ } catch (error) {
3194
+ if (error instanceof SessionQueryError && error.code === "SESSION_QUERY_SESSION_NOT_FOUND") throw new RemoteError("session/not-found", `session "${sessionId}" not found`, { sessionId });
3195
+ throw new RemoteError("gateway/internal", `session "${sessionId}" could not be inspected: ${String(error)}`, {});
3196
+ }
3197
+ const live = this.ctx.agents.get(sessionId);
3198
+ const presets = this.ctx.get("agentPresets");
3199
+ const skillRegistry = (live === void 0 ? void 0 : presets?.serviceFor(live, "skills")) ?? this.ctx.get("skills");
3200
+ if (skillRegistry === void 0) throw new RemoteError("gateway/internal", "skill registry is absent: neither this session's agent preset nor the host composition mounts @unieai/rabi-skill", {});
3201
+ const lease = __addDisposableResource$1(env_1, live === void 0 ? await this.scopeFor(agentPreset) : void 0, true);
3202
+ const scope = live ?? lease?.key;
3203
+ try {
3204
+ return { skills: (await skillRegistry.list({
3205
+ cwd,
3206
+ scope
3207
+ })).filter(isUserInvocable).map((skill) => ({
3208
+ name: skill.name,
3209
+ ...skill.path === void 0 ? {} : { path: skill.path },
3210
+ description: skill.description,
3211
+ ...skill.whenToUse === void 0 ? {} : { whenToUse: skill.whenToUse },
3212
+ modelInvocable: skill.invocation.modelInvocable
3213
+ })) };
3214
+ } catch (error) {
3215
+ throw new RemoteError("gateway/internal", `skill listing failed: ${String(error)}`, {});
3216
+ }
3217
+ } catch (e_2) {
3218
+ env_1.error = e_2;
3219
+ env_1.hasError = true;
3220
+ } finally {
3221
+ const result_1 = __disposeResources$1(env_1);
3222
+ if (result_1) await result_1;
3223
+ }
3224
+ }
3225
+ /** Resolve a live or standing preset scope without creating an Agent. */
3226
+ async scopeFor(agentPreset) {
3227
+ const presets = this.ctx.get("agentPresets");
3228
+ if (presets === void 0) return void 0;
3229
+ try {
3230
+ return await presets.acquireScope(agentPreset);
3231
+ } catch {
3232
+ return;
3233
+ }
3234
+ }
3235
+ };
3236
+ })();
3237
+ //#endregion
3238
+ //#region lib/types/media-references.js
3239
+ /**
3240
+ * Authenticated GET/HEAD /api/file reads bounded file responses through
3241
+ * the composed filesystem provider. Paths and MIME types do not restrict access;
3242
+ * the connection service authenticates requests before this handler. A request
3243
+ * without the current `v` version is redirected, uncached, to the versioned URL,
3244
+ * whose response is cacheable indefinitely.
3245
+ * @module @unieai/rabi-api-session-controller/media-references
3246
+ */
3247
+ const BASE_HEADERS = {
3248
+ "X-Content-Type-Options": "nosniff",
3249
+ "Content-Security-Policy": "sandbox; default-src 'none'"
3250
+ };
3251
+ const NO_STORE = {
3252
+ ...BASE_HEADERS,
3253
+ "Cache-Control": "private, no-store"
3254
+ };
3255
+ const VERSIONED = {
3256
+ ...BASE_HEADERS,
3257
+ "Cache-Control": "private, max-age=31536000, immutable"
3258
+ };
3259
+ async function serveFile(request, fs, maxBytes) {
3260
+ const fail = (status, text) => new Response(request.method === "HEAD" ? null : text, {
3261
+ status,
3262
+ headers: NO_STORE
3263
+ });
3264
+ const params = new URL(request.url).searchParams;
3265
+ const path = params.get("path");
3266
+ if (path === null || path.length === 0) return fail(400, "missing path");
3267
+ if (path.includes("\0") || !isAbsolute(path)) return fail(400, "absolute path required");
3268
+ try {
3269
+ const target = await fs.resolve(path, { signal: request.signal });
3270
+ const info = await fs.stat(target, request.signal);
3271
+ if (info === void 0) return fail(404, "not found");
3272
+ if (info.type !== "file") return fail(403, "not a regular file");
3273
+ if (info.size !== void 0 && info.size > maxBytes) return fail(413, "file exceeds byte limit");
3274
+ if (params.get("v") !== info.version) {
3275
+ const location = `?${new URLSearchParams({
3276
+ path,
3277
+ v: info.version
3278
+ }).toString()}`;
3279
+ return new Response(null, {
3280
+ status: 302,
3281
+ headers: {
3282
+ ...NO_STORE,
3283
+ Location: location
3284
+ }
3285
+ });
3286
+ }
3287
+ const headers = {
3288
+ ...VERSIONED,
3289
+ "Content-Type": mime.lookup(target.displayPath) || "application/octet-stream"
3290
+ };
3291
+ if (request.method === "HEAD") {
3292
+ if (info.size !== void 0) headers["Content-Length"] = String(info.size);
3293
+ return new Response(null, { headers });
3294
+ }
3295
+ const bytes = await fs.readBytes(target, request.signal, maxBytes);
3296
+ headers["Content-Length"] = String(bytes.byteLength);
3297
+ return new Response(bytes.slice(), { headers });
3298
+ } catch (error) {
3299
+ if (!(error instanceof FsError)) throw error;
3300
+ return fail({
3301
+ FS_NOT_FOUND: 404,
3302
+ FS_NOT_REGULAR_FILE: 403,
3303
+ FS_PERMISSION_DENIED: 403,
3304
+ FS_SANDBOX_DENIED: 403,
3305
+ FS_TOO_LARGE: 413,
3306
+ FS_ABORTED: 499
3307
+ }[error.code] ?? 500, error.code);
3308
+ }
3309
+ }
3310
+ /**
3311
+ * File-display contribution. The connection service supplies authentication;
3312
+ * `ctx.fs` supplies the execution world's paths, reads, and access policy.
3313
+ */
3314
+ const SessionMediaReferences = {
3315
+ inject: [
3316
+ "connection",
3317
+ "fs",
3318
+ "attachments"
3319
+ ],
3320
+ apply(ctx) {
3321
+ const maxBytes = ctx.attachments.imageLimits.maxImageBytes;
3322
+ ctx.effect(() => ctx.connection.fetch.register({
3323
+ path: "/api/file",
3324
+ methods: ["GET", "HEAD"],
3325
+ requestBody: "buffered",
3326
+ fetch: (request) => serveFile(request, ctx.fs, maxBytes)
3327
+ }), "session-controller: /api/file");
3328
+ }
3329
+ };
3330
+ //#endregion
3331
+ //#region lib/types/archived-session-gate.js
3332
+ /**
3333
+ * The controller's admission gate for archived Sessions: an archived
3334
+ * Session, or a subagent descendant of one, must not run a model step until
3335
+ * it is restored. The work a Session still runs is reported and stopped by
3336
+ * its owners — the Agent registry (`turn`), the job registry seam (`job`),
3337
+ * the Subagent runtime (`subagent`), and the Schedule plugin (`schedule`) —
3338
+ * through the Workspace registry's archive-admission events. The Subagent
3339
+ * runtime also checks its retained ancestry before each step, so a released
3340
+ * intermediate Session cannot hide an archived ancestor.
3341
+ */
3342
+ /**
3343
+ * The gate as a plugin for `ctx.plugin(...)`: it loads once the Agent
3344
+ * registry, Session store, and Workspace registry are available and unwinds
3345
+ * with the plugin's fiber. A late waking delivery to an archived Session — a
3346
+ * subagent settlement, a queued follow-up — proposes a step the gate rejects,
3347
+ * which the loop ends as `blocked` without a request; unarchiving lifts the
3348
+ * gate for the whole lineage.
3349
+ */
3350
+ const ArchivedSessionGate = {
3351
+ name: "archived-session-gate",
3352
+ inject: [
3353
+ "agents",
3354
+ "sessions",
3355
+ "workspaceRegistry"
3356
+ ],
3357
+ apply(ctx) {
3358
+ ctx.on("agent/pre-step", (payload, next) => underArchivedSession(ctx, payload.agent) ? Promise.resolve({ kind: "reject" }) : next());
3359
+ }
3360
+ };
3361
+ /**
3362
+ * Whether the Agent's Session, or a Session above it in its subagent lineage,
3363
+ * is archived. This header-only check follows the durable fields through
3364
+ * subagent-origin Sessions only: a fork of an archived Session is an
3365
+ * independent conversation. The Subagent runtime separately checks managed
3366
+ * ancestry when an intermediate Session is unavailable here.
3367
+ * @param ctx - Host context.
3368
+ * @param agent - the Agent proposing a step.
3369
+ * @returns whether an archived Session owns the step.
3370
+ */
3371
+ function underArchivedSession(ctx, agent) {
3372
+ const archived = ctx.workspaceRegistry.archivedSessionIds;
3373
+ let header = agent.session.header;
3374
+ const visited = /* @__PURE__ */ new Set();
3375
+ while (!visited.has(header.id)) {
3376
+ if (archived.includes(header.id)) return true;
3377
+ visited.add(header.id);
3378
+ if (header.origin !== "subagent" || header.parentSession === void 0) return false;
3379
+ const parent = ctx.sessions.get(header.parentSession);
3380
+ if (parent === void 0) return archived.includes(header.parentSession);
3381
+ header = parent.header;
3382
+ }
3383
+ return false;
3384
+ }
3385
+ //#endregion
3386
+ //#region lib/types/index.js
3387
+ /** Session Remote owner: cold reads, explicit Agent commands, and live control state. */
3388
+ var __runInitializers = function(thisArg, initializers, value) {
3389
+ var useValue = arguments.length > 2;
3390
+ for (var i = 0; i < initializers.length; i++) value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
3391
+ return useValue ? value : void 0;
3392
+ };
3393
+ var __esDecorate = function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
3394
+ function accept(f) {
3395
+ if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
3396
+ return f;
3397
+ }
3398
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
3399
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
3400
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
3401
+ var _, done = false;
3402
+ for (var i = decorators.length - 1; i >= 0; i--) {
3403
+ var context = {};
3404
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
3405
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
3406
+ context.addInitializer = function(f) {
3407
+ if (done) throw new TypeError("Cannot add initializers after decoration has completed");
3408
+ extraInitializers.push(accept(f || null));
3409
+ };
3410
+ var result = (0, decorators[i])(kind === "accessor" ? {
3411
+ get: descriptor.get,
3412
+ set: descriptor.set
3413
+ } : descriptor[key], context);
3414
+ if (kind === "accessor") {
3415
+ if (result === void 0) continue;
3416
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
3417
+ if (_ = accept(result.get)) descriptor.get = _;
3418
+ if (_ = accept(result.set)) descriptor.set = _;
3419
+ if (_ = accept(result.init)) initializers.unshift(_);
3420
+ } else if (_ = accept(result)) if (kind === "field") initializers.unshift(_);
3421
+ else descriptor[key] = _;
3422
+ }
3423
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
3424
+ done = true;
3425
+ };
3426
+ var __addDisposableResource = function(env, value, async) {
3427
+ if (value !== null && value !== void 0) {
3428
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
3429
+ var dispose, inner;
3430
+ if (async) {
3431
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
3432
+ dispose = value[Symbol.asyncDispose];
3433
+ }
3434
+ if (dispose === void 0) {
3435
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
3436
+ dispose = value[Symbol.dispose];
3437
+ if (async) inner = dispose;
3438
+ }
3439
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
3440
+ if (inner) dispose = function() {
3441
+ try {
3442
+ inner.call(this);
3443
+ } catch (e) {
3444
+ return Promise.reject(e);
3445
+ }
3446
+ };
3447
+ env.stack.push({
3448
+ value,
3449
+ dispose,
3450
+ async
3451
+ });
3452
+ } else if (async) env.stack.push({ async: true });
3453
+ return value;
3454
+ };
3455
+ var __disposeResources = (function(SuppressedError) {
3456
+ return function(env) {
3457
+ function fail(e) {
3458
+ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
3459
+ env.hasError = true;
3460
+ }
3461
+ var r, s = 0;
3462
+ function next() {
3463
+ while (r = env.stack.pop()) try {
3464
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
3465
+ if (r.dispose) {
3466
+ var result = r.dispose.call(r.value);
3467
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
3468
+ fail(e);
3469
+ return next();
3470
+ });
3471
+ } else s |= 1;
3472
+ } catch (e) {
3473
+ fail(e);
3474
+ }
3475
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
3476
+ if (env.hasError) throw env.error;
3477
+ }
3478
+ return next();
3479
+ };
3480
+ })(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
3481
+ var e = new Error(message);
3482
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
3483
+ });
3484
+ /**
3485
+ * Extract the Session resource from an ID or a history address.
3486
+ *
3487
+ * Registers as the `session` kind default, so it applies to every Remote method of
3488
+ * every namespace: a top-level `sessionId` parameter, otherwise the first object
3489
+ * parameter carrying `sessionId` or an `address`. A new request type whose first
3490
+ * object parameter has an unrelated `address` field would be read as an address.
3491
+ * @param input - validated wire arguments and their ordered parameter descriptions.
3492
+ * @returns the named Session identity, otherwise the first object's Session identity or history address.
3493
+ * @throws Error when the request object supplies both sessionId and address.
3494
+ */
3495
+ function resolveSessionResource({ args, parameters }) {
3496
+ const sessionParameter = parameters.find((parameter) => parameter.name === "sessionId" || parameter.wire === "sessionId");
3497
+ if (sessionParameter !== void 0) return args[sessionParameter.wire];
3498
+ for (const parameter of parameters) {
3499
+ const value = args[parameter.wire];
3500
+ if (typeof value !== "object" || value === null || Array.isArray(value)) continue;
3501
+ const request = value;
3502
+ const address = request.address;
3503
+ if (request.sessionId !== void 0 && address !== void 0) throw new Error("Session resource request must not contain both sessionId and address");
3504
+ return request.sessionId ?? (address === void 0 ? void 0 : address.kind === "session" ? address.sessionId : address.childSessionId);
3505
+ }
3506
+ }
3507
+ /** Host service backing the generated `ctx.remote.session` namespace. */
3508
+ let SessionController = (() => {
3509
+ let _classSuper = TypertRemoteService;
3510
+ let _instanceExtraInitializers = [];
3511
+ let _list_decorators;
3512
+ let _search_decorators;
3513
+ let _create_decorators;
3514
+ let _selectModel_decorators;
3515
+ let _initializeDefaultModel_decorators;
3516
+ let _modelCatalog_decorators;
3517
+ let _canOpenWorkspacePath_decorators;
3518
+ let _openWorkspacePath_decorators;
3519
+ let _workspacePathApplications_decorators;
3520
+ let _rename_decorators;
3521
+ let _fork_decorators;
3522
+ let _prompt_decorators;
3523
+ let _attachment_decorators;
3524
+ let _updateQueue_decorators;
3525
+ let _cancel_decorators;
3526
+ let _page_decorators;
3527
+ let _events_decorators;
3528
+ let _observeEvent_decorators;
3529
+ let _observeProjections_decorators;
3530
+ let _state_decorators;
3531
+ let _observeState_decorators;
3532
+ let _wait_decorators;
3533
+ let _follow_decorators;
3534
+ let _projections_decorators;
3535
+ let _control_decorators;
3536
+ return class SessionController extends _classSuper {
3537
+ static {
3538
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
3539
+ _list_decorators = [Remote("list")];
3540
+ _search_decorators = [Remote("search")];
3541
+ _create_decorators = [Remote("create")];
3542
+ _selectModel_decorators = [Remote("selectModel")];
3543
+ _initializeDefaultModel_decorators = [Remote];
3544
+ _modelCatalog_decorators = [Remote("modelCatalog")];
3545
+ _canOpenWorkspacePath_decorators = [Remote];
3546
+ _openWorkspacePath_decorators = [Remote("openWorkspacePath")];
3547
+ _workspacePathApplications_decorators = [Remote("workspacePathApplications")];
3548
+ _rename_decorators = [Remote("rename")];
3549
+ _fork_decorators = [Remote("fork")];
3550
+ _prompt_decorators = [Remote("prompt")];
3551
+ _attachment_decorators = [Remote("attachment")];
3552
+ _updateQueue_decorators = [Remote("updateQueue")];
3553
+ _cancel_decorators = [Remote("cancel")];
3554
+ _page_decorators = [Remote("page")];
3555
+ _events_decorators = [Remote];
3556
+ _observeEvent_decorators = [Remote({ mode: "stream" })];
3557
+ _observeProjections_decorators = [Remote({ mode: "stream" })];
3558
+ _state_decorators = [Remote];
3559
+ _observeState_decorators = [Remote({ mode: "stream" })];
3560
+ _wait_decorators = [Remote];
3561
+ _follow_decorators = [Remote({ mode: "stream" })];
3562
+ _projections_decorators = [Remote("projections")];
3563
+ _control_decorators = [Remote({ mode: "stream" })];
3564
+ __esDecorate(this, null, _list_decorators, {
3565
+ kind: "method",
3566
+ name: "list",
3567
+ static: false,
3568
+ private: false,
3569
+ access: {
3570
+ has: (obj) => "list" in obj,
3571
+ get: (obj) => obj.list
3572
+ },
3573
+ metadata: _metadata
3574
+ }, null, _instanceExtraInitializers);
3575
+ __esDecorate(this, null, _search_decorators, {
3576
+ kind: "method",
3577
+ name: "search",
3578
+ static: false,
3579
+ private: false,
3580
+ access: {
3581
+ has: (obj) => "search" in obj,
3582
+ get: (obj) => obj.search
3583
+ },
3584
+ metadata: _metadata
3585
+ }, null, _instanceExtraInitializers);
3586
+ __esDecorate(this, null, _create_decorators, {
3587
+ kind: "method",
3588
+ name: "create",
3589
+ static: false,
3590
+ private: false,
3591
+ access: {
3592
+ has: (obj) => "create" in obj,
3593
+ get: (obj) => obj.create
3594
+ },
3595
+ metadata: _metadata
3596
+ }, null, _instanceExtraInitializers);
3597
+ __esDecorate(this, null, _selectModel_decorators, {
3598
+ kind: "method",
3599
+ name: "selectModel",
3600
+ static: false,
3601
+ private: false,
3602
+ access: {
3603
+ has: (obj) => "selectModel" in obj,
3604
+ get: (obj) => obj.selectModel
3605
+ },
3606
+ metadata: _metadata
3607
+ }, null, _instanceExtraInitializers);
3608
+ __esDecorate(this, null, _initializeDefaultModel_decorators, {
3609
+ kind: "method",
3610
+ name: "initializeDefaultModel",
3611
+ static: false,
3612
+ private: false,
3613
+ access: {
3614
+ has: (obj) => "initializeDefaultModel" in obj,
3615
+ get: (obj) => obj.initializeDefaultModel
3616
+ },
3617
+ metadata: _metadata
3618
+ }, null, _instanceExtraInitializers);
3619
+ __esDecorate(this, null, _modelCatalog_decorators, {
3620
+ kind: "method",
3621
+ name: "modelCatalog",
3622
+ static: false,
3623
+ private: false,
3624
+ access: {
3625
+ has: (obj) => "modelCatalog" in obj,
3626
+ get: (obj) => obj.modelCatalog
3627
+ },
3628
+ metadata: _metadata
3629
+ }, null, _instanceExtraInitializers);
3630
+ __esDecorate(this, null, _canOpenWorkspacePath_decorators, {
3631
+ kind: "method",
3632
+ name: "canOpenWorkspacePath",
3633
+ static: false,
3634
+ private: false,
3635
+ access: {
3636
+ has: (obj) => "canOpenWorkspacePath" in obj,
3637
+ get: (obj) => obj.canOpenWorkspacePath
3638
+ },
3639
+ metadata: _metadata
3640
+ }, null, _instanceExtraInitializers);
3641
+ __esDecorate(this, null, _openWorkspacePath_decorators, {
3642
+ kind: "method",
3643
+ name: "openWorkspacePath",
3644
+ static: false,
3645
+ private: false,
3646
+ access: {
3647
+ has: (obj) => "openWorkspacePath" in obj,
3648
+ get: (obj) => obj.openWorkspacePath
3649
+ },
3650
+ metadata: _metadata
3651
+ }, null, _instanceExtraInitializers);
3652
+ __esDecorate(this, null, _workspacePathApplications_decorators, {
3653
+ kind: "method",
3654
+ name: "workspacePathApplications",
3655
+ static: false,
3656
+ private: false,
3657
+ access: {
3658
+ has: (obj) => "workspacePathApplications" in obj,
3659
+ get: (obj) => obj.workspacePathApplications
3660
+ },
3661
+ metadata: _metadata
3662
+ }, null, _instanceExtraInitializers);
3663
+ __esDecorate(this, null, _rename_decorators, {
3664
+ kind: "method",
3665
+ name: "rename",
3666
+ static: false,
3667
+ private: false,
3668
+ access: {
3669
+ has: (obj) => "rename" in obj,
3670
+ get: (obj) => obj.rename
3671
+ },
3672
+ metadata: _metadata
3673
+ }, null, _instanceExtraInitializers);
3674
+ __esDecorate(this, null, _fork_decorators, {
3675
+ kind: "method",
3676
+ name: "fork",
3677
+ static: false,
3678
+ private: false,
3679
+ access: {
3680
+ has: (obj) => "fork" in obj,
3681
+ get: (obj) => obj.fork
3682
+ },
3683
+ metadata: _metadata
3684
+ }, null, _instanceExtraInitializers);
3685
+ __esDecorate(this, null, _prompt_decorators, {
3686
+ kind: "method",
3687
+ name: "prompt",
3688
+ static: false,
3689
+ private: false,
3690
+ access: {
3691
+ has: (obj) => "prompt" in obj,
3692
+ get: (obj) => obj.prompt
3693
+ },
3694
+ metadata: _metadata
3695
+ }, null, _instanceExtraInitializers);
3696
+ __esDecorate(this, null, _attachment_decorators, {
3697
+ kind: "method",
3698
+ name: "attachment",
3699
+ static: false,
3700
+ private: false,
3701
+ access: {
3702
+ has: (obj) => "attachment" in obj,
3703
+ get: (obj) => obj.attachment
3704
+ },
3705
+ metadata: _metadata
3706
+ }, null, _instanceExtraInitializers);
3707
+ __esDecorate(this, null, _updateQueue_decorators, {
3708
+ kind: "method",
3709
+ name: "updateQueue",
3710
+ static: false,
3711
+ private: false,
3712
+ access: {
3713
+ has: (obj) => "updateQueue" in obj,
3714
+ get: (obj) => obj.updateQueue
3715
+ },
3716
+ metadata: _metadata
3717
+ }, null, _instanceExtraInitializers);
3718
+ __esDecorate(this, null, _cancel_decorators, {
3719
+ kind: "method",
3720
+ name: "cancel",
3721
+ static: false,
3722
+ private: false,
3723
+ access: {
3724
+ has: (obj) => "cancel" in obj,
3725
+ get: (obj) => obj.cancel
3726
+ },
3727
+ metadata: _metadata
3728
+ }, null, _instanceExtraInitializers);
3729
+ __esDecorate(this, null, _page_decorators, {
3730
+ kind: "method",
3731
+ name: "page",
3732
+ static: false,
3733
+ private: false,
3734
+ access: {
3735
+ has: (obj) => "page" in obj,
3736
+ get: (obj) => obj.page
3737
+ },
3738
+ metadata: _metadata
3739
+ }, null, _instanceExtraInitializers);
3740
+ __esDecorate(this, null, _events_decorators, {
3741
+ kind: "method",
3742
+ name: "events",
3743
+ static: false,
3744
+ private: false,
3745
+ access: {
3746
+ has: (obj) => "events" in obj,
3747
+ get: (obj) => obj.events
3748
+ },
3749
+ metadata: _metadata
3750
+ }, null, _instanceExtraInitializers);
3751
+ __esDecorate(this, null, _observeEvent_decorators, {
3752
+ kind: "method",
3753
+ name: "observeEvent",
3754
+ static: false,
3755
+ private: false,
3756
+ access: {
3757
+ has: (obj) => "observeEvent" in obj,
3758
+ get: (obj) => obj.observeEvent
3759
+ },
3760
+ metadata: _metadata
3761
+ }, null, _instanceExtraInitializers);
3762
+ __esDecorate(this, null, _observeProjections_decorators, {
3763
+ kind: "method",
3764
+ name: "observeProjections",
3765
+ static: false,
3766
+ private: false,
3767
+ access: {
3768
+ has: (obj) => "observeProjections" in obj,
3769
+ get: (obj) => obj.observeProjections
3770
+ },
3771
+ metadata: _metadata
3772
+ }, null, _instanceExtraInitializers);
3773
+ __esDecorate(this, null, _state_decorators, {
3774
+ kind: "method",
3775
+ name: "state",
3776
+ static: false,
3777
+ private: false,
3778
+ access: {
3779
+ has: (obj) => "state" in obj,
3780
+ get: (obj) => obj.state
3781
+ },
3782
+ metadata: _metadata
3783
+ }, null, _instanceExtraInitializers);
3784
+ __esDecorate(this, null, _observeState_decorators, {
3785
+ kind: "method",
3786
+ name: "observeState",
3787
+ static: false,
3788
+ private: false,
3789
+ access: {
3790
+ has: (obj) => "observeState" in obj,
3791
+ get: (obj) => obj.observeState
3792
+ },
3793
+ metadata: _metadata
3794
+ }, null, _instanceExtraInitializers);
3795
+ __esDecorate(this, null, _wait_decorators, {
3796
+ kind: "method",
3797
+ name: "wait",
3798
+ static: false,
3799
+ private: false,
3800
+ access: {
3801
+ has: (obj) => "wait" in obj,
3802
+ get: (obj) => obj.wait
3803
+ },
3804
+ metadata: _metadata
3805
+ }, null, _instanceExtraInitializers);
3806
+ __esDecorate(this, null, _follow_decorators, {
3807
+ kind: "method",
3808
+ name: "follow",
3809
+ static: false,
3810
+ private: false,
3811
+ access: {
3812
+ has: (obj) => "follow" in obj,
3813
+ get: (obj) => obj.follow
3814
+ },
3815
+ metadata: _metadata
3816
+ }, null, _instanceExtraInitializers);
3817
+ __esDecorate(this, null, _projections_decorators, {
3818
+ kind: "method",
3819
+ name: "projections",
3820
+ static: false,
3821
+ private: false,
3822
+ access: {
3823
+ has: (obj) => "projections" in obj,
3824
+ get: (obj) => obj.projections
3825
+ },
3826
+ metadata: _metadata
3827
+ }, null, _instanceExtraInitializers);
3828
+ __esDecorate(this, null, _control_decorators, {
3829
+ kind: "method",
3830
+ name: "control",
3831
+ static: false,
3832
+ private: false,
3833
+ access: {
3834
+ has: (obj) => "control" in obj,
3835
+ get: (obj) => obj.control
3836
+ },
3837
+ metadata: _metadata
3838
+ }, null, _instanceExtraInitializers);
3839
+ if (_metadata) Object.defineProperty(this, Symbol.metadata, {
3840
+ enumerable: true,
3841
+ configurable: true,
3842
+ writable: true,
3843
+ value: _metadata
3844
+ });
3845
+ }
3846
+ static inject = [
3847
+ "agentDefaultModel",
3848
+ "agents",
3849
+ "attachments",
3850
+ "fileUploads",
3851
+ "fs",
3852
+ "llm",
3853
+ "remoteAccess",
3854
+ "sessions",
3855
+ "sessionProjections",
3856
+ "sessionQuery",
3857
+ "typert",
3858
+ "typertGateway",
3859
+ "workspaceRegistry"
3860
+ ];
3861
+ static Config = z.object({
3862
+ nativeOpen: z.boolean(),
3863
+ listWorkSliceMs: z.natural().min(1).default(16)
3864
+ });
3865
+ historyController = __runInitializers(this, _instanceExtraInitializers);
3866
+ stateController;
3867
+ webController;
3868
+ agents;
3869
+ commands;
3870
+ controlState;
3871
+ listState;
3872
+ openPath;
3873
+ fileApplications;
3874
+ openFileApplication;
3875
+ revealPath;
3876
+ canOpenPath;
3877
+ listWorkSliceMs;
3878
+ promotions = /* @__PURE__ */ new Set();
3879
+ /**
3880
+ * @param ctx - Host context containing the Session capability assembly.
3881
+ * @param config - native-opener and list-scheduling deployment policy.
3882
+ * @param internals - host integrations replaceable by direct unit tests.
3883
+ */
3884
+ constructor(ctx, config, internals = {}) {
3885
+ super(ctx, "sessionController", { namespace: "session" });
3886
+ this.listWorkSliceMs = SessionController.Config(config).listWorkSliceMs;
3887
+ this.fileApplications = internals.fileApplications ?? nativeFileApplications;
3888
+ this.openFileApplication = internals.openFileApplication ?? openNativeFileApplication;
3889
+ this.openPath = internals.openPath ?? openNativeAssociatedPath;
3890
+ this.revealPath = internals.revealPath ?? revealNativePath;
3891
+ this.canOpenPath = internals.canOpenPath ?? (() => config.nativeOpen ?? (internals.openPath !== void 0 || canOpenNativePath()));
3892
+ }
3893
+ async [Service.init]() {
3894
+ const ctx = this.ctx;
3895
+ ctx.typert.resources.register("session", { resolve: resolveSessionResource });
3896
+ this.agents = new ApiSessionAgentController(ctx);
3897
+ this.agents.initialize();
3898
+ this.commands = new SessionCommandController(ctx, this.agents, process.cwd());
3899
+ ctx.effect(() => ctx.fileUploads.registerAgentResolver(async (sessionId) => {
3900
+ const result = await this.agents.resolveAgent(sessionId);
3901
+ if ("error" in result) throw result.error;
3902
+ return result.agent;
3903
+ }), "session-controller: file-upload Agent resolver");
3904
+ this.controlState = new SessionControlController(ctx);
3905
+ ctx.effect(() => async () => {
3906
+ await Promise.allSettled([...this.promotions]);
3907
+ }, "session-controller.promotions");
3908
+ this.historyController = new HistoryController(ctx);
3909
+ this.stateController = new StateController(ctx, this.historyController);
3910
+ this.webController = new WebController(ctx, this.historyController, (observation) => {
3911
+ this.promote(observation);
3912
+ });
3913
+ this.listState = new ApiSessionList(ctx, this.listWorkSliceMs);
3914
+ await this.commands.initialize();
3915
+ ctx.fiber.assertActive();
3916
+ await this.listState.initialize();
3917
+ ctx.fiber.assertActive();
3918
+ ctx.plugin(SessionFileReferences);
3919
+ ctx.plugin(SessionMediaReferences);
3920
+ ctx.plugin(SessionSkillCatalog);
3921
+ ctx.plugin(ArchivedSessionGate);
3922
+ ctx.on("session/created", (session) => {
3923
+ ctx.emit("api-session/added", this.listState.summaryFor(session));
3924
+ });
3925
+ ctx.on("session/disposed", (session) => {
3926
+ ctx.emit("api-session/removed", session.id);
3927
+ });
3928
+ const publishAgentAvailability = ({ agent }) => {
3929
+ if (ctx.sessions.get(agent.id) === agent.session) ctx.emit("api-session/added", this.listState.summaryFor(agent.session));
3930
+ };
3931
+ ctx.on("agent/created", publishAgentAvailability);
3932
+ ctx.on("agent/disposed", publishAgentAvailability);
3933
+ ctx.on("agent/status", ({ agent, status }) => {
3934
+ ctx.emit("api-session/status", agent.id, status === "running");
3935
+ });
3936
+ ctx.on("agent/error", ({ agent, error }) => {
3937
+ ctx.emit("api-session/error", agent.id, errorChain(error));
3938
+ });
3939
+ ctx.on("session/event", (session, event) => {
3940
+ if (event.type !== "user/message" || event.data.source.kind !== "user") return;
3941
+ ctx.emit("api-session/activity", session.id, event.time);
3942
+ });
3943
+ }
3944
+ /**
3945
+ * Request background activation through the existing Session Agent controller.
3946
+ * @param observation - owned lease disposed by the background task; callers retain their own lease separately.
3947
+ */
3948
+ promote(observation) {
3949
+ const sessionId = observation.header.id;
3950
+ const task = (async () => {
3951
+ const env_1 = {
3952
+ stack: [],
3953
+ error: void 0,
3954
+ hasError: false
3955
+ };
3956
+ try {
3957
+ const ownedObservation = __addDisposableResource(env_1, observation, false);
3958
+ const result = await this.agents.resolveObservedAgent(ownedObservation);
3959
+ if ("error" in result) this.ctx.emit("api-session/error", sessionId, result.error.message);
3960
+ } catch (e_1) {
3961
+ env_1.error = e_1;
3962
+ env_1.hasError = true;
3963
+ } finally {
3964
+ __disposeResources(env_1);
3965
+ }
3966
+ })().catch((error) => {
3967
+ this.ctx.logger.error(`session-controller: background activation for "${sessionId}" failed: ${errorChain(error)}`);
3968
+ });
3969
+ this.promotions.add(task);
3970
+ task.finally(() => {
3971
+ this.promotions.delete(task);
3972
+ });
3973
+ }
3974
+ /**
3975
+ * Resolve or resume one ordinary Session for another Host API domain.
3976
+ * @param sessionId - Session identity whose Agent owns the operation.
3977
+ * @returns the live Agent or the stable Session-domain failure.
3978
+ */
3979
+ resolveAgent(sessionId) {
3980
+ return this.agents.resolveAgent(sessionId);
3981
+ }
3982
+ /**
3983
+ * Read all visible Session rows without resuming an Agent.
3984
+ * @param _request - reserved empty list request.
3985
+ * @param signal - cancellation for persistence reads and summary generation.
3986
+ * @returns visible Session summaries ordered by activity.
3987
+ */
3988
+ async list(_request, signal) {
3989
+ return { items: (await this.listState.list(signal)).filter((item) => this.ctx.remoteAccess.allows({
3990
+ kind: "session",
3991
+ id: item.sessionId
3992
+ })) };
3993
+ }
3994
+ /**
3995
+ * Search visible Session content without resuming an Agent. A non-owner
3996
+ * receives only the hits whose Session `allows()` admits; `hasMore`
3997
+ * describes the bounded result before that filtering.
3998
+ * @param request - literal message-content query.
3999
+ * @param signal - cancellation for list and search reads.
4000
+ * @returns authorized bounded Session search results.
4001
+ */
4002
+ async search(request, signal) {
4003
+ const result = await this.listState.search(request.query, signal);
4004
+ return {
4005
+ ...result,
4006
+ items: result.items.filter((item) => this.ctx.remoteAccess.allows({
4007
+ kind: "session",
4008
+ id: item.sessionId
4009
+ }))
4010
+ };
4011
+ }
4012
+ /**
4013
+ * Create one ordinary Session for a new conversation, reusing the named blank Session while it is reusable.
4014
+ * @param request - optional blank Session to reuse, location, and Agent preset.
4015
+ * @returns the created or reused Session identity and its preset when configured.
4016
+ */
4017
+ create(request) {
4018
+ return this.commands.create(request);
4019
+ }
4020
+ /**
4021
+ * Select one Session-local model after explicitly resuming the Session; save the default in the background.
4022
+ * @param request - Session identity and requested model selection.
4023
+ * @returns the normalized selection installed for the Session, without waiting for default persistence.
4024
+ */
4025
+ selectModel(request) {
4026
+ return this.commands.selectModel(request);
4027
+ }
4028
+ /**
4029
+ * Select the first available account model after login when no provider API key is configured.
4030
+ * @returns after saving the first available model or retaining the existing default.
4031
+ */
4032
+ async initializeDefaultModel() {
4033
+ const provider = "deepseek-account";
4034
+ if (await hasProviderApiKey(this.ctx)) return;
4035
+ const model = (await buildModelCatalog(this.ctx)).groups.find((group) => group.id === provider)?.models[0];
4036
+ if (model === void 0) throw new RemoteError("session/provider-models-unavailable", `provider "${provider}" has no available models`, { provider });
4037
+ const selection = {
4038
+ provider,
4039
+ model: model.id,
4040
+ ...model.reasoning?.defaultEffort === void 0 ? {} : { reasoningEffort: ReasoningEffortId(model.reasoning.defaultEffort) }
4041
+ };
4042
+ await this.ctx.agentDefaultModel.saveSelection(selection);
4043
+ }
4044
+ /**
4045
+ * Describe every currently routable model for Host-generation selectors.
4046
+ * @returns provider-grouped models, the deployment default, and isolated provider failures.
4047
+ */
4048
+ modelCatalog() {
4049
+ return buildModelCatalog(this.ctx);
4050
+ }
4051
+ /**
4052
+ * Report whether this deployment can hand a Session workspace path to a native desktop.
4053
+ * @returns true when the matching open operation is available.
4054
+ */
4055
+ canOpenWorkspacePath() {
4056
+ return this.canOpenPath();
4057
+ }
4058
+ /**
4059
+ * Describe the serving desktop for authenticated file-action routes.
4060
+ * @returns Host name, configured availability, and platform-specific file-manager behavior.
4061
+ */
4062
+ workspaceDesktop() {
4063
+ const fileManager = nativeFileManager();
4064
+ return {
4065
+ name: hostname(),
4066
+ available: fileManager !== null && this.canOpenPath(),
4067
+ fileManager
4068
+ };
4069
+ }
4070
+ /**
4071
+ * Verify one path through the composed filesystem and open it on the Host desktop.
4072
+ * @param request - path after best-effort Session workspace resolution.
4073
+ * @param signal - caller lifetime; abort terminates the native command.
4074
+ * @returns confirmation after the native opener accepts the path.
4075
+ * @throws RemoteError when the request is invalid, has no verified Host mapping, is cancelled, or the opener fails.
4076
+ */
4077
+ async openWorkspacePath(request, signal) {
4078
+ try {
4079
+ const path = await this.verifyDesktopPath(request.path, signal);
4080
+ if (request.action === "reveal") await this.revealPath(path, signal);
4081
+ else if (request.application !== void 0) await this.openFileApplication(path, request.application, signal);
4082
+ else await this.openPath(path, signal);
4083
+ return { opened: true };
4084
+ } catch (error) {
4085
+ if (signal.aborted) throw new RemoteError("gateway/cancelled", "path open was aborted", {});
4086
+ if (error instanceof RemoteError) throw error;
4087
+ throw new RemoteError("gateway/internal", "path open failed", {}, { cause: error });
4088
+ }
4089
+ }
4090
+ /**
4091
+ * Query current file handlers on the serving desktop without activating an Agent.
4092
+ * @param request - file path in Host filesystem syntax.
4093
+ * @param signal - caller lifetime, propagated to filesystem and desktop queries.
4094
+ * @returns OS application names, icons, and default selection; empty when desktop opening is unavailable.
4095
+ * @throws RemoteError when the path is invalid, the query is cancelled, or native discovery fails.
4096
+ */
4097
+ async workspacePathApplications(request, signal) {
4098
+ if (!this.canOpenPath()) return [];
4099
+ try {
4100
+ const path = await this.verifyDesktopPath(request.path, signal);
4101
+ return await this.fileApplications(path, signal);
4102
+ } catch (error) {
4103
+ if (signal.aborted) throw new RemoteError("gateway/cancelled", "application query was aborted", {});
4104
+ if (error instanceof RemoteError) throw error;
4105
+ throw new RemoteError("gateway/internal", "file application query failed", {}, { cause: error });
4106
+ }
4107
+ }
4108
+ async verifyDesktopPath(path, signal) {
4109
+ if (path.length === 0) throw new RemoteError("gateway/bad-request", "A non-empty file path is required", {});
4110
+ signal.throwIfAborted();
4111
+ const hostPath = resolve(path);
4112
+ const { fs } = this.ctx;
4113
+ const mapped = fs.processPathFromHostPath(hostPath);
4114
+ if (mapped === void 0 || fs.processPath(await fs.resolve(mapped, { signal })) !== hostPath) throw new RemoteError("gateway/bad-request", "Path has no verified Host path", {});
4115
+ signal.throwIfAborted();
4116
+ return hostPath;
4117
+ }
4118
+ /**
4119
+ * Rename one Session after explicitly resuming it.
4120
+ * @param request - Session identity and proposed title.
4121
+ * @returns the accepted title and durable event sequence.
4122
+ */
4123
+ rename(request) {
4124
+ return this.commands.rename(request);
4125
+ }
4126
+ /**
4127
+ * Fork one cold-readable exact event prefix into a new Session. An omitted
4128
+ * boundary selects the latest completed-turn prefix; an open cut receives
4129
+ * synthetic fork closers.
4130
+ * @param request - source Session, optional exact inclusive event boundary, and migration preflight choice.
4131
+ * @returns the new Session identity.
4132
+ */
4133
+ async fork(request) {
4134
+ if (request.allowMigration === false && this.ctx.sessions.get(request.sessionId) === void 0) {
4135
+ if ((await this.ctx.get("sessionPersistence")?.stat(request.sessionId))?.formatStatus === "migration-required" && this.ctx.sessions.get(request.sessionId) === void 0) throw new RemoteError("session/migration-required", "Open the source Session to complete migration before forking", { sessionId: request.sessionId });
4136
+ }
4137
+ return this.commands.fork(request);
4138
+ }
4139
+ /**
4140
+ * Admit one prompt after explicitly resuming its Session.
4141
+ * @param request - Session identity, prompt content, source metadata, and delivery mode.
4142
+ * @param signal - caller cancellation before prompt admission begins.
4143
+ * @returns acknowledgement that the Agent accepted the prompt.
4144
+ */
4145
+ async prompt(request, signal) {
4146
+ signal.throwIfAborted();
4147
+ if (request.content.length > 0 && !hasPromptContent(request.content)) throw new RemoteError("gateway/bad-request", "prompt content must include non-whitespace text or an attachment", {});
4148
+ const clientTimeZone = request.clientTimeZone === void 0 ? void 0 : canonicalClientTimeZone(request.clientTimeZone);
4149
+ if (request.clientTimeZone !== void 0 && clientTimeZone === void 0) throw new RemoteError("session/invalid-time-zone", "clientTimeZone must be UTC or a valid IANA Area/Location name", { value: request.clientTimeZone });
4150
+ const principal = principalOf(this.ctx.invocation);
4151
+ const source = {
4152
+ kind: request.content.length === 0 ? "retry" : "user",
4153
+ rpcId: request.requestId,
4154
+ ...clientTimeZone === void 0 ? {} : { clientTimeZone },
4155
+ ...principal === void 0 ? {} : { principal }
4156
+ };
4157
+ return this.commands.prompt(request, source);
4158
+ }
4159
+ /**
4160
+ * Read one image from the attachment store after gateway authorization.
4161
+ * @param request - image reference and gateway permission scope; Session existence is not checked.
4162
+ * @returns the durable attachment reference and base64-encoded bytes.
4163
+ */
4164
+ attachment(request) {
4165
+ return this.commands.attachment(request);
4166
+ }
4167
+ /**
4168
+ * Mutate one still-pending queue occurrence, resuming a cold Agent first.
4169
+ * @param request - Session, queue item, and requested mutation.
4170
+ * @returns acknowledgement that the queue mutation was applied.
4171
+ */
4172
+ updateQueue(request) {
4173
+ return this.commands.updateQueue(request);
4174
+ }
4175
+ /**
4176
+ * Cancel one active Agent turn without dropping its pending inbox.
4177
+ * @param request - Session whose active Agent turn is cancelled.
4178
+ * @returns acknowledgement that cancellation was requested.
4179
+ */
4180
+ cancel(request) {
4181
+ return this.commands.cancel(request);
4182
+ }
4183
+ /**
4184
+ * Read one cold-safe, message-aligned Session history page.
4185
+ * @deprecated Use `events`; this entry point remains for existing Web callers.
4186
+ * @param request - durable address, optional fixed cut, backward cursor, and page budget.
4187
+ * @param signal - cancellation for persistence reads.
4188
+ * @returns one chronological page with its inclusive cursor; an omitted `throughSeq` selects the observed log end.
4189
+ */
4190
+ page(request, signal) {
4191
+ return this.historyController.events(request, signal);
4192
+ }
4193
+ /**
4194
+ * Read one cold-safe, message-aligned Session history page.
4195
+ * @param request - durable address, optional fixed cut, backward cursor, and page budget.
4196
+ * @param signal - cancellation for persistence reads.
4197
+ * @returns one chronological page with its inclusive cursor.
4198
+ */
4199
+ events(request, signal) {
4200
+ return this.historyController.events(request, signal);
4201
+ }
4202
+ /**
4203
+ * Subscribe to Session events without reading a snapshot.
4204
+ * @param request - Session address.
4205
+ * @param signal - subscription cancellation.
4206
+ * @returns readiness and subsequent events, without a snapshot.
4207
+ */
4208
+ observeEvent(request, signal) {
4209
+ return this.historyController.observeEvent(request, signal);
4210
+ }
4211
+ /**
4212
+ * Subscribe to Session projection changes.
4213
+ * @param request - target Session.
4214
+ * @param signal - subscription cancellation.
4215
+ * @returns readiness followed by one projection change frame per committed event.
4216
+ */
4217
+ observeProjections(request, signal) {
4218
+ return this.historyController.observeProjections(request, signal);
4219
+ }
4220
+ /**
4221
+ * Read passive Session state.
4222
+ * @param request - target Session.
4223
+ * @param signal - read cancellation.
4224
+ * @returns current passive state.
4225
+ */
4226
+ state(request, signal) {
4227
+ return this.stateController.state(request, signal);
4228
+ }
4229
+ /**
4230
+ * Subscribe to complete Session state replacements.
4231
+ * @param request - target Session.
4232
+ * @param signal - subscription cancellation.
4233
+ * @returns complete passive state replacements.
4234
+ */
4235
+ observeState(request, signal) {
4236
+ return this.stateController.observeState(request, signal);
4237
+ }
4238
+ /**
4239
+ * Wait for Session quiescence or pending input with bounded assistant output.
4240
+ * @param request - Session, wait bounds and output window.
4241
+ * @param signal - caller cancellation.
4242
+ * @returns stopping state and bounded assistant output.
4243
+ */
4244
+ wait(request, signal) {
4245
+ return this.stateController.wait(request, signal);
4246
+ }
4247
+ /**
4248
+ * Follow one Session log from its opening or resume cursor.
4249
+ * @param request - durable address and last committed sequence already held by the caller.
4250
+ * @param signal - cancellation owned by the Remote stream carrier.
4251
+ * @returns a complete opening snapshot followed by gap-free durable event
4252
+ * frames and optional cursorless assistant-stream frames.
4253
+ */
4254
+ follow(request, signal) {
4255
+ return this.webController.follow(request, signal);
4256
+ }
4257
+ /**
4258
+ * Read exact projections, returning cached hints only when migration is required.
4259
+ * @param request - Session whose current values are required.
4260
+ * @param signal - cancellation for the Session read.
4261
+ * @returns a sequenced baseline, cached hints when migration is deferred, or null when absent.
4262
+ */
4263
+ projections(request, signal) {
4264
+ return this.historyController.projections(request, signal);
4265
+ }
4266
+ /**
4267
+ * Stream a complete live-control baseline followed by replacement frames.
4268
+ * @param signal - cancellation owned by the Remote stream carrier.
4269
+ * @returns one complete baseline followed by live replacement frames.
4270
+ */
4271
+ async *control(signal) {
4272
+ for await (const frame of this.controlState.control(signal)) switch (frame.type) {
4273
+ case "baseline": {
4274
+ const projections = Object.fromEntries(Object.entries(frame.value.projections).filter(([sessionId]) => this.ctx.remoteAccess.allows({
4275
+ kind: "session",
4276
+ id: sessionId
4277
+ })));
4278
+ yield {
4279
+ type: "baseline",
4280
+ value: {
4281
+ ...frame.value,
4282
+ projections
4283
+ }
4284
+ };
4285
+ break;
4286
+ }
4287
+ case "projection":
4288
+ if (this.ctx.remoteAccess.allows({
4289
+ kind: "session",
4290
+ id: frame.sessionId
4291
+ })) yield frame;
4292
+ break;
4293
+ /* v8 ignore next -- closed control-frame union. */
4294
+ default: assertNever(frame);
4295
+ }
4296
+ }
4297
+ };
4298
+ })();
4299
+ //#endregion
4300
+ export { ApiSessionNotFound, SessionController, SessionController as default, SessionFileReferences, SessionSkillCatalog };