@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.
- package/LICENSE +21 -0
- package/README.md +7 -2
- package/lib/client.js +4325 -0
- package/lib/index.js +3367 -0
- package/lib/typert.host.d.ts +3 -0
- package/lib/typert.host.js +4053 -0
- package/lib/typert.remote-client.d.ts +97 -0
- package/lib/typert.remote-client.js +2013 -0
- package/lib/types/agent.d.ts +198 -0
- package/lib/types/agent.js +609 -0
- package/lib/types/archived-session-gate.d.ts +30 -0
- package/lib/types/archived-session-gate.js +51 -0
- package/lib/types/assistant-stream.d.ts +26 -0
- package/lib/types/assistant-stream.js +82 -0
- package/lib/types/catalog.d.ts +24 -0
- package/lib/types/catalog.js +106 -0
- package/lib/types/client/contract/events.d.ts +102 -0
- package/lib/types/client/contract/events.js +111 -0
- package/lib/types/client/contract/session.d.ts +157 -0
- package/lib/types/client/contract/session.js +1 -0
- package/lib/types/client/contract/sessions.d.ts +161 -0
- package/lib/types/client/contract/sessions.js +1 -0
- package/lib/types/client/contract/snapshot.d.ts +81 -0
- package/lib/types/client/contract/snapshot.js +1 -0
- package/lib/types/client/index.d.ts +39 -0
- package/lib/types/client/index.js +60 -0
- package/lib/types/client/ordered-baseline.d.ts +12 -0
- package/lib/types/client/ordered-baseline.js +40 -0
- package/lib/types/client/scope.d.ts +46 -0
- package/lib/types/client/scope.js +46 -0
- package/lib/types/client/session-wire-event.d.ts +11 -0
- package/lib/types/client/session-wire-event.js +42 -0
- package/lib/types/client/sessions/assistant-stream.d.ts +56 -0
- package/lib/types/client/sessions/assistant-stream.js +182 -0
- package/lib/types/client/sessions/history-records.d.ts +22 -0
- package/lib/types/client/sessions/history-records.js +25 -0
- package/lib/types/client/sessions/lineage.d.ts +40 -0
- package/lib/types/client/sessions/lineage.js +54 -0
- package/lib/types/client/sessions/manager.d.ts +269 -0
- package/lib/types/client/sessions/manager.js +799 -0
- package/lib/types/client/sessions/notifier.d.ts +39 -0
- package/lib/types/client/sessions/notifier.js +97 -0
- package/lib/types/client/sessions/projection-store.d.ts +128 -0
- package/lib/types/client/sessions/projection-store.js +161 -0
- package/lib/types/client/sessions/remotes.d.ts +29 -0
- package/lib/types/client/sessions/remotes.js +7 -0
- package/lib/types/client/sessions/service.d.ts +258 -0
- package/lib/types/client/sessions/service.js +582 -0
- package/lib/types/client/sessions/session.d.ts +287 -0
- package/lib/types/client/sessions/session.js +866 -0
- package/lib/types/client/time-zone.d.ts +8 -0
- package/lib/types/client/time-zone.js +13 -0
- package/lib/types/client/transport.d.ts +77 -0
- package/lib/types/client/transport.js +129 -0
- package/lib/types/commands.d.ts +86 -0
- package/lib/types/commands.js +624 -0
- package/lib/types/control.d.ts +20 -0
- package/lib/types/control.js +106 -0
- package/lib/types/file-references.d.ts +27 -0
- package/lib/types/file-references.js +68 -0
- package/lib/types/history.d.ts +32 -0
- package/lib/types/history.js +441 -0
- package/lib/types/index.d.ts +222 -0
- package/lib/types/index.js +658 -0
- package/lib/types/list.d.ts +50 -0
- package/lib/types/list.js +325 -0
- package/lib/types/media-references.d.ts +16 -0
- package/lib/types/media-references.js +76 -0
- package/lib/types/model-selection-projection.d.ts +8 -0
- package/lib/types/model-selection-projection.js +65 -0
- package/lib/types/remote-events.d.ts +8 -0
- package/lib/types/remote-events.js +1 -0
- package/lib/types/skill-catalog.d.ts +28 -0
- package/lib/types/skill-catalog.js +203 -0
- package/lib/types/types.d.ts +611 -0
- package/lib/types/types.js +4 -0
- package/locale/en.json +5 -0
- package/locale/zh.json +6 -0
- package/package.json +114 -4
|
@@ -0,0 +1,624 @@
|
|
|
1
|
+
/** Session commands whose activation policy is explicit at each Remote method. */
|
|
2
|
+
var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {
|
|
3
|
+
if (value !== null && value !== void 0) {
|
|
4
|
+
if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
|
|
5
|
+
var dispose, inner;
|
|
6
|
+
if (async) {
|
|
7
|
+
if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
|
|
8
|
+
dispose = value[Symbol.asyncDispose];
|
|
9
|
+
}
|
|
10
|
+
if (dispose === void 0) {
|
|
11
|
+
if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
|
|
12
|
+
dispose = value[Symbol.dispose];
|
|
13
|
+
if (async) inner = dispose;
|
|
14
|
+
}
|
|
15
|
+
if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
|
|
16
|
+
if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
|
|
17
|
+
env.stack.push({ value: value, dispose: dispose, async: async });
|
|
18
|
+
}
|
|
19
|
+
else if (async) {
|
|
20
|
+
env.stack.push({ async: true });
|
|
21
|
+
}
|
|
22
|
+
return value;
|
|
23
|
+
};
|
|
24
|
+
var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {
|
|
25
|
+
return function (env) {
|
|
26
|
+
function fail(e) {
|
|
27
|
+
env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
|
|
28
|
+
env.hasError = true;
|
|
29
|
+
}
|
|
30
|
+
var r, s = 0;
|
|
31
|
+
function next() {
|
|
32
|
+
while (r = env.stack.pop()) {
|
|
33
|
+
try {
|
|
34
|
+
if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
|
|
35
|
+
if (r.dispose) {
|
|
36
|
+
var result = r.dispose.call(r.value);
|
|
37
|
+
if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
|
|
38
|
+
}
|
|
39
|
+
else s |= 1;
|
|
40
|
+
}
|
|
41
|
+
catch (e) {
|
|
42
|
+
fail(e);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
|
|
46
|
+
if (env.hasError) throw env.error;
|
|
47
|
+
}
|
|
48
|
+
return next();
|
|
49
|
+
};
|
|
50
|
+
})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
|
|
51
|
+
var e = new Error(message);
|
|
52
|
+
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
|
|
53
|
+
});
|
|
54
|
+
import { modelAvailable } from "./catalog.js";
|
|
55
|
+
import { randomUUID } from 'node:crypto';
|
|
56
|
+
import { brandString } from '@unieai/rabi-brand';
|
|
57
|
+
import { AttachmentError } from '@unieai/rabi-attachment';
|
|
58
|
+
import { ReasoningEffortId, assistantStreamChunks, createUserMessage, freezeMessage, } from '@unieai/rabi-llm';
|
|
59
|
+
import { buildForkSeed } from '@unieai/rabi-session/fork';
|
|
60
|
+
import { SessionLogOffset, SessionSeq } from '@unieai/rabi-session';
|
|
61
|
+
import { SessionQueryError } from '@unieai/rabi-session-query';
|
|
62
|
+
import { SessionTitleInvalidError } from '@unieai/rabi-session-title';
|
|
63
|
+
import { assertNever } from '@unieai/rabi-util-values';
|
|
64
|
+
import { RemoteError, remoteErrorOf } from '@unieai/rabi-typert-protocol';
|
|
65
|
+
import { ApiSessionCwdConflict, ApiSessionNotFound, ApiSessionPresetConflict, ApiSessionSubagentOwnership, apiSessionSubagentOwnershipError, hasApiSessionSubagentOwner, inspectApiSession, } from "./agent.js";
|
|
66
|
+
/**
|
|
67
|
+
* Whether prompt content carries non-whitespace text or an attachment.
|
|
68
|
+
* @param content - submitted or edited prompt parts.
|
|
69
|
+
* @returns false for content the Agent must not receive.
|
|
70
|
+
*/
|
|
71
|
+
export function hasPromptContent(content) {
|
|
72
|
+
return content.some(part => part.type !== 'text' || part.text.trim().length > 0);
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Resolve the omitted-`atSeq` default to the latest completed-turn prefix,
|
|
76
|
+
* including standalone events before the next turn begins.
|
|
77
|
+
*/
|
|
78
|
+
function latestCompletedPrefixBoundary(events) {
|
|
79
|
+
const lastTurnEnd = events.findLast(event => event.type === 'turn/end');
|
|
80
|
+
if (lastTurnEnd === undefined)
|
|
81
|
+
return undefined;
|
|
82
|
+
let boundary = lastTurnEnd.seq;
|
|
83
|
+
for (const next of events.slice(boundary + 1)) {
|
|
84
|
+
if (next.type === 'turn/start' || (next.type === 'user/message' && next.surfaceOp === 'append')
|
|
85
|
+
|| next.type === 'agent/inbox/spliced')
|
|
86
|
+
break;
|
|
87
|
+
boundary = next.seq;
|
|
88
|
+
}
|
|
89
|
+
return boundary;
|
|
90
|
+
}
|
|
91
|
+
/** Implements Session business commands delegated by the Session Controller Remote service. */
|
|
92
|
+
export class SessionCommandController {
|
|
93
|
+
ctx;
|
|
94
|
+
agents;
|
|
95
|
+
defaultCwd;
|
|
96
|
+
/**
|
|
97
|
+
* @param ctx - Host context carrying Agent, model, attachment, title, and Workspace services.
|
|
98
|
+
* @param agents - sole owner of create, resume, and Session-local model selection.
|
|
99
|
+
* @param defaultCwd - project directory used when create names neither a Workspace nor a cwd.
|
|
100
|
+
*/
|
|
101
|
+
constructor(ctx, agents, defaultCwd) {
|
|
102
|
+
this.ctx = ctx;
|
|
103
|
+
this.agents = agents;
|
|
104
|
+
this.defaultCwd = defaultCwd;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Create one ordinary Session for a new conversation, reusing the named
|
|
108
|
+
* blank Session while it is an unarchived member of the requested Workspace.
|
|
109
|
+
* @param request - optional blank Session to reuse, location, and Agent preset.
|
|
110
|
+
* @returns the created or reused Session identity and its preset when configured.
|
|
111
|
+
*/
|
|
112
|
+
async create(request) {
|
|
113
|
+
if (request.workspaceId !== undefined && request.cwd !== undefined) {
|
|
114
|
+
throw new RemoteError('gateway/bad-request', 'session.create accepts workspaceId or cwd, not both', {});
|
|
115
|
+
}
|
|
116
|
+
let workspace;
|
|
117
|
+
if (request.workspaceId !== undefined) {
|
|
118
|
+
workspace = this.ctx.workspaceRegistry.get(request.workspaceId);
|
|
119
|
+
if (workspace === undefined) {
|
|
120
|
+
throw new RemoteError('workspace/not-found', `workspace "${request.workspaceId}" not found`, {
|
|
121
|
+
workspaceId: request.workspaceId,
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
const cwd = workspace?.path ?? request.cwd ?? this.defaultCwd;
|
|
126
|
+
let created;
|
|
127
|
+
try {
|
|
128
|
+
created = await this.agents.createSession({
|
|
129
|
+
...(request.sessionId === undefined ? {} : { sessionId: request.sessionId }),
|
|
130
|
+
cwd,
|
|
131
|
+
...(request.agentPreset === undefined ? {} : { agentPreset: request.agentPreset }),
|
|
132
|
+
reusable: sessionId => !this.ctx.workspaceRegistry.archivedSessionIds.includes(sessionId)
|
|
133
|
+
&& (workspace === undefined || workspace.sessionIds.includes(sessionId)),
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
catch (error) {
|
|
137
|
+
this.rejectCreation(error);
|
|
138
|
+
}
|
|
139
|
+
const sessionId = created.agent.id;
|
|
140
|
+
if (workspace !== undefined) {
|
|
141
|
+
try {
|
|
142
|
+
await workspace.attachSession(sessionId);
|
|
143
|
+
}
|
|
144
|
+
catch (error) {
|
|
145
|
+
throw new RemoteError('session/workspace-attach-failed', `session "${sessionId}" was created but could not attach to workspace "${workspace.id}": ${String(error)}`, { sessionId, workspaceId: workspace.id });
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
return { sessionId, ...(created.agentPreset === undefined ? {} : { agentPreset: created.agentPreset }) };
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Validate and install one Session-local model selection; save the default in the background.
|
|
152
|
+
* @param request - Session identity and requested model selection.
|
|
153
|
+
* @returns the normalized selection installed for the Session, without waiting for default persistence.
|
|
154
|
+
*/
|
|
155
|
+
async selectModel(request) {
|
|
156
|
+
const agent = await this.resolveAgent(request.sessionId);
|
|
157
|
+
return this.agents.serializeImageAdmission(agent, async () => {
|
|
158
|
+
try {
|
|
159
|
+
await this.requireModel(request);
|
|
160
|
+
const resolved = await this.ctx.llm.resolveCallConfig({
|
|
161
|
+
provider: request.provider,
|
|
162
|
+
model: request.model,
|
|
163
|
+
...(request.reasoningEffort === undefined
|
|
164
|
+
? {}
|
|
165
|
+
: { reasoningEffort: ReasoningEffortId(request.reasoningEffort) }),
|
|
166
|
+
});
|
|
167
|
+
const selected = {
|
|
168
|
+
provider: resolved.provider,
|
|
169
|
+
model: resolved.model,
|
|
170
|
+
...(resolved.reasoningEffort === undefined
|
|
171
|
+
? {}
|
|
172
|
+
: { reasoningEffort: resolved.reasoningEffort }),
|
|
173
|
+
};
|
|
174
|
+
this.agents.selectForNextRequest(agent, selected);
|
|
175
|
+
void this.ctx.agentDefaultModel.saveSelection(selected).catch((error) => {
|
|
176
|
+
this.ctx.logger.warn(`session-controller: model selection changed for the Session but the default was not saved: ${String(error)}`);
|
|
177
|
+
});
|
|
178
|
+
return { selected: { ...selected } };
|
|
179
|
+
}
|
|
180
|
+
catch (error) {
|
|
181
|
+
if (remoteErrorOf(error) !== undefined)
|
|
182
|
+
throw error;
|
|
183
|
+
throw new RemoteError('session/model-unavailable', error instanceof Error ? error.message : String(error), { provider: request.provider, model: request.model });
|
|
184
|
+
}
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* Normalize and append a user-owned Session title.
|
|
189
|
+
* @param request - Session identity and proposed title.
|
|
190
|
+
* @returns the accepted title and durable event sequence.
|
|
191
|
+
*/
|
|
192
|
+
async rename(request) {
|
|
193
|
+
const agent = await this.resolveAgent(request.sessionId);
|
|
194
|
+
const titles = this.ctx.get('sessionTitle');
|
|
195
|
+
if (titles === undefined) {
|
|
196
|
+
throw new RemoteError('gateway/internal', 'renaming is unavailable: this deployment mounts no session-title service', {});
|
|
197
|
+
}
|
|
198
|
+
try {
|
|
199
|
+
const accepted = titles.rename(agent.session, request.title);
|
|
200
|
+
return { title: accepted.title, seq: accepted.eventSeq };
|
|
201
|
+
}
|
|
202
|
+
catch (error) {
|
|
203
|
+
if (error instanceof SessionTitleInvalidError) {
|
|
204
|
+
throw new RemoteError('session/title-invalid', error.message, { sessionId: request.sessionId });
|
|
205
|
+
}
|
|
206
|
+
throw new RemoteError('gateway/internal', `failed to rename session "${request.sessionId}": ${String(error)}`, {});
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Create a new ordinary Session from an exact event prefix. An explicit
|
|
211
|
+
* `atSeq` is the inclusive cut; an omitted value selects the latest
|
|
212
|
+
* completed-turn prefix. An open cut receives synthetic fork closers.
|
|
213
|
+
* @param request - source Session and optional exact event boundary.
|
|
214
|
+
* @returns the new Session identity.
|
|
215
|
+
*/
|
|
216
|
+
async fork(request) {
|
|
217
|
+
const env_1 = { stack: [], error: void 0, hasError: false };
|
|
218
|
+
try {
|
|
219
|
+
let atSeq;
|
|
220
|
+
try {
|
|
221
|
+
atSeq = request.atSeq === undefined ? undefined : SessionSeq(request.atSeq);
|
|
222
|
+
}
|
|
223
|
+
catch {
|
|
224
|
+
throw new RemoteError('gateway/bad-request', 'atSeq must be a non-negative safe integer', {});
|
|
225
|
+
}
|
|
226
|
+
let observed;
|
|
227
|
+
try {
|
|
228
|
+
observed = await this.ctx.sessionQuery.observeSession(request.sessionId);
|
|
229
|
+
}
|
|
230
|
+
catch (error) {
|
|
231
|
+
if (error instanceof SessionQueryError
|
|
232
|
+
&& error.code === 'SESSION_QUERY_SESSION_NOT_FOUND') {
|
|
233
|
+
throw new RemoteError('session/not-found', `session "${request.sessionId}" not found`, {
|
|
234
|
+
sessionId: request.sessionId,
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
throw new RemoteError('gateway/internal', `fork source unavailable for session "${request.sessionId}": ${String(error)}`, {});
|
|
238
|
+
}
|
|
239
|
+
const source = __addDisposableResource(env_1, observed, false);
|
|
240
|
+
const boundary = atSeq ?? latestCompletedPrefixBoundary(source.events);
|
|
241
|
+
if (boundary === undefined || source.events[boundary]?.seq !== boundary) {
|
|
242
|
+
throw new RemoteError('session/fork-unavailable', request.atSeq === undefined
|
|
243
|
+
? `session "${request.sessionId}" has no completed turn to fork from`
|
|
244
|
+
: `event ${String(request.atSeq)} does not exist in session "${request.sessionId}" (last seq: ${String(source.events.at(-1)?.seq ?? 'none')})`, { sessionId: request.sessionId });
|
|
245
|
+
}
|
|
246
|
+
const seed = buildForkSeed(source.events, boundary);
|
|
247
|
+
let workspace;
|
|
248
|
+
try {
|
|
249
|
+
workspace = await this.forkWorkspace(source.header);
|
|
250
|
+
}
|
|
251
|
+
catch (error) {
|
|
252
|
+
throw new RemoteError('gateway/internal', `failed to resolve fork workspace for session "${request.sessionId}": ${String(error)}`, {});
|
|
253
|
+
}
|
|
254
|
+
const childId = brandString(`session-${randomUUID()}`);
|
|
255
|
+
const composition = await this.agents.composeAgent(this.agents.presetForObservation(source));
|
|
256
|
+
try {
|
|
257
|
+
const { provider, model } = this.ctx.agentDefaultModel.currentSelection();
|
|
258
|
+
await this.ctx.agents.create({
|
|
259
|
+
sessionId: childId,
|
|
260
|
+
seed,
|
|
261
|
+
inheritedEventCount: SessionLogOffset(boundary + 1),
|
|
262
|
+
meta: {
|
|
263
|
+
...(source.header.cwd === undefined ? {} : { cwd: source.header.cwd }),
|
|
264
|
+
parentSession: source.header.id,
|
|
265
|
+
isSeeded: true,
|
|
266
|
+
...(composition.agentPreset === undefined
|
|
267
|
+
? {}
|
|
268
|
+
: { agentPreset: composition.agentPreset }),
|
|
269
|
+
},
|
|
270
|
+
agentOptions: { provider, model },
|
|
271
|
+
setup: composition.setup,
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
catch (error) {
|
|
275
|
+
throw new RemoteError('gateway/internal', `failed to fork session "${request.sessionId}": ${String(error)}`, {});
|
|
276
|
+
}
|
|
277
|
+
if (workspace !== undefined) {
|
|
278
|
+
try {
|
|
279
|
+
await workspace.attachSession(childId);
|
|
280
|
+
}
|
|
281
|
+
catch (error) {
|
|
282
|
+
throw new RemoteError('session/workspace-attach-failed', `session "${childId}" was forked but could not attach to workspace "${workspace.id}": ${String(error)}`, { sessionId: childId, workspaceId: workspace.id });
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
return { sessionId: childId };
|
|
286
|
+
}
|
|
287
|
+
catch (e_1) {
|
|
288
|
+
env_1.error = e_1;
|
|
289
|
+
env_1.hasError = true;
|
|
290
|
+
}
|
|
291
|
+
finally {
|
|
292
|
+
__disposeResources(env_1);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* Admit one prompt after Agent and attachment validation; the Remote method
|
|
297
|
+
* has already validated the content and built the durable message source.
|
|
298
|
+
* @param request - Session identity, prompt content, and delivery mode.
|
|
299
|
+
* @param source - the `user-rpc` source recorded on the accepted message.
|
|
300
|
+
* @returns acknowledgement that the Agent accepted the prompt.
|
|
301
|
+
*/
|
|
302
|
+
async prompt(request, source) {
|
|
303
|
+
const agent = await this.resolveAgent(request.sessionId);
|
|
304
|
+
if (hasPromptRequest(agent, request.requestId))
|
|
305
|
+
return { accepted: true };
|
|
306
|
+
const hasImage = request.content.some(part => part.type === 'image');
|
|
307
|
+
const admit = async () => {
|
|
308
|
+
try {
|
|
309
|
+
const env_2 = { stack: [], error: void 0, hasError: false };
|
|
310
|
+
try {
|
|
311
|
+
if (hasImage) {
|
|
312
|
+
const current = this.agents.selectionFor(agent).current;
|
|
313
|
+
const model = await this.ctx.llm.resolveModelInfo(current.provider, current.model);
|
|
314
|
+
if (model.inputModalities !== undefined && !model.inputModalities.includes('image')) {
|
|
315
|
+
throw new RemoteError('session/attachment-invalid', `Model "${current.model}" does not support image input.`, { reason: 'MODEL_DOES_NOT_SUPPORT_IMAGES' });
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
const admission = resolvePromptFileReceipts(request.content, receiptId => this.ctx.fileUploads.resolve(agent, receiptId));
|
|
319
|
+
const content = await this.ctx.attachments.admitPromptContent(admission.content);
|
|
320
|
+
const message = createUserMessage({ content, source });
|
|
321
|
+
if (this.ctx.agents.get(agent.id) !== agent) {
|
|
322
|
+
throw new RemoteError('session/not-found', `session "${agent.id}" was disposed during prompt admission`, { sessionId: agent.id });
|
|
323
|
+
}
|
|
324
|
+
const binding = __addDisposableResource(env_2, this.ctx.fileUploads.bindPrompt(agent, admission.receiptIds, request.requestId), false);
|
|
325
|
+
if (request.mode === 'steer')
|
|
326
|
+
agent.steer(message);
|
|
327
|
+
else
|
|
328
|
+
agent.followup(message);
|
|
329
|
+
binding.commit();
|
|
330
|
+
}
|
|
331
|
+
catch (e_2) {
|
|
332
|
+
env_2.error = e_2;
|
|
333
|
+
env_2.hasError = true;
|
|
334
|
+
}
|
|
335
|
+
finally {
|
|
336
|
+
__disposeResources(env_2);
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
catch (error) {
|
|
340
|
+
if (remoteErrorOf(error) !== undefined)
|
|
341
|
+
throw error;
|
|
342
|
+
if (error instanceof AttachmentError) {
|
|
343
|
+
throw new RemoteError('session/attachment-invalid', error.message, { reason: error.code });
|
|
344
|
+
}
|
|
345
|
+
throw new RemoteError('session/agent-busy', 'prompt rejected', { reason: String(error) });
|
|
346
|
+
}
|
|
347
|
+
return { accepted: true };
|
|
348
|
+
};
|
|
349
|
+
return hasImage ? this.agents.serializeImageAdmission(agent, admit) : admit();
|
|
350
|
+
}
|
|
351
|
+
async requireModel(selection) {
|
|
352
|
+
if (!await modelAvailable(this.ctx, selection)) {
|
|
353
|
+
throw new RemoteError('session/model-unavailable', 'Select an available model before sending a message.', { provider: selection.provider, model: selection.model });
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
/**
|
|
357
|
+
* Read one durable image after proving the Session log references it.
|
|
358
|
+
* @param request - Session and attachment identities used for authorization.
|
|
359
|
+
* @returns the durable attachment reference and base64-encoded bytes.
|
|
360
|
+
*/
|
|
361
|
+
async attachment(request) {
|
|
362
|
+
let source;
|
|
363
|
+
try {
|
|
364
|
+
source = await this.readSessionState(request.sessionId);
|
|
365
|
+
}
|
|
366
|
+
catch (error) {
|
|
367
|
+
if (error instanceof ApiSessionNotFound) {
|
|
368
|
+
throw new RemoteError('session/not-found', error.message, { sessionId: request.sessionId });
|
|
369
|
+
}
|
|
370
|
+
throw new RemoteError('gateway/internal', `attachment authorization unavailable for session "${request.sessionId}": ${String(error)}`, {});
|
|
371
|
+
}
|
|
372
|
+
const ref = referencedImage(source.events, String(request.attachmentId));
|
|
373
|
+
if (ref === undefined) {
|
|
374
|
+
throw new RemoteError('session/attachment-invalid', 'Image is not referenced by this session.', { reason: 'ATTACHMENT_NOT_REFERENCED' });
|
|
375
|
+
}
|
|
376
|
+
try {
|
|
377
|
+
const stored = await this.ctx.attachments.readImage(ref);
|
|
378
|
+
return {
|
|
379
|
+
attachment: stored.ref,
|
|
380
|
+
data: Buffer.from(stored.data).toString('base64'),
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
catch (error) {
|
|
384
|
+
if (error instanceof AttachmentError) {
|
|
385
|
+
throw new RemoteError('session/attachment-invalid', error.message, { reason: error.code });
|
|
386
|
+
}
|
|
387
|
+
throw new RemoteError('gateway/internal', 'Unable to read image attachment.', {});
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
/**
|
|
391
|
+
* Mutate one pending Inbox occurrence, restoring an ordinary cold Agent when needed.
|
|
392
|
+
* @param request - Session, queue item, and requested mutation.
|
|
393
|
+
* @returns acknowledgement that the queue mutation was applied.
|
|
394
|
+
*/
|
|
395
|
+
async updateQueue(request) {
|
|
396
|
+
if (request.action.kind === 'edit') {
|
|
397
|
+
// oxlint-disable-next-line typescript/no-unnecessary-condition -- Remote callers can submit untyped JSON.
|
|
398
|
+
if (request.action.content.some(block => block.type !== 'text')) {
|
|
399
|
+
throw new RemoteError('session/attachment-invalid', 'queue edits accept text content only', { reason: 'QUEUE_EDIT_NON_TEXT' });
|
|
400
|
+
}
|
|
401
|
+
if (!hasPromptContent(request.action.content)) {
|
|
402
|
+
throw new RemoteError('gateway/bad-request', 'queue edit content must include non-whitespace text', {});
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
let agent = this.ctx.agents.get(request.sessionId);
|
|
406
|
+
if (agent === undefined) {
|
|
407
|
+
const found = await this.agents.resolveAgent(request.sessionId);
|
|
408
|
+
if ('error' in found) {
|
|
409
|
+
if (found.error.code !== 'session/not-found')
|
|
410
|
+
throw found.error;
|
|
411
|
+
throw new RemoteError('session/queue-item-not-found', 'queued item is no longer pending', { itemId: request.itemId });
|
|
412
|
+
}
|
|
413
|
+
agent = found.agent;
|
|
414
|
+
}
|
|
415
|
+
if (hasApiSessionSubagentOwner(this.ctx, agent.session, agent)) {
|
|
416
|
+
const identity = this.ctx.sessionProjections
|
|
417
|
+
.snapshot(agent.session, ['subagent'])
|
|
418
|
+
.values.subagent;
|
|
419
|
+
if (identity?.mode !== 'continuable'
|
|
420
|
+
|| !agent.session.isOwnSeq(identity.seq)) {
|
|
421
|
+
throw apiSessionSubagentOwnershipError(request.sessionId);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
const nextTurn = agent.inbox.nextTurn.find(message => message.id === request.itemId);
|
|
425
|
+
const nextStep = agent.inbox.nextStep.find(message => message.id === request.itemId);
|
|
426
|
+
const located = nextTurn === undefined
|
|
427
|
+
? nextStep === undefined ? undefined : { target: 'next-step', message: nextStep }
|
|
428
|
+
: { target: 'next-turn', message: nextTurn };
|
|
429
|
+
if (located === undefined) {
|
|
430
|
+
throw new RemoteError('session/queue-item-not-found', 'queued item is no longer pending', { itemId: request.itemId });
|
|
431
|
+
}
|
|
432
|
+
const { target, message } = located;
|
|
433
|
+
if (request.action.kind === 'steer' && (target !== 'next-turn' || agent.status !== 'running')) {
|
|
434
|
+
throw new RemoteError('session/steer-unavailable', 'current turn no longer accepts steering', { itemId: request.itemId });
|
|
435
|
+
}
|
|
436
|
+
switch (request.action.kind) {
|
|
437
|
+
case 'edit':
|
|
438
|
+
agent.inbox.replace(request.itemId, freezeMessage({
|
|
439
|
+
...message,
|
|
440
|
+
content: [...request.action.content],
|
|
441
|
+
}));
|
|
442
|
+
break;
|
|
443
|
+
case 'remove': {
|
|
444
|
+
agent.inbox.remove(request.itemId);
|
|
445
|
+
const source = message.source;
|
|
446
|
+
if (source.kind === 'user' && 'rpcId' in source) {
|
|
447
|
+
this.ctx.fileUploads.retirePrompt(agent, source.rpcId);
|
|
448
|
+
}
|
|
449
|
+
break;
|
|
450
|
+
}
|
|
451
|
+
case 'steer':
|
|
452
|
+
agent.inbox.remove(request.itemId);
|
|
453
|
+
agent.steer(message);
|
|
454
|
+
break;
|
|
455
|
+
/* v8 ignore next 2 -- closed-union exhaustiveness guard */
|
|
456
|
+
default:
|
|
457
|
+
assertNever(request.action, 'queue action');
|
|
458
|
+
}
|
|
459
|
+
return { accepted: true };
|
|
460
|
+
}
|
|
461
|
+
/**
|
|
462
|
+
* Cancel one live ordinary Agent while retaining pending inbox work.
|
|
463
|
+
* @param request - Session whose active Agent turn is cancelled.
|
|
464
|
+
* @returns acknowledgement that cancellation was requested.
|
|
465
|
+
*/
|
|
466
|
+
cancel(request) {
|
|
467
|
+
const agent = this.ctx.agents.get(request.sessionId);
|
|
468
|
+
if (agent === undefined) {
|
|
469
|
+
throw new RemoteError('session/not-found', `session "${request.sessionId}" not found (not attached)`, { sessionId: request.sessionId });
|
|
470
|
+
}
|
|
471
|
+
if (hasApiSessionSubagentOwner(this.ctx, agent.session, agent)) {
|
|
472
|
+
throw apiSessionSubagentOwnershipError(request.sessionId);
|
|
473
|
+
}
|
|
474
|
+
agent.cancel({ kind: 'user' }, { keepInbox: true });
|
|
475
|
+
return { accepted: true };
|
|
476
|
+
}
|
|
477
|
+
async resolveAgent(sessionId) {
|
|
478
|
+
const found = await this.agents.resolveAgent(sessionId);
|
|
479
|
+
if ('error' in found)
|
|
480
|
+
throw found.error;
|
|
481
|
+
return found.agent;
|
|
482
|
+
}
|
|
483
|
+
rejectCreation(error) {
|
|
484
|
+
if (remoteErrorOf(error) !== undefined)
|
|
485
|
+
throw error;
|
|
486
|
+
if (error instanceof ApiSessionPresetConflict) {
|
|
487
|
+
throw new RemoteError('agent-preset/conflict', error.message, {
|
|
488
|
+
sessionId: error.sessionId,
|
|
489
|
+
requestedPreset: error.requestedPreset,
|
|
490
|
+
});
|
|
491
|
+
}
|
|
492
|
+
if (error instanceof ApiSessionCwdConflict) {
|
|
493
|
+
throw new RemoteError('session/conflict', error.message, {
|
|
494
|
+
sessionId: error.sessionId,
|
|
495
|
+
requestedCwd: error.requestedCwd,
|
|
496
|
+
...(error.existingCwd === undefined ? {} : { existingCwd: error.existingCwd }),
|
|
497
|
+
});
|
|
498
|
+
}
|
|
499
|
+
if (error instanceof ApiSessionSubagentOwnership) {
|
|
500
|
+
throw apiSessionSubagentOwnershipError(error.sessionId);
|
|
501
|
+
}
|
|
502
|
+
throw new RemoteError('gateway/internal', `failed to create session: ${String(error)}`, {});
|
|
503
|
+
}
|
|
504
|
+
async readSessionState(sessionId) {
|
|
505
|
+
const attached = this.ctx.sessions.get(sessionId);
|
|
506
|
+
if (attached !== undefined) {
|
|
507
|
+
// oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
|
|
508
|
+
return { id: attached.id, header: attached.header, events: attached.snapshotEvents() };
|
|
509
|
+
}
|
|
510
|
+
const inspected = await inspectApiSession(this.ctx, sessionId);
|
|
511
|
+
return { id: inspected.meta.id, header: inspected.meta, events: inspected.events };
|
|
512
|
+
}
|
|
513
|
+
async forkWorkspace(source) {
|
|
514
|
+
const workspaces = this.ctx.workspaceRegistry.list();
|
|
515
|
+
const direct = workspaces.find(workspace => workspace.sessionIds.includes(source.id));
|
|
516
|
+
if (direct !== undefined || source.origin !== 'subagent')
|
|
517
|
+
return direct;
|
|
518
|
+
const lineage = await this.ctx.sessionQuery.traceSession(source.id);
|
|
519
|
+
for (const ancestor of lineage.ancestors) {
|
|
520
|
+
const workspace = workspaces.find(candidate => candidate.sessionIds.includes(ancestor.header.id));
|
|
521
|
+
if (workspace !== undefined)
|
|
522
|
+
return workspace;
|
|
523
|
+
}
|
|
524
|
+
return undefined;
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
function resolvePromptFileReceipts(content, stagedFile) {
|
|
528
|
+
const receiptIds = new Set();
|
|
529
|
+
const resolved = content.map((part) => {
|
|
530
|
+
if (part.type !== 'file')
|
|
531
|
+
return part;
|
|
532
|
+
const attachment = stagedFile(part.receiptId);
|
|
533
|
+
if (attachment === undefined) {
|
|
534
|
+
throw new RemoteError('session/attachment-invalid', 'File was not uploaded for this session.', { reason: 'FILE_NOT_STAGED' });
|
|
535
|
+
}
|
|
536
|
+
receiptIds.add(part.receiptId);
|
|
537
|
+
return { type: 'file', attachment };
|
|
538
|
+
});
|
|
539
|
+
return { content: resolved, receiptIds: [...receiptIds] };
|
|
540
|
+
}
|
|
541
|
+
function hasPromptRequest(agent, requestId) {
|
|
542
|
+
const matches = (message) => {
|
|
543
|
+
const source = message.source;
|
|
544
|
+
return source.kind === 'user' && 'rpcId' in source && source.rpcId === requestId;
|
|
545
|
+
};
|
|
546
|
+
if (agent.inbox.nextTurn.some(matches) || agent.inbox.nextStep.some(matches))
|
|
547
|
+
return true;
|
|
548
|
+
// oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
|
|
549
|
+
return agent.session.snapshotEvents().some((event) => {
|
|
550
|
+
if (event.type !== 'user/message')
|
|
551
|
+
return false;
|
|
552
|
+
const source = event.data.source;
|
|
553
|
+
return source.kind === 'user' && 'rpcId' in source && source.rpcId === requestId;
|
|
554
|
+
});
|
|
555
|
+
}
|
|
556
|
+
function imageBlockIn(content, match) {
|
|
557
|
+
if (!Array.isArray(content))
|
|
558
|
+
return undefined;
|
|
559
|
+
for (const value of content) {
|
|
560
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value))
|
|
561
|
+
continue;
|
|
562
|
+
const block = value;
|
|
563
|
+
if (block.type === 'image' && typeof block.attachment === 'object' && block.attachment !== null) {
|
|
564
|
+
const ref = block.attachment;
|
|
565
|
+
if (match(ref))
|
|
566
|
+
return ref;
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
return undefined;
|
|
570
|
+
}
|
|
571
|
+
/** Read only first-party declared content fields; unknown event payloads stay opaque. */
|
|
572
|
+
function imageInEvent(event, match) {
|
|
573
|
+
const data = event.data;
|
|
574
|
+
// First-party event payloads can be present without their producer plugin mounted.
|
|
575
|
+
const type = event.type;
|
|
576
|
+
switch (type) {
|
|
577
|
+
case 'user/message':
|
|
578
|
+
case 'tool/ptc-dispatch':
|
|
579
|
+
return imageBlockIn(data.content, match);
|
|
580
|
+
case 'system/message':
|
|
581
|
+
case 'developer/message':
|
|
582
|
+
case 'tool/result':
|
|
583
|
+
case 'team/message/queued':
|
|
584
|
+
return imageBlockIn(data.message?.content, match);
|
|
585
|
+
case 'agent/inbox/spliced': {
|
|
586
|
+
const messages = data.inserted;
|
|
587
|
+
if (!Array.isArray(messages))
|
|
588
|
+
return undefined;
|
|
589
|
+
for (const message of messages) {
|
|
590
|
+
if (typeof message !== 'object' || message === null || Array.isArray(message))
|
|
591
|
+
continue;
|
|
592
|
+
const found = imageBlockIn(message.content, match);
|
|
593
|
+
if (found !== undefined)
|
|
594
|
+
return found;
|
|
595
|
+
}
|
|
596
|
+
return undefined;
|
|
597
|
+
}
|
|
598
|
+
case 'compaction/summary':
|
|
599
|
+
return imageBlockIn(data.summary, match) ?? imageBlockIn(data.rawOutput, match);
|
|
600
|
+
case 'assistant/message': {
|
|
601
|
+
const found = imageBlockIn(data.message?.content, match);
|
|
602
|
+
if (found !== undefined)
|
|
603
|
+
return found;
|
|
604
|
+
break;
|
|
605
|
+
}
|
|
606
|
+
case 'assistant/attempt': break;
|
|
607
|
+
default: return undefined;
|
|
608
|
+
}
|
|
609
|
+
const assistant = event;
|
|
610
|
+
for (const chunk of assistantStreamChunks(assistant.data.stream, 'block-end')) {
|
|
611
|
+
const found = imageBlockIn([chunk.block], match);
|
|
612
|
+
if (found !== undefined)
|
|
613
|
+
return found;
|
|
614
|
+
}
|
|
615
|
+
return undefined;
|
|
616
|
+
}
|
|
617
|
+
function referencedImage(events, attachmentId) {
|
|
618
|
+
for (const event of events) {
|
|
619
|
+
const found = imageInEvent(event, ref => String(ref.attachmentId) === attachmentId);
|
|
620
|
+
if (found !== undefined)
|
|
621
|
+
return found;
|
|
622
|
+
}
|
|
623
|
+
return undefined;
|
|
624
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** Live Session projection state with reconnect baselines. */
|
|
2
|
+
import type { Context } from '@unieai/cordis';
|
|
3
|
+
import type { SessionControlFrame } from './types.ts';
|
|
4
|
+
/** Owns the Host-wide Session control stream. */
|
|
5
|
+
export declare class SessionControlController {
|
|
6
|
+
private readonly ctx;
|
|
7
|
+
private readonly streams;
|
|
8
|
+
/** @param ctx - Host context carrying live Agent and projection services. */
|
|
9
|
+
constructor(ctx: Context);
|
|
10
|
+
/**
|
|
11
|
+
* Open one generation of Host-wide live control state.
|
|
12
|
+
* @param signal - Remote stream cancellation.
|
|
13
|
+
* @returns one complete baseline followed by live replacement frames.
|
|
14
|
+
*/
|
|
15
|
+
control(signal: AbortSignal): AsyncIterable<SessionControlFrame>;
|
|
16
|
+
private baseline;
|
|
17
|
+
private projectionBaseline;
|
|
18
|
+
private broadcast;
|
|
19
|
+
}
|
|
20
|
+
//# sourceMappingURL=control.d.ts.map
|