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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +7 -2
  3. package/lib/client.js +4325 -0
  4. package/lib/index.js +3367 -0
  5. package/lib/typert.host.d.ts +3 -0
  6. package/lib/typert.host.js +4053 -0
  7. package/lib/typert.remote-client.d.ts +97 -0
  8. package/lib/typert.remote-client.js +2013 -0
  9. package/lib/types/agent.d.ts +198 -0
  10. package/lib/types/agent.js +609 -0
  11. package/lib/types/archived-session-gate.d.ts +30 -0
  12. package/lib/types/archived-session-gate.js +51 -0
  13. package/lib/types/assistant-stream.d.ts +26 -0
  14. package/lib/types/assistant-stream.js +82 -0
  15. package/lib/types/catalog.d.ts +24 -0
  16. package/lib/types/catalog.js +106 -0
  17. package/lib/types/client/contract/events.d.ts +102 -0
  18. package/lib/types/client/contract/events.js +111 -0
  19. package/lib/types/client/contract/session.d.ts +157 -0
  20. package/lib/types/client/contract/session.js +1 -0
  21. package/lib/types/client/contract/sessions.d.ts +161 -0
  22. package/lib/types/client/contract/sessions.js +1 -0
  23. package/lib/types/client/contract/snapshot.d.ts +81 -0
  24. package/lib/types/client/contract/snapshot.js +1 -0
  25. package/lib/types/client/index.d.ts +39 -0
  26. package/lib/types/client/index.js +60 -0
  27. package/lib/types/client/ordered-baseline.d.ts +12 -0
  28. package/lib/types/client/ordered-baseline.js +40 -0
  29. package/lib/types/client/scope.d.ts +46 -0
  30. package/lib/types/client/scope.js +46 -0
  31. package/lib/types/client/session-wire-event.d.ts +11 -0
  32. package/lib/types/client/session-wire-event.js +42 -0
  33. package/lib/types/client/sessions/assistant-stream.d.ts +56 -0
  34. package/lib/types/client/sessions/assistant-stream.js +182 -0
  35. package/lib/types/client/sessions/history-records.d.ts +22 -0
  36. package/lib/types/client/sessions/history-records.js +25 -0
  37. package/lib/types/client/sessions/lineage.d.ts +40 -0
  38. package/lib/types/client/sessions/lineage.js +54 -0
  39. package/lib/types/client/sessions/manager.d.ts +269 -0
  40. package/lib/types/client/sessions/manager.js +799 -0
  41. package/lib/types/client/sessions/notifier.d.ts +39 -0
  42. package/lib/types/client/sessions/notifier.js +97 -0
  43. package/lib/types/client/sessions/projection-store.d.ts +128 -0
  44. package/lib/types/client/sessions/projection-store.js +161 -0
  45. package/lib/types/client/sessions/remotes.d.ts +29 -0
  46. package/lib/types/client/sessions/remotes.js +7 -0
  47. package/lib/types/client/sessions/service.d.ts +258 -0
  48. package/lib/types/client/sessions/service.js +582 -0
  49. package/lib/types/client/sessions/session.d.ts +287 -0
  50. package/lib/types/client/sessions/session.js +866 -0
  51. package/lib/types/client/time-zone.d.ts +8 -0
  52. package/lib/types/client/time-zone.js +13 -0
  53. package/lib/types/client/transport.d.ts +77 -0
  54. package/lib/types/client/transport.js +129 -0
  55. package/lib/types/commands.d.ts +86 -0
  56. package/lib/types/commands.js +624 -0
  57. package/lib/types/control.d.ts +20 -0
  58. package/lib/types/control.js +106 -0
  59. package/lib/types/file-references.d.ts +27 -0
  60. package/lib/types/file-references.js +68 -0
  61. package/lib/types/history.d.ts +32 -0
  62. package/lib/types/history.js +441 -0
  63. package/lib/types/index.d.ts +222 -0
  64. package/lib/types/index.js +658 -0
  65. package/lib/types/list.d.ts +50 -0
  66. package/lib/types/list.js +325 -0
  67. package/lib/types/media-references.d.ts +16 -0
  68. package/lib/types/media-references.js +76 -0
  69. package/lib/types/model-selection-projection.d.ts +8 -0
  70. package/lib/types/model-selection-projection.js +65 -0
  71. package/lib/types/remote-events.d.ts +8 -0
  72. package/lib/types/remote-events.js +1 -0
  73. package/lib/types/skill-catalog.d.ts +28 -0
  74. package/lib/types/skill-catalog.js +203 -0
  75. package/lib/types/types.d.ts +611 -0
  76. package/lib/types/types.js +4 -0
  77. package/locale/en.json +5 -0
  78. package/locale/zh.json +6 -0
  79. package/package.json +114 -4
