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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +7 -2
  3. package/lib/client.js +4325 -0
  4. package/lib/index.js +3367 -0
  5. package/lib/typert.host.d.ts +3 -0
  6. package/lib/typert.host.js +4053 -0
  7. package/lib/typert.remote-client.d.ts +97 -0
  8. package/lib/typert.remote-client.js +2013 -0
  9. package/lib/types/agent.d.ts +198 -0
  10. package/lib/types/agent.js +609 -0
  11. package/lib/types/archived-session-gate.d.ts +30 -0
  12. package/lib/types/archived-session-gate.js +51 -0
  13. package/lib/types/assistant-stream.d.ts +26 -0
  14. package/lib/types/assistant-stream.js +82 -0
  15. package/lib/types/catalog.d.ts +24 -0
  16. package/lib/types/catalog.js +106 -0
  17. package/lib/types/client/contract/events.d.ts +102 -0
  18. package/lib/types/client/contract/events.js +111 -0
  19. package/lib/types/client/contract/session.d.ts +157 -0
  20. package/lib/types/client/contract/session.js +1 -0
  21. package/lib/types/client/contract/sessions.d.ts +161 -0
  22. package/lib/types/client/contract/sessions.js +1 -0
  23. package/lib/types/client/contract/snapshot.d.ts +81 -0
  24. package/lib/types/client/contract/snapshot.js +1 -0
  25. package/lib/types/client/index.d.ts +39 -0
  26. package/lib/types/client/index.js +60 -0
  27. package/lib/types/client/ordered-baseline.d.ts +12 -0
  28. package/lib/types/client/ordered-baseline.js +40 -0
  29. package/lib/types/client/scope.d.ts +46 -0
  30. package/lib/types/client/scope.js +46 -0
  31. package/lib/types/client/session-wire-event.d.ts +11 -0
  32. package/lib/types/client/session-wire-event.js +42 -0
  33. package/lib/types/client/sessions/assistant-stream.d.ts +56 -0
  34. package/lib/types/client/sessions/assistant-stream.js +182 -0
  35. package/lib/types/client/sessions/history-records.d.ts +22 -0
  36. package/lib/types/client/sessions/history-records.js +25 -0
  37. package/lib/types/client/sessions/lineage.d.ts +40 -0
  38. package/lib/types/client/sessions/lineage.js +54 -0
  39. package/lib/types/client/sessions/manager.d.ts +269 -0
  40. package/lib/types/client/sessions/manager.js +799 -0
  41. package/lib/types/client/sessions/notifier.d.ts +39 -0
  42. package/lib/types/client/sessions/notifier.js +97 -0
  43. package/lib/types/client/sessions/projection-store.d.ts +128 -0
  44. package/lib/types/client/sessions/projection-store.js +161 -0
  45. package/lib/types/client/sessions/remotes.d.ts +29 -0
  46. package/lib/types/client/sessions/remotes.js +7 -0
  47. package/lib/types/client/sessions/service.d.ts +258 -0
  48. package/lib/types/client/sessions/service.js +582 -0
  49. package/lib/types/client/sessions/session.d.ts +287 -0
  50. package/lib/types/client/sessions/session.js +866 -0
  51. package/lib/types/client/time-zone.d.ts +8 -0
  52. package/lib/types/client/time-zone.js +13 -0
  53. package/lib/types/client/transport.d.ts +77 -0
  54. package/lib/types/client/transport.js +129 -0
  55. package/lib/types/commands.d.ts +86 -0
  56. package/lib/types/commands.js +624 -0
  57. package/lib/types/control.d.ts +20 -0
  58. package/lib/types/control.js +106 -0
  59. package/lib/types/file-references.d.ts +27 -0
  60. package/lib/types/file-references.js +68 -0
  61. package/lib/types/history.d.ts +32 -0
  62. package/lib/types/history.js +441 -0
  63. package/lib/types/index.d.ts +222 -0
  64. package/lib/types/index.js +658 -0
  65. package/lib/types/list.d.ts +50 -0
  66. package/lib/types/list.js +325 -0
  67. package/lib/types/media-references.d.ts +16 -0
  68. package/lib/types/media-references.js +76 -0
  69. package/lib/types/model-selection-projection.d.ts +8 -0
  70. package/lib/types/model-selection-projection.js +65 -0
  71. package/lib/types/remote-events.d.ts +8 -0
  72. package/lib/types/remote-events.js +1 -0
  73. package/lib/types/skill-catalog.d.ts +28 -0
  74. package/lib/types/skill-catalog.js +203 -0
  75. package/lib/types/types.d.ts +611 -0
  76. package/lib/types/types.js +4 -0
  77. package/locale/en.json +5 -0
  78. package/locale/zh.json +6 -0
  79. package/package.json +114 -4