@@ -0,0 +1,658 @@
1
+ /** Session Remote owner: cold reads, explicit Agent commands, and live control state. */
2
+ var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
3
+ var useValue = arguments.length > 2;
4
+ for (var i = 0; i < initializers.length; i++) {
5
+ value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
6
+ }
7
+ return useValue ? value : void 0;
8
+ };
9
+ var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
10
+ function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
11
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
12
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
13
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
14
+ var _, done = false;
15
+ for (var i = decorators.length - 1; i >= 0; i--) {
16
+ var context = {};
17
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
18
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
19
+ context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
20
+ var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
21
+ if (kind === "accessor") {
22
+ if (result === void 0) continue;
23
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
24
+ if (_ = accept(result.get)) descriptor.get = _;
25
+ if (_ = accept(result.set)) descriptor.set = _;
26
+ if (_ = accept(result.init)) initializers.unshift(_);
27
+ }
28
+ else if (_ = accept(result)) {
29
+ if (kind === "field") initializers.unshift(_);
30
+ else descriptor[key] = _;
31
+ }
32
+ }
33
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
34
+ done = true;
35
+ };
36
+ var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {
37
+ if (value !== null && value !== void 0) {
38
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
39
+ var dispose, inner;
40
+ if (async) {
41
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
42
+ dispose = value[Symbol.asyncDispose];
43
+ }
44
+ if (dispose === void 0) {
45
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
46
+ dispose = value[Symbol.dispose];
47
+ if (async) inner = dispose;
48
+ }
49
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
50
+ if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
51
+ env.stack.push({ value: value, dispose: dispose, async: async });
52
+ }
53
+ else if (async) {
54
+ env.stack.push({ async: true });
55
+ }
56
+ return value;
57
+ };
58
+ var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {
59
+ return function (env) {
60
+ function fail(e) {
61
+ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
62
+ env.hasError = true;
63
+ }
64
+ var r, s = 0;
65
+ function next() {
66
+ while (r = env.stack.pop()) {
67
+ try {
68
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
69
+ if (r.dispose) {
70
+ var result = r.dispose.call(r.value);
71
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
72
+ }
73
+ else s |= 1;
74
+ }
75
+ catch (e) {
76
+ fail(e);
77
+ }
78
+ }
79
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
80
+ if (env.hasError) throw env.error;
81
+ }
82
+ return next();
83
+ };
84
+ })(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
85
+ var e = new Error(message);
86
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
87
+ });
88
+ import { hostname } from 'node:os';
89
+ import { resolve } from 'node:path';
90
+ import z from '@unieai/schemastery';
91
+ import { errorChain, ReasoningEffortId } from '@unieai/rabi-llm';
92
+ import { canOpenNativePath, nativeFileManager, nativeFileApplications, openNativeFileApplication, openNativeAssociatedPath, revealNativePath } from '@unieai/rabi-native-command';
93
+ import { SessionQueryError } from '@unieai/rabi-session-query';
94
+ import { Remote, RemoteError, TypertRemoteService, principalOf } from '@unieai/rabi-typert-protocol';
95
+ import { canonicalClientTimeZone } from '@unieai/rabi-util-time';
96
+ import { assertNever } from '@unieai/rabi-util-values';
97
+ import { ApiSessionAgentController, inspectApiSession, } from "./agent.js";
98
+ import { SessionCommandController, hasPromptContent } from "./commands.js";
99
+ import { SessionControlController } from "./control.js";
100
+ import { SessionHistoryController } from "./history.js";
101
+ import { SessionFileReferences } from "./file-references.js";
102
+ import { ApiSessionList } from "./list.js";
103
+ import { buildModelCatalog, hasProviderApiKey } from "./catalog.js";
104
+ import { installModelSelectionProjection } from "./model-selection-projection.js";
105
+ import { SessionSkillCatalog } from "./skill-catalog.js";
106
+ import { SessionMediaReferences } from "./media-references.js";
107
+ import { ArchivedSessionGate } from "./archived-session-gate.js";
108
+ export { ApiSessionNotFound } from "./agent.js";
109
+ export { SessionFileReferences } from "./file-references.js";
110
+ export { SessionSkillCatalog } from "./skill-catalog.js";
111
+ /**
112
+ * Read the Session resource a history address names: the Session itself, or
113
+ * the child Session whose transcript a subagent address reads.
114
+ * @param request - history request carrying the durable address.
115
+ * @returns the Session whose access the read requires.
116
+ */
117
+ function addressedSession(request) {
118
+ return request.address.kind === 'session' ? request.address.sessionId : request.address.childSessionId;
119
+ }
120
+ /** Host service backing the generated `ctx.remote.session` namespace. */
121
+ let SessionController = (() => {
122
+ let _classSuper = TypertRemoteService;
123
+ let _instanceExtraInitializers = [];
124
+ let _list_decorators;
125
+ let _search_decorators;
126
+ let _create_decorators;
127
+ let _selectModel_decorators;
128
+ let _initializeDefaultModel_decorators;
129
+ let _modelCatalog_decorators;
130
+ let _canOpenWorkspacePath_decorators;
131
+ let _openWorkspacePath_decorators;
132
+ let _workspacePathApplications_decorators;
133
+ let _rename_decorators;
134
+ let _fork_decorators;
135
+ let _prompt_decorators;
136
+ let _attachment_decorators;
137
+ let _updateQueue_decorators;
138
+ let _cancel_decorators;
139
+ let _page_decorators;
140
+ let _follow_decorators;
141
+ let _projections_decorators;
142
+ let _control_decorators;
143
+ return class SessionController extends _classSuper {
144
+ static {
145
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
146
+ _list_decorators = [Remote('list')];
147
+ _search_decorators = [Remote('search')];
148
+ _create_decorators = [Remote('create')];
149
+ _selectModel_decorators = [Remote('selectModel')];
150
+ _initializeDefaultModel_decorators = [Remote];
151
+ _modelCatalog_decorators = [Remote('modelCatalog')];
152
+ _canOpenWorkspacePath_decorators = [Remote];
153
+ _openWorkspacePath_decorators = [Remote('openWorkspacePath')];
154
+ _workspacePathApplications_decorators = [Remote('workspacePathApplications')];
155
+ _rename_decorators = [Remote('rename')];
156
+ _fork_decorators = [Remote('fork')];
157
+ _prompt_decorators = [Remote('prompt')];
158
+ _attachment_decorators = [Remote('attachment')];
159
+ _updateQueue_decorators = [Remote('updateQueue')];
160
+ _cancel_decorators = [Remote('cancel')];
161
+ _page_decorators = [Remote({ name: 'page', resources: { session: addressedSession } })];
162
+ _follow_decorators = [Remote({ mode: 'stream', resources: { session: addressedSession } })];
163
+ _projections_decorators = [Remote('projections')];
164
+ _control_decorators = [Remote({ mode: 'stream' })];
165
+ __esDecorate(this, null, _list_decorators, { kind: "method", name: "list", static: false, private: false, access: { has: obj => "list" in obj, get: obj => obj.list }, metadata: _metadata }, null, _instanceExtraInitializers);
166
+ __esDecorate(this, null, _search_decorators, { kind: "method", name: "search", static: false, private: false, access: { has: obj => "search" in obj, get: obj => obj.search }, metadata: _metadata }, null, _instanceExtraInitializers);
167
+ __esDecorate(this, null, _create_decorators, { kind: "method", name: "create", static: false, private: false, access: { has: obj => "create" in obj, get: obj => obj.create }, metadata: _metadata }, null, _instanceExtraInitializers);
168
+ __esDecorate(this, null, _selectModel_decorators, { kind: "method", name: "selectModel", static: false, private: false, access: { has: obj => "selectModel" in obj, get: obj => obj.selectModel }, metadata: _metadata }, null, _instanceExtraInitializers);
169
+ __esDecorate(this, null, _initializeDefaultModel_decorators, { kind: "method", name: "initializeDefaultModel", static: false, private: false, access: { has: obj => "initializeDefaultModel" in obj, get: obj => obj.initializeDefaultModel }, metadata: _metadata }, null, _instanceExtraInitializers);
170
+ __esDecorate(this, null, _modelCatalog_decorators, { kind: "method", name: "modelCatalog", static: false, private: false, access: { has: obj => "modelCatalog" in obj, get: obj => obj.modelCatalog }, metadata: _metadata }, null, _instanceExtraInitializers);
171
+ __esDecorate(this, null, _canOpenWorkspacePath_decorators, { kind: "method", name: "canOpenWorkspacePath", static: false, private: false, access: { has: obj => "canOpenWorkspacePath" in obj, get: obj => obj.canOpenWorkspacePath }, metadata: _metadata }, null, _instanceExtraInitializers);
172
+ __esDecorate(this, null, _openWorkspacePath_decorators, { kind: "method", name: "openWorkspacePath", static: false, private: false, access: { has: obj => "openWorkspacePath" in obj, get: obj => obj.openWorkspacePath }, metadata: _metadata }, null, _instanceExtraInitializers);
173
+ __esDecorate(this, null, _workspacePathApplications_decorators, { kind: "method", name: "workspacePathApplications", static: false, private: false, access: { has: obj => "workspacePathApplications" in obj, get: obj => obj.workspacePathApplications }, metadata: _metadata }, null, _instanceExtraInitializers);
174
+ __esDecorate(this, null, _rename_decorators, { kind: "method", name: "rename", static: false, private: false, access: { has: obj => "rename" in obj, get: obj => obj.rename }, metadata: _metadata }, null, _instanceExtraInitializers);
175
+ __esDecorate(this, null, _fork_decorators, { kind: "method", name: "fork", static: false, private: false, access: { has: obj => "fork" in obj, get: obj => obj.fork }, metadata: _metadata }, null, _instanceExtraInitializers);
176
+ __esDecorate(this, null, _prompt_decorators, { kind: "method", name: "prompt", static: false, private: false, access: { has: obj => "prompt" in obj, get: obj => obj.prompt }, metadata: _metadata }, null, _instanceExtraInitializers);
177
+ __esDecorate(this, null, _attachment_decorators, { kind: "method", name: "attachment", static: false, private: false, access: { has: obj => "attachment" in obj, get: obj => obj.attachment }, metadata: _metadata }, null, _instanceExtraInitializers);
178
+ __esDecorate(this, null, _updateQueue_decorators, { kind: "method", name: "updateQueue", static: false, private: false, access: { has: obj => "updateQueue" in obj, get: obj => obj.updateQueue }, metadata: _metadata }, null, _instanceExtraInitializers);
179
+ __esDecorate(this, null, _cancel_decorators, { kind: "method", name: "cancel", static: false, private: false, access: { has: obj => "cancel" in obj, get: obj => obj.cancel }, metadata: _metadata }, null, _instanceExtraInitializers);
180
+ __esDecorate(this, null, _page_decorators, { kind: "method", name: "page", static: false, private: false, access: { has: obj => "page" in obj, get: obj => obj.page }, metadata: _metadata }, null, _instanceExtraInitializers);
181
+ __esDecorate(this, null, _follow_decorators, { kind: "method", name: "follow", static: false, private: false, access: { has: obj => "follow" in obj, get: obj => obj.follow }, metadata: _metadata }, null, _instanceExtraInitializers);
182
+ __esDecorate(this, null, _projections_decorators, { kind: "method", name: "projections", static: false, private: false, access: { has: obj => "projections" in obj, get: obj => obj.projections }, metadata: _metadata }, null, _instanceExtraInitializers);
183
+ __esDecorate(this, null, _control_decorators, { kind: "method", name: "control", static: false, private: false, access: { has: obj => "control" in obj, get: obj => obj.control }, metadata: _metadata }, null, _instanceExtraInitializers);
184
+ if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
185
+ }
186
+ static inject = [
187
+ 'agentDefaultModel',
188
+ 'agents',
189
+ 'attachments',
190
+ 'fileUploads',
191
+ 'fs',
192
+ 'llm',
193
+ 'remoteAccess',
194
+ 'sessions',
195
+ 'sessionProjections',
196
+ 'sessionQuery',
197
+ 'typert',
198
+ 'workspaceRegistry',
199
+ ];
200
+ static Config = z.object({
201
+ nativeOpen: z.boolean(),
202
+ listWorkSliceMs: z.natural().min(1).default(16),
203
+ });
204
+ agents = __runInitializers(this, _instanceExtraInitializers);
205
+ commands;
206
+ controlState;
207
+ history;
208
+ listState;
209
+ openPath;
210
+ fileApplications;
211
+ openFileApplication;
212
+ revealPath;
213
+ canOpenPath;
214
+ promotions = new Set();
215
+ /**
216
+ * @param ctx - Host context containing the Session capability assembly.
217
+ * @param config - native-opener and list-scheduling deployment policy.
218
+ * @param internals - host integrations replaceable by direct unit tests.
219
+ */
220
+ constructor(ctx, config, internals = {}) {
221
+ super(ctx, 'sessionController', { namespace: 'session' });
222
+ ctx.typert.resources.register('session', { field: 'sessionId' });
223
+ const resolved = SessionController.Config(config);
224
+ installModelSelectionProjection(ctx);
225
+ this.agents = new ApiSessionAgentController(ctx);
226
+ this.commands = new SessionCommandController(ctx, this.agents, process.cwd());
227
+ ctx.effect(() => ctx.fileUploads.registerAgentResolver(async (sessionId) => {
228
+ const result = await this.agents.resolveAgent(sessionId);
229
+ if ('error' in result)
230
+ throw result.error;
231
+ return result.agent;
232
+ }), 'session-controller: file-upload Agent resolver');
233
+ this.controlState = new SessionControlController(ctx);
234
+ // Registered before history so reverse-order teardown closes every
235
+ // follower before waiting for already-admitted promotions.
236
+ ctx.effect(() => async () => {
237
+ await Promise.allSettled([...this.promotions]);
238
+ }, 'session-controller.promotions');
239
+ this.history = new SessionHistoryController(ctx, (observation) => { this.promote(observation); });
240
+ this.listState = new ApiSessionList(ctx, resolved.listWorkSliceMs);
241
+ this.fileApplications = internals.fileApplications ?? nativeFileApplications;
242
+ this.openFileApplication = internals.openFileApplication ?? openNativeFileApplication;
243
+ this.openPath = internals.openPath ?? openNativeAssociatedPath;
244
+ this.revealPath = internals.revealPath ?? revealNativePath;
245
+ this.canOpenPath = internals.canOpenPath
246
+ ?? (() => config.nativeOpen ?? (internals.openPath !== undefined || canOpenNativePath()));
247
+ ctx.plugin(SessionFileReferences);
248
+ ctx.plugin(SessionMediaReferences);
249
+ ctx.plugin(SessionSkillCatalog);
250
+ // An archived Session, or a subagent descendant of one, runs no model step
251
+ // until it is restored; what it still runs is stopped by the owners that
252
+ // answer the Workspace registry's archive-admission events.
253
+ ctx.plugin(ArchivedSessionGate);
254
+ ctx.on('session/created', (session) => {
255
+ ctx.emit('api-session/added', this.listState.summaryFor(session));
256
+ });
257
+ ctx.on('session/disposed', (session) => {
258
+ ctx.emit('api-session/removed', session.id);
259
+ });
260
+ const publishAgentAvailability = ({ agent }) => {
261
+ if (ctx.sessions.get(agent.id) === agent.session) {
262
+ ctx.emit('api-session/added', this.listState.summaryFor(agent.session));
263
+ }
264
+ };
265
+ ctx.on('agent/created', publishAgentAvailability);
266
+ ctx.on('agent/disposed', publishAgentAvailability);
267
+ ctx.on('agent/status', ({ agent, status }) => {
268
+ ctx.emit('api-session/status', agent.id, status === 'running');
269
+ });
270
+ ctx.on('agent/error', ({ agent, error }) => {
271
+ ctx.emit('api-session/error', agent.id, errorChain(error));
272
+ });
273
+ ctx.on('session/event', (session, event) => {
274
+ if (event.type === 'request/header') {
275
+ const agent = ctx.agents.get(session.id);
276
+ if (agent?.session === session)
277
+ this.agents.consumeSelection(agent, event.data.header.config.provider, event.data.header.config.model, event.data.header.config.reasoningEffort);
278
+ }
279
+ if (event.type !== 'user/message' || event.data.source.kind !== 'user')
280
+ return;
281
+ ctx.emit('api-session/activity', session.id, event.time);
282
+ });
283
+ }
284
+ promote(observation) {
285
+ const sessionId = observation.header.id;
286
+ const task = (async () => {
287
+ const env_1 = { stack: [], error: void 0, hasError: false };
288
+ try {
289
+ const ownedObservation = __addDisposableResource(env_1, observation, false);
290
+ const result = await this.agents.resolveObservedAgent(ownedObservation);
291
+ if ('error' in result)
292
+ this.ctx.emit('api-session/error', sessionId, result.error.message);
293
+ }
294
+ catch (e_1) {
295
+ env_1.error = e_1;
296
+ env_1.hasError = true;
297
+ }
298
+ finally {
299
+ __disposeResources(env_1);
300
+ }
301
+ })().catch((error) => {
302
+ this.ctx.logger.error(`session-controller: background activation for "${sessionId}" failed: ${errorChain(error)}`);
303
+ });
304
+ this.promotions.add(task);
305
+ void task.finally(() => { this.promotions.delete(task); });
306
+ }
307
+ /**
308
+ * Resolve or resume one ordinary Session for another Host API domain.
309
+ * @param sessionId - Session identity whose Agent owns the operation.
310
+ * @returns the live Agent or the stable Session-domain failure.
311
+ */
312
+ resolveAgent(sessionId) {
313
+ return this.agents.resolveAgent(sessionId);
314
+ }
315
+ /**
316
+ * Inspect one attached or persisted Session without activating its Agent.
317
+ * @param sessionId - durable Session identity.
318
+ * @param signal - optional caller cancellation for persistence reads.
319
+ * @returns the current attached state or persisted header and event prefix.
320
+ */
321
+ inspect(sessionId, signal) {
322
+ const attached = this.ctx.sessions.get(sessionId);
323
+ if (attached !== undefined) {
324
+ return Promise.resolve({
325
+ meta: attached.header,
326
+ inheritedEventCount: attached.inheritedEventCount,
327
+ // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
328
+ events: attached.snapshotEvents(),
329
+ });
330
+ }
331
+ return inspectApiSession(this.ctx, sessionId, signal);
332
+ }
333
+ /**
334
+ * Read all visible Session rows without resuming an Agent.
335
+ * @param _request - reserved empty list request.
336
+ * @param signal - cancellation for persistence reads and summary generation.
337
+ * @returns visible Session summaries ordered by activity.
338
+ */
339
+ async list(_request, signal) {
340
+ const items = await this.listState.list(signal);
341
+ return { items: items.filter(item => this.ctx.remoteAccess.allows({ kind: 'session', id: item.sessionId })) };
342
+ }
343
+ /**
344
+ * Search visible Session content without resuming an Agent. A non-owner
345
+ * receives only the hits whose Session `allows()` admits; `hasMore`
346
+ * describes the bounded result before that filtering.
347
+ * @param request - literal message-content query.
348
+ * @param signal - cancellation for list and search reads.
349
+ * @returns authorized bounded Session search results.
350
+ */
351
+ async search(request, signal) {
352
+ const result = await this.listState.search(request.query, signal);
353
+ return { ...result, items: result.items.filter(item => this.ctx.remoteAccess.allows({ kind: 'session', id: item.sessionId })) };
354
+ }
355
+ /**
356
+ * Create one ordinary Session for a new conversation, reusing the named blank Session while it is reusable.
357
+ * @param request - optional blank Session to reuse, location, and Agent preset.
358
+ * @returns the created or reused Session identity and its preset when configured.
359
+ */
360
+ create(request) {
361
+ return this.commands.create(request);
362
+ }
363
+ /**
364
+ * Select one Session-local model after explicitly resuming the Session; save the default in the background.
365
+ * @param request - Session identity and requested model selection.
366
+ * @returns the normalized selection installed for the Session, without waiting for default persistence.
367
+ */
368
+ selectModel(request) {
369
+ return this.commands.selectModel(request);
370
+ }
371
+ /**
372
+ * Select the first available account model after login when no provider API key is configured.
373
+ * @returns after saving the first available model or retaining the existing default.
374
+ */
375
+ async initializeDefaultModel() {
376
+ const provider = 'deepseek-account';
377
+ if (await hasProviderApiKey(this.ctx))
378
+ return;
379
+ const catalog = await buildModelCatalog(this.ctx);
380
+ const model = catalog.groups.find(group => group.id === provider)?.models[0];
381
+ if (model === undefined)
382
+ throw new RemoteError('session/provider-models-unavailable', `provider "${provider}" has no available models`, { provider });
383
+ const selection = { provider, model: model.id,
384
+ ...model.reasoning?.defaultEffort === undefined ? {} : { reasoningEffort: ReasoningEffortId(model.reasoning.defaultEffort) },
385
+ };
386
+ await this.ctx.agentDefaultModel.saveSelection(selection);
387
+ }
388
+ /**
389
+ * Describe every currently routable model for Host-generation selectors.
390
+ * @returns provider-grouped models, the deployment default, and isolated provider failures.
391
+ */
392
+ modelCatalog() {
393
+ return buildModelCatalog(this.ctx);
394
+ }
395
+ /**
396
+ * Report whether this deployment can hand a Session workspace path to a native desktop.
397
+ * @returns true when the matching open operation is available.
398
+ */
399
+ canOpenWorkspacePath() {
400
+ return this.canOpenPath();
401
+ }
402
+ /**
403
+ * Describe the serving desktop for authenticated file-action routes.
404
+ * @returns Host name, configured availability, and platform-specific file-manager behavior.
405
+ */
406
+ workspaceDesktop() {
407
+ const fileManager = nativeFileManager();
408
+ return { name: hostname(), available: fileManager !== null && this.canOpenPath(), fileManager };
409
+ }
410
+ /**
411
+ * Verify one path through the composed filesystem and open it on the Host desktop.
412
+ * @param request - path after best-effort Session workspace resolution.
413
+ * @param signal - caller lifetime; abort terminates the native command.
414
+ * @returns confirmation after the native opener accepts the path.
415
+ * @throws RemoteError when the request is invalid, has no verified Host mapping, is cancelled, or the opener fails.
416
+ */
417
+ async openWorkspacePath(request, signal) {
418
+ try {
419
+ const path = await this.verifyDesktopPath(request.path, signal);
420
+ if (request.action === 'reveal')
421
+ await this.revealPath(path, signal);
422
+ else if (request.application !== undefined)
423
+ await this.openFileApplication(path, request.application, signal);
424
+ else
425
+ await this.openPath(path, signal);
426
+ return { opened: true };
427
+ }
428
+ catch (error) {
429
+ if (signal.aborted)
430
+ throw new RemoteError('gateway/cancelled', 'path open was aborted', {});
431
+ if (error instanceof RemoteError)
432
+ throw error;
433
+ throw new RemoteError('gateway/internal', 'path open failed', {}, { cause: error });
434
+ }
435
+ }
436
+ /**
437
+ * Query current file handlers on the serving desktop without activating an Agent.
438
+ * @param request - file path in Host filesystem syntax.
439
+ * @param signal - caller lifetime, propagated to filesystem and desktop queries.
440
+ * @returns OS application names, icons, and default selection; empty when desktop opening is unavailable.
441
+ * @throws RemoteError when the path is invalid, the query is cancelled, or native discovery fails.
442
+ */
443
+ async workspacePathApplications(request, signal) {
444
+ if (!this.canOpenPath())
445
+ return [];
446
+ try {
447
+ const path = await this.verifyDesktopPath(request.path, signal);
448
+ return await this.fileApplications(path, signal);
449
+ }
450
+ catch (error) {
451
+ if (signal.aborted)
452
+ throw new RemoteError('gateway/cancelled', 'application query was aborted', {});
453
+ if (error instanceof RemoteError)
454
+ throw error;
455
+ throw new RemoteError('gateway/internal', 'file application query failed', {}, { cause: error });
456
+ }
457
+ }
458
+ async verifyDesktopPath(path, signal) {
459
+ if (path.length === 0)
460
+ throw new RemoteError('gateway/bad-request', 'A non-empty file path is required', {});
461
+ signal.throwIfAborted();
462
+ const hostPath = resolve(path);
463
+ const { fs } = this.ctx;
464
+ const mapped = fs.processPathFromHostPath(hostPath);
465
+ if (mapped === undefined || fs.processPath(await fs.resolve(mapped, { signal })) !== hostPath) {
466
+ throw new RemoteError('gateway/bad-request', 'Path has no verified Host path', {});
467
+ }
468
+ signal.throwIfAborted();
469
+ return hostPath;
470
+ }
471
+ /**
472
+ * Rename one Session after explicitly resuming it.
473
+ * @param request - Session identity and proposed title.
474
+ * @returns the accepted title and durable event sequence.
475
+ */
476
+ rename(request) {
477
+ return this.commands.rename(request);
478
+ }
479
+ /**
480
+ * Fork one cold-readable exact event prefix into a new Session. An omitted
481
+ * boundary selects the latest completed-turn prefix; an open cut receives
482
+ * synthetic fork closers.
483
+ * @param request - source Session, optional exact inclusive event boundary, and migration preflight choice.
484
+ * @returns the new Session identity.
485
+ */
486
+ async fork(request) {
487
+ if (request.allowMigration === false && this.ctx.sessions.get(request.sessionId) === undefined) {
488
+ const stored = await this.ctx.get('sessionPersistence')?.stat(request.sessionId);
489
+ if (stored?.formatStatus === 'migration-required' && this.ctx.sessions.get(request.sessionId) === undefined) {
490
+ throw new RemoteError('session/migration-required', 'Open the source Session to complete migration before forking', {
491
+ sessionId: request.sessionId,
492
+ });
493
+ }
494
+ }
495
+ return this.commands.fork(request);
496
+ }
497
+ /**
498
+ * Admit one prompt after explicitly resuming its Session.
499
+ * @param request - Session identity, prompt content, source metadata, and delivery mode.
500
+ * @param signal - caller cancellation before prompt admission begins.
501
+ * @returns acknowledgement that the Agent accepted the prompt.
502
+ */
503
+ async prompt(request, signal) {
504
+ signal.throwIfAborted();
505
+ if (!hasPromptContent(request.content)) {
506
+ throw new RemoteError('gateway/bad-request', 'prompt content must include non-whitespace text or an attachment', {});
507
+ }
508
+ const clientTimeZone = request.clientTimeZone === undefined
509
+ ? undefined
510
+ : canonicalClientTimeZone(request.clientTimeZone);
511
+ if (request.clientTimeZone !== undefined && clientTimeZone === undefined) {
512
+ throw new RemoteError('session/invalid-time-zone', 'clientTimeZone must be UTC or a valid IANA Area/Location name', { value: request.clientTimeZone });
513
+ }
514
+ // The caller is recorded only when it is not the owner, so owner messages keep their exact source.
515
+ const principal = principalOf(this.ctx.invocation);
516
+ const source = {
517
+ kind: 'user',
518
+ rpcId: request.requestId,
519
+ ...(clientTimeZone === undefined ? {} : { clientTimeZone }),
520
+ ...(principal === undefined ? {} : { principal }),
521
+ };
522
+ return this.commands.prompt(request, source);
523
+ }
524
+ /**
525
+ * Read one image proven reachable from the addressed Session log.
526
+ * @param request - Session and attachment identities used for authorization.
527
+ * @returns the durable attachment reference and base64-encoded bytes.
528
+ */
529
+ attachment(request) {
530
+ return this.commands.attachment(request);
531
+ }
532
+ /**
533
+ * Mutate one still-pending queue occurrence, resuming a cold Agent first.
534
+ * @param request - Session, queue item, and requested mutation.
535
+ * @returns acknowledgement that the queue mutation was applied.
536
+ */
537
+ updateQueue(request) {
538
+ return this.commands.updateQueue(request);
539
+ }
540
+ /**
541
+ * Cancel one active Agent turn without dropping its pending inbox.
542
+ * @param request - Session whose active Agent turn is cancelled.
543
+ * @returns acknowledgement that cancellation was requested.
544
+ */
545
+ cancel(request) {
546
+ return this.commands.cancel(request);
547
+ }
548
+ /**
549
+ * Read one cold-safe, message-aligned Session history page.
550
+ * @param request - durable address, backward cursor, and page budget.
551
+ * @param signal - cancellation for persistence reads.
552
+ * @returns one chronological page.
553
+ */
554
+ page(request, signal) {
555
+ return this.history.page(request, signal);
556
+ }
557
+ /**
558
+ * Follow one Session log from its opening or resume cursor.
559
+ * @param request - durable address and last committed sequence already held by the caller.
560
+ * @param signal - cancellation owned by the Remote stream carrier.
561
+ * @returns a complete opening snapshot followed by gap-free durable event
562
+ * frames and optional cursorless assistant-stream frames.
563
+ */
564
+ follow(request, signal) {
565
+ return this.history.follow(request, signal);
566
+ }
567
+ /**
568
+ * Read exact projections, returning cached hints only when migration is required.
569
+ * @param request - Session whose current values are required.
570
+ * @param signal - cancellation for the Session read.
571
+ * @returns a sequenced baseline, cached hints when migration is deferred, or null when absent.
572
+ */
573
+ async projections(request, signal) {
574
+ const { sessionId } = request;
575
+ if (sessionId.length === 0) {
576
+ throw new RemoteError('gateway/bad-request', 'sessionId must not be empty', {});
577
+ }
578
+ try {
579
+ const env_2 = { stack: [], error: void 0, hasError: false };
580
+ try {
581
+ signal.throwIfAborted();
582
+ const live = this.liveProjections(sessionId);
583
+ if (live !== undefined)
584
+ return live;
585
+ const stored = await this.ctx.get('sessionPersistence')?.stat(sessionId, { signal });
586
+ signal.throwIfAborted();
587
+ const attached = this.liveProjections(sessionId);
588
+ if (attached !== undefined)
589
+ return attached;
590
+ if (stored === undefined)
591
+ return null;
592
+ if (stored.formatStatus === 'migration-required') {
593
+ const cached = this.ctx.get('sessionProjectionCache')?.cachedSnapshot(stored.header);
594
+ return { kind: 'migration-required', values: { ...cached?.values } };
595
+ }
596
+ const observation = __addDisposableResource(env_2, await this.ctx.sessionQuery.observeSession(sessionId, { signal }), false);
597
+ const projections = observation.projections;
598
+ if (projections === undefined) {
599
+ throw new RemoteError('session/projections-unavailable', 'Session projections are unavailable', {});
600
+ }
601
+ return { kind: 'sequenced', asOfSeq: projections.asOfSeq, values: projections.values };
602
+ }
603
+ catch (e_2) {
604
+ env_2.error = e_2;
605
+ env_2.hasError = true;
606
+ }
607
+ finally {
608
+ __disposeResources(env_2);
609
+ }
610
+ }
611
+ catch (error) {
612
+ if (error instanceof SessionQueryError && error.code === 'SESSION_QUERY_SESSION_NOT_FOUND') {
613
+ return this.liveProjections(sessionId) ?? null;
614
+ }
615
+ if (signal.aborted || (error instanceof SessionQueryError && error.code === 'SESSION_QUERY_ABORTED')) {
616
+ throw new RemoteError('gateway/cancelled', 'Session projection read was cancelled', {}, { cause: error });
617
+ }
618
+ if (error instanceof RemoteError)
619
+ throw error;
620
+ throw new RemoteError('gateway/internal', 'Session projection read failed', {}, { cause: error });
621
+ }
622
+ }
623
+ liveProjections(sessionId) {
624
+ const session = this.ctx.sessions.get(sessionId);
625
+ if (session === undefined)
626
+ return undefined;
627
+ const snapshot = this.ctx.sessionProjections.snapshot(session);
628
+ return { kind: 'sequenced', asOfSeq: snapshot.asOfSeq, values: snapshot.values };
629
+ }
630
+ /**
631
+ * Stream a complete live-control baseline followed by replacement frames.
632
+ * @param signal - cancellation owned by the Remote stream carrier.
633
+ * @returns one complete baseline followed by live replacement frames.
634
+ */
635
+ async *control(signal) {
636
+ for await (const frame of this.controlState.control(signal)) {
637
+ switch (frame.type) {
638
+ case 'baseline': {
639
+ const projections = Object.fromEntries(Object.entries(frame.value.projections)
640
+ .filter(([sessionId]) => this.ctx.remoteAccess.allows({ kind: 'session', id: sessionId })));
641
+ yield { type: 'baseline', value: { ...frame.value, projections } };
642
+ break;
643
+ }
644
+ case 'projection':
645
+ if (this.ctx.remoteAccess.allows({ kind: 'session', id: frame.sessionId }))
646
+ yield frame;
647
+ break;
648
+ /* v8 ignore next -- closed control-frame union. */
649
+ default:
650
+ assertNever(frame);
651
+ }
652
+ }
653
+ }
654
+ };
655
+ })();
656
+ export { SessionController };
657
+ export { buildModelCatalog };
658
+ export default SessionController;