package/lib/index.js ADDED
@@ -0,0 +1,3367 @@
1
+ import { hostname } from "node:os";
2
+ import { isAbsolute, resolve } from "node:path";
3
+ import z from "@unieai/schemastery";
4
+ import { AssistantStreamAccumulator, ReasoningEffortId, assistantStreamChunks, createUserMessage, errorChain, freezeMessage } from "@unieai/rabi-llm";
5
+ import { canOpenNativePath, nativeFileApplications, nativeFileManager, openNativeAssociatedPath, openNativeFileApplication, revealNativePath } from "@unieai/rabi-native-command";
6
+ import { SessionQueryError } from "@unieai/rabi-session-query";
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 { brandString } from "@unieai/rabi-brand";
14
+ import { credentialRef } from "@unieai/rabi-credentials";
15
+ import { AttachmentError } from "@unieai/rabi-attachment";
16
+ import { buildForkSeed } from "@unieai/rabi-session/fork";
17
+ import { SessionLogOffset, SessionSeq, isAppendSurfaceEvent } from "@unieai/rabi-session";
18
+ import { SessionTitleInvalidError } from "@unieai/rabi-session-title";
19
+ import { Deque } from "@unieai/rabi-deque";
20
+ import { performance } from "node:perf_hooks";
21
+ import { scheduler } from "node:timers/promises";
22
+ import { z as z$1 } from "zod";
23
+ import { isUserInvocable } from "@unieai/rabi-skill";
24
+ import { FsError } from "@unieai/rabi-fs";
25
+ import mime from "mime-types";
26
+ //#region lib/types/agent.js
27
+ /** Agent activation, composition, and model-selection policy owned by API Session. */
28
+ var __addDisposableResource$4 = function(env, value, async) {
29
+ if (value !== null && value !== void 0) {
30
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
31
+ var dispose, inner;
32
+ if (async) {
33
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
34
+ dispose = value[Symbol.asyncDispose];
35
+ }
36
+ if (dispose === void 0) {
37
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
38
+ dispose = value[Symbol.dispose];
39
+ if (async) inner = dispose;
40
+ }
41
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
42
+ if (inner) dispose = function() {
43
+ try {
44
+ inner.call(this);
45
+ } catch (e) {
46
+ return Promise.reject(e);
47
+ }
48
+ };
49
+ env.stack.push({
50
+ value,
51
+ dispose,
52
+ async
53
+ });
54
+ } else if (async) env.stack.push({ async: true });
55
+ return value;
56
+ };
57
+ var __disposeResources$4 = (function(SuppressedError) {
58
+ return function(env) {
59
+ function fail(e) {
60
+ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
61
+ env.hasError = true;
62
+ }
63
+ var r, s = 0;
64
+ function next() {
65
+ while (r = env.stack.pop()) try {
66
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
67
+ if (r.dispose) {
68
+ var result = r.dispose.call(r.value);
69
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
70
+ fail(e);
71
+ return next();
72
+ });
73
+ } else s |= 1;
74
+ } catch (e) {
75
+ fail(e);
76
+ }
77
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
78
+ if (env.hasError) throw env.error;
79
+ }
80
+ return next();
81
+ };
82
+ })(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
83
+ var e = new Error(message);
84
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
85
+ });
86
+ /** Cold Session identity absent from persistence. */
87
+ var ApiSessionNotFound = class extends Error {};
88
+ /** Session identity whose lifecycle belongs to subagent routing. */
89
+ var ApiSessionSubagentOwnership = class extends Error {
90
+ sessionId;
91
+ /** @param sessionId - identity reserved to subagent routing. */
92
+ constructor(sessionId) {
93
+ super(`session "${sessionId}" is a subagent session; use subagent delivery`);
94
+ this.sessionId = sessionId;
95
+ }
96
+ };
97
+ /** Explicit-id creation attempted to adopt a Session under another cwd. */
98
+ var ApiSessionCwdConflict = class extends Error {
99
+ sessionId;
100
+ requestedCwd;
101
+ existingCwd;
102
+ constructor(sessionId, requestedCwd, existingCwd) {
103
+ super(existingCwd === void 0 ? `session "${sessionId}" records no cwd and cannot be adopted for "${requestedCwd}"` : `session "${sessionId}" belongs to "${existingCwd}", not "${requestedCwd}"`);
104
+ this.sessionId = sessionId;
105
+ this.requestedCwd = requestedCwd;
106
+ this.existingCwd = existingCwd;
107
+ }
108
+ };
109
+ /** Reuse of a Session named an Agent preset while the deployment composes no preset roster. */
110
+ var ApiSessionPresetConflict = class extends Error {
111
+ sessionId;
112
+ requestedPreset;
113
+ constructor(sessionId, requestedPreset) {
114
+ super(`the deployment composes no agent preset roster, so session "${sessionId}" cannot run preset "${requestedPreset}"`);
115
+ this.sessionId = sessionId;
116
+ this.requestedPreset = requestedPreset;
117
+ }
118
+ };
119
+ /** A blank Session chosen for reuse started a turn before this Host acquired its writer. */
120
+ var ApiSessionStartedSinceObserved = class extends Error {};
121
+ /**
122
+ * Test whether generic Session routing must leave an identity to subagent routing.
123
+ * @param ctx - Host context carrying the Agent ownership registry.
124
+ * @param session - attached or live Session whose ownership is tested.
125
+ * @param agent - live Agent when one exists for the Session.
126
+ * @returns whether subagent routing owns the Session identity.
127
+ */
128
+ function hasApiSessionSubagentOwner(ctx, session, agent) {
129
+ if (session.header.origin === "subagent") return true;
130
+ const parentId = session.header.parentSession;
131
+ if (parentId === void 0 || agent === void 0) return false;
132
+ const parent = ctx.agents.get(parentId);
133
+ return parent !== void 0 && ctx.agents.isOwnedBy(agent.id, parent);
134
+ }
135
+ /**
136
+ * Build the stable caller-facing subagent ownership rejection.
137
+ * @param sessionId - Session identity owned by subagent routing.
138
+ * @returns a stable Session-domain failure.
139
+ */
140
+ function apiSessionSubagentOwnershipError(sessionId) {
141
+ return new RemoteError("session/agent-busy", `session "${sessionId}" is owned by subagent routing`, { reason: "use subagent delivery for this child session" });
142
+ }
143
+ /**
144
+ * Inspect one cold Session without repairing, resuming, or publishing it.
145
+ * @param ctx - Host context carrying Session persistence.
146
+ * @param sessionId - durable Session identity.
147
+ * @param signal - optional cancellation for persistence reads.
148
+ * @returns the persisted header and complete event prefix.
149
+ */
150
+ async function inspectApiSession(ctx, sessionId, signal) {
151
+ try {
152
+ const env_1 = {
153
+ stack: [],
154
+ error: void 0,
155
+ hasError: false
156
+ };
157
+ try {
158
+ const observation = __addDisposableResource$4(env_1, await ctx.sessionQuery.observeSession(sessionId, {
159
+ ...signal === void 0 ? {} : { signal },
160
+ projectionMode: "none"
161
+ }), false);
162
+ if (observation.header.cwd === void 0) throw new ApiSessionNotFound(`session "${sessionId}" not found`);
163
+ return {
164
+ meta: observation.header,
165
+ inheritedEventCount: observation.inheritedEventCount,
166
+ events: [...observation.events]
167
+ };
168
+ } catch (e_1) {
169
+ env_1.error = e_1;
170
+ env_1.hasError = true;
171
+ } finally {
172
+ __disposeResources$4(env_1);
173
+ }
174
+ } catch (error) {
175
+ if (error instanceof SessionQueryError && error.code === "SESSION_QUERY_SESSION_NOT_FOUND") throw new ApiSessionNotFound(`session "${sessionId}" not found`);
176
+ throw error;
177
+ }
178
+ }
179
+ /** Owns every operation that may create, resume, or configure a Web Agent. */
180
+ var ApiSessionAgentController = class {
181
+ ctx;
182
+ resumes = /* @__PURE__ */ new Map();
183
+ claims = /* @__PURE__ */ new Map();
184
+ selections = /* @__PURE__ */ new WeakMap();
185
+ imageAdmissionChains = /* @__PURE__ */ new WeakMap();
186
+ /** @param ctx - Host context carrying Agent, model, persistence, and Typert services. */
187
+ constructor(ctx) {
188
+ this.ctx = ctx;
189
+ ctx.typert.lookups.configure("agent", async (sessionId) => {
190
+ const found = await this.resolveAgent(sessionId);
191
+ if ("error" in found) throw found.error;
192
+ return found.agent;
193
+ });
194
+ ctx.typert.lookups.configure("session", async (sessionId) => {
195
+ const found = await this.resolveAgent(sessionId);
196
+ if ("error" in found) throw found.error;
197
+ return found.agent.session;
198
+ });
199
+ ctx.typert.contexts.configureHost("agent", async (sessionId) => {
200
+ const found = await this.resolveAgent(sessionId);
201
+ if ("error" in found) throw found.error;
202
+ return found.agent.ctx;
203
+ });
204
+ }
205
+ /**
206
+ * Resolve or resume one ordinary Session, deduplicating concurrent resumes.
207
+ * @param sessionId - ordinary Session identity.
208
+ * @returns the live Agent or a stable Session-domain failure.
209
+ */
210
+ async resolveAgent(sessionId) {
211
+ return this.resolve(sessionId);
212
+ }
213
+ /**
214
+ * Resolve one ordinary Session from an already-retained exact observation.
215
+ * @param observation - Host-owned observation whose preparation stays pinned through setup.
216
+ * @returns the live Agent or a stable Session-domain failure.
217
+ */
218
+ async resolveObservedAgent(observation) {
219
+ return this.resolve(observation.header.id, observation);
220
+ }
221
+ async resolve(sessionId, observation) {
222
+ const live = this.liveAgent(sessionId);
223
+ if (live !== void 0) return live;
224
+ const attached = this.ctx.sessions.get(sessionId);
225
+ if (attached !== void 0 && hasApiSessionSubagentOwner(this.ctx, attached, void 0)) return { error: apiSessionSubagentOwnershipError(sessionId) };
226
+ let resume = this.resumes.get(sessionId);
227
+ if (resume === void 0) {
228
+ resume = this.resume(sessionId, observation).finally(() => {
229
+ this.resumes.delete(sessionId);
230
+ });
231
+ this.resumes.set(sessionId, resume);
232
+ }
233
+ try {
234
+ const agent = await resume;
235
+ return this.liveAgent(sessionId) ?? { agent };
236
+ } catch (error) {
237
+ if (error instanceof ApiSessionNotFound) return { error: new RemoteError("session/not-found", error.message, { sessionId }) };
238
+ if (error instanceof ApiSessionSubagentOwnership) return { error: apiSessionSubagentOwnershipError(error.sessionId) };
239
+ const raced = this.liveAgent(sessionId);
240
+ if (raced !== void 0) return raced;
241
+ const racedSession = this.ctx.sessions.get(sessionId);
242
+ if (racedSession !== void 0 && hasApiSessionSubagentOwner(this.ctx, racedSession, void 0)) return { error: apiSessionSubagentOwnershipError(sessionId) };
243
+ if (error instanceof Error && error.name === "SessionAlreadyOwnedError") return { error: new RemoteError("session/writer-held", error.message, { sessionId }) };
244
+ return { error: new RemoteError("gateway/internal", `resume failed for session "${sessionId}": ${String(error)}`, {}) };
245
+ }
246
+ }
247
+ /**
248
+ * Create a Session for a new conversation, reusing the named blank Session
249
+ * while it is still reusable. A reused Session runs the requested preset, or
250
+ * the configured default when the request names none; the preset it recorded
251
+ * is not resolved, and a change is logged as `agent-preset/selected` before
252
+ * the Agent is published. A named Session that has started a turn, fails the
253
+ * caller's placement rule, or is written by another owner stays unchanged,
254
+ * and a new Session is created instead. Requests naming one identity run in
255
+ * arrival order, including their preset resolution, and check the named
256
+ * Session's directory and ownership before resolving the preset.
257
+ * @param request - optional Session to reuse, directory, preset, and placement rule.
258
+ * @returns the reused or created Session and the preset it ran when this request finished.
259
+ * @throws ApiSessionCwdConflict when the named Session belongs to another directory.
260
+ * @throws ApiSessionSubagentOwnership when subagent routing owns the named Session.
261
+ * @throws RemoteError `agent-preset/not-found` or `agent-preset/invalid` for the requested or default preset.
262
+ * @throws ApiSessionPresetConflict when no roster is composed and the request names a preset for a reused Session.
263
+ */
264
+ async createSession(request) {
265
+ const named = request.sessionId;
266
+ if (named === void 0) return this.created(await this.createMinted(request.cwd, await this.composeAgent(request.agentPreset)));
267
+ return this.inOrder(named, async () => this.created(await this.claim(named, request)));
268
+ }
269
+ /**
270
+ * Install or return the Session-local model selection used by prompt assembly.
271
+ * @param agent - live Agent that owns the selection.
272
+ * @returns the installed mutable selection reference.
273
+ */
274
+ selectionFor(agent) {
275
+ const installed = this.selections.get(agent);
276
+ if (installed !== void 0) return installed;
277
+ const projectionState = this.ctx.sessionProjections.stateOf(agent.session, "modelSelection");
278
+ if (projectionState === void 0) throw new Error("api-session: required modelSelection projection is not registered");
279
+ let picked = projectionState.pending === null ? void 0 : agentModelSelection(projectionState.pending);
280
+ const defaultModel = this.ctx.agentDefaultModel;
281
+ const selection = {
282
+ get current() {
283
+ if (picked !== void 0) return picked;
284
+ const loggedHeader = agent.session.requestHeader();
285
+ if (loggedHeader === void 0) return defaultModel.currentSelection();
286
+ const logged = loggedHeader.config;
287
+ return {
288
+ provider: logged.provider,
289
+ model: logged.model,
290
+ ...logged.reasoningEffort === void 0 || loggedHeader.adapterDefaults?.reasoningEffort === true ? {} : { reasoningEffort: logged.reasoningEffort }
291
+ };
292
+ },
293
+ set current(next) {
294
+ picked = next;
295
+ },
296
+ consume(provider, model, reasoningEffort) {
297
+ if (picked?.provider !== provider || picked.model !== model || picked.reasoningEffort !== reasoningEffort) return false;
298
+ picked = void 0;
299
+ return true;
300
+ },
301
+ assembled: void 0
302
+ };
303
+ installModelSelection(agent.ctx, selection);
304
+ this.selections.set(agent, selection);
305
+ return selection;
306
+ }
307
+ /**
308
+ * Commit and cache one validated selection for the next prompt assembly.
309
+ * @param agent - live Agent that owns the selection.
310
+ * @param selection - validated selection to record and apply.
311
+ */
312
+ selectForNextRequest(agent, selection) {
313
+ agent.session.append("model/selection", selection);
314
+ this.selectionFor(agent).current = selection;
315
+ }
316
+ /**
317
+ * Let a matching durable request header retire the execution cache.
318
+ * @param agent - live Agent whose request was recorded.
319
+ * @param provider - provider route used by the request.
320
+ * @param model - provider-owned model used by the request.
321
+ * @param reasoningEffort - adapter-owned effort used by the request.
322
+ * @returns whether the pending selection was consumed.
323
+ */
324
+ consumeSelection(agent, provider, model, reasoningEffort) {
325
+ return this.selections.get(agent)?.consume(provider, model, reasoningEffort) ?? false;
326
+ }
327
+ /**
328
+ * Read the current Agent preset from the Session projection.
329
+ * @param session - live Session whose projection state is available.
330
+ * @returns the current preset, or undefined when the capability is absent.
331
+ */
332
+ presetForSession(session) {
333
+ return this.ctx.sessionProjections.stateOf(session, "agentPreset") ?? void 0;
334
+ }
335
+ /**
336
+ * Serialize image admission and model selection for one Agent.
337
+ * @param agent - live Agent that owns the serialization chain.
338
+ * @param operation - asynchronous operation admitted after prior work settles.
339
+ * @returns the operation result or rejection.
340
+ */
341
+ serializeImageAdmission(agent, operation) {
342
+ const result = (this.imageAdmissionChains.get(agent) ?? Promise.resolve()).then(operation);
343
+ this.imageAdmissionChains.set(agent, result.then(() => void 0, () => void 0));
344
+ return result;
345
+ }
346
+ /**
347
+ * Resolve the preset id and pre-publication Agent setup for a create or resume.
348
+ * @param presetId - requested preset or the configured default when omitted.
349
+ * @returns the resolved preset identity and Agent setup callback.
350
+ */
351
+ async composeAgent(presetId) {
352
+ const presets = this.ctx.get("agentPresets");
353
+ if (presets === void 0) return { setup: (_agentCtx, agent) => {
354
+ this.installSelection(agent);
355
+ } };
356
+ const resolvedId = (await presets.resolve(presetId)).id;
357
+ return {
358
+ agentPreset: resolvedId,
359
+ setup: async (agentCtx, agent) => {
360
+ this.installSelection(agent);
361
+ await presets.mount(agentCtx, resolvedId);
362
+ }
363
+ };
364
+ }
365
+ liveAgent(sessionId) {
366
+ const agent = this.ctx.agents.get(sessionId);
367
+ if (agent === void 0) return void 0;
368
+ return hasApiSessionSubagentOwner(this.ctx, agent.session, agent) ? { error: apiSessionSubagentOwnershipError(sessionId) } : { agent };
369
+ }
370
+ async resume(sessionId, supplied) {
371
+ if (supplied !== void 0) return this.resumeObserved(sessionId, supplied);
372
+ try {
373
+ const env_2 = {
374
+ stack: [],
375
+ error: void 0,
376
+ hasError: false
377
+ };
378
+ try {
379
+ const observation = __addDisposableResource$4(env_2, await this.ctx.sessionQuery.observeSession(sessionId), false);
380
+ return await this.resumeObserved(sessionId, observation);
381
+ } catch (e_2) {
382
+ env_2.error = e_2;
383
+ env_2.hasError = true;
384
+ } finally {
385
+ __disposeResources$4(env_2);
386
+ }
387
+ } catch (error) {
388
+ if (error instanceof SessionQueryError && error.code === "SESSION_QUERY_SESSION_NOT_FOUND") throw new ApiSessionNotFound(`session "${sessionId}" not found`);
389
+ throw error;
390
+ }
391
+ }
392
+ async resumeObserved(sessionId, observation) {
393
+ if (observation.header.id !== sessionId || observation.header.cwd === void 0) throw new ApiSessionNotFound(`session "${sessionId}" not found`);
394
+ if (hasApiSessionSubagentOwner(this.ctx, { header: observation.header }, void 0)) throw new ApiSessionSubagentOwnership(sessionId);
395
+ const composition = await this.composeAgent(this.presetForObservation(observation));
396
+ const published = this.ctx.sessions.get(sessionId);
397
+ const live = this.ctx.agents.get(sessionId);
398
+ if (published !== void 0 && hasApiSessionSubagentOwner(this.ctx, published, live)) throw new ApiSessionSubagentOwnership(sessionId);
399
+ return (await this.ctx.agents.resume({
400
+ resumeSessionId: sessionId,
401
+ agentOptions: this.agentOptions(),
402
+ setup: composition.setup
403
+ })).agent;
404
+ }
405
+ async inOrder(sessionId, operation) {
406
+ const result = (this.claims.get(sessionId) ?? Promise.resolve()).then(operation);
407
+ const settled = result.then(() => void 0, () => void 0);
408
+ this.claims.set(sessionId, settled);
409
+ try {
410
+ return await result;
411
+ } finally {
412
+ if (this.claims.get(sessionId) === settled) this.claims.delete(sessionId);
413
+ }
414
+ }
415
+ /** @returns the reused Session, a new Session under `sessionId` when none is stored, or a new Session under a minted identity. */
416
+ async claim(sessionId, request) {
417
+ const attached = this.ctx.sessions.get(sessionId);
418
+ const live = this.ctx.agents.get(sessionId);
419
+ if (attached !== void 0 && hasApiSessionSubagentOwner(this.ctx, attached, live)) throw new ApiSessionSubagentOwnership(sessionId);
420
+ if (live !== void 0) {
421
+ if (live.session.header.cwd !== request.cwd) throw new ApiSessionCwdConflict(live.id, request.cwd, live.session.header.cwd);
422
+ const composition = await this.composeAgent(request.agentPreset);
423
+ return await this.reuseLive(live, request, composition) ?? this.createMinted(request.cwd, composition);
424
+ }
425
+ let observation;
426
+ try {
427
+ observation = await this.ctx.sessionQuery.observeSession(sessionId);
428
+ } catch (error) {
429
+ if (!(error instanceof SessionQueryError) || error.code !== "SESSION_QUERY_SESSION_NOT_FOUND") throw error;
430
+ return this.createAgent(sessionId, request.cwd, await this.composeAgent(request.agentPreset));
431
+ }
432
+ let reusable;
433
+ {
434
+ const env_3 = {
435
+ stack: [],
436
+ error: void 0,
437
+ hasError: false
438
+ };
439
+ try {
440
+ const observed = __addDisposableResource$4(env_3, observation, false);
441
+ if (hasApiSessionSubagentOwner(this.ctx, { header: observed.header }, void 0)) throw new ApiSessionSubagentOwnership(sessionId);
442
+ if (observed.header.cwd !== request.cwd) throw new ApiSessionCwdConflict(sessionId, request.cwd, observed.header.cwd);
443
+ reusable = request.reusable(sessionId) && !observed.events.some((event) => event.type === "turn/start");
444
+ } catch (e_3) {
445
+ env_3.error = e_3;
446
+ env_3.hasError = true;
447
+ } finally {
448
+ __disposeResources$4(env_3);
449
+ }
450
+ }
451
+ const composition = await this.composeAgent(request.agentPreset);
452
+ if (!reusable) return this.createMinted(request.cwd, composition);
453
+ this.assertPresetApplicable(sessionId, request.agentPreset);
454
+ try {
455
+ return (await this.ctx.agents.resume({
456
+ resumeSessionId: sessionId,
457
+ agentOptions: this.agentOptions(),
458
+ setup: this.reuseSetup(composition)
459
+ })).agent;
460
+ } catch (error) {
461
+ if (error instanceof ApiSessionStartedSinceObserved) return this.createMinted(request.cwd, composition);
462
+ if (!(error instanceof Error) || error.name !== "SessionAlreadyOwnedError") throw error;
463
+ return this.ctx.agents.get(sessionId) === void 0 ? this.createMinted(request.cwd, composition) : this.claim(sessionId, request);
464
+ }
465
+ }
466
+ /** @returns the live blank Session under the requested preset, or undefined when it cannot be reused. */
467
+ async reuseLive(live, request, composition) {
468
+ if (!request.reusable(live.id) || !this.isBlank(live.session)) return void 0;
469
+ this.assertPresetApplicable(live.id, request.agentPreset);
470
+ const current = this.presetForSession(live.session);
471
+ const presets = this.ctx.get("agentPresets");
472
+ const target = composition.agentPreset;
473
+ if (presets === void 0 || target === void 0 || target === current) return live;
474
+ try {
475
+ await presets.select(live, target);
476
+ } catch (error) {
477
+ if (remoteErrorOf(error)?.code !== "agent-preset/locked") throw error;
478
+ return;
479
+ }
480
+ return live;
481
+ }
482
+ /** Setup that re-checks blankness under the acquired writer, then records a preset change before publication. */
483
+ reuseSetup(composition) {
484
+ return async (agentCtx, agent) => {
485
+ if (!this.isBlank(agent.session)) throw new ApiSessionStartedSinceObserved();
486
+ const commit = await composition.setup(agentCtx, agent);
487
+ const target = composition.agentPreset;
488
+ if (target !== void 0 && this.presetForSession(agent.session) !== target) agent.session.append("agent-preset/selected", { agentPreset: target });
489
+ return commit;
490
+ };
491
+ }
492
+ /** Whether no turn has started, by the predicate the preset registry's `select` enforces. */
493
+ isBlank(session) {
494
+ const boundary = this.ctx.sessionProjections.stateOf(session, "turnBoundary");
495
+ return boundary === void 0 || boundary.openTurnStartSeq === null && boundary.lastTurn === 0;
496
+ }
497
+ /** Without a roster, reuse cannot apply a named preset. */
498
+ assertPresetApplicable(sessionId, requested) {
499
+ if (requested === void 0 || this.ctx.get("agentPresets") !== void 0) return;
500
+ throw new ApiSessionPresetConflict(sessionId, requested);
501
+ }
502
+ created(agent) {
503
+ return {
504
+ agent,
505
+ agentPreset: this.presetForSession(agent.session)
506
+ };
507
+ }
508
+ createMinted(cwd, composition) {
509
+ return this.createAgent(brandString(`session-${randomUUID()}`), cwd, composition);
510
+ }
511
+ async createAgent(sessionId, cwd, composition) {
512
+ try {
513
+ await mkdir(cwd, { recursive: true });
514
+ } catch (error) {
515
+ throw new Error(`failed to ensure project directory "${cwd}": ${String(error)}`, { cause: error });
516
+ }
517
+ return (await this.ctx.agents.create({
518
+ sessionId,
519
+ agentOptions: this.agentOptions(),
520
+ meta: {
521
+ cwd,
522
+ ...composition.agentPreset === void 0 ? {} : { agentPreset: composition.agentPreset }
523
+ },
524
+ setup: composition.setup
525
+ })).agent;
526
+ }
527
+ agentOptions() {
528
+ const { provider, model } = this.ctx.agentDefaultModel.currentSelection();
529
+ return {
530
+ provider,
531
+ model
532
+ };
533
+ }
534
+ installSelection(agent) {
535
+ this.selectionFor(agent);
536
+ }
537
+ /**
538
+ * Read the current Agent preset from an all-projections observation.
539
+ * @param observation - exact Session observation carrying its projection snapshot.
540
+ * @returns the current preset, or undefined when the capability is absent.
541
+ */
542
+ presetForObservation(observation) {
543
+ if (observation.projections === void 0) throw new Error("api-session: Agent activation requires a projected Session observation");
544
+ return observation.projections.values.agentPreset ?? void 0;
545
+ }
546
+ };
547
+ function agentModelSelection(selection) {
548
+ return {
549
+ provider: selection.provider,
550
+ model: selection.model,
551
+ ...selection.reasoningEffort === void 0 ? {} : { reasoningEffort: ReasoningEffortId(selection.reasoningEffort) }
552
+ };
553
+ }
554
+ //#endregion
555
+ //#region lib/types/catalog.js
556
+ /** Shared projection of the live LLM registry into the browser model catalog. */
557
+ /**
558
+ * Build the browser model catalog without requiring a Session.
559
+ * @param ctx - Host context carrying the live LLM registry.
560
+ * @param defaultSelection - deployment default used before a Session selects a model.
561
+ * @returns successful non-empty provider groups and isolated provider failures.
562
+ */
563
+ async function buildModelCatalog(ctx, defaultSelection = ctx.agentDefaultModel.currentSelection()) {
564
+ const providers = ctx.llm.listProviders();
565
+ const catalog = await Promise.all(providers.map(async (provider) => {
566
+ try {
567
+ const models = await ctx.llm.listModels(provider.id);
568
+ const entries = await Promise.all(models.map(async (model) => {
569
+ const resolved = await ctx.llm.resolveModelInfo(provider.id, model.id);
570
+ const reasoning = resolved.reasoning === void 0 ? void 0 : {
571
+ efforts: resolved.reasoning.efforts.map((effort) => ({
572
+ id: effort.id,
573
+ name: effort.name,
574
+ ...effort.description === void 0 ? {} : { description: effort.description }
575
+ })),
576
+ ...resolved.reasoning.defaultEffort === void 0 ? {} : { defaultEffort: resolved.reasoning.defaultEffort }
577
+ };
578
+ return {
579
+ id: model.id,
580
+ name: model.name,
581
+ ...model.description === void 0 ? {} : { description: model.description },
582
+ ...reasoning === void 0 ? {} : { reasoning }
583
+ };
584
+ }));
585
+ return {
586
+ kind: "group",
587
+ group: {
588
+ id: provider.id,
589
+ name: provider.name,
590
+ models: entries
591
+ }
592
+ };
593
+ } catch (error) {
594
+ return {
595
+ kind: "failure",
596
+ failure: {
597
+ id: provider.id,
598
+ name: provider.name,
599
+ message: error instanceof Error ? error.message : String(error)
600
+ }
601
+ };
602
+ }
603
+ }));
604
+ const groups = catalog.flatMap((item) => item.kind === "group" ? [item.group] : []).filter((group) => group.models.length > 0);
605
+ return {
606
+ default: { ...defaultSelection },
607
+ routableProviders: groups.map((group) => group.id),
608
+ groups,
609
+ failures: catalog.flatMap((item) => item.kind === "failure" ? [item.failure] : [])
610
+ };
611
+ }
612
+ /**
613
+ * Check a GUI selection against the current available provider catalog.
614
+ * @param ctx - Host LLM registry.
615
+ * @param selection - stored or explicitly requested selection.
616
+ * @returns whether the exact model is currently advertised as available.
617
+ */
618
+ async function modelAvailable(ctx, selection) {
619
+ if (!ctx.llm.listProviders().some((provider) => provider.id === selection.provider)) return false;
620
+ let models;
621
+ try {
622
+ models = await ctx.llm.listModels(selection.provider);
623
+ } catch (error) {
624
+ throw new RemoteError("session/model-unavailable", error instanceof Error ? error.message : String(error), {
625
+ provider: selection.provider,
626
+ model: selection.model
627
+ });
628
+ }
629
+ return models.some((model) => model.id === selection.model);
630
+ }
631
+ /**
632
+ * Check configured provider API-key references independently of model availability.
633
+ * @param ctx - Host registry, settings, and credential services.
634
+ * @returns whether any API-key provider has a configured credential.
635
+ */
636
+ async function hasProviderApiKey(ctx) {
637
+ const settings = ctx.get("settings");
638
+ const credentials = ctx.get("credentials");
639
+ if (settings === void 0 || credentials === void 0) throw new RemoteError("session/provider-credentials-unavailable", "provider credentials are unavailable", {});
640
+ const namespaces = settings.describe({ redactSecrets: true });
641
+ for (const provider of ctx.llm.listConfigurableProviders()) {
642
+ if (provider.provider === "deepseek-account") continue;
643
+ let profile = namespaces.find((namespace) => namespace.ns === provider.settingsNs)?.value;
644
+ for (const key of provider.settingsPath) profile = typeof profile === "object" && profile !== null ? Reflect.get(profile, key) : void 0;
645
+ if (typeof profile !== "object" || profile === null) continue;
646
+ const ref = Reflect.get(profile, "apiKeyEnv");
647
+ if (typeof ref === "string" && ref.length > 0 && (await credentials.describe(credentialRef(ref))).configured) return true;
648
+ }
649
+ return false;
650
+ }
651
+ //#endregion
652
+ //#region lib/types/commands.js
653
+ /** Session commands whose activation policy is explicit at each Remote method. */
654
+ var __addDisposableResource$3 = function(env, value, async) {
655
+ if (value !== null && value !== void 0) {
656
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
657
+ var dispose, inner;
658
+ if (async) {
659
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
660
+ dispose = value[Symbol.asyncDispose];
661
+ }
662
+ if (dispose === void 0) {
663
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
664
+ dispose = value[Symbol.dispose];
665
+ if (async) inner = dispose;
666
+ }
667
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
668
+ if (inner) dispose = function() {
669
+ try {
670
+ inner.call(this);
671
+ } catch (e) {
672
+ return Promise.reject(e);
673
+ }
674
+ };
675
+ env.stack.push({
676
+ value,
677
+ dispose,
678
+ async
679
+ });
680
+ } else if (async) env.stack.push({ async: true });
681
+ return value;
682
+ };
683
+ var __disposeResources$3 = (function(SuppressedError) {
684
+ return function(env) {
685
+ function fail(e) {
686
+ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
687
+ env.hasError = true;
688
+ }
689
+ var r, s = 0;
690
+ function next() {
691
+ while (r = env.stack.pop()) try {
692
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
693
+ if (r.dispose) {
694
+ var result = r.dispose.call(r.value);
695
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
696
+ fail(e);
697
+ return next();
698
+ });
699
+ } else s |= 1;
700
+ } catch (e) {
701
+ fail(e);
702
+ }
703
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
704
+ if (env.hasError) throw env.error;
705
+ }
706
+ return next();
707
+ };
708
+ })(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
709
+ var e = new Error(message);
710
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
711
+ });
712
+ /**
713
+ * Whether prompt content carries non-whitespace text or an attachment.
714
+ * @param content - submitted or edited prompt parts.
715
+ * @returns false for content the Agent must not receive.
716
+ */
717
+ function hasPromptContent(content) {
718
+ return content.some((part) => part.type !== "text" || part.text.trim().length > 0);
719
+ }
720
+ /**
721
+ * Resolve the omitted-`atSeq` default to the latest completed-turn prefix,
722
+ * including standalone events before the next turn begins.
723
+ */
724
+ function latestCompletedPrefixBoundary(events) {
725
+ const lastTurnEnd = events.findLast((event) => event.type === "turn/end");
726
+ if (lastTurnEnd === void 0) return void 0;
727
+ let boundary = lastTurnEnd.seq;
728
+ for (const next of events.slice(boundary + 1)) {
729
+ if (next.type === "turn/start" || next.type === "user/message" && next.surfaceOp === "append" || next.type === "agent/inbox/spliced") break;
730
+ boundary = next.seq;
731
+ }
732
+ return boundary;
733
+ }
734
+ /** Implements Session business commands delegated by the Session Controller Remote service. */
735
+ var SessionCommandController = class {
736
+ ctx;
737
+ agents;
738
+ defaultCwd;
739
+ /**
740
+ * @param ctx - Host context carrying Agent, model, attachment, title, and Workspace services.
741
+ * @param agents - sole owner of create, resume, and Session-local model selection.
742
+ * @param defaultCwd - project directory used when create names neither a Workspace nor a cwd.
743
+ */
744
+ constructor(ctx, agents, defaultCwd) {
745
+ this.ctx = ctx;
746
+ this.agents = agents;
747
+ this.defaultCwd = defaultCwd;
748
+ }
749
+ /**
750
+ * Create one ordinary Session for a new conversation, reusing the named
751
+ * blank Session while it is an unarchived member of the requested Workspace.
752
+ * @param request - optional blank Session to reuse, location, and Agent preset.
753
+ * @returns the created or reused Session identity and its preset when configured.
754
+ */
755
+ async create(request) {
756
+ if (request.workspaceId !== void 0 && request.cwd !== void 0) throw new RemoteError("gateway/bad-request", "session.create accepts workspaceId or cwd, not both", {});
757
+ let workspace;
758
+ if (request.workspaceId !== void 0) {
759
+ workspace = this.ctx.workspaceRegistry.get(request.workspaceId);
760
+ if (workspace === void 0) throw new RemoteError("workspace/not-found", `workspace "${request.workspaceId}" not found`, { workspaceId: request.workspaceId });
761
+ }
762
+ const cwd = workspace?.path ?? request.cwd ?? this.defaultCwd;
763
+ let created;
764
+ try {
765
+ created = await this.agents.createSession({
766
+ ...request.sessionId === void 0 ? {} : { sessionId: request.sessionId },
767
+ cwd,
768
+ ...request.agentPreset === void 0 ? {} : { agentPreset: request.agentPreset },
769
+ reusable: (sessionId) => !this.ctx.workspaceRegistry.archivedSessionIds.includes(sessionId) && (workspace === void 0 || workspace.sessionIds.includes(sessionId))
770
+ });
771
+ } catch (error) {
772
+ this.rejectCreation(error);
773
+ }
774
+ const sessionId = created.agent.id;
775
+ if (workspace !== void 0) try {
776
+ await workspace.attachSession(sessionId);
777
+ } catch (error) {
778
+ throw new RemoteError("session/workspace-attach-failed", `session "${sessionId}" was created but could not attach to workspace "${workspace.id}": ${String(error)}`, {
779
+ sessionId,
780
+ workspaceId: workspace.id
781
+ });
782
+ }
783
+ return {
784
+ sessionId,
785
+ ...created.agentPreset === void 0 ? {} : { agentPreset: created.agentPreset }
786
+ };
787
+ }
788
+ /**
789
+ * Validate and install one Session-local model selection; save the default in the background.
790
+ * @param request - Session identity and requested model selection.
791
+ * @returns the normalized selection installed for the Session, without waiting for default persistence.
792
+ */
793
+ async selectModel(request) {
794
+ const agent = await this.resolveAgent(request.sessionId);
795
+ return this.agents.serializeImageAdmission(agent, async () => {
796
+ try {
797
+ await this.requireModel(request);
798
+ const resolved = await this.ctx.llm.resolveCallConfig({
799
+ provider: request.provider,
800
+ model: request.model,
801
+ ...request.reasoningEffort === void 0 ? {} : { reasoningEffort: ReasoningEffortId(request.reasoningEffort) }
802
+ });
803
+ const selected = {
804
+ provider: resolved.provider,
805
+ model: resolved.model,
806
+ ...resolved.reasoningEffort === void 0 ? {} : { reasoningEffort: resolved.reasoningEffort }
807
+ };
808
+ this.agents.selectForNextRequest(agent, selected);
809
+ this.ctx.agentDefaultModel.saveSelection(selected).catch((error) => {
810
+ this.ctx.logger.warn(`session-controller: model selection changed for the Session but the default was not saved: ${String(error)}`);
811
+ });
812
+ return { selected: { ...selected } };
813
+ } catch (error) {
814
+ if (remoteErrorOf(error) !== void 0) throw error;
815
+ throw new RemoteError("session/model-unavailable", error instanceof Error ? error.message : String(error), {
816
+ provider: request.provider,
817
+ model: request.model
818
+ });
819
+ }
820
+ });
821
+ }
822
+ /**
823
+ * Normalize and append a user-owned Session title.
824
+ * @param request - Session identity and proposed title.
825
+ * @returns the accepted title and durable event sequence.
826
+ */
827
+ async rename(request) {
828
+ const agent = await this.resolveAgent(request.sessionId);
829
+ const titles = this.ctx.get("sessionTitle");
830
+ if (titles === void 0) throw new RemoteError("gateway/internal", "renaming is unavailable: this deployment mounts no session-title service", {});
831
+ try {
832
+ const accepted = titles.rename(agent.session, request.title);
833
+ return {
834
+ title: accepted.title,
835
+ seq: accepted.eventSeq
836
+ };
837
+ } catch (error) {
838
+ if (error instanceof SessionTitleInvalidError) throw new RemoteError("session/title-invalid", error.message, { sessionId: request.sessionId });
839
+ throw new RemoteError("gateway/internal", `failed to rename session "${request.sessionId}": ${String(error)}`, {});
840
+ }
841
+ }
842
+ /**
843
+ * Create a new ordinary Session from an exact event prefix. An explicit
844
+ * `atSeq` is the inclusive cut; an omitted value selects the latest
845
+ * completed-turn prefix. An open cut receives synthetic fork closers.
846
+ * @param request - source Session and optional exact event boundary.
847
+ * @returns the new Session identity.
848
+ */
849
+ async fork(request) {
850
+ const env_1 = {
851
+ stack: [],
852
+ error: void 0,
853
+ hasError: false
854
+ };
855
+ try {
856
+ let atSeq;
857
+ try {
858
+ atSeq = request.atSeq === void 0 ? void 0 : SessionSeq(request.atSeq);
859
+ } catch {
860
+ throw new RemoteError("gateway/bad-request", "atSeq must be a non-negative safe integer", {});
861
+ }
862
+ let observed;
863
+ try {
864
+ observed = await this.ctx.sessionQuery.observeSession(request.sessionId);
865
+ } catch (error) {
866
+ 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 });
867
+ throw new RemoteError("gateway/internal", `fork source unavailable for session "${request.sessionId}": ${String(error)}`, {});
868
+ }
869
+ const source = __addDisposableResource$3(env_1, observed, false);
870
+ const boundary = atSeq ?? latestCompletedPrefixBoundary(source.events);
871
+ 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 });
872
+ const seed = buildForkSeed(source.events, boundary);
873
+ let workspace;
874
+ try {
875
+ workspace = await this.forkWorkspace(source.header);
876
+ } catch (error) {
877
+ throw new RemoteError("gateway/internal", `failed to resolve fork workspace for session "${request.sessionId}": ${String(error)}`, {});
878
+ }
879
+ const childId = brandString(`session-${randomUUID()}`);
880
+ const composition = await this.agents.composeAgent(this.agents.presetForObservation(source));
881
+ try {
882
+ const { provider, model } = this.ctx.agentDefaultModel.currentSelection();
883
+ await this.ctx.agents.create({
884
+ sessionId: childId,
885
+ seed,
886
+ inheritedEventCount: SessionLogOffset(boundary + 1),
887
+ meta: {
888
+ ...source.header.cwd === void 0 ? {} : { cwd: source.header.cwd },
889
+ parentSession: source.header.id,
890
+ isSeeded: true,
891
+ ...composition.agentPreset === void 0 ? {} : { agentPreset: composition.agentPreset }
892
+ },
893
+ agentOptions: {
894
+ provider,
895
+ model
896
+ },
897
+ setup: composition.setup
898
+ });
899
+ } catch (error) {
900
+ throw new RemoteError("gateway/internal", `failed to fork session "${request.sessionId}": ${String(error)}`, {});
901
+ }
902
+ if (workspace !== void 0) try {
903
+ await workspace.attachSession(childId);
904
+ } catch (error) {
905
+ throw new RemoteError("session/workspace-attach-failed", `session "${childId}" was forked but could not attach to workspace "${workspace.id}": ${String(error)}`, {
906
+ sessionId: childId,
907
+ workspaceId: workspace.id
908
+ });
909
+ }
910
+ return { sessionId: childId };
911
+ } catch (e_1) {
912
+ env_1.error = e_1;
913
+ env_1.hasError = true;
914
+ } finally {
915
+ __disposeResources$3(env_1);
916
+ }
917
+ }
918
+ /**
919
+ * Admit one prompt after Agent and attachment validation; the Remote method
920
+ * has already validated the content and built the durable message source.
921
+ * @param request - Session identity, prompt content, and delivery mode.
922
+ * @param source - the `user-rpc` source recorded on the accepted message.
923
+ * @returns acknowledgement that the Agent accepted the prompt.
924
+ */
925
+ async prompt(request, source) {
926
+ const agent = await this.resolveAgent(request.sessionId);
927
+ if (hasPromptRequest(agent, request.requestId)) return { accepted: true };
928
+ const hasImage = request.content.some((part) => part.type === "image");
929
+ const admit = async () => {
930
+ try {
931
+ const env_2 = {
932
+ stack: [],
933
+ error: void 0,
934
+ hasError: false
935
+ };
936
+ try {
937
+ if (hasImage) {
938
+ const current = this.agents.selectionFor(agent).current;
939
+ const model = await this.ctx.llm.resolveModelInfo(current.provider, current.model);
940
+ 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" });
941
+ }
942
+ const admission = resolvePromptFileReceipts(request.content, (receiptId) => this.ctx.fileUploads.resolve(agent, receiptId));
943
+ const message = createUserMessage({
944
+ content: await this.ctx.attachments.admitPromptContent(admission.content),
945
+ source
946
+ });
947
+ 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 });
948
+ const binding = __addDisposableResource$3(env_2, this.ctx.fileUploads.bindPrompt(agent, admission.receiptIds, request.requestId), false);
949
+ if (request.mode === "steer") agent.steer(message);
950
+ else agent.followup(message);
951
+ binding.commit();
952
+ } catch (e_2) {
953
+ env_2.error = e_2;
954
+ env_2.hasError = true;
955
+ } finally {
956
+ __disposeResources$3(env_2);
957
+ }
958
+ } catch (error) {
959
+ if (remoteErrorOf(error) !== void 0) throw error;
960
+ if (error instanceof AttachmentError) throw new RemoteError("session/attachment-invalid", error.message, { reason: error.code });
961
+ throw new RemoteError("session/agent-busy", "prompt rejected", { reason: String(error) });
962
+ }
963
+ return { accepted: true };
964
+ };
965
+ return hasImage ? this.agents.serializeImageAdmission(agent, admit) : admit();
966
+ }
967
+ async requireModel(selection) {
968
+ if (!await modelAvailable(this.ctx, selection)) throw new RemoteError("session/model-unavailable", "Select an available model before sending a message.", {
969
+ provider: selection.provider,
970
+ model: selection.model
971
+ });
972
+ }
973
+ /**
974
+ * Read one durable image after proving the Session log references it.
975
+ * @param request - Session and attachment identities used for authorization.
976
+ * @returns the durable attachment reference and base64-encoded bytes.
977
+ */
978
+ async attachment(request) {
979
+ let source;
980
+ try {
981
+ source = await this.readSessionState(request.sessionId);
982
+ } catch (error) {
983
+ if (error instanceof ApiSessionNotFound) throw new RemoteError("session/not-found", error.message, { sessionId: request.sessionId });
984
+ throw new RemoteError("gateway/internal", `attachment authorization unavailable for session "${request.sessionId}": ${String(error)}`, {});
985
+ }
986
+ const ref = referencedImage(source.events, String(request.attachmentId));
987
+ if (ref === void 0) throw new RemoteError("session/attachment-invalid", "Image is not referenced by this session.", { reason: "ATTACHMENT_NOT_REFERENCED" });
988
+ try {
989
+ const stored = await this.ctx.attachments.readImage(ref);
990
+ return {
991
+ attachment: stored.ref,
992
+ data: Buffer.from(stored.data).toString("base64")
993
+ };
994
+ } catch (error) {
995
+ if (error instanceof AttachmentError) throw new RemoteError("session/attachment-invalid", error.message, { reason: error.code });
996
+ throw new RemoteError("gateway/internal", "Unable to read image attachment.", {});
997
+ }
998
+ }
999
+ /**
1000
+ * Mutate one pending Inbox occurrence, restoring an ordinary cold Agent when needed.
1001
+ * @param request - Session, queue item, and requested mutation.
1002
+ * @returns acknowledgement that the queue mutation was applied.
1003
+ */
1004
+ async updateQueue(request) {
1005
+ if (request.action.kind === "edit") {
1006
+ 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" });
1007
+ if (!hasPromptContent(request.action.content)) throw new RemoteError("gateway/bad-request", "queue edit content must include non-whitespace text", {});
1008
+ }
1009
+ let agent = this.ctx.agents.get(request.sessionId);
1010
+ if (agent === void 0) {
1011
+ const found = await this.agents.resolveAgent(request.sessionId);
1012
+ if ("error" in found) {
1013
+ if (found.error.code !== "session/not-found") throw found.error;
1014
+ throw new RemoteError("session/queue-item-not-found", "queued item is no longer pending", { itemId: request.itemId });
1015
+ }
1016
+ agent = found.agent;
1017
+ }
1018
+ if (hasApiSessionSubagentOwner(this.ctx, agent.session, agent)) {
1019
+ const identity = this.ctx.sessionProjections.snapshot(agent.session, ["subagent"]).values.subagent;
1020
+ if (identity?.mode !== "continuable" || !agent.session.isOwnSeq(identity.seq)) throw apiSessionSubagentOwnershipError(request.sessionId);
1021
+ }
1022
+ const nextTurn = agent.inbox.nextTurn.find((message) => message.id === request.itemId);
1023
+ const nextStep = agent.inbox.nextStep.find((message) => message.id === request.itemId);
1024
+ const located = nextTurn === void 0 ? nextStep === void 0 ? void 0 : {
1025
+ target: "next-step",
1026
+ message: nextStep
1027
+ } : {
1028
+ target: "next-turn",
1029
+ message: nextTurn
1030
+ };
1031
+ if (located === void 0) throw new RemoteError("session/queue-item-not-found", "queued item is no longer pending", { itemId: request.itemId });
1032
+ const { target, message } = located;
1033
+ 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 });
1034
+ switch (request.action.kind) {
1035
+ case "edit":
1036
+ agent.inbox.replace(request.itemId, freezeMessage({
1037
+ ...message,
1038
+ content: [...request.action.content]
1039
+ }));
1040
+ break;
1041
+ case "remove": {
1042
+ agent.inbox.remove(request.itemId);
1043
+ const source = message.source;
1044
+ if (source.kind === "user" && "rpcId" in source) this.ctx.fileUploads.retirePrompt(agent, source.rpcId);
1045
+ break;
1046
+ }
1047
+ case "steer":
1048
+ agent.inbox.remove(request.itemId);
1049
+ agent.steer(message);
1050
+ break;
1051
+ /* v8 ignore next 2 -- closed-union exhaustiveness guard */
1052
+ default: assertNever(request.action, "queue action");
1053
+ }
1054
+ return { accepted: true };
1055
+ }
1056
+ /**
1057
+ * Cancel one live ordinary Agent while retaining pending inbox work.
1058
+ * @param request - Session whose active Agent turn is cancelled.
1059
+ * @returns acknowledgement that cancellation was requested.
1060
+ */
1061
+ cancel(request) {
1062
+ const agent = this.ctx.agents.get(request.sessionId);
1063
+ if (agent === void 0) throw new RemoteError("session/not-found", `session "${request.sessionId}" not found (not attached)`, { sessionId: request.sessionId });
1064
+ if (hasApiSessionSubagentOwner(this.ctx, agent.session, agent)) throw apiSessionSubagentOwnershipError(request.sessionId);
1065
+ agent.cancel({ kind: "user" }, { keepInbox: true });
1066
+ return { accepted: true };
1067
+ }
1068
+ async resolveAgent(sessionId) {
1069
+ const found = await this.agents.resolveAgent(sessionId);
1070
+ if ("error" in found) throw found.error;
1071
+ return found.agent;
1072
+ }
1073
+ rejectCreation(error) {
1074
+ if (remoteErrorOf(error) !== void 0) throw error;
1075
+ if (error instanceof ApiSessionPresetConflict) throw new RemoteError("agent-preset/conflict", error.message, {
1076
+ sessionId: error.sessionId,
1077
+ requestedPreset: error.requestedPreset
1078
+ });
1079
+ if (error instanceof ApiSessionCwdConflict) throw new RemoteError("session/conflict", error.message, {
1080
+ sessionId: error.sessionId,
1081
+ requestedCwd: error.requestedCwd,
1082
+ ...error.existingCwd === void 0 ? {} : { existingCwd: error.existingCwd }
1083
+ });
1084
+ if (error instanceof ApiSessionSubagentOwnership) throw apiSessionSubagentOwnershipError(error.sessionId);
1085
+ throw new RemoteError("gateway/internal", `failed to create session: ${String(error)}`, {});
1086
+ }
1087
+ async readSessionState(sessionId) {
1088
+ const attached = this.ctx.sessions.get(sessionId);
1089
+ if (attached !== void 0) return {
1090
+ id: attached.id,
1091
+ header: attached.header,
1092
+ events: attached.snapshotEvents()
1093
+ };
1094
+ const inspected = await inspectApiSession(this.ctx, sessionId);
1095
+ return {
1096
+ id: inspected.meta.id,
1097
+ header: inspected.meta,
1098
+ events: inspected.events
1099
+ };
1100
+ }
1101
+ async forkWorkspace(source) {
1102
+ const workspaces = this.ctx.workspaceRegistry.list();
1103
+ const direct = workspaces.find((workspace) => workspace.sessionIds.includes(source.id));
1104
+ if (direct !== void 0 || source.origin !== "subagent") return direct;
1105
+ const lineage = await this.ctx.sessionQuery.traceSession(source.id);
1106
+ for (const ancestor of lineage.ancestors) {
1107
+ const workspace = workspaces.find((candidate) => candidate.sessionIds.includes(ancestor.header.id));
1108
+ if (workspace !== void 0) return workspace;
1109
+ }
1110
+ }
1111
+ };
1112
+ function resolvePromptFileReceipts(content, stagedFile) {
1113
+ const receiptIds = /* @__PURE__ */ new Set();
1114
+ return {
1115
+ content: content.map((part) => {
1116
+ if (part.type !== "file") return part;
1117
+ const attachment = stagedFile(part.receiptId);
1118
+ if (attachment === void 0) throw new RemoteError("session/attachment-invalid", "File was not uploaded for this session.", { reason: "FILE_NOT_STAGED" });
1119
+ receiptIds.add(part.receiptId);
1120
+ return {
1121
+ type: "file",
1122
+ attachment
1123
+ };
1124
+ }),
1125
+ receiptIds: [...receiptIds]
1126
+ };
1127
+ }
1128
+ function hasPromptRequest(agent, requestId) {
1129
+ const matches = (message) => {
1130
+ const source = message.source;
1131
+ return source.kind === "user" && "rpcId" in source && source.rpcId === requestId;
1132
+ };
1133
+ if (agent.inbox.nextTurn.some(matches) || agent.inbox.nextStep.some(matches)) return true;
1134
+ return agent.session.snapshotEvents().some((event) => {
1135
+ if (event.type !== "user/message") return false;
1136
+ const source = event.data.source;
1137
+ return source.kind === "user" && "rpcId" in source && source.rpcId === requestId;
1138
+ });
1139
+ }
1140
+ function imageBlockIn(content, match) {
1141
+ if (!Array.isArray(content)) return void 0;
1142
+ for (const value of content) {
1143
+ if (typeof value !== "object" || value === null || Array.isArray(value)) continue;
1144
+ const block = value;
1145
+ if (block.type === "image" && typeof block.attachment === "object" && block.attachment !== null) {
1146
+ const ref = block.attachment;
1147
+ if (match(ref)) return ref;
1148
+ }
1149
+ }
1150
+ }
1151
+ /** Read only first-party declared content fields; unknown event payloads stay opaque. */
1152
+ function imageInEvent(event, match) {
1153
+ const data = event.data;
1154
+ switch (event.type) {
1155
+ case "user/message":
1156
+ case "tool/ptc-dispatch": return imageBlockIn(data.content, match);
1157
+ case "system/message":
1158
+ case "developer/message":
1159
+ case "tool/result":
1160
+ case "team/message/queued": return imageBlockIn(data.message?.content, match);
1161
+ case "agent/inbox/spliced": {
1162
+ const messages = data.inserted;
1163
+ if (!Array.isArray(messages)) return void 0;
1164
+ for (const message of messages) {
1165
+ if (typeof message !== "object" || message === null || Array.isArray(message)) continue;
1166
+ const found = imageBlockIn(message.content, match);
1167
+ if (found !== void 0) return found;
1168
+ }
1169
+ return;
1170
+ }
1171
+ case "compaction/summary": return imageBlockIn(data.summary, match) ?? imageBlockIn(data.rawOutput, match);
1172
+ case "assistant/message": {
1173
+ const found = imageBlockIn(data.message?.content, match);
1174
+ if (found !== void 0) return found;
1175
+ break;
1176
+ }
1177
+ case "assistant/attempt": break;
1178
+ default: return;
1179
+ }
1180
+ const assistant = event;
1181
+ for (const chunk of assistantStreamChunks(assistant.data.stream, "block-end")) {
1182
+ const found = imageBlockIn([chunk.block], match);
1183
+ if (found !== void 0) return found;
1184
+ }
1185
+ }
1186
+ function referencedImage(events, attachmentId) {
1187
+ for (const event of events) {
1188
+ const found = imageInEvent(event, (ref) => String(ref.attachmentId) === attachmentId);
1189
+ if (found !== void 0) return found;
1190
+ }
1191
+ }
1192
+ //#endregion
1193
+ //#region lib/types/control.js
1194
+ /** Live Session projection state with reconnect baselines. */
1195
+ /** Owns the Host-wide Session control stream. */
1196
+ var SessionControlController = class {
1197
+ ctx;
1198
+ streams = /* @__PURE__ */ new Set();
1199
+ /** @param ctx - Host context carrying live Agent and projection services. */
1200
+ constructor(ctx) {
1201
+ this.ctx = ctx;
1202
+ ctx.sessionProjections.onChanged((session, key, value, seq) => {
1203
+ this.broadcast({
1204
+ type: "projection",
1205
+ sessionId: session.id,
1206
+ key,
1207
+ value,
1208
+ seq
1209
+ });
1210
+ });
1211
+ ctx.effect(() => () => {
1212
+ for (const stream of this.streams) stream.end();
1213
+ this.streams.clear();
1214
+ }, "session-controller.control");
1215
+ }
1216
+ /**
1217
+ * Open one generation of Host-wide live control state.
1218
+ * @param signal - Remote stream cancellation.
1219
+ * @returns one complete baseline followed by live replacement frames.
1220
+ */
1221
+ async *control(signal) {
1222
+ signal.throwIfAborted();
1223
+ const queue = new ControlQueue();
1224
+ this.streams.add(queue);
1225
+ try {
1226
+ yield {
1227
+ type: "baseline",
1228
+ value: this.baseline()
1229
+ };
1230
+ yield* queue.iterate(signal);
1231
+ } finally {
1232
+ this.streams.delete(queue);
1233
+ queue.end();
1234
+ }
1235
+ }
1236
+ baseline() {
1237
+ const sessions = this.ctx.sessions.list();
1238
+ return { projections: this.projectionBaseline(sessions) };
1239
+ }
1240
+ projectionBaseline(sessions) {
1241
+ const blocks = Object.create(null);
1242
+ for (const session of sessions) {
1243
+ const snapshot = this.ctx.sessionProjections.snapshot(session);
1244
+ blocks[session.id] = {
1245
+ asOfSeq: snapshot.asOfSeq,
1246
+ values: snapshot.values
1247
+ };
1248
+ }
1249
+ return blocks;
1250
+ }
1251
+ broadcast(frame) {
1252
+ for (const stream of this.streams) stream.push(frame);
1253
+ }
1254
+ };
1255
+ var ControlQueue = class {
1256
+ buffer = new Deque();
1257
+ wake;
1258
+ done = false;
1259
+ push(frame) {
1260
+ if (this.done) return;
1261
+ this.buffer.pushBack(frame);
1262
+ const wake = this.wake;
1263
+ this.wake = void 0;
1264
+ wake?.();
1265
+ }
1266
+ end() {
1267
+ if (this.done) return;
1268
+ this.done = true;
1269
+ const wake = this.wake;
1270
+ this.wake = void 0;
1271
+ wake?.();
1272
+ }
1273
+ async *iterate(signal) {
1274
+ const onAbort = () => {
1275
+ this.end();
1276
+ };
1277
+ signal.addEventListener("abort", onAbort, { once: true });
1278
+ try {
1279
+ while (!this.done && !signal.aborted) {
1280
+ const frame = this.buffer.popFront();
1281
+ if (frame !== void 0) {
1282
+ yield frame;
1283
+ continue;
1284
+ }
1285
+ await new Promise((resolve) => {
1286
+ this.wake = resolve;
1287
+ });
1288
+ }
1289
+ while (this.buffer.size > 0 && !signal.aborted) yield this.buffer.popFront();
1290
+ } finally {
1291
+ signal.removeEventListener("abort", onAbort);
1292
+ this.end();
1293
+ }
1294
+ }
1295
+ };
1296
+ //#endregion
1297
+ //#region lib/types/assistant-stream.js
1298
+ /** Process-local assistant state retained for reconnecting Web followers. */
1299
+ const EMPTY_BASELINE = { revision: 0 };
1300
+ /**
1301
+ * Folds dense Agent frames and materializes one shared immutable reconnect
1302
+ * baseline per accepted revision.
1303
+ */
1304
+ var SessionAssistantStreamAccumulator = class {
1305
+ activeAttempt;
1306
+ revision = 0;
1307
+ snapshotValue = EMPTY_BASELINE;
1308
+ dirty = false;
1309
+ /**
1310
+ * Fold one trusted frame from the current attached Agent lifecycle.
1311
+ * @param frame - next dense process-local Assistant frame.
1312
+ * @param durableCursor - last committed Session seq when this frame was observed.
1313
+ */
1314
+ accept(frame, durableCursor) {
1315
+ if (frame.type === "start" && frame.revision === 1 && this.revision !== 0) {
1316
+ this.activeAttempt = void 0;
1317
+ this.revision = 0;
1318
+ }
1319
+ if (frame.revision !== this.revision + 1) {
1320
+ this.activeAttempt = void 0;
1321
+ this.revision = frame.revision;
1322
+ this.dirty = true;
1323
+ return;
1324
+ }
1325
+ this.revision = frame.revision;
1326
+ switch (frame.type) {
1327
+ case "start":
1328
+ this.activeAttempt = {
1329
+ attemptId: frame.attemptId,
1330
+ startedAfterSeq: durableCursor,
1331
+ turn: frame.turn,
1332
+ step: frame.step,
1333
+ stream: new AssistantStreamAccumulator(),
1334
+ nextIndex: 0
1335
+ };
1336
+ break;
1337
+ case "chunk": {
1338
+ const attempt = this.activeAttempt;
1339
+ if (attempt === void 0 || attempt.attemptId !== frame.attemptId || frame.index !== attempt.nextIndex) {
1340
+ this.activeAttempt = void 0;
1341
+ break;
1342
+ }
1343
+ attempt.stream.push({
1344
+ time: frame.time,
1345
+ chunk: frame.chunk
1346
+ });
1347
+ attempt.nextIndex += 1;
1348
+ break;
1349
+ }
1350
+ case "end":
1351
+ this.activeAttempt = void 0;
1352
+ break;
1353
+ }
1354
+ this.dirty = true;
1355
+ }
1356
+ /**
1357
+ * Read the cached reconnect baseline, materializing it after a state change.
1358
+ * @returns the identity-stable baseline for the latest accepted revision.
1359
+ */
1360
+ snapshot() {
1361
+ if (!this.dirty) return this.snapshotValue;
1362
+ this.snapshotValue = {
1363
+ revision: this.revision,
1364
+ ...this.activeAttempt === void 0 ? {} : { activeAttempt: {
1365
+ attemptId: this.activeAttempt.attemptId,
1366
+ startedAfterSeq: this.activeAttempt.startedAfterSeq,
1367
+ turn: this.activeAttempt.turn,
1368
+ step: this.activeAttempt.step,
1369
+ nextIndex: this.activeAttempt.nextIndex,
1370
+ stream: this.activeAttempt.stream.snapshot()
1371
+ } }
1372
+ };
1373
+ this.dirty = false;
1374
+ return this.snapshotValue;
1375
+ }
1376
+ };
1377
+ //#endregion
1378
+ //#region lib/types/history.js
1379
+ /** Cold Session history pagination and live-event source. */
1380
+ var __addDisposableResource$2 = function(env, value, async) {
1381
+ if (value !== null && value !== void 0) {
1382
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
1383
+ var dispose, inner;
1384
+ if (async) {
1385
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
1386
+ dispose = value[Symbol.asyncDispose];
1387
+ }
1388
+ if (dispose === void 0) {
1389
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
1390
+ dispose = value[Symbol.dispose];
1391
+ if (async) inner = dispose;
1392
+ }
1393
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
1394
+ if (inner) dispose = function() {
1395
+ try {
1396
+ inner.call(this);
1397
+ } catch (e) {
1398
+ return Promise.reject(e);
1399
+ }
1400
+ };
1401
+ env.stack.push({
1402
+ value,
1403
+ dispose,
1404
+ async
1405
+ });
1406
+ } else if (async) env.stack.push({ async: true });
1407
+ return value;
1408
+ };
1409
+ var __disposeResources$2 = (function(SuppressedError) {
1410
+ return function(env) {
1411
+ function fail(e) {
1412
+ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
1413
+ env.hasError = true;
1414
+ }
1415
+ var r, s = 0;
1416
+ function next() {
1417
+ while (r = env.stack.pop()) try {
1418
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
1419
+ if (r.dispose) {
1420
+ var result = r.dispose.call(r.value);
1421
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
1422
+ fail(e);
1423
+ return next();
1424
+ });
1425
+ } else s |= 1;
1426
+ } catch (e) {
1427
+ fail(e);
1428
+ }
1429
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
1430
+ if (env.hasError) throw env.error;
1431
+ }
1432
+ return next();
1433
+ };
1434
+ })(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
1435
+ var e = new Error(message);
1436
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
1437
+ });
1438
+ const DEFAULT_MAX_MESSAGES = 50;
1439
+ const MESSAGE_TYPES$1 = new Set(["user/message", "assistant/message"]);
1440
+ /** Implements cold-safe history operations delegated by the Session Controller. */
1441
+ var SessionHistoryController = class {
1442
+ ctx;
1443
+ promote;
1444
+ closeFollowers = /* @__PURE__ */ new Set();
1445
+ assistantStreams = /* @__PURE__ */ new Map();
1446
+ /**
1447
+ * @param ctx - Host context carrying Session query and projection services.
1448
+ * @param promote - starts ordinary Session activation after snapshot delivery.
1449
+ */
1450
+ constructor(ctx, promote) {
1451
+ this.ctx = ctx;
1452
+ this.promote = promote;
1453
+ ctx.on("agent/assistant-stream", ({ agent, frame }) => {
1454
+ let stream = this.assistantStreams.get(agent.session.id);
1455
+ if (stream === void 0) {
1456
+ stream = new SessionAssistantStreamAccumulator();
1457
+ this.assistantStreams.set(agent.session.id, stream);
1458
+ }
1459
+ stream.accept(frame, cursorBeforeNext(agent.session.seq));
1460
+ }, { global: true });
1461
+ ctx.on("agent/disposed", ({ agent }) => {
1462
+ this.assistantStreams.delete(agent.session.id);
1463
+ }, { global: true });
1464
+ ctx.effect(() => () => {
1465
+ for (const close of this.closeFollowers) close();
1466
+ this.closeFollowers.clear();
1467
+ }, "session-controller.history");
1468
+ }
1469
+ /**
1470
+ * Read one message-aligned history page without activating an Agent.
1471
+ * @param request - durable address and backwards-page cursor.
1472
+ * @param signal - caller cancellation for persistence reads.
1473
+ * @returns a contiguous event page.
1474
+ */
1475
+ async page(request, signal) {
1476
+ const env_1 = {
1477
+ stack: [],
1478
+ error: void 0,
1479
+ hasError: false
1480
+ };
1481
+ try {
1482
+ validatePageRequest(request);
1483
+ const throughSeq = request.throughSeq === -1 ? -1 : SessionSeq(request.throughSeq);
1484
+ const beforeSeq = request.beforeSeq === void 0 ? void 0 : SessionLogOffset(request.beforeSeq);
1485
+ const source = __addDisposableResource$2(env_1, await this.sourceFor(request.address, signal, false), false);
1486
+ signal.throwIfAborted();
1487
+ const sourceLog = source.events;
1488
+ const sourceCursor = sourceLog.at(-1)?.seq ?? -1;
1489
+ if (throughSeq > sourceCursor) throw new RemoteError("gateway/bad-request", `session page through seq ${String(throughSeq)} is past cursor ${String(sourceCursor)}`, {});
1490
+ /* v8 ignore next -- Session and persistence validation guarantee a dense zero-based event prefix. */
1491
+ if (throughSeq >= 0 && sourceLog[throughSeq]?.seq !== throughSeq) throw new RemoteError("gateway/internal", `session log does not contain through seq ${String(throughSeq)}`, {});
1492
+ const page = paginate(sourceLog, beforeSeq, request.maxMessages ?? DEFAULT_MAX_MESSAGES, throughSeq, request.turnWindow);
1493
+ return {
1494
+ records: pageRecords(page.events),
1495
+ hasMore: page.hasMore
1496
+ };
1497
+ } catch (e_1) {
1498
+ env_1.error = e_1;
1499
+ env_1.hasError = true;
1500
+ } finally {
1501
+ __disposeResources$2(env_1);
1502
+ }
1503
+ }
1504
+ /**
1505
+ * Follow events appended after an initial cursor on one durable address.
1506
+ * @param request - durable address and last committed sequence already held by the caller.
1507
+ * @param signal - stream cancellation owned by the Remote carrier.
1508
+ * @returns a complete opening snapshot followed by gap-free durable events and opted-in assistant frames.
1509
+ */
1510
+ async *follow(request, signal) {
1511
+ validateHistoryWindow(request);
1512
+ const { address } = request;
1513
+ const target = addressId(address);
1514
+ const buffered = new Deque();
1515
+ let snapshotCursor;
1516
+ let assistantStreamOrdinal = 0;
1517
+ let wake;
1518
+ const notify = () => {
1519
+ const resume = wake;
1520
+ wake = void 0;
1521
+ resume?.();
1522
+ };
1523
+ const follower = { closed: false };
1524
+ const close = () => {
1525
+ follower.closed = true;
1526
+ notify();
1527
+ };
1528
+ this.closeFollowers.add(close);
1529
+ const disposeEvent = this.ctx.on("session/event", (session, event) => {
1530
+ if (session.id !== target) return;
1531
+ buffered.pushBack({
1532
+ type: "event",
1533
+ event
1534
+ });
1535
+ notify();
1536
+ }, { global: true });
1537
+ const disposeCreated = this.ctx.on("session/created", (session) => {
1538
+ if (session.id !== target) return;
1539
+ const suffix = session.snapshotEvents(snapshotCursor === void 0 ? session.firstLiveSeq : SessionLogOffset(snapshotCursor + 1));
1540
+ for (let index = suffix.length - 1; index >= 0; index -= 1) buffered.pushFront({
1541
+ type: "event",
1542
+ event: suffix[index]
1543
+ });
1544
+ notify();
1545
+ }, { global: true });
1546
+ const disposeAssistantStream = request.assistantStream !== true ? void 0 : this.ctx.on("agent/assistant-stream", ({ agent, frame }) => {
1547
+ if (agent.session.id !== target) return;
1548
+ buffered.pushBack({
1549
+ type: "assistant-stream",
1550
+ frame: wireAssistantStreamFrame(frame, cursorBeforeNext(agent.session.seq)),
1551
+ ordinal: ++assistantStreamOrdinal
1552
+ });
1553
+ notify();
1554
+ }, { global: true });
1555
+ const onAbort = () => {
1556
+ notify();
1557
+ };
1558
+ signal.addEventListener("abort", onAbort, { once: true });
1559
+ try {
1560
+ const env_2 = {
1561
+ stack: [],
1562
+ error: void 0,
1563
+ hasError: false
1564
+ };
1565
+ try {
1566
+ const source = __addDisposableResource$2(env_2, await this.sourceFor(address, signal, true), false);
1567
+ const events = source.events;
1568
+ signal.throwIfAborted();
1569
+ const cursor = source.cursor;
1570
+ snapshotCursor = cursor;
1571
+ const page = paginate(events, void 0, request.maxMessages ?? DEFAULT_MAX_MESSAGES, cursor, request.turnWindow);
1572
+ const assistantStream = request.assistantStream === true ? this.assistantStreams.get(target)?.snapshot() ?? { revision: 0 } : void 0;
1573
+ const assistantStreamOrdinalCut = assistantStreamOrdinal;
1574
+ yield {
1575
+ type: "snapshot",
1576
+ header: wireHeader(source.header),
1577
+ cursor,
1578
+ records: pageRecords(page.events),
1579
+ hasMore: page.hasMore,
1580
+ projections: source.projections === void 0 ? {
1581
+ asOfSeq: cursor,
1582
+ values: {}
1583
+ } : projectionBlock(source.projections),
1584
+ ...assistantStream === void 0 ? {} : { assistantStream }
1585
+ };
1586
+ if (address.kind === "session" && source.source === "prepared") {
1587
+ const promotion = source.retain();
1588
+ try {
1589
+ this.promote(promotion);
1590
+ } catch (error) {
1591
+ promotion[Symbol.dispose]();
1592
+ throw error;
1593
+ }
1594
+ }
1595
+ let nextOffset = SessionLogOffset(cursor + 1);
1596
+ while (!follower.closed && !signal.aborted) {
1597
+ const item = buffered.popFront();
1598
+ if (item === void 0) {
1599
+ await new Promise((resolve) => {
1600
+ wake = resolve;
1601
+ });
1602
+ continue;
1603
+ }
1604
+ if (item.type === "assistant-stream") {
1605
+ if (item.ordinal > assistantStreamOrdinalCut) yield {
1606
+ type: "assistant-stream",
1607
+ frame: item.frame
1608
+ };
1609
+ continue;
1610
+ }
1611
+ const expectedSeq = SessionSeq(nextOffset);
1612
+ if (item.event.seq < expectedSeq) continue;
1613
+ if (item.event.seq !== expectedSeq) throw new RemoteError("gateway/internal", `session event stream skipped seq ${String(expectedSeq)}`, {});
1614
+ nextOffset = SessionLogOffset(nextOffset + 1);
1615
+ yield entryFor(item.event);
1616
+ }
1617
+ } catch (e_2) {
1618
+ env_2.error = e_2;
1619
+ env_2.hasError = true;
1620
+ } finally {
1621
+ __disposeResources$2(env_2);
1622
+ }
1623
+ } finally {
1624
+ this.closeFollowers.delete(close);
1625
+ signal.removeEventListener("abort", onAbort);
1626
+ disposeCreated();
1627
+ disposeEvent();
1628
+ disposeAssistantStream?.();
1629
+ }
1630
+ }
1631
+ async sourceFor(address, signal, withProjections) {
1632
+ const sessionId = addressId(address);
1633
+ try {
1634
+ const observation = await this.ctx.sessionQuery.observeSession(sessionId, {
1635
+ signal,
1636
+ projectionMode: withProjections || address.kind === "subagent" ? "all" : "none"
1637
+ });
1638
+ if (observation.header.cwd === void 0) {
1639
+ observation[Symbol.dispose]();
1640
+ rejectNotFound(address);
1641
+ }
1642
+ try {
1643
+ validateAddress(address, observation.header, observation.inheritedEventCount, observation.projections);
1644
+ } catch (error) {
1645
+ observation[Symbol.dispose]();
1646
+ throw error;
1647
+ }
1648
+ return observation;
1649
+ } catch (error) {
1650
+ if (error instanceof SessionQueryError && error.code === "SESSION_QUERY_SESSION_NOT_FOUND") rejectNotFound(address);
1651
+ throw error;
1652
+ }
1653
+ }
1654
+ };
1655
+ function cursorBeforeNext(nextSeq) {
1656
+ return nextSeq === 0 ? -1 : SessionSeq(nextSeq - 1);
1657
+ }
1658
+ function wireAssistantStreamFrame(frame, durableCursor) {
1659
+ if (frame.type === "start") return {
1660
+ ...frame,
1661
+ startedAfterSeq: durableCursor
1662
+ };
1663
+ if (frame.type === "end") return frame;
1664
+ return {
1665
+ ...frame,
1666
+ chunk: frame.chunk
1667
+ };
1668
+ }
1669
+ function projectionBlock(snapshot) {
1670
+ return {
1671
+ asOfSeq: snapshot.asOfSeq,
1672
+ values: snapshot.values
1673
+ };
1674
+ }
1675
+ function validatePageRequest(request) {
1676
+ if (!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", {});
1677
+ 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", {});
1678
+ validateHistoryWindow(request);
1679
+ }
1680
+ function validateHistoryWindow(request) {
1681
+ 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", {});
1682
+ const window = request.turnWindow;
1683
+ if (window !== void 0) {
1684
+ if (!Number.isSafeInteger(window.minMessages) || window.minMessages <= 0 || window.minMessages > (request.maxMessages ?? DEFAULT_MAX_MESSAGES)) throw new RemoteError("gateway/bad-request", "turnWindow.minMessages must be a positive safe integer no greater than maxMessages", {});
1685
+ if (!Number.isSafeInteger(window.minTurns) || window.minTurns <= 0) throw new RemoteError("gateway/bad-request", "turnWindow.minTurns must be a positive safe integer", {});
1686
+ }
1687
+ }
1688
+ function addressId(address) {
1689
+ return address.kind === "session" ? address.sessionId : address.childSessionId;
1690
+ }
1691
+ function validateAddress(address, header, inheritedEventCount, projections) {
1692
+ if (address.kind === "session") {
1693
+ 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" });
1694
+ return;
1695
+ }
1696
+ if (header.origin !== "subagent" || header.parentSession !== address.parentSessionId) throw new RemoteError("subagent/unauthorized", "subagent does not belong to the supplied parent", { childSessionId: address.childSessionId });
1697
+ const identity = projections?.values.subagent;
1698
+ if (identity === null) throw new RemoteError("subagent/catalog-diagnostic", "subagent descriptor is corrupt", {
1699
+ parentSessionId: address.parentSessionId,
1700
+ childSessionId: address.childSessionId,
1701
+ reason: "corrupt"
1702
+ });
1703
+ if (identity === void 0 || identity.seq < inheritedEventCount) throw new RemoteError("subagent/catalog-diagnostic", "subagent descriptor is unavailable", {
1704
+ parentSessionId: address.parentSessionId,
1705
+ childSessionId: address.childSessionId,
1706
+ reason: "unsupported"
1707
+ });
1708
+ if (address.mode !== "unknown" && identity.mode !== address.mode) throw new RemoteError("subagent/unauthorized", "subagent mode does not match the supplied address", { childSessionId: address.childSessionId });
1709
+ }
1710
+ function rejectNotFound(address) {
1711
+ if (address.kind === "session") throw new RemoteError("session/not-found", `session "${address.sessionId}" not found`, { sessionId: address.sessionId });
1712
+ throw new RemoteError("subagent/not-found", "subagent is unavailable", {
1713
+ parentSessionId: address.parentSessionId,
1714
+ childSessionId: address.childSessionId
1715
+ });
1716
+ }
1717
+ function paginate(events, beforeSeq, maxMessages, throughSeq, turnWindow) {
1718
+ const end = SessionLogOffset(Math.min(throughSeq + 1, beforeSeq ?? throughSeq + 1));
1719
+ let count = 0;
1720
+ let turns = 0;
1721
+ let cut = SessionLogOffset(0);
1722
+ for (let index = end - 1; index >= 0; index--) {
1723
+ const event = events[index];
1724
+ if (turnWindow !== void 0 && event.type === "turn/start") {
1725
+ turns++;
1726
+ if (count >= turnWindow.minMessages && turns >= turnWindow.minTurns) {
1727
+ cut = SessionLogOffset(index);
1728
+ break;
1729
+ }
1730
+ }
1731
+ if (!MESSAGE_TYPES$1.has(event.type) || !isAppendSurfaceEvent(event)) continue;
1732
+ count++;
1733
+ const sources = event.sourceEventSeqs;
1734
+ let groupStart = event.seq;
1735
+ if (sources !== void 0) {
1736
+ for (const source of sources) if (source < groupStart) groupStart = source;
1737
+ }
1738
+ if (count >= maxMessages) {
1739
+ cut = SessionLogOffset(groupStart);
1740
+ break;
1741
+ }
1742
+ }
1743
+ return {
1744
+ events: events.slice(cut, end),
1745
+ hasMore: cut > 0
1746
+ };
1747
+ }
1748
+ /** Translate current logical Session metadata to the browser wire. */
1749
+ function wireHeader(header) {
1750
+ return { ...header };
1751
+ }
1752
+ function entryFor(event) {
1753
+ return {
1754
+ type: "event",
1755
+ event
1756
+ };
1757
+ }
1758
+ /** Encode one bounded logical page without changing its pagination cut. */
1759
+ function pageRecords(events) {
1760
+ return events.map(entryFor);
1761
+ }
1762
+ //#endregion
1763
+ //#region lib/types/file-references.js
1764
+ /** Session Controller adapter for Agent-scoped file-reference discovery. */
1765
+ var __runInitializers$2 = function(thisArg, initializers, value) {
1766
+ var useValue = arguments.length > 2;
1767
+ for (var i = 0; i < initializers.length; i++) value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
1768
+ return useValue ? value : void 0;
1769
+ };
1770
+ var __esDecorate$2 = function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
1771
+ function accept(f) {
1772
+ if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
1773
+ return f;
1774
+ }
1775
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
1776
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
1777
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
1778
+ var _, done = false;
1779
+ for (var i = decorators.length - 1; i >= 0; i--) {
1780
+ var context = {};
1781
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
1782
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
1783
+ context.addInitializer = function(f) {
1784
+ if (done) throw new TypeError("Cannot add initializers after decoration has completed");
1785
+ extraInitializers.push(accept(f || null));
1786
+ };
1787
+ var result = (0, decorators[i])(kind === "accessor" ? {
1788
+ get: descriptor.get,
1789
+ set: descriptor.set
1790
+ } : descriptor[key], context);
1791
+ if (kind === "accessor") {
1792
+ if (result === void 0) continue;
1793
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
1794
+ if (_ = accept(result.get)) descriptor.get = _;
1795
+ if (_ = accept(result.set)) descriptor.set = _;
1796
+ if (_ = accept(result.init)) initializers.unshift(_);
1797
+ } else if (_ = accept(result)) if (kind === "field") initializers.unshift(_);
1798
+ else descriptor[key] = _;
1799
+ }
1800
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
1801
+ done = true;
1802
+ };
1803
+ /** Host Remote adapter over the composed file-reference provider. */
1804
+ let SessionFileReferences = (() => {
1805
+ let _classSuper = TypertRemoteService;
1806
+ let _instanceExtraInitializers = [];
1807
+ let _list_decorators;
1808
+ return class SessionFileReferences extends _classSuper {
1809
+ static {
1810
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
1811
+ _list_decorators = [Remote];
1812
+ __esDecorate$2(this, null, _list_decorators, {
1813
+ kind: "method",
1814
+ name: "list",
1815
+ static: false,
1816
+ private: false,
1817
+ access: {
1818
+ has: (obj) => "list" in obj,
1819
+ get: (obj) => obj.list
1820
+ },
1821
+ metadata: _metadata
1822
+ }, null, _instanceExtraInitializers);
1823
+ if (_metadata) Object.defineProperty(this, Symbol.metadata, {
1824
+ enumerable: true,
1825
+ configurable: true,
1826
+ writable: true,
1827
+ value: _metadata
1828
+ });
1829
+ }
1830
+ static inject = ["fileReferences", "typert"];
1831
+ /** @param ctx - Host context carrying the selected file-reference provider. */
1832
+ constructor(ctx) {
1833
+ super(ctx, "sessionFileReferences", { namespace: "fileReferences" });
1834
+ __runInitializers$2(this, _instanceExtraInitializers);
1835
+ }
1836
+ /**
1837
+ * List file and directory candidates for one Agent's working directory.
1838
+ * @param agent - target Agent resolved from the Session identity on the wire.
1839
+ * @param query - path text following `@` or `@"`.
1840
+ * @param signal - caller cancellation.
1841
+ * @returns deterministic path-only candidates from the composed provider.
1842
+ */
1843
+ list(agent, query, signal) {
1844
+ return this.ctx.fileReferences.list(agent, query, signal);
1845
+ }
1846
+ };
1847
+ })();
1848
+ //#endregion
1849
+ //#region lib/types/list.js
1850
+ /** Cold-safe Session list and search projection. */
1851
+ const SEARCH_PROVIDER_CALL_LIMIT = 100;
1852
+ const SESSION_SEARCH_QUERY_MAX_CHARS = 500;
1853
+ const MESSAGE_TYPES = new Set(["user/message", "assistant/message"]);
1854
+ const sessionListMetadataSchema = z$1.object({
1855
+ blank: z$1.boolean(),
1856
+ lastPromptAt: z$1.number().nullable()
1857
+ });
1858
+ const imageLimitsSchema = z$1.object({
1859
+ maxImageBytes: z$1.number().int().positive(),
1860
+ maxImagesPerMessage: z$1.number().int().positive(),
1861
+ maxMessageImageBytes: z$1.number().int().positive(),
1862
+ maxImagePixels: z$1.number().int().positive(),
1863
+ maxImageDimension: z$1.number().int().positive(),
1864
+ mediaTypes: z$1.array(z$1.string())
1865
+ });
1866
+ /**
1867
+ * Advance the Session-list metadata projection by one committed event.
1868
+ * @param state - metadata before the event.
1869
+ * @param event - next committed Session event.
1870
+ * @returns the original or advanced metadata value.
1871
+ */
1872
+ function applySessionListMetadata(state, event) {
1873
+ const blank = state.blank && event.type !== "turn/start";
1874
+ const lastPromptAt = event.type === "user/message" && event.data.source.kind === "user" ? event.time : state.lastPromptAt;
1875
+ return blank === state.blank && lastPromptAt === state.lastPromptAt ? state : {
1876
+ blank,
1877
+ lastPromptAt
1878
+ };
1879
+ }
1880
+ /**
1881
+ * Return the longest prefix containing at most `maximum` Unicode code points.
1882
+ * @param value - source text.
1883
+ * @param maximum - maximum number of Unicode code points.
1884
+ * @returns the source text or its longest allowed prefix.
1885
+ */
1886
+ function truncateUnicodeCodePoints(value, maximum) {
1887
+ let count = 0;
1888
+ let end = 0;
1889
+ for (const codePoint of value) {
1890
+ if (count === maximum) return value.slice(0, end);
1891
+ count++;
1892
+ end += codePoint.length;
1893
+ }
1894
+ return value;
1895
+ }
1896
+ /** Owns list projection registration, bounded cold summaries, and authorized search. */
1897
+ var ApiSessionList = class {
1898
+ ctx;
1899
+ workSliceMs;
1900
+ /**
1901
+ * @param ctx - Host context carrying Session, query, persistence, and projection services.
1902
+ * @param workSliceMs - Resolved positive integral list-work budget in milliseconds.
1903
+ */
1904
+ constructor(ctx, workSliceMs) {
1905
+ this.ctx = ctx;
1906
+ this.workSliceMs = workSliceMs;
1907
+ ctx.sessionProjections.register({
1908
+ key: "sessionListMetadata",
1909
+ stateSchema: sessionListMetadataSchema,
1910
+ init: () => ({
1911
+ blank: true,
1912
+ lastPromptAt: null
1913
+ }),
1914
+ apply: applySessionListMetadata,
1915
+ wire: {
1916
+ viewSchema: sessionListMetadataSchema,
1917
+ view: (state) => state
1918
+ },
1919
+ stateVersion: 1
1920
+ });
1921
+ ctx.inject(["attachments"], (attachmentCtx) => {
1922
+ ctx.sessionProjections.register({
1923
+ key: "imageLimits",
1924
+ stateSchema: z$1.null(),
1925
+ init: () => null,
1926
+ apply: (state) => state,
1927
+ wire: {
1928
+ viewSchema: imageLimitsSchema,
1929
+ view: () => attachmentCtx.attachments.imageLimits
1930
+ },
1931
+ stateVersion: 1
1932
+ });
1933
+ });
1934
+ }
1935
+ /**
1936
+ * Build one current attached-Session summary.
1937
+ * @param session - attached Session to summarize.
1938
+ * @returns current list metadata and available projections.
1939
+ */
1940
+ summaryFor(session) {
1941
+ const projections = this.projectionsFor(session.header, session);
1942
+ const metadata = projections?.values.sessionListMetadata;
1943
+ return {
1944
+ sessionId: session.id,
1945
+ updatedAt: updatedAt(session.header, metadata),
1946
+ agentAvailable: this.ctx.agents.get(session.id)?.session === session,
1947
+ formatStatus: "current",
1948
+ running: this.ctx.agents.get(session.id)?.status === "running",
1949
+ blank: metadata?.blank ?? session.seq === 0,
1950
+ ...listFields(session.header),
1951
+ ...projections === void 0 ? {} : { projections }
1952
+ };
1953
+ }
1954
+ /**
1955
+ * Read every visible attached and persisted Session without activating an Agent.
1956
+ * @param signal - optional cancellation for persistence reads and summary generation.
1957
+ * @returns visible Session summaries ordered by activity.
1958
+ */
1959
+ async list(signal) {
1960
+ signal?.throwIfAborted();
1961
+ const records = await this.ctx.sessionQuery.listSessions(signal);
1962
+ signal?.throwIfAborted();
1963
+ const items = [];
1964
+ const cold = [];
1965
+ let yieldDeadline = performance.now() + this.workSliceMs;
1966
+ for (const record of records) {
1967
+ signal?.throwIfAborted();
1968
+ const live = this.ctx.sessions.get(record.header.id);
1969
+ if (live !== void 0) items.push(this.summaryFor(live));
1970
+ else if (record.header.cwd !== void 0) cold.push(record);
1971
+ if (performance.now() >= yieldDeadline) {
1972
+ await scheduler.yield();
1973
+ signal?.throwIfAborted();
1974
+ yieldDeadline = performance.now() + this.workSliceMs;
1975
+ }
1976
+ }
1977
+ for (const record of cold) {
1978
+ signal?.throwIfAborted();
1979
+ items.push(this.summarizeCold(record));
1980
+ if (performance.now() >= yieldDeadline) {
1981
+ await scheduler.yield();
1982
+ signal?.throwIfAborted();
1983
+ yieldDeadline = performance.now() + this.workSliceMs;
1984
+ }
1985
+ }
1986
+ signal?.throwIfAborted();
1987
+ items.sort((left, right) => right.updatedAt - left.updatedAt);
1988
+ return items;
1989
+ }
1990
+ summarizeCold({ header, formatStatus }) {
1991
+ const projections = this.projectionsFor(header, void 0);
1992
+ const metadata = projections?.values.sessionListMetadata;
1993
+ return {
1994
+ sessionId: header.id,
1995
+ updatedAt: updatedAt(header, metadata),
1996
+ agentAvailable: false,
1997
+ ...formatStatus === void 0 ? {} : { formatStatus },
1998
+ running: false,
1999
+ blank: metadata?.blank ?? false,
2000
+ ...listFields(header),
2001
+ ...projections === void 0 ? {} : { projections }
2002
+ };
2003
+ }
2004
+ /**
2005
+ * Search current visible message content without activating any matching Session.
2006
+ * @param query - literal message-content query.
2007
+ * @param signal - cancellation for list and search reads.
2008
+ * @returns authorized bounded Session search results.
2009
+ */
2010
+ async search(query, signal) {
2011
+ const normalizedQuery = normalizeSearchQuery(query);
2012
+ signal.throwIfAborted();
2013
+ const provider = this.ctx.get("sessionQuery");
2014
+ if (provider === void 0) throw new RemoteError("gateway/internal", "session search is unavailable: this deployment does not mount @unieai/rabi-session-query", {});
2015
+ try {
2016
+ const visible = await provider.listSessions(signal);
2017
+ signal.throwIfAborted();
2018
+ const visibleIds = new Set(visible.filter((record) => record.header.cwd !== void 0).map((record) => record.header.id));
2019
+ if (visibleIds.size === 0) return {
2020
+ items: [],
2021
+ hasMore: false
2022
+ };
2023
+ const authorized = [];
2024
+ const acceptedIds = /* @__PURE__ */ new Set();
2025
+ const seenCursors = /* @__PURE__ */ new Set();
2026
+ let cursor;
2027
+ let providerCalls = 0;
2028
+ let pageLimit = 20;
2029
+ while (authorized.length <= 20) {
2030
+ signal.throwIfAborted();
2031
+ if (providerCalls >= SEARCH_PROVIDER_CALL_LIMIT) throw new Error(`session search provider exceeded the ${SEARCH_PROVIDER_CALL_LIMIT}-call work budget`);
2032
+ providerCalls++;
2033
+ const requestedCursor = cursor;
2034
+ const requestedLimit = pageLimit;
2035
+ let page;
2036
+ try {
2037
+ page = await provider.searchSessions({
2038
+ query: normalizedQuery,
2039
+ eventFilters: [{
2040
+ kind: "type",
2041
+ values: ["user/message", "assistant/message"]
2042
+ }, {
2043
+ kind: "surface",
2044
+ values: ["current"]
2045
+ }],
2046
+ limit: requestedLimit,
2047
+ ...requestedCursor === void 0 ? {} : { cursor: requestedCursor }
2048
+ }, { signal });
2049
+ signal.throwIfAborted();
2050
+ } catch (error) {
2051
+ signal.throwIfAborted();
2052
+ if (requestedCursor === void 0 && error instanceof SessionQueryError && error.code === "SESSION_QUERY_INVALID_LIMIT" && requestedLimit > 1) {
2053
+ pageLimit = Math.max(1, Math.floor(requestedLimit / 2));
2054
+ continue;
2055
+ }
2056
+ if (requestedCursor !== void 0 && error instanceof SessionQueryError && error.code === "SESSION_QUERY_STALE_CURSOR") {
2057
+ authorized.length = 0;
2058
+ acceptedIds.clear();
2059
+ seenCursors.clear();
2060
+ cursor = void 0;
2061
+ continue;
2062
+ }
2063
+ throw error;
2064
+ }
2065
+ if (page.items.length > requestedLimit) throw new Error(`session search provider returned ${String(page.items.length)} items; maximum is ${String(requestedLimit)}`);
2066
+ for (const hit of page.items) {
2067
+ if (authorized.length > 20) continue;
2068
+ 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;
2069
+ acceptedIds.add(hit.header.id);
2070
+ authorized.push({
2071
+ sessionId: hit.header.id,
2072
+ snippet: truncateUnicodeCodePoints(hit.bestMatch.snippet, 240)
2073
+ });
2074
+ }
2075
+ if (page.nextCursor !== void 0) {
2076
+ if (seenCursors.has(page.nextCursor)) throw new Error("session search provider repeated a continuation cursor");
2077
+ seenCursors.add(page.nextCursor);
2078
+ }
2079
+ if (authorized.length > 20 || page.nextCursor === void 0) break;
2080
+ cursor = page.nextCursor;
2081
+ }
2082
+ return {
2083
+ items: authorized.slice(0, 20),
2084
+ hasMore: authorized.length > 20
2085
+ };
2086
+ } catch (error) {
2087
+ signal.throwIfAborted();
2088
+ if (error instanceof SessionQueryError && error.code === "SESSION_QUERY_ABORTED") throw new RemoteError("gateway/cancelled", "session search was aborted", {});
2089
+ throw new RemoteError("gateway/internal", `session search failed: ${String(error)}`, {});
2090
+ }
2091
+ }
2092
+ projectionsFor(header, session) {
2093
+ try {
2094
+ if (session !== void 0) return hintsOf("sequenced", this.ctx.sessionProjections.cachedSnapshot(session));
2095
+ const cache = this.ctx.get("sessionProjectionCache");
2096
+ return hintsOf("cached", cache?.cachedSnapshot(header) ?? cache?.cachedPredecessorTitle(header));
2097
+ } catch (error) {
2098
+ this.ctx.logger.warn(`api-session.list: projection column for "${header.id}" failed; serving the row without it: ${String(error)}`);
2099
+ return;
2100
+ }
2101
+ }
2102
+ };
2103
+ /**
2104
+ * Wrap one projection block as Session-list hints of the named sequence space.
2105
+ * @param kind - which sequence space the block's watermark belongs to.
2106
+ * @param block - the block, or `undefined` when no source served one.
2107
+ * @returns the hints, or `undefined` when the block is absent or carries no value.
2108
+ */
2109
+ function hintsOf(kind, block) {
2110
+ if (block === void 0 || Object.keys(block.values).length === 0) return void 0;
2111
+ return {
2112
+ kind,
2113
+ asOfSeq: block.asOfSeq,
2114
+ values: block.values
2115
+ };
2116
+ }
2117
+ function normalizeSearchQuery(query) {
2118
+ const normalized = query.trim();
2119
+ if (normalized.length === 0) throw new RemoteError("gateway/bad-request", "session search query must not be empty", {});
2120
+ 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`, {});
2121
+ if (normalized.includes("\0")) throw new RemoteError("gateway/bad-request", "session search query must not contain NUL", {});
2122
+ return normalized;
2123
+ }
2124
+ function updatedAt(header, metadata) {
2125
+ return Math.max(header.createdAt, metadata?.lastPromptAt ?? 0);
2126
+ }
2127
+ function listFields(header) {
2128
+ return {
2129
+ ...header.parentSession === void 0 ? {} : { parentSessionId: header.parentSession },
2130
+ ...header.origin === void 0 ? {} : { origin: header.origin },
2131
+ ...header.cwd === void 0 ? {} : { cwd: header.cwd }
2132
+ };
2133
+ }
2134
+ //#endregion
2135
+ //#region lib/types/model-selection-projection.js
2136
+ /** Durable model-selection intent and request-use projection. */
2137
+ const modelSelectionSchema = z$1.object({
2138
+ provider: z$1.string().min(1),
2139
+ model: z$1.string().min(1),
2140
+ reasoningEffort: z$1.string().min(1).optional()
2141
+ });
2142
+ const modelSelectionProjectionStateSchema = z$1.object({
2143
+ lastUsed: modelSelectionSchema.nullable(),
2144
+ pending: modelSelectionSchema.nullable()
2145
+ });
2146
+ const modelSelectionProjectionSchema = z$1.object({
2147
+ lastUsed: modelSelectionSchema.nullable(),
2148
+ next: modelSelectionSchema.nullable()
2149
+ });
2150
+ /**
2151
+ * Advance durable model-selection state by one Session event.
2152
+ * @param state - selection state before the event.
2153
+ * @param event - next committed Session event.
2154
+ * @returns the original or advanced selection state.
2155
+ */
2156
+ function applyModelSelectionProjection(state, event) {
2157
+ if (event.type === "model/selection") return sameSelection(state.pending, event.data) ? state : {
2158
+ lastUsed: state.lastUsed,
2159
+ pending: event.data
2160
+ };
2161
+ if (event.type !== "request/header") return state;
2162
+ const lastUsed = {
2163
+ provider: event.data.header.config.provider,
2164
+ model: event.data.header.config.model,
2165
+ ...event.data.header.config.reasoningEffort === void 0 ? {} : { reasoningEffort: String(event.data.header.config.reasoningEffort) }
2166
+ };
2167
+ const pending = sameSelection(state.pending, lastUsed) ? null : state.pending;
2168
+ return sameSelection(state.lastUsed, lastUsed) && pending === state.pending ? state : {
2169
+ lastUsed,
2170
+ pending
2171
+ };
2172
+ }
2173
+ const modelSelectionProjection = {
2174
+ key: "modelSelection",
2175
+ stateSchema: modelSelectionProjectionStateSchema,
2176
+ init: () => ({
2177
+ lastUsed: null,
2178
+ pending: null
2179
+ }),
2180
+ apply: applyModelSelectionProjection,
2181
+ wire: {
2182
+ viewSchema: modelSelectionProjectionSchema,
2183
+ view: (state) => ({
2184
+ lastUsed: state.lastUsed,
2185
+ next: state.pending ?? state.lastUsed
2186
+ })
2187
+ },
2188
+ stateVersion: 2
2189
+ };
2190
+ function sameSelection(left, right) {
2191
+ return left === right || left !== null && right !== null && left.provider === right.provider && left.model === right.model && left.reasoningEffort === right.reasoningEffort;
2192
+ }
2193
+ /**
2194
+ * Register the durable model-selection projection when the registry is present.
2195
+ * @param ctx - Session Controller context.
2196
+ */
2197
+ function installModelSelectionProjection(ctx) {
2198
+ ctx.sessionProjections.register(modelSelectionProjection);
2199
+ }
2200
+ //#endregion
2201
+ //#region lib/types/skill-catalog.js
2202
+ /** Session-addressed, cold-readable skill catalog Remote. */
2203
+ var __runInitializers$1 = function(thisArg, initializers, value) {
2204
+ var useValue = arguments.length > 2;
2205
+ for (var i = 0; i < initializers.length; i++) value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
2206
+ return useValue ? value : void 0;
2207
+ };
2208
+ var __esDecorate$1 = function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
2209
+ function accept(f) {
2210
+ if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
2211
+ return f;
2212
+ }
2213
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
2214
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
2215
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
2216
+ var _, done = false;
2217
+ for (var i = decorators.length - 1; i >= 0; i--) {
2218
+ var context = {};
2219
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
2220
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
2221
+ context.addInitializer = function(f) {
2222
+ if (done) throw new TypeError("Cannot add initializers after decoration has completed");
2223
+ extraInitializers.push(accept(f || null));
2224
+ };
2225
+ var result = (0, decorators[i])(kind === "accessor" ? {
2226
+ get: descriptor.get,
2227
+ set: descriptor.set
2228
+ } : descriptor[key], context);
2229
+ if (kind === "accessor") {
2230
+ if (result === void 0) continue;
2231
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
2232
+ if (_ = accept(result.get)) descriptor.get = _;
2233
+ if (_ = accept(result.set)) descriptor.set = _;
2234
+ if (_ = accept(result.init)) initializers.unshift(_);
2235
+ } else if (_ = accept(result)) if (kind === "field") initializers.unshift(_);
2236
+ else descriptor[key] = _;
2237
+ }
2238
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
2239
+ done = true;
2240
+ };
2241
+ var __addDisposableResource$1 = function(env, value, async) {
2242
+ if (value !== null && value !== void 0) {
2243
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
2244
+ var dispose, inner;
2245
+ if (async) {
2246
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
2247
+ dispose = value[Symbol.asyncDispose];
2248
+ }
2249
+ if (dispose === void 0) {
2250
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
2251
+ dispose = value[Symbol.dispose];
2252
+ if (async) inner = dispose;
2253
+ }
2254
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
2255
+ if (inner) dispose = function() {
2256
+ try {
2257
+ inner.call(this);
2258
+ } catch (e) {
2259
+ return Promise.reject(e);
2260
+ }
2261
+ };
2262
+ env.stack.push({
2263
+ value,
2264
+ dispose,
2265
+ async
2266
+ });
2267
+ } else if (async) env.stack.push({ async: true });
2268
+ return value;
2269
+ };
2270
+ var __disposeResources$1 = (function(SuppressedError) {
2271
+ return function(env) {
2272
+ function fail(e) {
2273
+ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
2274
+ env.hasError = true;
2275
+ }
2276
+ var r, s = 0;
2277
+ function next() {
2278
+ while (r = env.stack.pop()) try {
2279
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
2280
+ if (r.dispose) {
2281
+ var result = r.dispose.call(r.value);
2282
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
2283
+ fail(e);
2284
+ return next();
2285
+ });
2286
+ } else s |= 1;
2287
+ } catch (e) {
2288
+ fail(e);
2289
+ }
2290
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
2291
+ if (env.hasError) throw env.error;
2292
+ }
2293
+ return next();
2294
+ };
2295
+ })(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
2296
+ var e = new Error(message);
2297
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
2298
+ });
2299
+ /** Host service backing `ctx.remote.skills` without activating a cold Agent. */
2300
+ let SessionSkillCatalog = (() => {
2301
+ let _classSuper = TypertRemoteService;
2302
+ let _instanceExtraInitializers = [];
2303
+ let _list_decorators;
2304
+ return class SessionSkillCatalog extends _classSuper {
2305
+ static {
2306
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
2307
+ _list_decorators = [Remote];
2308
+ __esDecorate$1(this, null, _list_decorators, {
2309
+ kind: "method",
2310
+ name: "list",
2311
+ static: false,
2312
+ private: false,
2313
+ access: {
2314
+ has: (obj) => "list" in obj,
2315
+ get: (obj) => obj.list
2316
+ },
2317
+ metadata: _metadata
2318
+ }, null, _instanceExtraInitializers);
2319
+ if (_metadata) Object.defineProperty(this, Symbol.metadata, {
2320
+ enumerable: true,
2321
+ configurable: true,
2322
+ writable: true,
2323
+ value: _metadata
2324
+ });
2325
+ }
2326
+ static inject = [
2327
+ "agents",
2328
+ "sessionQuery",
2329
+ "typert",
2330
+ "workingDirectory"
2331
+ ];
2332
+ /** @param ctx - Host context carrying Session reads and optional skill/preset services. */
2333
+ constructor(ctx) {
2334
+ super(ctx, "sessionSkillCatalog", { namespace: "skills" });
2335
+ __runInitializers$1(this, _instanceExtraInitializers);
2336
+ }
2337
+ /**
2338
+ * List the user-invocable skills visible to one Session composition.
2339
+ * @param request - Session identity whose cwd and preset select the catalog view.
2340
+ * @param signal - caller lifetime carried by the Remote transport; admitted catalog reads retain their existing completion semantics.
2341
+ * @returns user-invocable skill metadata without loading skill bodies.
2342
+ * @throws RemoteError when the Session cannot be inspected or no registry can serve it.
2343
+ */
2344
+ async list(request, signal) {
2345
+ const env_1 = {
2346
+ stack: [],
2347
+ error: void 0,
2348
+ hasError: false
2349
+ };
2350
+ try {
2351
+ const { sessionId } = request;
2352
+ let cwd;
2353
+ let agentPreset;
2354
+ try {
2355
+ const env_2 = {
2356
+ stack: [],
2357
+ error: void 0,
2358
+ hasError: false
2359
+ };
2360
+ try {
2361
+ const observation = __addDisposableResource$1(env_2, await this.ctx.sessionQuery.observeSession(sessionId), false);
2362
+ if (observation.projections === void 0) throw new Error("skill catalog requires a projected Session observation");
2363
+ cwd = observation.projections.values.workingDirectory ?? observation.header.cwd ?? this.ctx.workingDirectory.defaultDirectory;
2364
+ agentPreset = observation.projections.values.agentPreset ?? void 0;
2365
+ const live = this.ctx.agents.get(sessionId);
2366
+ if (live !== void 0) cwd = await this.ctx.workingDirectory.ensure(live, signal);
2367
+ } catch (e_1) {
2368
+ env_2.error = e_1;
2369
+ env_2.hasError = true;
2370
+ } finally {
2371
+ __disposeResources$1(env_2);
2372
+ }
2373
+ } catch (error) {
2374
+ if (error instanceof SessionQueryError && error.code === "SESSION_QUERY_SESSION_NOT_FOUND") throw new RemoteError("session/not-found", `session "${sessionId}" not found`, { sessionId });
2375
+ throw new RemoteError("gateway/internal", `session "${sessionId}" could not be inspected: ${String(error)}`, {});
2376
+ }
2377
+ const live = this.ctx.agents.get(sessionId);
2378
+ const presets = this.ctx.get("agentPresets");
2379
+ const skillRegistry = (live === void 0 ? void 0 : presets?.serviceFor(live, "skills")) ?? this.ctx.get("skills");
2380
+ 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", {});
2381
+ const lease = __addDisposableResource$1(env_1, live === void 0 ? await this.scopeFor(agentPreset) : void 0, true);
2382
+ const scope = live ?? lease?.key;
2383
+ try {
2384
+ return { skills: (await skillRegistry.list({
2385
+ cwd,
2386
+ scope
2387
+ })).filter(isUserInvocable).map((skill) => ({
2388
+ name: skill.name,
2389
+ ...skill.path === void 0 ? {} : { path: skill.path },
2390
+ description: skill.description,
2391
+ ...skill.whenToUse === void 0 ? {} : { whenToUse: skill.whenToUse },
2392
+ modelInvocable: skill.invocation.modelInvocable
2393
+ })) };
2394
+ } catch (error) {
2395
+ throw new RemoteError("gateway/internal", `skill listing failed: ${String(error)}`, {});
2396
+ }
2397
+ } catch (e_2) {
2398
+ env_1.error = e_2;
2399
+ env_1.hasError = true;
2400
+ } finally {
2401
+ const result_1 = __disposeResources$1(env_1);
2402
+ if (result_1) await result_1;
2403
+ }
2404
+ }
2405
+ /** Resolve a live or standing preset scope without creating an Agent. */
2406
+ async scopeFor(agentPreset) {
2407
+ const presets = this.ctx.get("agentPresets");
2408
+ if (presets === void 0) return void 0;
2409
+ try {
2410
+ return await presets.acquireScope(agentPreset);
2411
+ } catch {
2412
+ return;
2413
+ }
2414
+ }
2415
+ };
2416
+ })();
2417
+ //#endregion
2418
+ //#region lib/types/media-references.js
2419
+ /**
2420
+ * Authenticated GET/HEAD /api/file reads bounded file responses through
2421
+ * the composed filesystem provider. Paths and MIME types do not restrict access;
2422
+ * the connection service authenticates requests before this handler.
2423
+ * @module @unieai/rabi-api-session-controller/media-references
2424
+ */
2425
+ const BASE_HEADERS = {
2426
+ "Cache-Control": "private, no-store",
2427
+ "X-Content-Type-Options": "nosniff",
2428
+ "Content-Security-Policy": "sandbox; default-src 'none'"
2429
+ };
2430
+ async function serveFile(request, fs, maxBytes) {
2431
+ const fail = (status, text) => new Response(request.method === "HEAD" ? null : text, {
2432
+ status,
2433
+ headers: BASE_HEADERS
2434
+ });
2435
+ const path = new URL(request.url).searchParams.get("path");
2436
+ if (path === null || path.length === 0) return fail(400, "missing path");
2437
+ if (path.includes("\0") || !isAbsolute(path)) return fail(400, "absolute path required");
2438
+ try {
2439
+ const target = await fs.resolve(path, { signal: request.signal });
2440
+ const mediaType = mime.lookup(target.displayPath) || "application/octet-stream";
2441
+ const headers = {
2442
+ ...BASE_HEADERS,
2443
+ "Content-Type": mediaType
2444
+ };
2445
+ if (request.method === "HEAD") {
2446
+ const info = await fs.stat(target, request.signal);
2447
+ if (info === void 0) return fail(404, "not found");
2448
+ if (info.type !== "file") return fail(403, "not a regular file");
2449
+ if (info.size !== void 0) {
2450
+ if (info.size > maxBytes) return fail(413, "file exceeds byte limit");
2451
+ headers["Content-Length"] = String(info.size);
2452
+ }
2453
+ return new Response(null, { headers });
2454
+ }
2455
+ const bytes = await fs.readBytes(target, request.signal, maxBytes);
2456
+ headers["Content-Length"] = String(bytes.byteLength);
2457
+ return new Response(bytes.slice(), { headers });
2458
+ } catch (error) {
2459
+ if (!(error instanceof FsError)) throw error;
2460
+ return fail({
2461
+ FS_NOT_FOUND: 404,
2462
+ FS_NOT_REGULAR_FILE: 403,
2463
+ FS_PERMISSION_DENIED: 403,
2464
+ FS_SANDBOX_DENIED: 403,
2465
+ FS_TOO_LARGE: 413,
2466
+ FS_ABORTED: 499
2467
+ }[error.code] ?? 500, error.code);
2468
+ }
2469
+ }
2470
+ /**
2471
+ * File-display contribution. The connection service supplies authentication;
2472
+ * `ctx.fs` supplies the execution world's paths, reads, and access policy.
2473
+ */
2474
+ const SessionMediaReferences = {
2475
+ inject: [
2476
+ "connection",
2477
+ "fs",
2478
+ "attachments"
2479
+ ],
2480
+ apply(ctx) {
2481
+ const maxBytes = ctx.attachments.imageLimits.maxImageBytes;
2482
+ ctx.effect(() => ctx.connection.fetch.register({
2483
+ path: "/api/file",
2484
+ methods: ["GET", "HEAD"],
2485
+ requestBody: "buffered",
2486
+ fetch: (request) => serveFile(request, ctx.fs, maxBytes)
2487
+ }), "session-controller: /api/file");
2488
+ }
2489
+ };
2490
+ //#endregion
2491
+ //#region lib/types/archived-session-gate.js
2492
+ /**
2493
+ * The controller's admission gate for archived Sessions: an archived
2494
+ * Session, or a subagent descendant of one, must not run a model step until
2495
+ * it is restored. The work a Session still runs is reported and stopped by
2496
+ * its owners — the Agent registry (`turn`), the job registry seam (`job`),
2497
+ * the Subagent runtime (`subagent`), and the Schedule plugin (`schedule`) —
2498
+ * through the Workspace registry's archive-admission events.
2499
+ */
2500
+ /**
2501
+ * The gate as a plugin for `ctx.plugin(...)`: it loads once the Agent
2502
+ * registry, Session store, and Workspace registry are available and unwinds
2503
+ * with the plugin's fiber. A late waking delivery to an archived Session — a
2504
+ * subagent settlement, a queued follow-up — proposes a step the gate rejects,
2505
+ * which the loop ends as `blocked` without a request; unarchiving lifts the
2506
+ * gate for the whole lineage.
2507
+ */
2508
+ const ArchivedSessionGate = {
2509
+ name: "archived-session-gate",
2510
+ inject: [
2511
+ "agents",
2512
+ "sessions",
2513
+ "workspaceRegistry"
2514
+ ],
2515
+ apply(ctx) {
2516
+ ctx.on("agent/pre-step", (payload, next) => underArchivedSession(ctx, payload.agent) ? Promise.resolve({ kind: "reject" }) : next());
2517
+ }
2518
+ };
2519
+ /**
2520
+ * Whether the Agent's Session, or a Session above it in its subagent lineage,
2521
+ * is archived. Lineage follows the durable header fields through
2522
+ * subagent-origin Sessions only: a fork of an archived Session is an
2523
+ * independent conversation.
2524
+ * @param ctx - Host context.
2525
+ * @param agent - the Agent proposing a step.
2526
+ * @returns whether an archived Session owns the step.
2527
+ */
2528
+ function underArchivedSession(ctx, agent) {
2529
+ const archived = ctx.workspaceRegistry.archivedSessionIds;
2530
+ let header = agent.session.header;
2531
+ const visited = /* @__PURE__ */ new Set();
2532
+ while (!visited.has(header.id)) {
2533
+ if (archived.includes(header.id)) return true;
2534
+ visited.add(header.id);
2535
+ if (header.origin !== "subagent" || header.parentSession === void 0) return false;
2536
+ const parent = ctx.sessions.get(header.parentSession);
2537
+ if (parent === void 0) return archived.includes(header.parentSession);
2538
+ header = parent.header;
2539
+ }
2540
+ return false;
2541
+ }
2542
+ //#endregion
2543
+ //#region lib/types/index.js
2544
+ /** Session Remote owner: cold reads, explicit Agent commands, and live control state. */
2545
+ var __runInitializers = function(thisArg, initializers, value) {
2546
+ var useValue = arguments.length > 2;
2547
+ for (var i = 0; i < initializers.length; i++) value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
2548
+ return useValue ? value : void 0;
2549
+ };
2550
+ var __esDecorate = function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
2551
+ function accept(f) {
2552
+ if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
2553
+ return f;
2554
+ }
2555
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
2556
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
2557
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
2558
+ var _, done = false;
2559
+ for (var i = decorators.length - 1; i >= 0; i--) {
2560
+ var context = {};
2561
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
2562
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
2563
+ context.addInitializer = function(f) {
2564
+ if (done) throw new TypeError("Cannot add initializers after decoration has completed");
2565
+ extraInitializers.push(accept(f || null));
2566
+ };
2567
+ var result = (0, decorators[i])(kind === "accessor" ? {
2568
+ get: descriptor.get,
2569
+ set: descriptor.set
2570
+ } : descriptor[key], context);
2571
+ if (kind === "accessor") {
2572
+ if (result === void 0) continue;
2573
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
2574
+ if (_ = accept(result.get)) descriptor.get = _;
2575
+ if (_ = accept(result.set)) descriptor.set = _;
2576
+ if (_ = accept(result.init)) initializers.unshift(_);
2577
+ } else if (_ = accept(result)) if (kind === "field") initializers.unshift(_);
2578
+ else descriptor[key] = _;
2579
+ }
2580
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
2581
+ done = true;
2582
+ };
2583
+ var __addDisposableResource = function(env, value, async) {
2584
+ if (value !== null && value !== void 0) {
2585
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
2586
+ var dispose, inner;
2587
+ if (async) {
2588
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
2589
+ dispose = value[Symbol.asyncDispose];
2590
+ }
2591
+ if (dispose === void 0) {
2592
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
2593
+ dispose = value[Symbol.dispose];
2594
+ if (async) inner = dispose;
2595
+ }
2596
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
2597
+ if (inner) dispose = function() {
2598
+ try {
2599
+ inner.call(this);
2600
+ } catch (e) {
2601
+ return Promise.reject(e);
2602
+ }
2603
+ };
2604
+ env.stack.push({
2605
+ value,
2606
+ dispose,
2607
+ async
2608
+ });
2609
+ } else if (async) env.stack.push({ async: true });
2610
+ return value;
2611
+ };
2612
+ var __disposeResources = (function(SuppressedError) {
2613
+ return function(env) {
2614
+ function fail(e) {
2615
+ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
2616
+ env.hasError = true;
2617
+ }
2618
+ var r, s = 0;
2619
+ function next() {
2620
+ while (r = env.stack.pop()) try {
2621
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
2622
+ if (r.dispose) {
2623
+ var result = r.dispose.call(r.value);
2624
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
2625
+ fail(e);
2626
+ return next();
2627
+ });
2628
+ } else s |= 1;
2629
+ } catch (e) {
2630
+ fail(e);
2631
+ }
2632
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
2633
+ if (env.hasError) throw env.error;
2634
+ }
2635
+ return next();
2636
+ };
2637
+ })(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
2638
+ var e = new Error(message);
2639
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
2640
+ });
2641
+ /**
2642
+ * Read the Session resource a history address names: the Session itself, or
2643
+ * the child Session whose transcript a subagent address reads.
2644
+ * @param request - history request carrying the durable address.
2645
+ * @returns the Session whose access the read requires.
2646
+ */
2647
+ function addressedSession(request) {
2648
+ return request.address.kind === "session" ? request.address.sessionId : request.address.childSessionId;
2649
+ }
2650
+ /** Host service backing the generated `ctx.remote.session` namespace. */
2651
+ let SessionController = (() => {
2652
+ let _classSuper = TypertRemoteService;
2653
+ let _instanceExtraInitializers = [];
2654
+ let _list_decorators;
2655
+ let _search_decorators;
2656
+ let _create_decorators;
2657
+ let _selectModel_decorators;
2658
+ let _initializeDefaultModel_decorators;
2659
+ let _modelCatalog_decorators;
2660
+ let _canOpenWorkspacePath_decorators;
2661
+ let _openWorkspacePath_decorators;
2662
+ let _workspacePathApplications_decorators;
2663
+ let _rename_decorators;
2664
+ let _fork_decorators;
2665
+ let _prompt_decorators;
2666
+ let _attachment_decorators;
2667
+ let _updateQueue_decorators;
2668
+ let _cancel_decorators;
2669
+ let _page_decorators;
2670
+ let _follow_decorators;
2671
+ let _projections_decorators;
2672
+ let _control_decorators;
2673
+ return class SessionController extends _classSuper {
2674
+ static {
2675
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
2676
+ _list_decorators = [Remote("list")];
2677
+ _search_decorators = [Remote("search")];
2678
+ _create_decorators = [Remote("create")];
2679
+ _selectModel_decorators = [Remote("selectModel")];
2680
+ _initializeDefaultModel_decorators = [Remote];
2681
+ _modelCatalog_decorators = [Remote("modelCatalog")];
2682
+ _canOpenWorkspacePath_decorators = [Remote];
2683
+ _openWorkspacePath_decorators = [Remote("openWorkspacePath")];
2684
+ _workspacePathApplications_decorators = [Remote("workspacePathApplications")];
2685
+ _rename_decorators = [Remote("rename")];
2686
+ _fork_decorators = [Remote("fork")];
2687
+ _prompt_decorators = [Remote("prompt")];
2688
+ _attachment_decorators = [Remote("attachment")];
2689
+ _updateQueue_decorators = [Remote("updateQueue")];
2690
+ _cancel_decorators = [Remote("cancel")];
2691
+ _page_decorators = [Remote({
2692
+ name: "page",
2693
+ resources: { session: addressedSession }
2694
+ })];
2695
+ _follow_decorators = [Remote({
2696
+ mode: "stream",
2697
+ resources: { session: addressedSession }
2698
+ })];
2699
+ _projections_decorators = [Remote("projections")];
2700
+ _control_decorators = [Remote({ mode: "stream" })];
2701
+ __esDecorate(this, null, _list_decorators, {
2702
+ kind: "method",
2703
+ name: "list",
2704
+ static: false,
2705
+ private: false,
2706
+ access: {
2707
+ has: (obj) => "list" in obj,
2708
+ get: (obj) => obj.list
2709
+ },
2710
+ metadata: _metadata
2711
+ }, null, _instanceExtraInitializers);
2712
+ __esDecorate(this, null, _search_decorators, {
2713
+ kind: "method",
2714
+ name: "search",
2715
+ static: false,
2716
+ private: false,
2717
+ access: {
2718
+ has: (obj) => "search" in obj,
2719
+ get: (obj) => obj.search
2720
+ },
2721
+ metadata: _metadata
2722
+ }, null, _instanceExtraInitializers);
2723
+ __esDecorate(this, null, _create_decorators, {
2724
+ kind: "method",
2725
+ name: "create",
2726
+ static: false,
2727
+ private: false,
2728
+ access: {
2729
+ has: (obj) => "create" in obj,
2730
+ get: (obj) => obj.create
2731
+ },
2732
+ metadata: _metadata
2733
+ }, null, _instanceExtraInitializers);
2734
+ __esDecorate(this, null, _selectModel_decorators, {
2735
+ kind: "method",
2736
+ name: "selectModel",
2737
+ static: false,
2738
+ private: false,
2739
+ access: {
2740
+ has: (obj) => "selectModel" in obj,
2741
+ get: (obj) => obj.selectModel
2742
+ },
2743
+ metadata: _metadata
2744
+ }, null, _instanceExtraInitializers);
2745
+ __esDecorate(this, null, _initializeDefaultModel_decorators, {
2746
+ kind: "method",
2747
+ name: "initializeDefaultModel",
2748
+ static: false,
2749
+ private: false,
2750
+ access: {
2751
+ has: (obj) => "initializeDefaultModel" in obj,
2752
+ get: (obj) => obj.initializeDefaultModel
2753
+ },
2754
+ metadata: _metadata
2755
+ }, null, _instanceExtraInitializers);
2756
+ __esDecorate(this, null, _modelCatalog_decorators, {
2757
+ kind: "method",
2758
+ name: "modelCatalog",
2759
+ static: false,
2760
+ private: false,
2761
+ access: {
2762
+ has: (obj) => "modelCatalog" in obj,
2763
+ get: (obj) => obj.modelCatalog
2764
+ },
2765
+ metadata: _metadata
2766
+ }, null, _instanceExtraInitializers);
2767
+ __esDecorate(this, null, _canOpenWorkspacePath_decorators, {
2768
+ kind: "method",
2769
+ name: "canOpenWorkspacePath",
2770
+ static: false,
2771
+ private: false,
2772
+ access: {
2773
+ has: (obj) => "canOpenWorkspacePath" in obj,
2774
+ get: (obj) => obj.canOpenWorkspacePath
2775
+ },
2776
+ metadata: _metadata
2777
+ }, null, _instanceExtraInitializers);
2778
+ __esDecorate(this, null, _openWorkspacePath_decorators, {
2779
+ kind: "method",
2780
+ name: "openWorkspacePath",
2781
+ static: false,
2782
+ private: false,
2783
+ access: {
2784
+ has: (obj) => "openWorkspacePath" in obj,
2785
+ get: (obj) => obj.openWorkspacePath
2786
+ },
2787
+ metadata: _metadata
2788
+ }, null, _instanceExtraInitializers);
2789
+ __esDecorate(this, null, _workspacePathApplications_decorators, {
2790
+ kind: "method",
2791
+ name: "workspacePathApplications",
2792
+ static: false,
2793
+ private: false,
2794
+ access: {
2795
+ has: (obj) => "workspacePathApplications" in obj,
2796
+ get: (obj) => obj.workspacePathApplications
2797
+ },
2798
+ metadata: _metadata
2799
+ }, null, _instanceExtraInitializers);
2800
+ __esDecorate(this, null, _rename_decorators, {
2801
+ kind: "method",
2802
+ name: "rename",
2803
+ static: false,
2804
+ private: false,
2805
+ access: {
2806
+ has: (obj) => "rename" in obj,
2807
+ get: (obj) => obj.rename
2808
+ },
2809
+ metadata: _metadata
2810
+ }, null, _instanceExtraInitializers);
2811
+ __esDecorate(this, null, _fork_decorators, {
2812
+ kind: "method",
2813
+ name: "fork",
2814
+ static: false,
2815
+ private: false,
2816
+ access: {
2817
+ has: (obj) => "fork" in obj,
2818
+ get: (obj) => obj.fork
2819
+ },
2820
+ metadata: _metadata
2821
+ }, null, _instanceExtraInitializers);
2822
+ __esDecorate(this, null, _prompt_decorators, {
2823
+ kind: "method",
2824
+ name: "prompt",
2825
+ static: false,
2826
+ private: false,
2827
+ access: {
2828
+ has: (obj) => "prompt" in obj,
2829
+ get: (obj) => obj.prompt
2830
+ },
2831
+ metadata: _metadata
2832
+ }, null, _instanceExtraInitializers);
2833
+ __esDecorate(this, null, _attachment_decorators, {
2834
+ kind: "method",
2835
+ name: "attachment",
2836
+ static: false,
2837
+ private: false,
2838
+ access: {
2839
+ has: (obj) => "attachment" in obj,
2840
+ get: (obj) => obj.attachment
2841
+ },
2842
+ metadata: _metadata
2843
+ }, null, _instanceExtraInitializers);
2844
+ __esDecorate(this, null, _updateQueue_decorators, {
2845
+ kind: "method",
2846
+ name: "updateQueue",
2847
+ static: false,
2848
+ private: false,
2849
+ access: {
2850
+ has: (obj) => "updateQueue" in obj,
2851
+ get: (obj) => obj.updateQueue
2852
+ },
2853
+ metadata: _metadata
2854
+ }, null, _instanceExtraInitializers);
2855
+ __esDecorate(this, null, _cancel_decorators, {
2856
+ kind: "method",
2857
+ name: "cancel",
2858
+ static: false,
2859
+ private: false,
2860
+ access: {
2861
+ has: (obj) => "cancel" in obj,
2862
+ get: (obj) => obj.cancel
2863
+ },
2864
+ metadata: _metadata
2865
+ }, null, _instanceExtraInitializers);
2866
+ __esDecorate(this, null, _page_decorators, {
2867
+ kind: "method",
2868
+ name: "page",
2869
+ static: false,
2870
+ private: false,
2871
+ access: {
2872
+ has: (obj) => "page" in obj,
2873
+ get: (obj) => obj.page
2874
+ },
2875
+ metadata: _metadata
2876
+ }, null, _instanceExtraInitializers);
2877
+ __esDecorate(this, null, _follow_decorators, {
2878
+ kind: "method",
2879
+ name: "follow",
2880
+ static: false,
2881
+ private: false,
2882
+ access: {
2883
+ has: (obj) => "follow" in obj,
2884
+ get: (obj) => obj.follow
2885
+ },
2886
+ metadata: _metadata
2887
+ }, null, _instanceExtraInitializers);
2888
+ __esDecorate(this, null, _projections_decorators, {
2889
+ kind: "method",
2890
+ name: "projections",
2891
+ static: false,
2892
+ private: false,
2893
+ access: {
2894
+ has: (obj) => "projections" in obj,
2895
+ get: (obj) => obj.projections
2896
+ },
2897
+ metadata: _metadata
2898
+ }, null, _instanceExtraInitializers);
2899
+ __esDecorate(this, null, _control_decorators, {
2900
+ kind: "method",
2901
+ name: "control",
2902
+ static: false,
2903
+ private: false,
2904
+ access: {
2905
+ has: (obj) => "control" in obj,
2906
+ get: (obj) => obj.control
2907
+ },
2908
+ metadata: _metadata
2909
+ }, null, _instanceExtraInitializers);
2910
+ if (_metadata) Object.defineProperty(this, Symbol.metadata, {
2911
+ enumerable: true,
2912
+ configurable: true,
2913
+ writable: true,
2914
+ value: _metadata
2915
+ });
2916
+ }
2917
+ static inject = [
2918
+ "agentDefaultModel",
2919
+ "agents",
2920
+ "attachments",
2921
+ "fileUploads",
2922
+ "fs",
2923
+ "llm",
2924
+ "remoteAccess",
2925
+ "sessions",
2926
+ "sessionProjections",
2927
+ "sessionQuery",
2928
+ "typert",
2929
+ "workspaceRegistry"
2930
+ ];
2931
+ static Config = z.object({
2932
+ nativeOpen: z.boolean(),
2933
+ listWorkSliceMs: z.natural().min(1).default(16)
2934
+ });
2935
+ agents = __runInitializers(this, _instanceExtraInitializers);
2936
+ commands;
2937
+ controlState;
2938
+ history;
2939
+ listState;
2940
+ openPath;
2941
+ fileApplications;
2942
+ openFileApplication;
2943
+ revealPath;
2944
+ canOpenPath;
2945
+ promotions = /* @__PURE__ */ new Set();
2946
+ /**
2947
+ * @param ctx - Host context containing the Session capability assembly.
2948
+ * @param config - native-opener and list-scheduling deployment policy.
2949
+ * @param internals - host integrations replaceable by direct unit tests.
2950
+ */
2951
+ constructor(ctx, config, internals = {}) {
2952
+ super(ctx, "sessionController", { namespace: "session" });
2953
+ ctx.typert.resources.register("session", { field: "sessionId" });
2954
+ const resolved = SessionController.Config(config);
2955
+ installModelSelectionProjection(ctx);
2956
+ this.agents = new ApiSessionAgentController(ctx);
2957
+ this.commands = new SessionCommandController(ctx, this.agents, process.cwd());
2958
+ ctx.effect(() => ctx.fileUploads.registerAgentResolver(async (sessionId) => {
2959
+ const result = await this.agents.resolveAgent(sessionId);
2960
+ if ("error" in result) throw result.error;
2961
+ return result.agent;
2962
+ }), "session-controller: file-upload Agent resolver");
2963
+ this.controlState = new SessionControlController(ctx);
2964
+ ctx.effect(() => async () => {
2965
+ await Promise.allSettled([...this.promotions]);
2966
+ }, "session-controller.promotions");
2967
+ this.history = new SessionHistoryController(ctx, (observation) => {
2968
+ this.promote(observation);
2969
+ });
2970
+ this.listState = new ApiSessionList(ctx, resolved.listWorkSliceMs);
2971
+ this.fileApplications = internals.fileApplications ?? nativeFileApplications;
2972
+ this.openFileApplication = internals.openFileApplication ?? openNativeFileApplication;
2973
+ this.openPath = internals.openPath ?? openNativeAssociatedPath;
2974
+ this.revealPath = internals.revealPath ?? revealNativePath;
2975
+ this.canOpenPath = internals.canOpenPath ?? (() => config.nativeOpen ?? (internals.openPath !== void 0 || canOpenNativePath()));
2976
+ ctx.plugin(SessionFileReferences);
2977
+ ctx.plugin(SessionMediaReferences);
2978
+ ctx.plugin(SessionSkillCatalog);
2979
+ ctx.plugin(ArchivedSessionGate);
2980
+ ctx.on("session/created", (session) => {
2981
+ ctx.emit("api-session/added", this.listState.summaryFor(session));
2982
+ });
2983
+ ctx.on("session/disposed", (session) => {
2984
+ ctx.emit("api-session/removed", session.id);
2985
+ });
2986
+ const publishAgentAvailability = ({ agent }) => {
2987
+ if (ctx.sessions.get(agent.id) === agent.session) ctx.emit("api-session/added", this.listState.summaryFor(agent.session));
2988
+ };
2989
+ ctx.on("agent/created", publishAgentAvailability);
2990
+ ctx.on("agent/disposed", publishAgentAvailability);
2991
+ ctx.on("agent/status", ({ agent, status }) => {
2992
+ ctx.emit("api-session/status", agent.id, status === "running");
2993
+ });
2994
+ ctx.on("agent/error", ({ agent, error }) => {
2995
+ ctx.emit("api-session/error", agent.id, errorChain(error));
2996
+ });
2997
+ ctx.on("session/event", (session, event) => {
2998
+ if (event.type === "request/header") {
2999
+ const agent = ctx.agents.get(session.id);
3000
+ if (agent?.session === session) this.agents.consumeSelection(agent, event.data.header.config.provider, event.data.header.config.model, event.data.header.config.reasoningEffort);
3001
+ }
3002
+ if (event.type !== "user/message" || event.data.source.kind !== "user") return;
3003
+ ctx.emit("api-session/activity", session.id, event.time);
3004
+ });
3005
+ }
3006
+ promote(observation) {
3007
+ const sessionId = observation.header.id;
3008
+ const task = (async () => {
3009
+ const env_1 = {
3010
+ stack: [],
3011
+ error: void 0,
3012
+ hasError: false
3013
+ };
3014
+ try {
3015
+ const ownedObservation = __addDisposableResource(env_1, observation, false);
3016
+ const result = await this.agents.resolveObservedAgent(ownedObservation);
3017
+ if ("error" in result) this.ctx.emit("api-session/error", sessionId, result.error.message);
3018
+ } catch (e_1) {
3019
+ env_1.error = e_1;
3020
+ env_1.hasError = true;
3021
+ } finally {
3022
+ __disposeResources(env_1);
3023
+ }
3024
+ })().catch((error) => {
3025
+ this.ctx.logger.error(`session-controller: background activation for "${sessionId}" failed: ${errorChain(error)}`);
3026
+ });
3027
+ this.promotions.add(task);
3028
+ task.finally(() => {
3029
+ this.promotions.delete(task);
3030
+ });
3031
+ }
3032
+ /**
3033
+ * Resolve or resume one ordinary Session for another Host API domain.
3034
+ * @param sessionId - Session identity whose Agent owns the operation.
3035
+ * @returns the live Agent or the stable Session-domain failure.
3036
+ */
3037
+ resolveAgent(sessionId) {
3038
+ return this.agents.resolveAgent(sessionId);
3039
+ }
3040
+ /**
3041
+ * Inspect one attached or persisted Session without activating its Agent.
3042
+ * @param sessionId - durable Session identity.
3043
+ * @param signal - optional caller cancellation for persistence reads.
3044
+ * @returns the current attached state or persisted header and event prefix.
3045
+ */
3046
+ inspect(sessionId, signal) {
3047
+ const attached = this.ctx.sessions.get(sessionId);
3048
+ if (attached !== void 0) return Promise.resolve({
3049
+ meta: attached.header,
3050
+ inheritedEventCount: attached.inheritedEventCount,
3051
+ events: attached.snapshotEvents()
3052
+ });
3053
+ return inspectApiSession(this.ctx, sessionId, signal);
3054
+ }
3055
+ /**
3056
+ * Read all visible Session rows without resuming an Agent.
3057
+ * @param _request - reserved empty list request.
3058
+ * @param signal - cancellation for persistence reads and summary generation.
3059
+ * @returns visible Session summaries ordered by activity.
3060
+ */
3061
+ async list(_request, signal) {
3062
+ return { items: (await this.listState.list(signal)).filter((item) => this.ctx.remoteAccess.allows({
3063
+ kind: "session",
3064
+ id: item.sessionId
3065
+ })) };
3066
+ }
3067
+ /**
3068
+ * Search visible Session content without resuming an Agent. A non-owner
3069
+ * receives only the hits whose Session `allows()` admits; `hasMore`
3070
+ * describes the bounded result before that filtering.
3071
+ * @param request - literal message-content query.
3072
+ * @param signal - cancellation for list and search reads.
3073
+ * @returns authorized bounded Session search results.
3074
+ */
3075
+ async search(request, signal) {
3076
+ const result = await this.listState.search(request.query, signal);
3077
+ return {
3078
+ ...result,
3079
+ items: result.items.filter((item) => this.ctx.remoteAccess.allows({
3080
+ kind: "session",
3081
+ id: item.sessionId
3082
+ }))
3083
+ };
3084
+ }
3085
+ /**
3086
+ * Create one ordinary Session for a new conversation, reusing the named blank Session while it is reusable.
3087
+ * @param request - optional blank Session to reuse, location, and Agent preset.
3088
+ * @returns the created or reused Session identity and its preset when configured.
3089
+ */
3090
+ create(request) {
3091
+ return this.commands.create(request);
3092
+ }
3093
+ /**
3094
+ * Select one Session-local model after explicitly resuming the Session; save the default in the background.
3095
+ * @param request - Session identity and requested model selection.
3096
+ * @returns the normalized selection installed for the Session, without waiting for default persistence.
3097
+ */
3098
+ selectModel(request) {
3099
+ return this.commands.selectModel(request);
3100
+ }
3101
+ /**
3102
+ * Select the first available account model after login when no provider API key is configured.
3103
+ * @returns after saving the first available model or retaining the existing default.
3104
+ */
3105
+ async initializeDefaultModel() {
3106
+ const provider = "deepseek-account";
3107
+ if (await hasProviderApiKey(this.ctx)) return;
3108
+ const model = (await buildModelCatalog(this.ctx)).groups.find((group) => group.id === provider)?.models[0];
3109
+ if (model === void 0) throw new RemoteError("session/provider-models-unavailable", `provider "${provider}" has no available models`, { provider });
3110
+ const selection = {
3111
+ provider,
3112
+ model: model.id,
3113
+ ...model.reasoning?.defaultEffort === void 0 ? {} : { reasoningEffort: ReasoningEffortId(model.reasoning.defaultEffort) }
3114
+ };
3115
+ await this.ctx.agentDefaultModel.saveSelection(selection);
3116
+ }
3117
+ /**
3118
+ * Describe every currently routable model for Host-generation selectors.
3119
+ * @returns provider-grouped models, the deployment default, and isolated provider failures.
3120
+ */
3121
+ modelCatalog() {
3122
+ return buildModelCatalog(this.ctx);
3123
+ }
3124
+ /**
3125
+ * Report whether this deployment can hand a Session workspace path to a native desktop.
3126
+ * @returns true when the matching open operation is available.
3127
+ */
3128
+ canOpenWorkspacePath() {
3129
+ return this.canOpenPath();
3130
+ }
3131
+ /**
3132
+ * Describe the serving desktop for authenticated file-action routes.
3133
+ * @returns Host name, configured availability, and platform-specific file-manager behavior.
3134
+ */
3135
+ workspaceDesktop() {
3136
+ const fileManager = nativeFileManager();
3137
+ return {
3138
+ name: hostname(),
3139
+ available: fileManager !== null && this.canOpenPath(),
3140
+ fileManager
3141
+ };
3142
+ }
3143
+ /**
3144
+ * Verify one path through the composed filesystem and open it on the Host desktop.
3145
+ * @param request - path after best-effort Session workspace resolution.
3146
+ * @param signal - caller lifetime; abort terminates the native command.
3147
+ * @returns confirmation after the native opener accepts the path.
3148
+ * @throws RemoteError when the request is invalid, has no verified Host mapping, is cancelled, or the opener fails.
3149
+ */
3150
+ async openWorkspacePath(request, signal) {
3151
+ try {
3152
+ const path = await this.verifyDesktopPath(request.path, signal);
3153
+ if (request.action === "reveal") await this.revealPath(path, signal);
3154
+ else if (request.application !== void 0) await this.openFileApplication(path, request.application, signal);
3155
+ else await this.openPath(path, signal);
3156
+ return { opened: true };
3157
+ } catch (error) {
3158
+ if (signal.aborted) throw new RemoteError("gateway/cancelled", "path open was aborted", {});
3159
+ if (error instanceof RemoteError) throw error;
3160
+ throw new RemoteError("gateway/internal", "path open failed", {}, { cause: error });
3161
+ }
3162
+ }
3163
+ /**
3164
+ * Query current file handlers on the serving desktop without activating an Agent.
3165
+ * @param request - file path in Host filesystem syntax.
3166
+ * @param signal - caller lifetime, propagated to filesystem and desktop queries.
3167
+ * @returns OS application names, icons, and default selection; empty when desktop opening is unavailable.
3168
+ * @throws RemoteError when the path is invalid, the query is cancelled, or native discovery fails.
3169
+ */
3170
+ async workspacePathApplications(request, signal) {
3171
+ if (!this.canOpenPath()) return [];
3172
+ try {
3173
+ const path = await this.verifyDesktopPath(request.path, signal);
3174
+ return await this.fileApplications(path, signal);
3175
+ } catch (error) {
3176
+ if (signal.aborted) throw new RemoteError("gateway/cancelled", "application query was aborted", {});
3177
+ if (error instanceof RemoteError) throw error;
3178
+ throw new RemoteError("gateway/internal", "file application query failed", {}, { cause: error });
3179
+ }
3180
+ }
3181
+ async verifyDesktopPath(path, signal) {
3182
+ if (path.length === 0) throw new RemoteError("gateway/bad-request", "A non-empty file path is required", {});
3183
+ signal.throwIfAborted();
3184
+ const hostPath = resolve(path);
3185
+ const { fs } = this.ctx;
3186
+ const mapped = fs.processPathFromHostPath(hostPath);
3187
+ if (mapped === void 0 || fs.processPath(await fs.resolve(mapped, { signal })) !== hostPath) throw new RemoteError("gateway/bad-request", "Path has no verified Host path", {});
3188
+ signal.throwIfAborted();
3189
+ return hostPath;
3190
+ }
3191
+ /**
3192
+ * Rename one Session after explicitly resuming it.
3193
+ * @param request - Session identity and proposed title.
3194
+ * @returns the accepted title and durable event sequence.
3195
+ */
3196
+ rename(request) {
3197
+ return this.commands.rename(request);
3198
+ }
3199
+ /**
3200
+ * Fork one cold-readable exact event prefix into a new Session. An omitted
3201
+ * boundary selects the latest completed-turn prefix; an open cut receives
3202
+ * synthetic fork closers.
3203
+ * @param request - source Session, optional exact inclusive event boundary, and migration preflight choice.
3204
+ * @returns the new Session identity.
3205
+ */
3206
+ async fork(request) {
3207
+ if (request.allowMigration === false && this.ctx.sessions.get(request.sessionId) === void 0) {
3208
+ 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 });
3209
+ }
3210
+ return this.commands.fork(request);
3211
+ }
3212
+ /**
3213
+ * Admit one prompt after explicitly resuming its Session.
3214
+ * @param request - Session identity, prompt content, source metadata, and delivery mode.
3215
+ * @param signal - caller cancellation before prompt admission begins.
3216
+ * @returns acknowledgement that the Agent accepted the prompt.
3217
+ */
3218
+ async prompt(request, signal) {
3219
+ signal.throwIfAborted();
3220
+ if (!hasPromptContent(request.content)) throw new RemoteError("gateway/bad-request", "prompt content must include non-whitespace text or an attachment", {});
3221
+ const clientTimeZone = request.clientTimeZone === void 0 ? void 0 : canonicalClientTimeZone(request.clientTimeZone);
3222
+ 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 });
3223
+ const principal = principalOf(this.ctx.invocation);
3224
+ const source = {
3225
+ kind: "user",
3226
+ rpcId: request.requestId,
3227
+ ...clientTimeZone === void 0 ? {} : { clientTimeZone },
3228
+ ...principal === void 0 ? {} : { principal }
3229
+ };
3230
+ return this.commands.prompt(request, source);
3231
+ }
3232
+ /**
3233
+ * Read one image proven reachable from the addressed Session log.
3234
+ * @param request - Session and attachment identities used for authorization.
3235
+ * @returns the durable attachment reference and base64-encoded bytes.
3236
+ */
3237
+ attachment(request) {
3238
+ return this.commands.attachment(request);
3239
+ }
3240
+ /**
3241
+ * Mutate one still-pending queue occurrence, resuming a cold Agent first.
3242
+ * @param request - Session, queue item, and requested mutation.
3243
+ * @returns acknowledgement that the queue mutation was applied.
3244
+ */
3245
+ updateQueue(request) {
3246
+ return this.commands.updateQueue(request);
3247
+ }
3248
+ /**
3249
+ * Cancel one active Agent turn without dropping its pending inbox.
3250
+ * @param request - Session whose active Agent turn is cancelled.
3251
+ * @returns acknowledgement that cancellation was requested.
3252
+ */
3253
+ cancel(request) {
3254
+ return this.commands.cancel(request);
3255
+ }
3256
+ /**
3257
+ * Read one cold-safe, message-aligned Session history page.
3258
+ * @param request - durable address, backward cursor, and page budget.
3259
+ * @param signal - cancellation for persistence reads.
3260
+ * @returns one chronological page.
3261
+ */
3262
+ page(request, signal) {
3263
+ return this.history.page(request, signal);
3264
+ }
3265
+ /**
3266
+ * Follow one Session log from its opening or resume cursor.
3267
+ * @param request - durable address and last committed sequence already held by the caller.
3268
+ * @param signal - cancellation owned by the Remote stream carrier.
3269
+ * @returns a complete opening snapshot followed by gap-free durable event
3270
+ * frames and optional cursorless assistant-stream frames.
3271
+ */
3272
+ follow(request, signal) {
3273
+ return this.history.follow(request, signal);
3274
+ }
3275
+ /**
3276
+ * Read exact projections, returning cached hints only when migration is required.
3277
+ * @param request - Session whose current values are required.
3278
+ * @param signal - cancellation for the Session read.
3279
+ * @returns a sequenced baseline, cached hints when migration is deferred, or null when absent.
3280
+ */
3281
+ async projections(request, signal) {
3282
+ const { sessionId } = request;
3283
+ if (sessionId.length === 0) throw new RemoteError("gateway/bad-request", "sessionId must not be empty", {});
3284
+ try {
3285
+ const env_2 = {
3286
+ stack: [],
3287
+ error: void 0,
3288
+ hasError: false
3289
+ };
3290
+ try {
3291
+ signal.throwIfAborted();
3292
+ const live = this.liveProjections(sessionId);
3293
+ if (live !== void 0) return live;
3294
+ const stored = await this.ctx.get("sessionPersistence")?.stat(sessionId, { signal });
3295
+ signal.throwIfAborted();
3296
+ const attached = this.liveProjections(sessionId);
3297
+ if (attached !== void 0) return attached;
3298
+ if (stored === void 0) return null;
3299
+ if (stored.formatStatus === "migration-required") return {
3300
+ kind: "migration-required",
3301
+ values: { ...(this.ctx.get("sessionProjectionCache")?.cachedSnapshot(stored.header))?.values }
3302
+ };
3303
+ const projections = __addDisposableResource(env_2, await this.ctx.sessionQuery.observeSession(sessionId, { signal }), false).projections;
3304
+ if (projections === void 0) throw new RemoteError("session/projections-unavailable", "Session projections are unavailable", {});
3305
+ return {
3306
+ kind: "sequenced",
3307
+ asOfSeq: projections.asOfSeq,
3308
+ values: projections.values
3309
+ };
3310
+ } catch (e_2) {
3311
+ env_2.error = e_2;
3312
+ env_2.hasError = true;
3313
+ } finally {
3314
+ __disposeResources(env_2);
3315
+ }
3316
+ } catch (error) {
3317
+ if (error instanceof SessionQueryError && error.code === "SESSION_QUERY_SESSION_NOT_FOUND") return this.liveProjections(sessionId) ?? null;
3318
+ if (signal.aborted || error instanceof SessionQueryError && error.code === "SESSION_QUERY_ABORTED") throw new RemoteError("gateway/cancelled", "Session projection read was cancelled", {}, { cause: error });
3319
+ if (error instanceof RemoteError) throw error;
3320
+ throw new RemoteError("gateway/internal", "Session projection read failed", {}, { cause: error });
3321
+ }
3322
+ }
3323
+ liveProjections(sessionId) {
3324
+ const session = this.ctx.sessions.get(sessionId);
3325
+ if (session === void 0) return void 0;
3326
+ const snapshot = this.ctx.sessionProjections.snapshot(session);
3327
+ return {
3328
+ kind: "sequenced",
3329
+ asOfSeq: snapshot.asOfSeq,
3330
+ values: snapshot.values
3331
+ };
3332
+ }
3333
+ /**
3334
+ * Stream a complete live-control baseline followed by replacement frames.
3335
+ * @param signal - cancellation owned by the Remote stream carrier.
3336
+ * @returns one complete baseline followed by live replacement frames.
3337
+ */
3338
+ async *control(signal) {
3339
+ for await (const frame of this.controlState.control(signal)) switch (frame.type) {
3340
+ case "baseline": {
3341
+ const projections = Object.fromEntries(Object.entries(frame.value.projections).filter(([sessionId]) => this.ctx.remoteAccess.allows({
3342
+ kind: "session",
3343
+ id: sessionId
3344
+ })));
3345
+ yield {
3346
+ type: "baseline",
3347
+ value: {
3348
+ ...frame.value,
3349
+ projections
3350
+ }
3351
+ };
3352
+ break;
3353
+ }
3354
+ case "projection":
3355
+ if (this.ctx.remoteAccess.allows({
3356
+ kind: "session",
3357
+ id: frame.sessionId
3358
+ })) yield frame;
3359
+ break;
3360
+ /* v8 ignore next -- closed control-frame union. */
3361
+ default: assertNever(frame);
3362
+ }
3363
+ }
3364
+ };
3365
+ })();
3366
+ //#endregion
3367
+ export { ApiSessionNotFound, SessionController, SessionController as default, SessionFileReferences, SessionSkillCatalog, buildModelCatalog };