@x-otto/service 0.1.0-alpha.9 → 0.4.0-beta.0
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/dist/ask-host.d.ts +18 -0
- package/dist/ask-validate.d.ts +47 -0
- package/dist/attached-writers.d.ts +9 -0
- package/dist/authorize.d.ts +8 -0
- package/dist/chat-routes.d.ts +4 -0
- package/dist/client-entry.d.ts +114 -0
- package/dist/client-entry.js +1414 -0
- package/dist/connection-binding.d.ts +9 -0
- package/dist/context.d.ts +51 -0
- package/dist/credential.d.ts +51 -0
- package/dist/errors.d.ts +11 -0
- package/dist/events.d.ts +21 -0
- package/dist/extension-approval.d.ts +41 -0
- package/dist/extension-rpc.d.ts +31 -0
- package/dist/fanout.d.ts +13 -0
- package/dist/handler-options.d.ts +252 -0
- package/dist/handlers.d.ts +23 -0
- package/dist/hub-capabilities.d.ts +15 -0
- package/dist/index.d.ts +1144 -625
- package/dist/index.js +8591 -44
- package/dist/methods.d.ts +5 -0
- package/dist/mock.d.ts +23 -0
- package/dist/resource-read.d.ts +4 -0
- package/dist/route-read-only.d.ts +1 -0
- package/dist/route-set.d.ts +22 -0
- package/dist/route-targets.d.ts +6 -0
- package/dist/route-validate.d.ts +15 -0
- package/dist/routes/ask-routes.d.ts +3 -0
- package/dist/routes/auth-routes.d.ts +3 -0
- package/dist/routes/core-routes.d.ts +3 -0
- package/dist/routes/extension-routes.d.ts +3 -0
- package/dist/routes/index.d.ts +6 -0
- package/dist/routes/plugin-routes.d.ts +3 -0
- package/dist/routes/repository-meta.d.ts +2 -0
- package/dist/routes/session-routes.d.ts +3 -0
- package/dist/routes/session-runtime-routes.d.ts +5 -0
- package/dist/routes/settings-routes.d.ts +3 -0
- package/dist/routes/support.d.ts +7 -0
- package/dist/routes/worker-routes.d.ts +2 -0
- package/dist/routes/workspace-routes.d.ts +3 -0
- package/dist/send-attempt-table.d.ts +35 -0
- package/dist/serialize-shared.d.ts +1 -0
- package/dist/source-for-session.d.ts +4 -0
- package/dist/subscription-backfill.d.ts +19 -0
- package/dist/target-extractors.d.ts +18 -0
- package/dist/token-verifier.d.ts +12 -0
- package/dist/vite.d.ts +11 -0
- package/dist/vite.js +4273 -0
- package/dist/web-host.d.ts +52 -0
- package/dist/wire-stats.d.ts +6 -0
- package/dist/wire.d.ts +12 -0
- package/dist/ws.d.ts +66 -0
- package/package.json +19 -31
- package/README.md +0 -135
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
package/dist/vite.js
ADDED
|
@@ -0,0 +1,4273 @@
|
|
|
1
|
+
import { createHash, randomUUID, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { AUTH_LOGIN_ASYNC_FEATURE, OFFERED_PERMISSION_MODES, PERMISSION_MODE_FIELD_SPEC, PERMISSION_MODE_SETTING_KEY, THINKING_LEVELS, effectiveSessionVisibility, isPermissionMode, matchesSessionSearch, parseThinkingLevel, parseWebLayoutPreferences, registerCapacityWireStatsProbe, sessionAccessStateOf } from "@x-otto/kernel";
|
|
3
|
+
import { WebSocket, WebSocketServer } from "ws";
|
|
4
|
+
import "@x-otto/kernel/sandbox";
|
|
5
|
+
|
|
6
|
+
//#region src/credential.ts
|
|
7
|
+
function eventsOfCredential(credential) {
|
|
8
|
+
return credential.kind === "ticket" ? credential.claims.events : void 0;
|
|
9
|
+
}
|
|
10
|
+
const TICKET_READ_METHODS = [
|
|
11
|
+
"session.list",
|
|
12
|
+
"session.restore",
|
|
13
|
+
"plan.list",
|
|
14
|
+
"model.list",
|
|
15
|
+
"ui.catalog",
|
|
16
|
+
"ui.preferences.get",
|
|
17
|
+
"resource.read",
|
|
18
|
+
"workspace.list",
|
|
19
|
+
"mention.search",
|
|
20
|
+
"command.catalog",
|
|
21
|
+
"repository.readCommitted",
|
|
22
|
+
"repository.readEvents",
|
|
23
|
+
"repository.countEvents",
|
|
24
|
+
"repository.loadMeta"
|
|
25
|
+
];
|
|
26
|
+
function sessionIdOf(payload) {
|
|
27
|
+
if (typeof payload !== "object" || payload === null) return;
|
|
28
|
+
const sessionId = payload.sessionId;
|
|
29
|
+
return typeof sessionId === "string" && sessionId !== "" ? sessionId : void 0;
|
|
30
|
+
}
|
|
31
|
+
function takeoverRequested(payload) {
|
|
32
|
+
if (typeof payload !== "object" || payload === null) return false;
|
|
33
|
+
return payload.takeover === true;
|
|
34
|
+
}
|
|
35
|
+
function ticketReadable(input) {
|
|
36
|
+
if (input.method === "session.restore") return !takeoverRequested(input.payload);
|
|
37
|
+
return input.readOnly;
|
|
38
|
+
}
|
|
39
|
+
function ticketSessionDenialOf(claims, input) {
|
|
40
|
+
if (claims.sessionId === void 0) return;
|
|
41
|
+
const requested = input.target?.sessionId ?? sessionIdOf(input.payload);
|
|
42
|
+
if (requested === void 0) return;
|
|
43
|
+
return requested === claims.sessionId ? void 0 : "cross-session";
|
|
44
|
+
}
|
|
45
|
+
function ticketDenialOf(claims, input) {
|
|
46
|
+
if (!(claims.methods ?? TICKET_READ_METHODS).includes(input.method)) return "method-not-granted";
|
|
47
|
+
if (claims.mode !== "write" && !ticketReadable(input)) return "not-a-read";
|
|
48
|
+
return ticketSessionDenialOf(claims, input);
|
|
49
|
+
}
|
|
50
|
+
function credentialDenialOf(input) {
|
|
51
|
+
if (input.credential.kind === "owner") return;
|
|
52
|
+
if (input.credential.kind === "reader") return input.readOnly ? void 0 : "not-a-read";
|
|
53
|
+
return ticketDenialOf(input.credential.claims, input);
|
|
54
|
+
}
|
|
55
|
+
function credentialFromFacts(facts) {
|
|
56
|
+
if (facts.sessionToken === true) return {
|
|
57
|
+
kind: "ticket",
|
|
58
|
+
claims: {
|
|
59
|
+
mode: "read",
|
|
60
|
+
...facts.sessionId === void 0 ? {} : { sessionId: facts.sessionId }
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
if (facts.follow === true) return { kind: "reader" };
|
|
64
|
+
return facts.source === "anonymous" ? { kind: "reader" } : { kind: "owner" };
|
|
65
|
+
}
|
|
66
|
+
function credentialOf(context) {
|
|
67
|
+
if (context.credential !== void 0) return context.credential;
|
|
68
|
+
const source = context.principal?.source;
|
|
69
|
+
return credentialFromFacts({
|
|
70
|
+
source: source ?? "anonymous",
|
|
71
|
+
...context.follow === true ? { follow: true } : {},
|
|
72
|
+
...context.principal?.sessionToken === true ? { sessionToken: true } : {},
|
|
73
|
+
...context.principal?.sessionId === void 0 ? {} : { sessionId: context.principal.sessionId }
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
//#endregion
|
|
78
|
+
//#region src/context.ts
|
|
79
|
+
const ANONYMOUS_LOCAL_CONTEXT = Object.freeze({
|
|
80
|
+
principalId: "local",
|
|
81
|
+
principal: Object.freeze({
|
|
82
|
+
id: "local",
|
|
83
|
+
source: "local"
|
|
84
|
+
}),
|
|
85
|
+
credential: Object.freeze({ kind: "owner" }),
|
|
86
|
+
clientId: "local",
|
|
87
|
+
transport: "in-process"
|
|
88
|
+
});
|
|
89
|
+
function tokensMatch(provided, expected) {
|
|
90
|
+
if (provided === void 0) return false;
|
|
91
|
+
return timingSafeEqual(createHash("sha256").update(provided).digest(), createHash("sha256").update(expected).digest());
|
|
92
|
+
}
|
|
93
|
+
function tokenFingerprint(token) {
|
|
94
|
+
return createHash("sha256").update(token).digest("hex").slice(0, 16);
|
|
95
|
+
}
|
|
96
|
+
function principalSourceOf(token, transport) {
|
|
97
|
+
if (token !== void 0 && token !== "") return "token";
|
|
98
|
+
return transport === "in-process" ? "local" : "anonymous";
|
|
99
|
+
}
|
|
100
|
+
function principalFromToken(token, options = {}) {
|
|
101
|
+
if (token !== void 0 && token !== "") {
|
|
102
|
+
const tokenId = tokenFingerprint(token);
|
|
103
|
+
return {
|
|
104
|
+
id: options.principalId ?? `token:${tokenId.slice(0, 8)}`,
|
|
105
|
+
tokenId,
|
|
106
|
+
source: "token",
|
|
107
|
+
...options.sessionToken === true ? { sessionToken: true } : {},
|
|
108
|
+
...options.sessionId === void 0 ? {} : { sessionId: options.sessionId }
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
const source = principalSourceOf(token, options.transport);
|
|
112
|
+
return {
|
|
113
|
+
id: options.principalId ?? source,
|
|
114
|
+
source
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
function credentialOfOptions(token, options) {
|
|
118
|
+
if (options.credential !== void 0) return options.credential;
|
|
119
|
+
return credentialFromFacts({
|
|
120
|
+
source: principalSourceOf(token, options.transport),
|
|
121
|
+
...options.follow === true ? { follow: true } : {},
|
|
122
|
+
...options.sessionToken === true ? { sessionToken: true } : {},
|
|
123
|
+
...options.sessionId === void 0 ? {} : { sessionId: options.sessionId }
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
function contextFromToken(token, options = {}) {
|
|
127
|
+
const credential = credentialOfOptions(token, options);
|
|
128
|
+
const claims = credential.kind === "ticket" ? credential.claims : void 0;
|
|
129
|
+
const principal = principalFromToken(token, {
|
|
130
|
+
...options,
|
|
131
|
+
sessionToken: claims !== void 0,
|
|
132
|
+
...claims?.sessionId === void 0 ? {} : { sessionId: claims.sessionId }
|
|
133
|
+
});
|
|
134
|
+
return {
|
|
135
|
+
principalId: principal.id,
|
|
136
|
+
principal,
|
|
137
|
+
credential,
|
|
138
|
+
clientId: options.clientId ?? claims?.clientId ?? options.connectionId ?? principal.id,
|
|
139
|
+
transport: options.transport ?? "http",
|
|
140
|
+
...options.connectionId === void 0 ? {} : { connectionId: options.connectionId },
|
|
141
|
+
...options.remoteAddr === void 0 ? {} : { remoteAddr: options.remoteAddr },
|
|
142
|
+
...principal.tokenId === void 0 && options.tokenId === void 0 ? {} : { tokenId: options.tokenId ?? principal.tokenId },
|
|
143
|
+
...options.workspaceScope === void 0 ? {} : { workspaceScope: options.workspaceScope },
|
|
144
|
+
...options.clientFeatures === void 0 ? {} : { clientFeatures: options.clientFeatures },
|
|
145
|
+
...options.follow === true ? { follow: true } : {}
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
//#endregion
|
|
150
|
+
//#region src/fanout.ts
|
|
151
|
+
function createEventFanout(options = {}) {
|
|
152
|
+
const subscriptions = /* @__PURE__ */ new Map();
|
|
153
|
+
function makeDisposer(sessionId, handler, entry, token) {
|
|
154
|
+
return () => {
|
|
155
|
+
if (token.released) return;
|
|
156
|
+
token.released = true;
|
|
157
|
+
if (subscriptions.get(sessionId) !== entry) return;
|
|
158
|
+
const count = entry.handlers.get(handler);
|
|
159
|
+
if (count === void 0) return;
|
|
160
|
+
if (count > 1) {
|
|
161
|
+
entry.handlers.set(handler, count - 1);
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
entry.handlers.delete(handler);
|
|
165
|
+
if (entry.handlers.size === 0) {
|
|
166
|
+
subscriptions.delete(sessionId);
|
|
167
|
+
options.onLastSubscriberRemoved?.(sessionId);
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
return {
|
|
172
|
+
add(sessionId, handler) {
|
|
173
|
+
const token = { released: false };
|
|
174
|
+
const existing = subscriptions.get(sessionId);
|
|
175
|
+
if (existing) {
|
|
176
|
+
existing.handlers.set(handler, (existing.handlers.get(handler) ?? 0) + 1);
|
|
177
|
+
return makeDisposer(sessionId, handler, existing, token);
|
|
178
|
+
}
|
|
179
|
+
const entry = { handlers: new Map([[handler, 1]]) };
|
|
180
|
+
subscriptions.set(sessionId, entry);
|
|
181
|
+
try {
|
|
182
|
+
options.onFirstSubscriber?.(sessionId);
|
|
183
|
+
} catch (error) {
|
|
184
|
+
entry.handlers.clear();
|
|
185
|
+
if (subscriptions.get(sessionId) === entry) subscriptions.delete(sessionId);
|
|
186
|
+
throw error;
|
|
187
|
+
}
|
|
188
|
+
return makeDisposer(sessionId, handler, entry, token);
|
|
189
|
+
},
|
|
190
|
+
deliver(sessionId, deliver) {
|
|
191
|
+
const entry = subscriptions.get(sessionId);
|
|
192
|
+
if (!entry) return;
|
|
193
|
+
for (const handler of Array.from(entry.handlers.keys())) try {
|
|
194
|
+
deliver(handler);
|
|
195
|
+
} catch {}
|
|
196
|
+
},
|
|
197
|
+
clear() {
|
|
198
|
+
const sessionIds = Array.from(subscriptions.keys());
|
|
199
|
+
subscriptions.clear();
|
|
200
|
+
const failures = [];
|
|
201
|
+
for (const sessionId of sessionIds) try {
|
|
202
|
+
options.onLastSubscriberRemoved?.(sessionId);
|
|
203
|
+
} catch (error) {
|
|
204
|
+
failures.push(error);
|
|
205
|
+
}
|
|
206
|
+
if (failures.length > 0) throw failures[0];
|
|
207
|
+
},
|
|
208
|
+
sessionCount() {
|
|
209
|
+
return subscriptions.size;
|
|
210
|
+
}
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
//#endregion
|
|
215
|
+
//#region src/events.ts
|
|
216
|
+
const GLOBAL_EVENTS_CHANNEL = "__global__";
|
|
217
|
+
const PRIVATE_ASK_EVENT_KINDS = new Set([
|
|
218
|
+
"approval.respond",
|
|
219
|
+
"approval.opened",
|
|
220
|
+
"approval.closed",
|
|
221
|
+
"hitl.request",
|
|
222
|
+
"hitl.respond",
|
|
223
|
+
"hitl.cancelled"
|
|
224
|
+
]);
|
|
225
|
+
const PER_SESSION_ONLY_EVENT_KINDS = /* @__PURE__ */ new Set();
|
|
226
|
+
const SCOPED_GLOBAL_EVENT_KINDS = new Set([
|
|
227
|
+
"session.title.preview",
|
|
228
|
+
"session.meta.changed",
|
|
229
|
+
"drafts.changed",
|
|
230
|
+
"editedFiles.changed"
|
|
231
|
+
]);
|
|
232
|
+
function isPrivateAskEvent(event) {
|
|
233
|
+
if (typeof event !== "object" || event === null) return false;
|
|
234
|
+
const kind = event.kind;
|
|
235
|
+
return typeof kind === "string" && PRIVATE_ASK_EVENT_KINDS.has(kind);
|
|
236
|
+
}
|
|
237
|
+
function isPerSessionOnlyEvent(event) {
|
|
238
|
+
if (typeof event !== "object" || event === null) return false;
|
|
239
|
+
const kind = event.kind;
|
|
240
|
+
return typeof kind === "string" && PER_SESSION_ONLY_EVENT_KINDS.has(kind);
|
|
241
|
+
}
|
|
242
|
+
function isScopedGlobalEvent(event) {
|
|
243
|
+
if (typeof event !== "object" || event === null) return false;
|
|
244
|
+
const kind = event.kind;
|
|
245
|
+
return typeof kind === "string" && SCOPED_GLOBAL_EVENT_KINDS.has(kind);
|
|
246
|
+
}
|
|
247
|
+
function lacksGlobalScope(event) {
|
|
248
|
+
if (typeof event !== "object" || event === null) return false;
|
|
249
|
+
const workspaceKey = event.workspaceKey;
|
|
250
|
+
return typeof workspaceKey !== "string" || workspaceKey === "";
|
|
251
|
+
}
|
|
252
|
+
function isSessionMetaChangedEvent(event) {
|
|
253
|
+
if (typeof event !== "object" || event === null) return false;
|
|
254
|
+
return event.kind === "session.meta.changed";
|
|
255
|
+
}
|
|
256
|
+
const filteredHandlers = /* @__PURE__ */ new WeakMap();
|
|
257
|
+
function filterPrivateAskEvents(handler) {
|
|
258
|
+
const existing = filteredHandlers.get(handler);
|
|
259
|
+
if (existing !== void 0) return existing;
|
|
260
|
+
const next = (event) => {
|
|
261
|
+
if (isPrivateAskEvent(event)) return;
|
|
262
|
+
handler(event);
|
|
263
|
+
};
|
|
264
|
+
filteredHandlers.set(handler, next);
|
|
265
|
+
return next;
|
|
266
|
+
}
|
|
267
|
+
function createEventRelay() {
|
|
268
|
+
const fanout = createEventFanout();
|
|
269
|
+
return {
|
|
270
|
+
push(sessionId, event) {
|
|
271
|
+
if (isPrivateAskEvent(event)) return;
|
|
272
|
+
if (sessionId === "__global__" && isPerSessionOnlyEvent(event)) return;
|
|
273
|
+
if (sessionId === "__global__" && isScopedGlobalEvent(event) && lacksGlobalScope(event)) return;
|
|
274
|
+
fanout.deliver(sessionId, (handler) => handler(event));
|
|
275
|
+
},
|
|
276
|
+
subscribe(sessionId, handler) {
|
|
277
|
+
return fanout.add(sessionId, filterPrivateAskEvents(handler));
|
|
278
|
+
},
|
|
279
|
+
sessionCount() {
|
|
280
|
+
return fanout.sessionCount();
|
|
281
|
+
},
|
|
282
|
+
broadcast(event) {
|
|
283
|
+
if (isPrivateAskEvent(event)) return;
|
|
284
|
+
if (isPerSessionOnlyEvent(event)) return;
|
|
285
|
+
if (isScopedGlobalEvent(event) && lacksGlobalScope(event)) return;
|
|
286
|
+
const scoped = {
|
|
287
|
+
...event,
|
|
288
|
+
sessionId: GLOBAL_EVENTS_CHANNEL
|
|
289
|
+
};
|
|
290
|
+
fanout.deliver(GLOBAL_EVENTS_CHANNEL, (handler) => handler(scoped));
|
|
291
|
+
}
|
|
292
|
+
};
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
//#endregion
|
|
296
|
+
//#region src/serialize-shared.ts
|
|
297
|
+
function createSharedSerializer() {
|
|
298
|
+
const serialized = /* @__PURE__ */ new WeakMap();
|
|
299
|
+
return (message) => {
|
|
300
|
+
if (typeof message !== "object" || message === null) return JSON.stringify(message);
|
|
301
|
+
const cached = serialized.get(message);
|
|
302
|
+
if (cached !== void 0) return cached;
|
|
303
|
+
const text = JSON.stringify(message);
|
|
304
|
+
serialized.set(message, text);
|
|
305
|
+
return text;
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
//#endregion
|
|
310
|
+
//#region src/errors.ts
|
|
311
|
+
var ServiceError = class extends Error {
|
|
312
|
+
constructor(code, message, details) {
|
|
313
|
+
super(message);
|
|
314
|
+
this.code = code;
|
|
315
|
+
this.details = details;
|
|
316
|
+
this.name = "ServiceError";
|
|
317
|
+
}
|
|
318
|
+
};
|
|
319
|
+
var RequestForbiddenError = class extends ServiceError {
|
|
320
|
+
constructor(action, principalId) {
|
|
321
|
+
super("FORBIDDEN", `principal "${principalId}" is not authorized for ${action}`, {
|
|
322
|
+
action,
|
|
323
|
+
principalId
|
|
324
|
+
});
|
|
325
|
+
this.action = action;
|
|
326
|
+
this.principalId = principalId;
|
|
327
|
+
this.name = "RequestForbiddenError";
|
|
328
|
+
}
|
|
329
|
+
};
|
|
330
|
+
|
|
331
|
+
//#endregion
|
|
332
|
+
//#region src/route-read-only.ts
|
|
333
|
+
const READ_ONLY_SERVICE_METHODS = new Set([
|
|
334
|
+
"ask.descendants",
|
|
335
|
+
"assembly.diagnostics",
|
|
336
|
+
"assembly.performanceDiagnostics",
|
|
337
|
+
"auth.status",
|
|
338
|
+
"chat.attempt.status",
|
|
339
|
+
"chat.executionStatus",
|
|
340
|
+
"chat.queue.list",
|
|
341
|
+
"command.catalog",
|
|
342
|
+
"composer.context",
|
|
343
|
+
"cost.summary",
|
|
344
|
+
"drafts.list",
|
|
345
|
+
"extension.permissions",
|
|
346
|
+
"fold.viewState",
|
|
347
|
+
"input.history",
|
|
348
|
+
"install.activation",
|
|
349
|
+
"install.list",
|
|
350
|
+
"jobs.list",
|
|
351
|
+
"jobs.read",
|
|
352
|
+
"mcp.snapshot",
|
|
353
|
+
"memory.entries",
|
|
354
|
+
"memory.read",
|
|
355
|
+
"mention.search",
|
|
356
|
+
"model.availability",
|
|
357
|
+
"model.list",
|
|
358
|
+
"model.preferences",
|
|
359
|
+
"perf.residency",
|
|
360
|
+
"plan.list",
|
|
361
|
+
"plugin.list",
|
|
362
|
+
"provider.list",
|
|
363
|
+
"recorder.pending.export",
|
|
364
|
+
"repository.capabilities",
|
|
365
|
+
"repository.committedNextSeq",
|
|
366
|
+
"repository.countEvents",
|
|
367
|
+
"repository.list",
|
|
368
|
+
"repository.loadMeta",
|
|
369
|
+
"repository.readArchivedEvents",
|
|
370
|
+
"repository.readCommitted",
|
|
371
|
+
"repository.readEvents",
|
|
372
|
+
"repository.recovery.capabilities",
|
|
373
|
+
"repository.recovery.get",
|
|
374
|
+
"repository.recovery.list",
|
|
375
|
+
"resource.read",
|
|
376
|
+
"runtime.askScope",
|
|
377
|
+
"schedules.list",
|
|
378
|
+
"service.handshake",
|
|
379
|
+
"session.archivedHistory",
|
|
380
|
+
"session.contextArchive.read",
|
|
381
|
+
"session.cwdContext",
|
|
382
|
+
"session.descendants",
|
|
383
|
+
"session.editedFiles",
|
|
384
|
+
"session.entry",
|
|
385
|
+
"session.permission.mode",
|
|
386
|
+
"session.forkPoints.list",
|
|
387
|
+
"session.list",
|
|
388
|
+
"session.counts",
|
|
389
|
+
"session.recovery.get",
|
|
390
|
+
"session.recovery.list",
|
|
391
|
+
"session.resultObligations",
|
|
392
|
+
"session.runtimeSnapshot",
|
|
393
|
+
"session.surface.read",
|
|
394
|
+
"session.timeline.detail",
|
|
395
|
+
"session.timeline.snapshot",
|
|
396
|
+
"session.work.snapshot",
|
|
397
|
+
"skill.snapshot",
|
|
398
|
+
"space.catalog",
|
|
399
|
+
"ui.catalog",
|
|
400
|
+
"ui.preferences.get",
|
|
401
|
+
"updates.status",
|
|
402
|
+
"worker.lifecycle",
|
|
403
|
+
"worker.restart.status",
|
|
404
|
+
"workspace.list",
|
|
405
|
+
"workspace.placement",
|
|
406
|
+
"workspace.readiness"
|
|
407
|
+
]);
|
|
408
|
+
|
|
409
|
+
//#endregion
|
|
410
|
+
//#region src/authorize.ts
|
|
411
|
+
function isReadOnlyMethod(action) {
|
|
412
|
+
return READ_ONLY_SERVICE_METHODS.has(action);
|
|
413
|
+
}
|
|
414
|
+
function targetWithinScope(context, target) {
|
|
415
|
+
const scope = context.workspaceScope;
|
|
416
|
+
if (scope === void 0 || scope === "*") return true;
|
|
417
|
+
if (target?.workspaceKey !== void 0) return scope.includes(target.workspaceKey);
|
|
418
|
+
return target?.global === true;
|
|
419
|
+
}
|
|
420
|
+
function createDefaultAuthorizer() {
|
|
421
|
+
return (context, action, payload, target) => {
|
|
422
|
+
if (!targetWithinScope(context, target)) throw new RequestForbiddenError(action, context.principalId);
|
|
423
|
+
assertCredentialAllowed(context, action, payload, target);
|
|
424
|
+
};
|
|
425
|
+
}
|
|
426
|
+
function assertCredentialAllowed(context, method, payload, target) {
|
|
427
|
+
if (credentialDenialOf({
|
|
428
|
+
credential: credentialOf(context),
|
|
429
|
+
method,
|
|
430
|
+
readOnly: isReadOnlyMethod(method),
|
|
431
|
+
payload,
|
|
432
|
+
target
|
|
433
|
+
}) !== void 0) throw new RequestForbiddenError(method, context.principalId);
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
//#endregion
|
|
437
|
+
//#region src/connection-binding.ts
|
|
438
|
+
function createConnectionBinding(input = {}) {
|
|
439
|
+
const allowList = input.methodAllowList === void 0 ? void 0 : new Set(input.methodAllowList);
|
|
440
|
+
const reasonFor = (method) => {
|
|
441
|
+
if (allowList !== void 0 && !allowList.has(method)) return "method-not-in-bindings";
|
|
442
|
+
};
|
|
443
|
+
return {
|
|
444
|
+
allows(method) {
|
|
445
|
+
return reasonFor(method) === void 0;
|
|
446
|
+
},
|
|
447
|
+
reasonFor
|
|
448
|
+
};
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
//#endregion
|
|
452
|
+
//#region src/methods.ts
|
|
453
|
+
const SERVICE_METHODS = [
|
|
454
|
+
"session.list",
|
|
455
|
+
"session.counts",
|
|
456
|
+
"session.create",
|
|
457
|
+
"session.descendants",
|
|
458
|
+
"chat.attempt.status",
|
|
459
|
+
"chat.send",
|
|
460
|
+
"chat.submitIntent",
|
|
461
|
+
"chat.clear",
|
|
462
|
+
"chat.compact",
|
|
463
|
+
"chat.interrupt",
|
|
464
|
+
"chat.executionStatus",
|
|
465
|
+
"chat.retryLastRound",
|
|
466
|
+
"chat.continueWithPending",
|
|
467
|
+
"chat.releaseAdmission",
|
|
468
|
+
"chat.retryCancel",
|
|
469
|
+
"chat.retryAccelerate",
|
|
470
|
+
"chat.withdraw",
|
|
471
|
+
"chat.steer",
|
|
472
|
+
"chat.queue.append",
|
|
473
|
+
"chat.queue.list",
|
|
474
|
+
"chat.queue.remove",
|
|
475
|
+
"chat.queue.clear",
|
|
476
|
+
"chat.queue.promote",
|
|
477
|
+
"chat.queue.update",
|
|
478
|
+
"chat.queue.move",
|
|
479
|
+
"chat.discardDanglingInput",
|
|
480
|
+
"session.discardResultObligation",
|
|
481
|
+
"session.resultObligations",
|
|
482
|
+
"session.rearmResultObligation",
|
|
483
|
+
"session.confirmResultObligation",
|
|
484
|
+
"chat.resumeQueue",
|
|
485
|
+
"chat.deferAwaitingResults",
|
|
486
|
+
"composer.context",
|
|
487
|
+
"session.entry",
|
|
488
|
+
"session.rename",
|
|
489
|
+
"session.model.select",
|
|
490
|
+
"session.effort.select",
|
|
491
|
+
"session.permission.select",
|
|
492
|
+
"session.permission.mode",
|
|
493
|
+
"session.pin",
|
|
494
|
+
"session.archive",
|
|
495
|
+
"session.reimport",
|
|
496
|
+
"session.unarchive",
|
|
497
|
+
"session.remove",
|
|
498
|
+
"session.restore",
|
|
499
|
+
"session.claim",
|
|
500
|
+
"session.recordDiagnostic",
|
|
501
|
+
"session.viewport",
|
|
502
|
+
"session.work.snapshot",
|
|
503
|
+
"session.timeline.snapshot",
|
|
504
|
+
"session.timeline.detail",
|
|
505
|
+
"session.contextArchive.read",
|
|
506
|
+
"session.archivedHistory",
|
|
507
|
+
"session.surface.read",
|
|
508
|
+
"session.forkPoints.list",
|
|
509
|
+
"session.fork",
|
|
510
|
+
"session.recovery.list",
|
|
511
|
+
"session.recovery.get",
|
|
512
|
+
"session.recovery.retry",
|
|
513
|
+
"session.recovery.resolve",
|
|
514
|
+
"session.recovery.repair",
|
|
515
|
+
"recorder.pending.export",
|
|
516
|
+
"recorder.pending.recover",
|
|
517
|
+
"runtime.askScope",
|
|
518
|
+
"session.prepare",
|
|
519
|
+
"session.deliver",
|
|
520
|
+
"plugin.list",
|
|
521
|
+
"plugin.add",
|
|
522
|
+
"plugin.remove",
|
|
523
|
+
"plugin.replace",
|
|
524
|
+
"model.list",
|
|
525
|
+
"model.select",
|
|
526
|
+
"plan.list",
|
|
527
|
+
"session.cwdContext",
|
|
528
|
+
"devApproval.pending",
|
|
529
|
+
"devApproval.respond",
|
|
530
|
+
"extension.write.request",
|
|
531
|
+
"extension.write.apply",
|
|
532
|
+
"session.editedFiles",
|
|
533
|
+
"workspace.list",
|
|
534
|
+
"workspace.placement",
|
|
535
|
+
"assembly.diagnostics",
|
|
536
|
+
"assembly.performanceDiagnostics",
|
|
537
|
+
"workspace.readiness",
|
|
538
|
+
"ui.catalog",
|
|
539
|
+
"ui.activity.record",
|
|
540
|
+
"mention.search",
|
|
541
|
+
"env.snapshot",
|
|
542
|
+
"command.run",
|
|
543
|
+
"command.catalog",
|
|
544
|
+
"view.frame",
|
|
545
|
+
"view.input",
|
|
546
|
+
"view.close",
|
|
547
|
+
"ui.preferences.get",
|
|
548
|
+
"ui.preferences.set",
|
|
549
|
+
"perf.residency",
|
|
550
|
+
"worker.lifecycle",
|
|
551
|
+
"worker.restart.prepare",
|
|
552
|
+
"worker.restart.status",
|
|
553
|
+
"worker.restart.resume",
|
|
554
|
+
"worker.restart.cancel",
|
|
555
|
+
"worker.exit",
|
|
556
|
+
"resource.read",
|
|
557
|
+
"approval.respond",
|
|
558
|
+
"hitl.respond",
|
|
559
|
+
"ask.open",
|
|
560
|
+
"ask.refresh",
|
|
561
|
+
"ask.close",
|
|
562
|
+
"ask.descendants",
|
|
563
|
+
"repository.capabilities",
|
|
564
|
+
"repository.recovery.capabilities",
|
|
565
|
+
"repository.recovery.save",
|
|
566
|
+
"repository.recovery.get",
|
|
567
|
+
"repository.recovery.list",
|
|
568
|
+
"repository.recovery.remove",
|
|
569
|
+
"repository.saveMeta",
|
|
570
|
+
"repository.loadMeta",
|
|
571
|
+
"repository.list",
|
|
572
|
+
"repository.purge",
|
|
573
|
+
"repository.appendEvents",
|
|
574
|
+
"repository.readEvents",
|
|
575
|
+
"repository.readArchivedEvents",
|
|
576
|
+
"repository.countEvents",
|
|
577
|
+
"repository.truncateBefore",
|
|
578
|
+
"repository.archive",
|
|
579
|
+
"repository.restoreArchived",
|
|
580
|
+
"repository.releaseCache",
|
|
581
|
+
"repository.readCommitted",
|
|
582
|
+
"repository.committedNextSeq",
|
|
583
|
+
"session.runtimeSnapshot",
|
|
584
|
+
"session.releaseView",
|
|
585
|
+
"session.reconcileLostJob",
|
|
586
|
+
"service.handshake",
|
|
587
|
+
"schedules.list",
|
|
588
|
+
"schedules.delete",
|
|
589
|
+
"schedules.runPending",
|
|
590
|
+
"schedules.dismissPending",
|
|
591
|
+
"schedules.health",
|
|
592
|
+
"space.catalog",
|
|
593
|
+
"provider.fallback",
|
|
594
|
+
"memory.entries",
|
|
595
|
+
"memory.read",
|
|
596
|
+
"install.activation",
|
|
597
|
+
"updates.status",
|
|
598
|
+
"updates.check",
|
|
599
|
+
"cost.summary",
|
|
600
|
+
"fold.viewState",
|
|
601
|
+
"fold.viewState.save",
|
|
602
|
+
"model.availability",
|
|
603
|
+
"input.history",
|
|
604
|
+
"input.history.save",
|
|
605
|
+
"drafts.list",
|
|
606
|
+
"drafts.save",
|
|
607
|
+
"drafts.remove",
|
|
608
|
+
"extension.permissions",
|
|
609
|
+
"provider.list",
|
|
610
|
+
"install.list",
|
|
611
|
+
"install.uninstall",
|
|
612
|
+
"model.preferences",
|
|
613
|
+
"model.setEnabled",
|
|
614
|
+
"model.setCapabilityOverride",
|
|
615
|
+
"model.clearCapabilityOverride",
|
|
616
|
+
"model.refresh",
|
|
617
|
+
"model.unfreeze",
|
|
618
|
+
"skill.snapshot",
|
|
619
|
+
"skill.setEnabled",
|
|
620
|
+
"skill.reload",
|
|
621
|
+
"mcp.snapshot",
|
|
622
|
+
"mcp.setEnabled",
|
|
623
|
+
"mcp.reload",
|
|
624
|
+
"mcp.reconnect",
|
|
625
|
+
"mcp.login",
|
|
626
|
+
"mcp.logout",
|
|
627
|
+
"session.inspectSource",
|
|
628
|
+
"session.auditLogs",
|
|
629
|
+
"trust.query",
|
|
630
|
+
"jobs.list",
|
|
631
|
+
"jobs.kill",
|
|
632
|
+
"jobs.read",
|
|
633
|
+
"settings.get",
|
|
634
|
+
"permission.mode",
|
|
635
|
+
"settings.getAll",
|
|
636
|
+
"settings.set",
|
|
637
|
+
"settings.clear",
|
|
638
|
+
"settings.describe",
|
|
639
|
+
"settings.subscribe",
|
|
640
|
+
"auth.status",
|
|
641
|
+
"auth.login",
|
|
642
|
+
"auth.login.status",
|
|
643
|
+
"auth.login.submit-code",
|
|
644
|
+
"auth.login.cancel",
|
|
645
|
+
"auth.set-key",
|
|
646
|
+
"auth.account",
|
|
647
|
+
"auth.logout"
|
|
648
|
+
];
|
|
649
|
+
const SERVICE_METHOD_SET = new Set(SERVICE_METHODS);
|
|
650
|
+
function isServiceMethod(type) {
|
|
651
|
+
return SERVICE_METHOD_SET.has(type);
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
//#endregion
|
|
655
|
+
//#region src/subscription-backfill.ts
|
|
656
|
+
function headSeqOf(result) {
|
|
657
|
+
if (typeof result !== "object" || result === null) return;
|
|
658
|
+
const coveredHead = result.coveredHead;
|
|
659
|
+
if (typeof coveredHead === "number" && Number.isSafeInteger(coveredHead) && coveredHead >= 0) return coveredHead;
|
|
660
|
+
}
|
|
661
|
+
function eventsOf(result) {
|
|
662
|
+
if (typeof result !== "object" || result === null) return [];
|
|
663
|
+
const events = result.events;
|
|
664
|
+
return Array.isArray(events) ? events : [];
|
|
665
|
+
}
|
|
666
|
+
async function readSubscriptionBackfill(input) {
|
|
667
|
+
const sinceSeq = input.sinceSeq;
|
|
668
|
+
if (sinceSeq === void 0) return { ok: true };
|
|
669
|
+
if (input.handlers.listTypes().includes("session.restore") !== true) return {
|
|
670
|
+
ok: false,
|
|
671
|
+
error: {
|
|
672
|
+
code: "NOT_HANDLED",
|
|
673
|
+
message: "session.restore is not available on this server"
|
|
674
|
+
}
|
|
675
|
+
};
|
|
676
|
+
try {
|
|
677
|
+
const restored = await input.handlers.handle("session.restore", {
|
|
678
|
+
sessionId: input.sessionId,
|
|
679
|
+
sinceSeq
|
|
680
|
+
}, input.context);
|
|
681
|
+
const headSeq = headSeqOf(restored);
|
|
682
|
+
if (headSeq === void 0) return {
|
|
683
|
+
ok: false,
|
|
684
|
+
error: {
|
|
685
|
+
code: "BACKFILL_UNAVAILABLE",
|
|
686
|
+
message: "session.restore did not report a covered head"
|
|
687
|
+
}
|
|
688
|
+
};
|
|
689
|
+
return {
|
|
690
|
+
ok: true,
|
|
691
|
+
headSeq,
|
|
692
|
+
events: eventsOf(restored)
|
|
693
|
+
};
|
|
694
|
+
} catch (error) {
|
|
695
|
+
const code = error.code;
|
|
696
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
697
|
+
return {
|
|
698
|
+
ok: false,
|
|
699
|
+
error: {
|
|
700
|
+
code: typeof code === "string" ? code : "BACKFILL_FAILED",
|
|
701
|
+
message
|
|
702
|
+
}
|
|
703
|
+
};
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
//#endregion
|
|
708
|
+
//#region src/token-verifier.ts
|
|
709
|
+
function createTokenVerifier(options) {
|
|
710
|
+
return (token) => {
|
|
711
|
+
if (options.readToken !== void 0 && tokensMatch(token, options.readToken)) return {
|
|
712
|
+
credential: { kind: "reader" },
|
|
713
|
+
channel: "read"
|
|
714
|
+
};
|
|
715
|
+
if (options.authToken === void 0) return {
|
|
716
|
+
credential: { kind: "reader" },
|
|
717
|
+
channel: "anonymous"
|
|
718
|
+
};
|
|
719
|
+
if (tokensMatch(token, options.authToken)) return {
|
|
720
|
+
credential: { kind: "owner" },
|
|
721
|
+
channel: "auth"
|
|
722
|
+
};
|
|
723
|
+
if (token === void 0 || options.ticketOf === void 0) return;
|
|
724
|
+
const claims = options.ticketOf(token);
|
|
725
|
+
return claims === void 0 ? void 0 : {
|
|
726
|
+
credential: {
|
|
727
|
+
kind: "ticket",
|
|
728
|
+
claims
|
|
729
|
+
},
|
|
730
|
+
channel: "ticket"
|
|
731
|
+
};
|
|
732
|
+
};
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
//#endregion
|
|
736
|
+
//#region src/web-host.ts
|
|
737
|
+
const LOOPBACK_HOSTNAMES = new Set([
|
|
738
|
+
"127.0.0.1",
|
|
739
|
+
"localhost",
|
|
740
|
+
"[::1]",
|
|
741
|
+
"::1"
|
|
742
|
+
]);
|
|
743
|
+
function checkHostHeader(hostHeader) {
|
|
744
|
+
if (hostHeader === void 0 || hostHeader === "") return {
|
|
745
|
+
allowed: false,
|
|
746
|
+
reason: "missing-host"
|
|
747
|
+
};
|
|
748
|
+
const hostname = hostHeader.replace(/:\d+$/, "");
|
|
749
|
+
return LOOPBACK_HOSTNAMES.has(hostname) ? { allowed: true } : {
|
|
750
|
+
allowed: false,
|
|
751
|
+
reason: "foreign-host"
|
|
752
|
+
};
|
|
753
|
+
}
|
|
754
|
+
function checkHostHeaderWhenPresent(hostHeader) {
|
|
755
|
+
if (hostHeader === void 0 || hostHeader === "") return { allowed: true };
|
|
756
|
+
return checkHostHeader(hostHeader);
|
|
757
|
+
}
|
|
758
|
+
function checkOriginHeader(origin) {
|
|
759
|
+
if (origin === void 0 || origin === "") return { allowed: true };
|
|
760
|
+
if (origin === "null") return {
|
|
761
|
+
allowed: false,
|
|
762
|
+
reason: "foreign-host"
|
|
763
|
+
};
|
|
764
|
+
let hostname;
|
|
765
|
+
try {
|
|
766
|
+
hostname = new URL(origin).hostname;
|
|
767
|
+
} catch {
|
|
768
|
+
return {
|
|
769
|
+
allowed: false,
|
|
770
|
+
reason: "foreign-host"
|
|
771
|
+
};
|
|
772
|
+
}
|
|
773
|
+
return LOOPBACK_HOSTNAMES.has(hostname) ? { allowed: true } : {
|
|
774
|
+
allowed: false,
|
|
775
|
+
reason: "foreign-host"
|
|
776
|
+
};
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
//#endregion
|
|
780
|
+
//#region src/route-set.ts
|
|
781
|
+
const EXT_OWNER_PATTERN = /^ext:[^\s.]+$/;
|
|
782
|
+
function route(method, readOnly, target, handle) {
|
|
783
|
+
return {
|
|
784
|
+
method,
|
|
785
|
+
meta: {
|
|
786
|
+
readOnly,
|
|
787
|
+
target
|
|
788
|
+
},
|
|
789
|
+
handle
|
|
790
|
+
};
|
|
791
|
+
}
|
|
792
|
+
function defineRoutes(owner, routes) {
|
|
793
|
+
for (const [key, entry] of Object.entries(routes)) if (entry.method !== key) throw new Error(`route key "${key}" does not match declared method "${entry.method}"`);
|
|
794
|
+
if (owner.startsWith("ext:")) {
|
|
795
|
+
if (!EXT_OWNER_PATTERN.test(owner)) throw new Error(`invalid extension route set owner: ${owner}`);
|
|
796
|
+
const prefix = `${owner}.`;
|
|
797
|
+
for (const key of Object.keys(routes)) if (!key.startsWith(prefix)) throw new Error(`route "${key}" is outside the extension namespace "${prefix}*"`);
|
|
798
|
+
}
|
|
799
|
+
return {
|
|
800
|
+
owner,
|
|
801
|
+
routes
|
|
802
|
+
};
|
|
803
|
+
}
|
|
804
|
+
function composeRoutes(sets) {
|
|
805
|
+
const composed = {};
|
|
806
|
+
for (const set of sets) for (const [name, entry] of Object.entries(set.routes)) {
|
|
807
|
+
if (composed[name] !== void 0) throw new Error(`duplicate route: ${name}`);
|
|
808
|
+
composed[name] = entry;
|
|
809
|
+
}
|
|
810
|
+
return composed;
|
|
811
|
+
}
|
|
812
|
+
function methodMetaOf(sets) {
|
|
813
|
+
const meta = {};
|
|
814
|
+
for (const set of sets) for (const [name, entry] of Object.entries(set.routes)) {
|
|
815
|
+
if (meta[name] !== void 0) throw new Error(`duplicate route meta: ${name}`);
|
|
816
|
+
meta[name] = entry.meta;
|
|
817
|
+
}
|
|
818
|
+
return meta;
|
|
819
|
+
}
|
|
820
|
+
async function runComposedRoute(routes, type, payload, context) {
|
|
821
|
+
const entry = routes[type];
|
|
822
|
+
if (entry === void 0) throw new ServiceError("NOT_HANDLED", `no handler for type: ${type}`);
|
|
823
|
+
return entry.handle(payload, context);
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
//#endregion
|
|
827
|
+
//#region src/target-extractors.ts
|
|
828
|
+
const epochField = (payload) => {
|
|
829
|
+
if (payload === null || typeof payload !== "object") return;
|
|
830
|
+
const value = payload["runtimeEpoch"];
|
|
831
|
+
return typeof value === "string" && value !== "" ? value : void 0;
|
|
832
|
+
};
|
|
833
|
+
const byWorkspaceWithEpoch = (payload) => {
|
|
834
|
+
const workspaceKey = stringField(payload, "workspaceKey");
|
|
835
|
+
const epoch = epochField(payload);
|
|
836
|
+
return {
|
|
837
|
+
...workspaceKey === void 0 ? {} : { workspaceKey },
|
|
838
|
+
...epoch === void 0 ? {} : { epoch }
|
|
839
|
+
};
|
|
840
|
+
};
|
|
841
|
+
function stringField(payload, key) {
|
|
842
|
+
const value = payload?.[key];
|
|
843
|
+
return typeof value === "string" && value !== "" ? value : void 0;
|
|
844
|
+
}
|
|
845
|
+
const globalTarget = () => ({ global: true });
|
|
846
|
+
const byAskRef = (payload) => {
|
|
847
|
+
const scope = payload?.ref?.scope;
|
|
848
|
+
if (scope?.kind === "runtime") return { global: true };
|
|
849
|
+
const sessionId = stringField(scope, "sessionId");
|
|
850
|
+
return sessionId === void 0 ? {} : { sessionId };
|
|
851
|
+
};
|
|
852
|
+
const byAskScope = (payload) => {
|
|
853
|
+
const scope = payload?.scope;
|
|
854
|
+
if (scope?.kind === "runtime") return { global: true };
|
|
855
|
+
const sessionId = stringField(scope, "sessionId");
|
|
856
|
+
return sessionId === void 0 ? {} : { sessionId };
|
|
857
|
+
};
|
|
858
|
+
const bySession = (payload) => {
|
|
859
|
+
const sessionId = stringField(payload, "sessionId");
|
|
860
|
+
return sessionId === void 0 ? {} : { sessionId };
|
|
861
|
+
};
|
|
862
|
+
const byWorkspace = (payload) => {
|
|
863
|
+
const workspaceKey = stringField(payload, "workspaceKey");
|
|
864
|
+
return workspaceKey === void 0 ? {} : { workspaceKey };
|
|
865
|
+
};
|
|
866
|
+
const bySessionOrGlobal = (payload) => {
|
|
867
|
+
const sessionId = stringField(payload, "sessionId");
|
|
868
|
+
return sessionId === void 0 ? { global: true } : { sessionId };
|
|
869
|
+
};
|
|
870
|
+
const byWorkspaceOrGlobal = (payload) => {
|
|
871
|
+
const workspaceKey = stringField(payload, "workspaceKey");
|
|
872
|
+
return workspaceKey === void 0 ? { global: true } : { workspaceKey };
|
|
873
|
+
};
|
|
874
|
+
const bySavedMeta = (payload) => {
|
|
875
|
+
const meta = payload?.meta;
|
|
876
|
+
const sessionId = stringField(meta, "id");
|
|
877
|
+
const workspaceKey = stringField(meta, "workspaceKey");
|
|
878
|
+
return {
|
|
879
|
+
...sessionId === void 0 ? {} : { sessionId },
|
|
880
|
+
...workspaceKey === void 0 ? {} : { workspaceKey }
|
|
881
|
+
};
|
|
882
|
+
};
|
|
883
|
+
const byListOptions = (payload) => {
|
|
884
|
+
const workspaceKey = stringField(payload?.options, "workspaceKey");
|
|
885
|
+
return workspaceKey === void 0 ? {} : { workspaceKey };
|
|
886
|
+
};
|
|
887
|
+
const sessionListTarget = (payload) => ({
|
|
888
|
+
...byWorkspace(payload),
|
|
889
|
+
global: true
|
|
890
|
+
});
|
|
891
|
+
|
|
892
|
+
//#endregion
|
|
893
|
+
//#region src/routes/auth-routes.ts
|
|
894
|
+
function authOwnerOf(context) {
|
|
895
|
+
return context.connectionId ?? context.principalId;
|
|
896
|
+
}
|
|
897
|
+
function isAccountLabel(value) {
|
|
898
|
+
return typeof value === "string" && value.length > 0 && value.length <= 120 && !/[\p{Cc}\p{Cf}]/u.test(value);
|
|
899
|
+
}
|
|
900
|
+
function authRoutes(deps) {
|
|
901
|
+
function authOrFail() {
|
|
902
|
+
if (deps.auth === void 0) throw new ServiceError("NOT_HANDLED", "auth.* requires a worker that implements the auth connection contract");
|
|
903
|
+
return deps.auth;
|
|
904
|
+
}
|
|
905
|
+
return defineRoutes("service:auth", {
|
|
906
|
+
"auth.status": route("auth.status", true, globalTarget, async () => authOrFail().status()),
|
|
907
|
+
"auth.login.status": route("auth.login.status", false, globalTarget, async (input, context) => {
|
|
908
|
+
const port = authOrFail();
|
|
909
|
+
if (port.loginStatus === void 0) throw new ServiceError("NOT_HANDLED", "auth.login.status is not supported by this worker");
|
|
910
|
+
if (input === void 0 || typeof input.loginId !== "string" || input.loginId === "") throw new ServiceError("INVALID_INPUT", "auth.login.status requires { loginId }");
|
|
911
|
+
const found = await port.loginStatus({ loginId: input.loginId }, authOwnerOf(context));
|
|
912
|
+
if (found === void 0) throw new ServiceError("NOT_FOUND", "unknown or expired login");
|
|
913
|
+
return found;
|
|
914
|
+
}),
|
|
915
|
+
"auth.login": route("auth.login", false, globalTarget, async (input, context) => {
|
|
916
|
+
const port = authOrFail();
|
|
917
|
+
if (input === void 0 || typeof input.providerId !== "string" || input.providerId === "") throw new ServiceError("INVALID_INPUT", "auth.login requires { providerId }");
|
|
918
|
+
if (input.accountLabel !== void 0 && !isAccountLabel(input.accountLabel)) throw new ServiceError("INVALID_INPUT", "auth.login accountLabel is invalid");
|
|
919
|
+
return await port.login(input, authOwnerOf(context), { async: context.clientFeatures?.includes(AUTH_LOGIN_ASYNC_FEATURE) === true });
|
|
920
|
+
}),
|
|
921
|
+
"auth.login.submit-code": route("auth.login.submit-code", false, globalTarget, async (input, context) => {
|
|
922
|
+
const port = authOrFail();
|
|
923
|
+
if (port.submitCode === void 0) throw new ServiceError("NOT_HANDLED", "auth.login.submit-code is not supported by this worker");
|
|
924
|
+
if (input === void 0 || typeof input.loginId !== "string" || typeof input.code !== "string") throw new ServiceError("INVALID_INPUT", "auth.login.submit-code requires { loginId, code }");
|
|
925
|
+
return await port.submitCode(input, authOwnerOf(context));
|
|
926
|
+
}),
|
|
927
|
+
"auth.login.cancel": route("auth.login.cancel", false, globalTarget, async (input, context) => {
|
|
928
|
+
const port = authOrFail();
|
|
929
|
+
if (port.cancel === void 0) throw new ServiceError("NOT_HANDLED", "auth.login.cancel is not supported by this worker");
|
|
930
|
+
if (input === void 0 || typeof input.loginId !== "string") throw new ServiceError("INVALID_INPUT", "auth.login.cancel requires { loginId }");
|
|
931
|
+
return await port.cancel(input.loginId, authOwnerOf(context));
|
|
932
|
+
}),
|
|
933
|
+
"auth.set-key": route("auth.set-key", false, globalTarget, async (input) => {
|
|
934
|
+
const port = authOrFail();
|
|
935
|
+
if (input === void 0 || typeof input.providerId !== "string" || typeof input.key !== "string") throw new ServiceError("INVALID_INPUT", "auth.set-key requires { providerId, key }");
|
|
936
|
+
if (input.accountLabel !== void 0 && !isAccountLabel(input.accountLabel)) throw new ServiceError("INVALID_INPUT", "auth.set-key accountLabel is invalid");
|
|
937
|
+
return await port.setKey(input);
|
|
938
|
+
}),
|
|
939
|
+
"auth.account": route("auth.account", false, globalTarget, async (input) => {
|
|
940
|
+
const port = authOrFail();
|
|
941
|
+
const action = input?.action;
|
|
942
|
+
if (port.account === void 0) throw new ServiceError("NOT_HANDLED", "auth.account is not supported by this worker");
|
|
943
|
+
if (input === void 0 || typeof input.providerId !== "string" || input.providerId === "" || action !== "activate" && action !== "probe" && action !== "rename" && action !== "remove" && action !== "reconcile") throw new ServiceError("INVALID_INPUT", "auth.account requires { providerId, action }");
|
|
944
|
+
if (action !== "reconcile" && (typeof input.accountId !== "string" || input.accountId === "")) throw new ServiceError("INVALID_INPUT", `auth.account ${action} requires { accountId }`);
|
|
945
|
+
if (action === "rename" && !isAccountLabel(input.label)) throw new ServiceError("INVALID_INPUT", "auth.account rename requires a valid label");
|
|
946
|
+
return await port.account(input);
|
|
947
|
+
}),
|
|
948
|
+
"auth.logout": route("auth.logout", false, globalTarget, async (input) => {
|
|
949
|
+
const port = authOrFail();
|
|
950
|
+
if (input === void 0 || typeof input.providerId !== "string" || input.providerId === "") throw new ServiceError("INVALID_INPUT", "auth.logout requires { providerId }");
|
|
951
|
+
return await port.logout(input.providerId);
|
|
952
|
+
})
|
|
953
|
+
});
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
//#endregion
|
|
957
|
+
//#region src/hub-capabilities.ts
|
|
958
|
+
const HUB_CAPABILITY_HTTP = "http";
|
|
959
|
+
const HUB_CAPABILITY_WS = "ws";
|
|
960
|
+
const HUB_CAPABILITY_ASK = "ask";
|
|
961
|
+
const HUB_CAPABILITY_REPOSITORY = "repository";
|
|
962
|
+
const HUB_CAPABILITY_WORK_IDENTITY_V2 = "work-identity-v2";
|
|
963
|
+
const HUB_CAPABILITY_FOLLOW_SCOPE = "follow-scope";
|
|
964
|
+
const HUB_CAPABILITY_EXTENSION_RPC = "extensionRpc";
|
|
965
|
+
const REPOSITORY_ROUTE_PREFIX = "repository.";
|
|
966
|
+
function hubCapabilitiesFrom(facts) {
|
|
967
|
+
const capabilities = [HUB_CAPABILITY_HTTP, "ws"];
|
|
968
|
+
if (facts.hasAsk) capabilities.push("ask");
|
|
969
|
+
if (facts.types.some((type) => type.startsWith(REPOSITORY_ROUTE_PREFIX))) capabilities.push(HUB_CAPABILITY_REPOSITORY);
|
|
970
|
+
if (facts.hasExtension === true) capabilities.push(HUB_CAPABILITY_EXTENSION_RPC);
|
|
971
|
+
capabilities.push(HUB_CAPABILITY_WORK_IDENTITY_V2);
|
|
972
|
+
capabilities.push(HUB_CAPABILITY_FOLLOW_SCOPE);
|
|
973
|
+
return capabilities;
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
//#endregion
|
|
977
|
+
//#region src/routes/core-routes.ts
|
|
978
|
+
function coreRoutes(deps, methodNames) {
|
|
979
|
+
return defineRoutes("service:core", {
|
|
980
|
+
"runtime.askScope": route("runtime.askScope", true, globalTarget, async () => {
|
|
981
|
+
const scope = deps.dataSource.runtimeAskScope?.();
|
|
982
|
+
if (!scope?.runtimeEpoch) throw new ServiceError("ROUTE_NOT_READY", "runtime scope is unavailable");
|
|
983
|
+
return scope;
|
|
984
|
+
}),
|
|
985
|
+
"service.handshake": route("service.handshake", true, globalTarget, async (input) => {
|
|
986
|
+
const clientWire = input?.wireVersion;
|
|
987
|
+
if (typeof clientWire === "number" && clientWire < 4) throw new ServiceError("INVALID_INPUT", `client wire version ${String(clientWire)} is older than ${String(4)}`);
|
|
988
|
+
if (typeof clientWire === "number" && clientWire > 4) throw new ServiceError("INVALID_INPUT", `client wire version ${String(clientWire)} is newer than ${String(4)}`);
|
|
989
|
+
return {
|
|
990
|
+
wireVersion: 4,
|
|
991
|
+
minWireVersion: 4,
|
|
992
|
+
methods: methodNames(),
|
|
993
|
+
transports: ["http", "ws"],
|
|
994
|
+
...deps.instanceBoot === void 0 ? {} : { instanceBoot: deps.instanceBoot },
|
|
995
|
+
features: Object.fromEntries(hubCapabilitiesFrom({
|
|
996
|
+
types: methodNames(),
|
|
997
|
+
hasAsk: deps.askHost !== void 0
|
|
998
|
+
}).map((capability) => [capability, true]))
|
|
999
|
+
};
|
|
1000
|
+
})
|
|
1001
|
+
});
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
//#endregion
|
|
1005
|
+
//#region src/routes/support.ts
|
|
1006
|
+
function requireName(input, field, capability) {
|
|
1007
|
+
const value = input?.[field];
|
|
1008
|
+
if (typeof value !== "string" || value === "") throw new ServiceError("INVALID_INPUT", `${capability} requires { ${field} }`);
|
|
1009
|
+
return value;
|
|
1010
|
+
}
|
|
1011
|
+
function requireSessionId$1(input, capability) {
|
|
1012
|
+
return requireName(input, "sessionId", capability);
|
|
1013
|
+
}
|
|
1014
|
+
function requireToggle(input, capability) {
|
|
1015
|
+
const typed = input;
|
|
1016
|
+
if (typeof typed?.name !== "string" || typed.name === "" || typeof typed.enabled !== "boolean") throw new ServiceError("INVALID_INPUT", `${capability} requires { name, enabled }`);
|
|
1017
|
+
return {
|
|
1018
|
+
name: typed.name,
|
|
1019
|
+
enabled: typed.enabled
|
|
1020
|
+
};
|
|
1021
|
+
}
|
|
1022
|
+
function requirePort(port, capability) {
|
|
1023
|
+
if (port === void 0) throw new ServiceError("NOT_HANDLED", `${capability} requires a worker port`);
|
|
1024
|
+
return port;
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
//#endregion
|
|
1028
|
+
//#region src/route-validate.ts
|
|
1029
|
+
function isTurn(value) {
|
|
1030
|
+
return typeof value === "number" && Number.isInteger(value) && value >= 0;
|
|
1031
|
+
}
|
|
1032
|
+
function requireSessionId(payload, action) {
|
|
1033
|
+
const sessionId = payload?.sessionId;
|
|
1034
|
+
if (typeof sessionId !== "string" || sessionId === "") throw new ServiceError("INVALID_INPUT", `${action} requires sessionId`);
|
|
1035
|
+
return sessionId;
|
|
1036
|
+
}
|
|
1037
|
+
function requireJobKey(payload, action) {
|
|
1038
|
+
const value = payload?.jobKey;
|
|
1039
|
+
if (typeof value !== "string" || value === "") throw new ServiceError("INVALID_INPUT", `${action} requires jobKey`);
|
|
1040
|
+
return value;
|
|
1041
|
+
}
|
|
1042
|
+
function requireCommitId(payload, action) {
|
|
1043
|
+
const commitId = payload?.commitId;
|
|
1044
|
+
if (typeof commitId !== "string" || commitId === "") throw new ServiceError("INVALID_INPUT", `${action} requires commitId`);
|
|
1045
|
+
return commitId;
|
|
1046
|
+
}
|
|
1047
|
+
function requireModelId(payload, action) {
|
|
1048
|
+
const modelId = payload?.modelId;
|
|
1049
|
+
if (typeof modelId !== "string" || modelId === "") throw new ServiceError("INVALID_INPUT", `${action} requires modelId`);
|
|
1050
|
+
return modelId;
|
|
1051
|
+
}
|
|
1052
|
+
function requireUiHost(payload, action) {
|
|
1053
|
+
const host = payload?.host;
|
|
1054
|
+
if (host !== "web" && host !== "tui") throw new ServiceError("INVALID_INPUT", `${action} requires host to be "web" or "tui"`);
|
|
1055
|
+
return host;
|
|
1056
|
+
}
|
|
1057
|
+
function requireTitle(payload, action) {
|
|
1058
|
+
const title = payload?.title;
|
|
1059
|
+
if (typeof title !== "string" || title.trim() === "") throw new ServiceError("INVALID_INPUT", `${action} requires a non-empty title`);
|
|
1060
|
+
return title.trim();
|
|
1061
|
+
}
|
|
1062
|
+
function requirePinTargets(payload, action) {
|
|
1063
|
+
const sessionIds = payload?.sessionIds;
|
|
1064
|
+
if (!Array.isArray(sessionIds) || sessionIds.length === 0) throw new ServiceError("INVALID_INPUT", `${action} requires a non-empty sessionIds array`);
|
|
1065
|
+
for (const sessionId of sessionIds) if (typeof sessionId !== "string" || sessionId === "") throw new ServiceError("INVALID_INPUT", `${action} sessionIds must be non-empty strings`);
|
|
1066
|
+
return sessionIds;
|
|
1067
|
+
}
|
|
1068
|
+
function requirePinMode(payload, action) {
|
|
1069
|
+
const mode = payload?.mode;
|
|
1070
|
+
if (mode === "clear") return mode;
|
|
1071
|
+
if (mode !== "toggle" && mode !== "ensure") throw new ServiceError("INVALID_INPUT", `${action} mode must be "toggle", "ensure" or "clear"`);
|
|
1072
|
+
return mode;
|
|
1073
|
+
}
|
|
1074
|
+
const PIN_GROUP_CONTROL = /[\u0000-\u001F\u007F]/;
|
|
1075
|
+
const PIN_GROUP_MAX_LENGTH = 64;
|
|
1076
|
+
function optionalPinGroup(payload, action) {
|
|
1077
|
+
const group = payload?.group;
|
|
1078
|
+
if (group === void 0) return;
|
|
1079
|
+
if (typeof group !== "string" || group.trim() === "") throw new ServiceError("INVALID_INPUT", `${action} group must be a non-empty string`);
|
|
1080
|
+
const trimmed = group.trim();
|
|
1081
|
+
if (PIN_GROUP_CONTROL.test(trimmed) || [...trimmed].length > PIN_GROUP_MAX_LENGTH) throw new ServiceError("INVALID_INPUT", `${action} group must not contain control characters and must be at most ${PIN_GROUP_MAX_LENGTH} characters`);
|
|
1082
|
+
return trimmed;
|
|
1083
|
+
}
|
|
1084
|
+
function denyUnbound(type) {
|
|
1085
|
+
throw new ServiceError("SCOPE_DENIED", `${type} requires a bound ask connection`);
|
|
1086
|
+
}
|
|
1087
|
+
function parseSessionDeliveryRequest(payload, action) {
|
|
1088
|
+
const record = payload;
|
|
1089
|
+
const sessionId = record?.sessionId;
|
|
1090
|
+
const actorSessionId = record?.actorSessionId;
|
|
1091
|
+
const text = record?.text;
|
|
1092
|
+
const clientRequestId = record?.clientRequestId;
|
|
1093
|
+
const mode = record?.mode;
|
|
1094
|
+
if (typeof sessionId !== "string" || sessionId === "") throw new ServiceError("INVALID_INPUT", `${action} requires sessionId`);
|
|
1095
|
+
if (typeof actorSessionId !== "string" || actorSessionId === "") throw new ServiceError("INVALID_INPUT", `${action} requires actorSessionId`);
|
|
1096
|
+
if (typeof text !== "string" || text === "") throw new ServiceError("INVALID_INPUT", `${action} requires text`);
|
|
1097
|
+
if (typeof clientRequestId !== "string" || clientRequestId === "") throw new ServiceError("INVALID_INPUT", `${action} requires clientRequestId`);
|
|
1098
|
+
if (mode !== "queue" && mode !== "steer") throw new ServiceError("INVALID_INPUT", `${action} requires mode queue|steer`);
|
|
1099
|
+
const peerDepth = record?.peerDepth;
|
|
1100
|
+
if (peerDepth !== void 0 && (typeof peerDepth !== "number" || !Number.isInteger(peerDepth) || peerDepth < 0)) throw new ServiceError("INVALID_INPUT", `${action} peerDepth must be a non-negative integer`);
|
|
1101
|
+
return {
|
|
1102
|
+
sessionId,
|
|
1103
|
+
actorSessionId,
|
|
1104
|
+
text,
|
|
1105
|
+
clientRequestId,
|
|
1106
|
+
mode,
|
|
1107
|
+
...peerDepth === void 0 ? {} : { peerDepth }
|
|
1108
|
+
};
|
|
1109
|
+
}
|
|
1110
|
+
function optionalSettingScope(payload, action) {
|
|
1111
|
+
const scope = payload?.scope;
|
|
1112
|
+
if (scope === void 0) return;
|
|
1113
|
+
if (scope !== "global" && scope !== "project") throw new ServiceError("INVALID_INPUT", `${action} scope must be 'global' or 'project'`);
|
|
1114
|
+
return scope;
|
|
1115
|
+
}
|
|
1116
|
+
function optionalConnectionId(payload) {
|
|
1117
|
+
const value = payload?.connectionId;
|
|
1118
|
+
return typeof value === "string" && value !== "" ? value : void 0;
|
|
1119
|
+
}
|
|
1120
|
+
|
|
1121
|
+
//#endregion
|
|
1122
|
+
//#region src/routes/ask-routes.ts
|
|
1123
|
+
function askRoutes(deps) {
|
|
1124
|
+
return defineRoutes("service:ask", {
|
|
1125
|
+
"ask.descendants": route("ask.descendants", true, bySession, async (payload) => {
|
|
1126
|
+
const sessionId = requireSessionId$1(payload, "ask.descendants");
|
|
1127
|
+
const read = deps.dataSource.askDescendants;
|
|
1128
|
+
if (read === void 0) throw new ServiceError("NOT_HANDLED", "askDescendants is not supported by this data source");
|
|
1129
|
+
return await read.call(deps.dataSource, sessionId);
|
|
1130
|
+
}),
|
|
1131
|
+
"approval.respond": route("approval.respond", false, byAskRef, async () => denyUnbound("approval.respond")),
|
|
1132
|
+
"hitl.respond": route("hitl.respond", false, byAskRef, async () => denyUnbound("hitl.respond")),
|
|
1133
|
+
"ask.open": route("ask.open", false, byAskScope, async () => denyUnbound("ask.open")),
|
|
1134
|
+
"ask.refresh": route("ask.refresh", false, byAskScope, async () => denyUnbound("ask.refresh")),
|
|
1135
|
+
"ask.close": route("ask.close", false, byAskScope, async () => denyUnbound("ask.close"))
|
|
1136
|
+
});
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
//#endregion
|
|
1140
|
+
//#region src/source-for-session.ts
|
|
1141
|
+
function sourceForSession(deps, sessionId) {
|
|
1142
|
+
const resolve = deps.dataSource.resolve;
|
|
1143
|
+
if (resolve === void 0) return deps.dataSource;
|
|
1144
|
+
return resolve.call(deps.dataSource, sessionId) ?? deps.dataSource;
|
|
1145
|
+
}
|
|
1146
|
+
async function sourceForSessionAsync(deps, sessionId) {
|
|
1147
|
+
const resolver = deps.dataSource;
|
|
1148
|
+
const sync = resolver.resolve?.call(deps.dataSource, sessionId);
|
|
1149
|
+
if (sync !== void 0) return await sync;
|
|
1150
|
+
if (resolver.resolveAsync === void 0) return deps.dataSource;
|
|
1151
|
+
return await resolver.resolveAsync.call(deps.dataSource, sessionId) ?? deps.dataSource;
|
|
1152
|
+
}
|
|
1153
|
+
|
|
1154
|
+
//#endregion
|
|
1155
|
+
//#region src/send-attempt-table.ts
|
|
1156
|
+
const SEND_ATTEMPT_LIMIT = 200;
|
|
1157
|
+
function digestSendAttemptText(text) {
|
|
1158
|
+
return createHash("sha256").update(text, "utf8").digest("hex");
|
|
1159
|
+
}
|
|
1160
|
+
function attemptOf(sessionId, attemptId) {
|
|
1161
|
+
return JSON.stringify([sessionId, attemptId]);
|
|
1162
|
+
}
|
|
1163
|
+
function keyOf(sessionId, attemptId, mode) {
|
|
1164
|
+
return JSON.stringify([
|
|
1165
|
+
sessionId,
|
|
1166
|
+
attemptId,
|
|
1167
|
+
mode
|
|
1168
|
+
]);
|
|
1169
|
+
}
|
|
1170
|
+
function createSendAttemptTable(options = {}) {
|
|
1171
|
+
const limit = options.limit ?? 200;
|
|
1172
|
+
const entries = /* @__PURE__ */ new Map();
|
|
1173
|
+
const latestOf = /* @__PURE__ */ new Map();
|
|
1174
|
+
const evict = () => {
|
|
1175
|
+
while (entries.size > limit) {
|
|
1176
|
+
let victim;
|
|
1177
|
+
for (const [key, entry] of entries) if (entry.settledReceipt !== void 0) {
|
|
1178
|
+
victim = key;
|
|
1179
|
+
break;
|
|
1180
|
+
}
|
|
1181
|
+
if (victim === void 0) return;
|
|
1182
|
+
const removed = entries.get(victim);
|
|
1183
|
+
entries.delete(victim);
|
|
1184
|
+
if (removed === void 0) continue;
|
|
1185
|
+
const attempt = attemptOf(removed.sessionId, removed.attemptId);
|
|
1186
|
+
if (latestOf.get(attempt) === victim) latestOf.delete(attempt);
|
|
1187
|
+
}
|
|
1188
|
+
};
|
|
1189
|
+
return {
|
|
1190
|
+
lookupOrReserve({ sessionId, attemptId, mode = "queue", fingerprint }) {
|
|
1191
|
+
const attempt = attemptOf(sessionId, attemptId);
|
|
1192
|
+
const key = keyOf(sessionId, attemptId, mode);
|
|
1193
|
+
const existing = entries.get(key);
|
|
1194
|
+
if (existing !== void 0) {
|
|
1195
|
+
if (existing.fingerprint !== fingerprint) return { kind: "conflict" };
|
|
1196
|
+
return {
|
|
1197
|
+
kind: "hit",
|
|
1198
|
+
promise: existing.promise
|
|
1199
|
+
};
|
|
1200
|
+
}
|
|
1201
|
+
let resolve = () => {};
|
|
1202
|
+
let reject = () => {};
|
|
1203
|
+
const promise = new Promise((settle, fail) => {
|
|
1204
|
+
resolve = settle;
|
|
1205
|
+
reject = fail;
|
|
1206
|
+
});
|
|
1207
|
+
promise.catch(() => void 0);
|
|
1208
|
+
const entry = {
|
|
1209
|
+
sessionId,
|
|
1210
|
+
attemptId,
|
|
1211
|
+
mode,
|
|
1212
|
+
fingerprint,
|
|
1213
|
+
promise,
|
|
1214
|
+
resolve,
|
|
1215
|
+
reject
|
|
1216
|
+
};
|
|
1217
|
+
entries.set(key, entry);
|
|
1218
|
+
latestOf.set(attempt, key);
|
|
1219
|
+
evict();
|
|
1220
|
+
return {
|
|
1221
|
+
kind: "reserved",
|
|
1222
|
+
reservation: {
|
|
1223
|
+
promise,
|
|
1224
|
+
settle(receipt) {
|
|
1225
|
+
if (entries.get(key) !== entry || entry.settledReceipt !== void 0) return;
|
|
1226
|
+
entry.settledReceipt = { ...receipt };
|
|
1227
|
+
evict();
|
|
1228
|
+
entry.resolve({ ...receipt });
|
|
1229
|
+
},
|
|
1230
|
+
release(receipt) {
|
|
1231
|
+
if (entries.get(key) === entry) {
|
|
1232
|
+
entries.delete(key);
|
|
1233
|
+
if (latestOf.get(attempt) === key) latestOf.delete(attempt);
|
|
1234
|
+
}
|
|
1235
|
+
entry.resolve({ ...receipt });
|
|
1236
|
+
},
|
|
1237
|
+
fail(error) {
|
|
1238
|
+
if (entries.get(key) === entry) {
|
|
1239
|
+
entries.delete(key);
|
|
1240
|
+
if (latestOf.get(attempt) === key) latestOf.delete(attempt);
|
|
1241
|
+
}
|
|
1242
|
+
entry.reject(error);
|
|
1243
|
+
}
|
|
1244
|
+
}
|
|
1245
|
+
};
|
|
1246
|
+
},
|
|
1247
|
+
query(sessionId, attemptId) {
|
|
1248
|
+
const key = latestOf.get(attemptOf(sessionId, attemptId));
|
|
1249
|
+
const entry = key === void 0 ? void 0 : entries.get(key);
|
|
1250
|
+
if (entry === void 0) return {
|
|
1251
|
+
kind: "unavailable",
|
|
1252
|
+
sessionId,
|
|
1253
|
+
attemptId
|
|
1254
|
+
};
|
|
1255
|
+
if (entry.settledReceipt === void 0) return {
|
|
1256
|
+
kind: "pending",
|
|
1257
|
+
sessionId,
|
|
1258
|
+
attemptId
|
|
1259
|
+
};
|
|
1260
|
+
return {
|
|
1261
|
+
kind: "settled",
|
|
1262
|
+
sessionId,
|
|
1263
|
+
attemptId,
|
|
1264
|
+
receipt: { ...entry.settledReceipt }
|
|
1265
|
+
};
|
|
1266
|
+
},
|
|
1267
|
+
markDurable(sessionId, attemptId, mode) {
|
|
1268
|
+
const entry = entries.get(keyOf(sessionId, attemptId, mode));
|
|
1269
|
+
if (entry === void 0 || entry.settledReceipt === void 0) return;
|
|
1270
|
+
if (entry.settledReceipt.accepted !== true) return;
|
|
1271
|
+
entry.settledReceipt.durable = "confirmed";
|
|
1272
|
+
},
|
|
1273
|
+
size: () => entries.size
|
|
1274
|
+
};
|
|
1275
|
+
}
|
|
1276
|
+
|
|
1277
|
+
//#endregion
|
|
1278
|
+
//#region src/chat-routes.ts
|
|
1279
|
+
function expectedQueueRevisionOf(payload) {
|
|
1280
|
+
const value = payload?.expectedQueueRevision;
|
|
1281
|
+
if (value === void 0) return {};
|
|
1282
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < 0) throw new ServiceError("INVALID_INPUT", "expectedQueueRevision must be a non-negative integer when provided");
|
|
1283
|
+
return { expectedQueueRevision: value };
|
|
1284
|
+
}
|
|
1285
|
+
function parseRecoveryOrigin(value) {
|
|
1286
|
+
if (value === void 0) return "automatic";
|
|
1287
|
+
if (value === "user" || value === "automatic") return value;
|
|
1288
|
+
throw new ServiceError("INVALID_ARGUMENT", "chat.retryLastRound origin must be 'user' or 'automatic'");
|
|
1289
|
+
}
|
|
1290
|
+
function parseRetryPending(value) {
|
|
1291
|
+
if (value === void 0) return "inject";
|
|
1292
|
+
if (value === "inject" || value === "discard") return value;
|
|
1293
|
+
throw new ServiceError("INVALID_INPUT", "chat.retryLastRound pending must be 'inject' or 'discard'");
|
|
1294
|
+
}
|
|
1295
|
+
function parseSendMode(value) {
|
|
1296
|
+
if (value === void 0) return "queue";
|
|
1297
|
+
if (value === "queue" || value === "takeover") return value;
|
|
1298
|
+
throw new ServiceError("INVALID_INPUT", "chat.send mode must be 'queue' or 'takeover'");
|
|
1299
|
+
}
|
|
1300
|
+
function requireRecoveryTarget(method, payload) {
|
|
1301
|
+
const input = payload;
|
|
1302
|
+
if (typeof input?.recoveryId !== "string" || input.recoveryId === "") throw new ServiceError("INVALID_INPUT", `${method} requires a non-empty recoveryId`);
|
|
1303
|
+
if (!isTurn(input.turn)) throw new ServiceError("INVALID_INPUT", `${method} requires a non-negative integer turn`);
|
|
1304
|
+
if (!isTurn(input.step)) throw new ServiceError("INVALID_INPUT", `${method} requires a non-negative integer step`);
|
|
1305
|
+
if (!isTurn(input.revision)) throw new ServiceError("INVALID_INPUT", `${method} requires a non-negative integer revision`);
|
|
1306
|
+
return {
|
|
1307
|
+
identity: {
|
|
1308
|
+
recoveryId: input.recoveryId,
|
|
1309
|
+
turn: input.turn,
|
|
1310
|
+
step: input.step
|
|
1311
|
+
},
|
|
1312
|
+
revision: input.revision
|
|
1313
|
+
};
|
|
1314
|
+
}
|
|
1315
|
+
function reportChatAttemptStatusSource(deps, sessionId, attemptId, source) {
|
|
1316
|
+
deps.reportDiagnostic?.({
|
|
1317
|
+
source: "send",
|
|
1318
|
+
severity: "info",
|
|
1319
|
+
sessionId,
|
|
1320
|
+
code: "CHAT_ATTEMPT_STATUS_SOURCE",
|
|
1321
|
+
message: `chat attempt status resolved from ${source}`,
|
|
1322
|
+
detail: {
|
|
1323
|
+
sessionId,
|
|
1324
|
+
attemptId,
|
|
1325
|
+
source
|
|
1326
|
+
}
|
|
1327
|
+
});
|
|
1328
|
+
}
|
|
1329
|
+
const CHAT_ATTEMPT_STATUS_BUDGET_MS = 1500;
|
|
1330
|
+
const ATTEMPT_STATUS_DEADLINE = Symbol("attempt-status-deadline");
|
|
1331
|
+
async function withAttemptQueryBudget(work, budgetMs) {
|
|
1332
|
+
if (work === void 0) return;
|
|
1333
|
+
let timer;
|
|
1334
|
+
const deadline = new Promise((resolve) => {
|
|
1335
|
+
timer = setTimeout(() => resolve(ATTEMPT_STATUS_DEADLINE), budgetMs);
|
|
1336
|
+
timer.unref?.();
|
|
1337
|
+
});
|
|
1338
|
+
try {
|
|
1339
|
+
return await Promise.race([work, deadline]);
|
|
1340
|
+
} finally {
|
|
1341
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
1342
|
+
}
|
|
1343
|
+
}
|
|
1344
|
+
function chatRoutes(deps, attempts = createSendAttemptTable()) {
|
|
1345
|
+
return defineRoutes("service:chat", {
|
|
1346
|
+
"chat.attempt.status": route("chat.attempt.status", true, bySession, async (payload) => {
|
|
1347
|
+
const sessionId = requireSessionId(payload, "chat.attempt.status");
|
|
1348
|
+
const attemptId = payload?.attemptId;
|
|
1349
|
+
if (typeof attemptId !== "string" || attemptId === "") throw new ServiceError("INVALID_INPUT", "chat.attempt.status requires a non-empty attemptId");
|
|
1350
|
+
const query = attempts.query(sessionId, attemptId);
|
|
1351
|
+
if (query.kind !== "unavailable") {
|
|
1352
|
+
reportChatAttemptStatusSource(deps, sessionId, attemptId, "memory");
|
|
1353
|
+
return query;
|
|
1354
|
+
}
|
|
1355
|
+
const outcome = await withAttemptQueryBudget(deps.dataSource.readChatSendAttemptById?.({
|
|
1356
|
+
sessionId,
|
|
1357
|
+
attemptId
|
|
1358
|
+
}), CHAT_ATTEMPT_STATUS_BUDGET_MS);
|
|
1359
|
+
if (outcome === ATTEMPT_STATUS_DEADLINE) {
|
|
1360
|
+
deps.reportDiagnostic?.({
|
|
1361
|
+
source: "send",
|
|
1362
|
+
severity: "warning",
|
|
1363
|
+
sessionId,
|
|
1364
|
+
code: "CHAT_ATTEMPT_STATUS_TIMEOUT",
|
|
1365
|
+
message: `chat attempt durable lookup exceeded ${CHAT_ATTEMPT_STATUS_BUDGET_MS}ms`,
|
|
1366
|
+
detail: {
|
|
1367
|
+
sessionId,
|
|
1368
|
+
attemptId,
|
|
1369
|
+
budgetMs: CHAT_ATTEMPT_STATUS_BUDGET_MS
|
|
1370
|
+
}
|
|
1371
|
+
});
|
|
1372
|
+
reportChatAttemptStatusSource(deps, sessionId, attemptId, "unavailable");
|
|
1373
|
+
return {
|
|
1374
|
+
kind: "unavailable",
|
|
1375
|
+
sessionId,
|
|
1376
|
+
attemptId
|
|
1377
|
+
};
|
|
1378
|
+
}
|
|
1379
|
+
const durable = outcome;
|
|
1380
|
+
if (durable !== void 0 && durable.kind === "hit") {
|
|
1381
|
+
reportChatAttemptStatusSource(deps, sessionId, attemptId, "durable");
|
|
1382
|
+
return {
|
|
1383
|
+
kind: "settled",
|
|
1384
|
+
sessionId,
|
|
1385
|
+
attemptId,
|
|
1386
|
+
receipt: {
|
|
1387
|
+
...durable.receipt,
|
|
1388
|
+
durable: "confirmed"
|
|
1389
|
+
}
|
|
1390
|
+
};
|
|
1391
|
+
}
|
|
1392
|
+
reportChatAttemptStatusSource(deps, sessionId, attemptId, "unavailable");
|
|
1393
|
+
return {
|
|
1394
|
+
kind: "unavailable",
|
|
1395
|
+
sessionId,
|
|
1396
|
+
attemptId
|
|
1397
|
+
};
|
|
1398
|
+
}),
|
|
1399
|
+
"chat.send": route("chat.send", false, bySession, async (payload) => {
|
|
1400
|
+
const input = payload;
|
|
1401
|
+
const text = input?.text;
|
|
1402
|
+
if (typeof text !== "string") throw new ServiceError("INVALID_INPUT", "chat.send requires text");
|
|
1403
|
+
const mode = parseSendMode(input?.mode);
|
|
1404
|
+
const clientRequestId = input?.clientRequestId;
|
|
1405
|
+
if (clientRequestId !== void 0 && (typeof clientRequestId !== "string" || clientRequestId === "")) throw new ServiceError("INVALID_INPUT", "chat.send clientRequestId must be a non-empty string");
|
|
1406
|
+
let sessionId = input?.sessionId;
|
|
1407
|
+
if (sessionId === void 0) try {
|
|
1408
|
+
sessionId = (await deps.dataSource.createSession()).id;
|
|
1409
|
+
} catch {
|
|
1410
|
+
return {
|
|
1411
|
+
accepted: false,
|
|
1412
|
+
sessionId: "",
|
|
1413
|
+
reason: "not-ready"
|
|
1414
|
+
};
|
|
1415
|
+
}
|
|
1416
|
+
const source = sourceForSession(deps, sessionId);
|
|
1417
|
+
if (typeof source.submitInput !== "function") return {
|
|
1418
|
+
accepted: false,
|
|
1419
|
+
sessionId,
|
|
1420
|
+
reason: "unsupported"
|
|
1421
|
+
};
|
|
1422
|
+
let reservation;
|
|
1423
|
+
if (clientRequestId !== void 0) {
|
|
1424
|
+
const lookup = attempts.lookupOrReserve({
|
|
1425
|
+
sessionId,
|
|
1426
|
+
attemptId: clientRequestId,
|
|
1427
|
+
mode,
|
|
1428
|
+
fingerprint: digestSendAttemptText(text)
|
|
1429
|
+
});
|
|
1430
|
+
if (lookup.kind === "conflict") throw new ServiceError("INVALID_INPUT", "chat.send clientRequestId was reused with different text");
|
|
1431
|
+
if (lookup.kind === "hit") return lookup.promise;
|
|
1432
|
+
reservation = lookup.reservation;
|
|
1433
|
+
const durable = await deps.dataSource.readChatSendAttempt?.({
|
|
1434
|
+
sessionId,
|
|
1435
|
+
attemptId: clientRequestId,
|
|
1436
|
+
mode,
|
|
1437
|
+
fingerprint: digestSendAttemptText(text)
|
|
1438
|
+
});
|
|
1439
|
+
if (durable?.kind === "conflict") {
|
|
1440
|
+
reservation.fail(/* @__PURE__ */ new Error("durable chat.send attempt conflict"));
|
|
1441
|
+
throw new ServiceError("INVALID_INPUT", "chat.send clientRequestId was reused with different text");
|
|
1442
|
+
}
|
|
1443
|
+
if (durable?.kind === "hit") {
|
|
1444
|
+
reservation.fail(/* @__PURE__ */ new Error("durable chat.send attempt hit"));
|
|
1445
|
+
return durable.receipt;
|
|
1446
|
+
}
|
|
1447
|
+
}
|
|
1448
|
+
try {
|
|
1449
|
+
if (typeof source.claimSessionLease === "function") {
|
|
1450
|
+
const claim = await source.claimSessionLease(sessionId);
|
|
1451
|
+
if (!claim.ok) {
|
|
1452
|
+
const busy = {
|
|
1453
|
+
accepted: false,
|
|
1454
|
+
sessionId,
|
|
1455
|
+
reason: "busy",
|
|
1456
|
+
message: claim.message,
|
|
1457
|
+
...claim.contended === true ? { contended: true } : {}
|
|
1458
|
+
};
|
|
1459
|
+
reservation?.release(busy);
|
|
1460
|
+
return busy;
|
|
1461
|
+
}
|
|
1462
|
+
}
|
|
1463
|
+
const stageAttemptId = typeof input?.stageAttemptId === "string" ? input.stageAttemptId : void 0;
|
|
1464
|
+
const attachments = input?.attachments;
|
|
1465
|
+
if (attachments !== void 0) {
|
|
1466
|
+
if (!Array.isArray(attachments) || attachments.length > 4) throw new ServiceError("INVALID_INPUT", "chat.send accepts at most 4 attachments");
|
|
1467
|
+
for (const attachment of attachments) if (typeof attachment !== "object" || attachment === null || typeof attachment.mime !== "string" || !attachment.mime.startsWith("image/") || typeof attachment.source !== "string" || attachment.source === "" || attachment.source.length > 12e6) throw new ServiceError("INVALID_INPUT", "chat.send attachment is malformed");
|
|
1468
|
+
}
|
|
1469
|
+
const receipt = await source.submitInput(sessionId, text, mode, stageAttemptId, attachments, clientRequestId);
|
|
1470
|
+
reservation?.settle(receipt);
|
|
1471
|
+
if (clientRequestId !== void 0) {
|
|
1472
|
+
const record = await deps.dataSource.recordChatSendAttempt?.({
|
|
1473
|
+
sessionId,
|
|
1474
|
+
attemptId: clientRequestId,
|
|
1475
|
+
mode,
|
|
1476
|
+
fingerprint: digestSendAttemptText(text),
|
|
1477
|
+
receipt
|
|
1478
|
+
}).catch(() => void 0);
|
|
1479
|
+
if (record !== void 0 && record.state === "unknown" && receipt.accepted === true) {
|
|
1480
|
+
record.settled.then((finalState) => {
|
|
1481
|
+
if (finalState === "confirmed") attempts.markDurable(sessionId, clientRequestId, mode);
|
|
1482
|
+
}, () => void 0);
|
|
1483
|
+
return {
|
|
1484
|
+
...receipt,
|
|
1485
|
+
durable: "unknown"
|
|
1486
|
+
};
|
|
1487
|
+
}
|
|
1488
|
+
}
|
|
1489
|
+
return receipt;
|
|
1490
|
+
} catch (error) {
|
|
1491
|
+
reservation?.fail(error);
|
|
1492
|
+
throw error;
|
|
1493
|
+
}
|
|
1494
|
+
}),
|
|
1495
|
+
"chat.submitIntent": route("chat.submitIntent", false, bySession, async (payload) => {
|
|
1496
|
+
const input = payload;
|
|
1497
|
+
if (typeof input?.sessionId !== "string" || input.sessionId === "") throw new ServiceError("INVALID_INPUT", "chat.submitIntent requires sessionId");
|
|
1498
|
+
if (typeof input.clientRequestId !== "string" || input.clientRequestId === "") throw new ServiceError("INVALID_INPUT", "chat.submitIntent requires clientRequestId");
|
|
1499
|
+
const source = sourceForSession(deps, input.sessionId);
|
|
1500
|
+
const intent = input.intent;
|
|
1501
|
+
if (intent?.kind === "shell" && typeof intent.command === "string" && intent.command !== "") {
|
|
1502
|
+
if (typeof source.submitIntent !== "function") return { status: "unsupported" };
|
|
1503
|
+
return await source.submitIntent(input.sessionId, {
|
|
1504
|
+
kind: "shell",
|
|
1505
|
+
command: intent.command,
|
|
1506
|
+
...typeof intent.background === "boolean" ? { background: intent.background } : {}
|
|
1507
|
+
}, input.clientRequestId);
|
|
1508
|
+
}
|
|
1509
|
+
if (intent?.kind === "memory" && typeof intent.text === "string" && intent.text !== "") {
|
|
1510
|
+
if (typeof source.submitIntent !== "function") return { status: "unsupported" };
|
|
1511
|
+
return await source.submitIntent(input.sessionId, {
|
|
1512
|
+
kind: "memory",
|
|
1513
|
+
text: intent.text
|
|
1514
|
+
}, input.clientRequestId);
|
|
1515
|
+
}
|
|
1516
|
+
return {
|
|
1517
|
+
status: "denied",
|
|
1518
|
+
reason: "invalid intent shape"
|
|
1519
|
+
};
|
|
1520
|
+
}),
|
|
1521
|
+
"chat.clear": route("chat.clear", false, bySession, async (payload) => {
|
|
1522
|
+
const sessionId = requireSessionId(payload, "chat.clear");
|
|
1523
|
+
const source = sourceForSession(deps, sessionId);
|
|
1524
|
+
if (!source.clear) throw new ServiceError("NOT_HANDLED", "clear is not supported by this data source");
|
|
1525
|
+
return { cleared: await source.clear(sessionId) };
|
|
1526
|
+
}),
|
|
1527
|
+
"chat.compact": route("chat.compact", false, bySession, async (payload) => {
|
|
1528
|
+
const sessionId = requireSessionId(payload, "chat.compact");
|
|
1529
|
+
const timeoutMs = payload?.timeoutMs;
|
|
1530
|
+
if (timeoutMs !== void 0 && !(typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs > 0)) throw new ServiceError("INVALID_INPUT", "chat.compact timeoutMs must be a positive number");
|
|
1531
|
+
const source = sourceForSession(deps, sessionId);
|
|
1532
|
+
if (!source.compact) throw new ServiceError("NOT_HANDLED", "compact is not supported by this data source");
|
|
1533
|
+
return source.compact(sessionId, timeoutMs === void 0 ? void 0 : { timeoutMs });
|
|
1534
|
+
}),
|
|
1535
|
+
"chat.interrupt": route("chat.interrupt", false, bySession, async (payload) => {
|
|
1536
|
+
const sessionId = requireSessionId(payload, "chat.interrupt");
|
|
1537
|
+
const source = sourceForSession(deps, sessionId);
|
|
1538
|
+
const mode = payload?.mode;
|
|
1539
|
+
if (mode !== void 0 && mode !== "stop-retry") throw new ServiceError("INVALID_INPUT", "chat.interrupt mode must be stop-retry");
|
|
1540
|
+
if (!source.interrupt) throw new ServiceError("NOT_HANDLED", "interrupt is not supported by this data source");
|
|
1541
|
+
const turn = payload?.turn;
|
|
1542
|
+
if (turn !== void 0 && !isTurn(turn)) throw new ServiceError("INVALID_INPUT", "chat.interrupt turn must be a non-negative integer");
|
|
1543
|
+
return source.interrupt(sessionId, turn === void 0 ? void 0 : { turn }, mode);
|
|
1544
|
+
}),
|
|
1545
|
+
"chat.executionStatus": route("chat.executionStatus", true, bySession, async (payload) => {
|
|
1546
|
+
const sessionId = requireSessionId(payload, "chat.executionStatus");
|
|
1547
|
+
const source = sourceForSession(deps, sessionId);
|
|
1548
|
+
const turn = payload?.turn;
|
|
1549
|
+
if (!isTurn(turn)) throw new ServiceError("INVALID_INPUT", "chat.executionStatus requires a non-negative integer turn");
|
|
1550
|
+
if (!source.executionStatus) throw new ServiceError("NOT_HANDLED", "executionStatus is not supported by this data source");
|
|
1551
|
+
return source.executionStatus(sessionId, turn);
|
|
1552
|
+
}),
|
|
1553
|
+
"chat.retryLastRound": route("chat.retryLastRound", false, bySession, async (payload) => {
|
|
1554
|
+
const sessionId = requireSessionId(payload, "chat.retryLastRound");
|
|
1555
|
+
const source = sourceForSession(deps, sessionId);
|
|
1556
|
+
if (!source.retryLastRound) throw new ServiceError("NOT_HANDLED", "retryLastRound is not supported by this data source");
|
|
1557
|
+
const pending = parseRetryPending(payload?.pending);
|
|
1558
|
+
const origin = parseRecoveryOrigin(payload?.origin);
|
|
1559
|
+
return source.retryLastRound(sessionId, pending, void 0, origin);
|
|
1560
|
+
}),
|
|
1561
|
+
"chat.continueWithPending": route("chat.continueWithPending", false, bySession, async (payload) => {
|
|
1562
|
+
const sessionId = requireSessionId(payload, "chat.continueWithPending");
|
|
1563
|
+
const source = sourceForSession(deps, sessionId);
|
|
1564
|
+
if (!source.continueWithPending) throw new ServiceError("NOT_HANDLED", "continueWithPending is not supported by this data source");
|
|
1565
|
+
return await source.continueWithPending(sessionId);
|
|
1566
|
+
}),
|
|
1567
|
+
"chat.releaseAdmission": route("chat.releaseAdmission", false, bySession, async (payload) => {
|
|
1568
|
+
const sessionId = requireSessionId(payload, "chat.releaseAdmission");
|
|
1569
|
+
const source = sourceForSession(deps, sessionId);
|
|
1570
|
+
if (typeof source.releaseAdmission !== "function") throw new ServiceError("NOT_HANDLED", "releaseAdmission is not supported by this data source");
|
|
1571
|
+
return source.releaseAdmission(sessionId);
|
|
1572
|
+
}),
|
|
1573
|
+
"chat.retryCancel": route("chat.retryCancel", false, bySession, async (payload) => {
|
|
1574
|
+
const sessionId = requireSessionId(payload, "chat.retryCancel");
|
|
1575
|
+
const source = sourceForSession(deps, sessionId);
|
|
1576
|
+
const target = requireRecoveryTarget("chat.retryCancel", payload);
|
|
1577
|
+
if (typeof source.retryCancel !== "function") throw new ServiceError("NOT_HANDLED", "retryCancel is not supported by this data source");
|
|
1578
|
+
return source.retryCancel(sessionId, target);
|
|
1579
|
+
}),
|
|
1580
|
+
"chat.retryAccelerate": route("chat.retryAccelerate", false, bySession, async (payload) => {
|
|
1581
|
+
const sessionId = requireSessionId(payload, "chat.retryAccelerate");
|
|
1582
|
+
const source = sourceForSession(deps, sessionId);
|
|
1583
|
+
const target = requireRecoveryTarget("chat.retryAccelerate", payload);
|
|
1584
|
+
if (typeof source.retryAccelerate !== "function") throw new ServiceError("NOT_HANDLED", "retryAccelerate is not supported by this data source");
|
|
1585
|
+
return source.retryAccelerate(sessionId, target);
|
|
1586
|
+
}),
|
|
1587
|
+
"chat.withdraw": route("chat.withdraw", false, bySession, async (payload) => {
|
|
1588
|
+
const sessionId = requireSessionId(payload, "chat.withdraw");
|
|
1589
|
+
const source = sourceForSession(deps, sessionId);
|
|
1590
|
+
if (!source.withdraw) throw new ServiceError("NOT_HANDLED", "withdraw is not supported by this data source");
|
|
1591
|
+
return source.withdraw(sessionId);
|
|
1592
|
+
}),
|
|
1593
|
+
"chat.steer": route("chat.steer", false, bySession, async (payload) => {
|
|
1594
|
+
const sessionId = requireSessionId(payload, "chat.steer");
|
|
1595
|
+
const source = sourceForSession(deps, sessionId);
|
|
1596
|
+
const text = payload?.text;
|
|
1597
|
+
if (typeof text !== "string") throw new ServiceError("INVALID_INPUT", "chat.steer requires text");
|
|
1598
|
+
if (typeof source.steer !== "function") throw new ServiceError("NOT_HANDLED", "steer is not supported by this data source");
|
|
1599
|
+
if (typeof source.claimSessionLease === "function") {
|
|
1600
|
+
const claim = await source.claimSessionLease(sessionId);
|
|
1601
|
+
if (!claim.ok) return {
|
|
1602
|
+
accepted: false,
|
|
1603
|
+
sessionId,
|
|
1604
|
+
reason: "busy",
|
|
1605
|
+
message: claim.message,
|
|
1606
|
+
...claim.contended === true ? { contended: true } : {}
|
|
1607
|
+
};
|
|
1608
|
+
}
|
|
1609
|
+
return await source.steer(sessionId, text);
|
|
1610
|
+
}),
|
|
1611
|
+
"chat.queue.append": route("chat.queue.append", false, bySession, async (payload) => {
|
|
1612
|
+
const sessionId = requireSessionId(payload, "chat.queue.append");
|
|
1613
|
+
const source = sourceForSession(deps, sessionId);
|
|
1614
|
+
const text = payload?.text;
|
|
1615
|
+
if (typeof text !== "string") throw new ServiceError("INVALID_INPUT", "chat.queue.append requires text");
|
|
1616
|
+
if (typeof source.queueAppend !== "function") throw new ServiceError("NOT_HANDLED", "queueAppend is not supported by this data source");
|
|
1617
|
+
if (typeof source.claimSessionLease === "function") {
|
|
1618
|
+
const claim = await source.claimSessionLease(sessionId);
|
|
1619
|
+
if (!claim.ok) return {
|
|
1620
|
+
accepted: false,
|
|
1621
|
+
sessionId,
|
|
1622
|
+
reason: "busy",
|
|
1623
|
+
message: claim.message,
|
|
1624
|
+
...claim.contended === true ? { contended: true } : {}
|
|
1625
|
+
};
|
|
1626
|
+
}
|
|
1627
|
+
return await source.queueAppend(sessionId, text);
|
|
1628
|
+
}),
|
|
1629
|
+
"chat.queue.list": route("chat.queue.list", true, bySession, async (payload) => {
|
|
1630
|
+
const sessionId = requireSessionId(payload, "chat.queue.list");
|
|
1631
|
+
const source = sourceForSession(deps, sessionId);
|
|
1632
|
+
if (typeof source.queueList !== "function") throw new ServiceError("NOT_HANDLED", "queueList is not supported by this data source");
|
|
1633
|
+
return { entries: await source.queueList(sessionId) };
|
|
1634
|
+
}),
|
|
1635
|
+
"chat.queue.remove": route("chat.queue.remove", false, bySession, async (payload) => {
|
|
1636
|
+
const sessionId = requireSessionId(payload, "chat.queue.remove");
|
|
1637
|
+
const source = sourceForSession(deps, sessionId);
|
|
1638
|
+
const input = payload;
|
|
1639
|
+
if (typeof input?.inputId !== "string" || input.inputId === "") throw new ServiceError("INVALID_INPUT", "chat.queue.remove requires inputId");
|
|
1640
|
+
if (typeof source.queueRemove !== "function") throw new ServiceError("NOT_HANDLED", "queueRemove is not supported by this data source");
|
|
1641
|
+
return await source.queueRemove(sessionId, input.inputId, { ...expectedQueueRevisionOf(payload) });
|
|
1642
|
+
}),
|
|
1643
|
+
"chat.queue.clear": route("chat.queue.clear", false, bySession, async (payload) => {
|
|
1644
|
+
const sessionId = requireSessionId(payload, "chat.queue.clear");
|
|
1645
|
+
const source = sourceForSession(deps, sessionId);
|
|
1646
|
+
if (typeof source.queueClear !== "function") throw new ServiceError("NOT_HANDLED", "queueClear is not supported by this data source");
|
|
1647
|
+
return await source.queueClear(sessionId, { ...expectedQueueRevisionOf(payload) });
|
|
1648
|
+
}),
|
|
1649
|
+
"chat.queue.promote": route("chat.queue.promote", false, bySession, async (payload) => {
|
|
1650
|
+
const sessionId = requireSessionId(payload, "chat.queue.promote");
|
|
1651
|
+
const source = sourceForSession(deps, sessionId);
|
|
1652
|
+
const input = payload;
|
|
1653
|
+
if (typeof input?.inputId !== "string" || input.inputId === "") throw new ServiceError("INVALID_INPUT", "chat.queue.promote requires inputId");
|
|
1654
|
+
const text = input.text;
|
|
1655
|
+
if (text !== void 0) {
|
|
1656
|
+
if (typeof text !== "string" || text.trim() === "") throw new ServiceError("INVALID_INPUT", "chat.queue.promote requires text to be a non-blank string when provided");
|
|
1657
|
+
}
|
|
1658
|
+
if (typeof source.queuePromote !== "function") throw new ServiceError("NOT_HANDLED", "queuePromote is not supported by this data source");
|
|
1659
|
+
return await source.queuePromote(sessionId, input.inputId, text, { ...expectedQueueRevisionOf(payload) });
|
|
1660
|
+
}),
|
|
1661
|
+
"chat.queue.update": route("chat.queue.update", false, bySession, async (payload) => {
|
|
1662
|
+
const sessionId = requireSessionId(payload, "chat.queue.update");
|
|
1663
|
+
const source = sourceForSession(deps, sessionId);
|
|
1664
|
+
const input = payload;
|
|
1665
|
+
if (typeof input?.inputId !== "string" || input.inputId === "") throw new ServiceError("INVALID_INPUT", "chat.queue.update requires inputId");
|
|
1666
|
+
if (typeof input.text !== "string" || input.text.trim() === "") throw new ServiceError("INVALID_INPUT", "chat.queue.update requires non-blank text");
|
|
1667
|
+
if (typeof source.queueUpdate !== "function") throw new ServiceError("NOT_HANDLED", "queueUpdate is not supported by this data source");
|
|
1668
|
+
return await source.queueUpdate(sessionId, input.inputId, input.text);
|
|
1669
|
+
}),
|
|
1670
|
+
"chat.queue.move": route("chat.queue.move", false, bySession, async (payload) => {
|
|
1671
|
+
const sessionId = requireSessionId(payload, "chat.queue.move");
|
|
1672
|
+
const source = sourceForSession(deps, sessionId);
|
|
1673
|
+
const input = payload;
|
|
1674
|
+
if (typeof input?.inputId !== "string" || input.inputId === "") throw new ServiceError("INVALID_INPUT", "chat.queue.move requires inputId");
|
|
1675
|
+
const delta = input.delta;
|
|
1676
|
+
if (delta !== -1 && delta !== 1) throw new ServiceError("INVALID_INPUT", "chat.queue.move requires delta of -1 or 1");
|
|
1677
|
+
if (typeof source.queueMove !== "function") throw new ServiceError("NOT_HANDLED", "queueMove is not supported by this data source");
|
|
1678
|
+
return await source.queueMove(sessionId, input.inputId, delta);
|
|
1679
|
+
}),
|
|
1680
|
+
"chat.discardDanglingInput": route("chat.discardDanglingInput", false, bySession, async (payload) => {
|
|
1681
|
+
const sessionId = requireSessionId(payload, "chat.discardDanglingInput");
|
|
1682
|
+
const source = sourceForSession(deps, sessionId);
|
|
1683
|
+
const input = payload;
|
|
1684
|
+
if (typeof input?.inputId !== "string" || input.inputId === "") throw new ServiceError("INVALID_INPUT", "chat.discardDanglingInput requires inputId");
|
|
1685
|
+
if (input?.target !== "next-turn" && input?.target !== "next-step") throw new ServiceError("INVALID_INPUT", "chat.discardDanglingInput requires target");
|
|
1686
|
+
if (!source.discardDanglingInput) throw new ServiceError("NOT_HANDLED", "discardDanglingInput is not supported by this data source");
|
|
1687
|
+
return await source.discardDanglingInput(sessionId, input.inputId, input.target);
|
|
1688
|
+
}),
|
|
1689
|
+
"chat.deferAwaitingResults": route("chat.deferAwaitingResults", false, bySession, async (payload) => {
|
|
1690
|
+
const sessionId = requireSessionId(payload, "chat.deferAwaitingResults");
|
|
1691
|
+
const source = sourceForSession(deps, sessionId);
|
|
1692
|
+
if (!source.deferAwaitingResults) throw new ServiceError("NOT_HANDLED", "deferAwaitingResults is not supported by this data source");
|
|
1693
|
+
return await source.deferAwaitingResults(sessionId);
|
|
1694
|
+
}),
|
|
1695
|
+
"chat.resumeQueue": route("chat.resumeQueue", false, bySession, async (payload) => {
|
|
1696
|
+
const sessionId = requireSessionId(payload, "chat.resumeQueue");
|
|
1697
|
+
const source = sourceForSession(deps, sessionId);
|
|
1698
|
+
if (!source.resumeQueue) throw new ServiceError("NOT_HANDLED", "resumeQueue is not supported by this data source");
|
|
1699
|
+
return await source.resumeQueue(sessionId);
|
|
1700
|
+
})
|
|
1701
|
+
});
|
|
1702
|
+
}
|
|
1703
|
+
|
|
1704
|
+
//#endregion
|
|
1705
|
+
//#region src/routes/extension-routes.ts
|
|
1706
|
+
const EXTENSION_GRANT_TTL_MS = 300 * 1e3;
|
|
1707
|
+
const EXTENSION_APPROVAL_WAIT_MS = 90 * 1e3;
|
|
1708
|
+
function extensionRoutes(deps) {
|
|
1709
|
+
const extensionGrants = /* @__PURE__ */ new Map();
|
|
1710
|
+
return defineRoutes("service:extension", {
|
|
1711
|
+
"devApproval.pending": route("devApproval.pending", false, byWorkspace, async (payload) => {
|
|
1712
|
+
const workspaceKey = requireName(payload, "workspaceKey", "devApproval.pending");
|
|
1713
|
+
const channel = deps.approvalChannelOf?.(workspaceKey);
|
|
1714
|
+
if (channel?.pending === void 0) throw new ServiceError("NOT_HANDLED", "devApproval.pending needs a channel with pending()");
|
|
1715
|
+
return { pending: channel.pending() };
|
|
1716
|
+
}),
|
|
1717
|
+
"devApproval.respond": route("devApproval.respond", false, byWorkspace, async (payload) => {
|
|
1718
|
+
const workspaceKey = requireName(payload, "workspaceKey", "devApproval.respond");
|
|
1719
|
+
const nonce = requireName(payload, "nonce", "devApproval.respond");
|
|
1720
|
+
const allow = payload.allow;
|
|
1721
|
+
if (typeof allow !== "boolean") throw new ServiceError("INVALID_INPUT", "devApproval.respond requires { allow: boolean }");
|
|
1722
|
+
const channel = deps.approvalChannelOf?.(workspaceKey);
|
|
1723
|
+
if (channel?.resolve === void 0) throw new ServiceError("NOT_HANDLED", "devApproval.respond needs a channel with resolve()");
|
|
1724
|
+
const pending = channel.pending?.().find((entry) => entry.nonce === nonce);
|
|
1725
|
+
if (channel.extensionApprovalNonce?.(nonce) === true || pending?.origin === "extension") throw new ServiceError("FORBIDDEN", "extension-rpc challenges require the private approval responder");
|
|
1726
|
+
return { applied: channel.resolve(nonce, allow ? "allow" : "deny") };
|
|
1727
|
+
}),
|
|
1728
|
+
"extension.write.request": route("extension.write.request", false, byWorkspace, async (payload) => {
|
|
1729
|
+
const request = payload;
|
|
1730
|
+
if (typeof request.workspaceKey !== "string" || request.workspaceKey === "" || typeof request.category !== "string" || typeof request.id !== "string" || request.id === "" || request.action !== "enable" && request.action !== "disable" && request.action !== "remove") throw new ServiceError("INVALID_INPUT", "extension.write.request needs workspaceKey, category, id, action");
|
|
1731
|
+
if (request.action === "remove" && request.category !== "plugin" && request.category !== "install") throw new ServiceError("INVALID_INPUT", "remove is only supported for category \"plugin\" or \"install\"");
|
|
1732
|
+
const channel = deps.approvalChannelOf?.(request.workspaceKey);
|
|
1733
|
+
if (channel === void 0) throw new ServiceError("NOT_HANDLED", "no approval channel for this workspace");
|
|
1734
|
+
const requestedTimeout = payload.timeoutMs;
|
|
1735
|
+
const timeoutMs = typeof requestedTimeout === "number" && requestedTimeout > 0 ? Math.min(requestedTimeout, EXTENSION_GRANT_TTL_MS) : EXTENSION_APPROVAL_WAIT_MS;
|
|
1736
|
+
if (await channel.request({
|
|
1737
|
+
workspaceKey: request.workspaceKey,
|
|
1738
|
+
action: request.action,
|
|
1739
|
+
subject: `${request.category}:${request.id}`,
|
|
1740
|
+
timeoutMs
|
|
1741
|
+
}) !== "allow") throw new ServiceError("FORBIDDEN", "extension write needs a human confirmation on the worker; none was given in time");
|
|
1742
|
+
const grantId = randomUUID();
|
|
1743
|
+
const expiresAt = Date.now() + EXTENSION_GRANT_TTL_MS;
|
|
1744
|
+
extensionGrants.set(grantId, {
|
|
1745
|
+
workspaceKey: request.workspaceKey,
|
|
1746
|
+
category: request.category,
|
|
1747
|
+
id: request.id,
|
|
1748
|
+
action: request.action,
|
|
1749
|
+
expiresAt
|
|
1750
|
+
});
|
|
1751
|
+
return {
|
|
1752
|
+
grantId,
|
|
1753
|
+
expiresAt
|
|
1754
|
+
};
|
|
1755
|
+
}),
|
|
1756
|
+
"extension.write.apply": route("extension.write.apply", false, byWorkspace, async (payload) => {
|
|
1757
|
+
const request = payload;
|
|
1758
|
+
if (typeof request.workspaceKey !== "string" || typeof request.grantId !== "string") throw new ServiceError("INVALID_INPUT", "extension.write.apply needs workspaceKey and grantId");
|
|
1759
|
+
const grant = extensionGrants.get(request.grantId);
|
|
1760
|
+
if (grant === void 0) throw new ServiceError("FORBIDDEN", "extension write grant is unknown or already used");
|
|
1761
|
+
extensionGrants.delete(request.grantId);
|
|
1762
|
+
if (grant.expiresAt <= Date.now()) throw new ServiceError("FORBIDDEN", "extension write grant expired");
|
|
1763
|
+
if (grant.workspaceKey !== request.workspaceKey) throw new ServiceError("FORBIDDEN", "extension write grant does not match this workspace");
|
|
1764
|
+
if (grant.action === "remove") {
|
|
1765
|
+
if (grant.category === "install") await requirePort(deps.installPort, "extension.write.apply").uninstall(grant.id);
|
|
1766
|
+
else if (deps.dataSource.pluginRemove === void 0) throw new ServiceError("NOT_HANDLED", "pluginRemove is not supported by this data source");
|
|
1767
|
+
else await deps.dataSource.pluginRemove(grant.id);
|
|
1768
|
+
return { ok: true };
|
|
1769
|
+
}
|
|
1770
|
+
const enabled = grant.action === "enable";
|
|
1771
|
+
if (grant.category === "skill") await requirePort(deps.skillPort, "extension.write.apply").setEnabled(grant.id, enabled);
|
|
1772
|
+
else if (grant.category === "mcp") await requirePort(deps.mcpPort, "extension.write.apply").setEnabled(grant.id, enabled);
|
|
1773
|
+
else throw new ServiceError("NOT_HANDLED", `extension category "${grant.category}" cannot be toggled`);
|
|
1774
|
+
return { ok: true };
|
|
1775
|
+
}),
|
|
1776
|
+
"extension.permissions": route("extension.permissions", true, globalTarget, async () => await requirePort(deps.extensionPermissionsPort, "extension.permissions").list())
|
|
1777
|
+
});
|
|
1778
|
+
}
|
|
1779
|
+
|
|
1780
|
+
//#endregion
|
|
1781
|
+
//#region src/routes/plugin-routes.ts
|
|
1782
|
+
function pluginRoutes(deps) {
|
|
1783
|
+
return defineRoutes("service:plugin", {
|
|
1784
|
+
"plugin.list": route("plugin.list", true, globalTarget, async () => {
|
|
1785
|
+
if (!deps.dataSource.plugins) throw new ServiceError("NOT_HANDLED", "plugins is not supported by this data source");
|
|
1786
|
+
return deps.dataSource.plugins();
|
|
1787
|
+
}),
|
|
1788
|
+
"plugin.add": route("plugin.add", false, byWorkspace, async (payload) => {
|
|
1789
|
+
const input = payload;
|
|
1790
|
+
const path = input?.path;
|
|
1791
|
+
if (!path) throw new ServiceError("INVALID_INPUT", "plugin.add requires path");
|
|
1792
|
+
if (!deps.dataSource.pluginAdd) throw new ServiceError("NOT_HANDLED", "pluginAdd is not supported by this data source");
|
|
1793
|
+
return deps.dataSource.pluginAdd({
|
|
1794
|
+
type: "file",
|
|
1795
|
+
path
|
|
1796
|
+
}, input?.config);
|
|
1797
|
+
}),
|
|
1798
|
+
"plugin.remove": route("plugin.remove", false, byWorkspace, async (payload) => {
|
|
1799
|
+
const id = payload?.id;
|
|
1800
|
+
if (!id) throw new ServiceError("INVALID_INPUT", "plugin.remove requires id");
|
|
1801
|
+
if (!deps.dataSource.pluginRemove) throw new ServiceError("NOT_HANDLED", "pluginRemove is not supported by this data source");
|
|
1802
|
+
return deps.dataSource.pluginRemove(id);
|
|
1803
|
+
}),
|
|
1804
|
+
"plugin.replace": route("plugin.replace", false, byWorkspace, async (payload) => {
|
|
1805
|
+
const input = payload;
|
|
1806
|
+
const id = input?.id;
|
|
1807
|
+
const path = input?.path;
|
|
1808
|
+
if (!id || !path) throw new ServiceError("INVALID_INPUT", "plugin.replace requires id and path");
|
|
1809
|
+
if (!deps.dataSource.pluginReplace) throw new ServiceError("NOT_HANDLED", "pluginReplace is not supported by this data source");
|
|
1810
|
+
return deps.dataSource.pluginReplace(id, {
|
|
1811
|
+
type: "file",
|
|
1812
|
+
path
|
|
1813
|
+
});
|
|
1814
|
+
}),
|
|
1815
|
+
"model.list": route("model.list", true, globalTarget, async () => {
|
|
1816
|
+
if (!deps.dataSource.listModels) throw new ServiceError("NOT_HANDLED", "listModels is not supported by this data source");
|
|
1817
|
+
return deps.dataSource.listModels();
|
|
1818
|
+
}),
|
|
1819
|
+
"model.select": route("model.select", false, globalTarget, async (payload) => {
|
|
1820
|
+
const modelId = requireModelId(payload, "model.select");
|
|
1821
|
+
if (!deps.dataSource.selectModel) throw new ServiceError("NOT_HANDLED", "selectModel is not supported by this data source");
|
|
1822
|
+
return await deps.dataSource.selectModel(modelId);
|
|
1823
|
+
}),
|
|
1824
|
+
"schedules.list": route("schedules.list", true, bySession, async (input) => {
|
|
1825
|
+
const port = deps.schedulesPort;
|
|
1826
|
+
if (port === void 0) throw new ServiceError("NOT_HANDLED", "schedules.* requires a worker schedules port");
|
|
1827
|
+
const sessionId = input?.sessionId;
|
|
1828
|
+
if (typeof sessionId !== "string" || sessionId === "") throw new ServiceError("INVALID_INPUT", "schedules.list requires { sessionId }");
|
|
1829
|
+
return { entries: await port.list(sessionId) };
|
|
1830
|
+
}),
|
|
1831
|
+
"schedules.delete": route("schedules.delete", false, bySession, async (input) => {
|
|
1832
|
+
const port = deps.schedulesPort;
|
|
1833
|
+
if (port === void 0) throw new ServiceError("NOT_HANDLED", "schedules.* requires a worker schedules port");
|
|
1834
|
+
const typed = input;
|
|
1835
|
+
if (typeof typed?.sessionId !== "string" || typed.sessionId === "") throw new ServiceError("INVALID_INPUT", "schedules.delete requires { sessionId }");
|
|
1836
|
+
if (typeof typed.id !== "string" || typed.id === "") throw new ServiceError("INVALID_INPUT", "schedules.delete requires { id }");
|
|
1837
|
+
return { deleted: await port.delete(typed.sessionId, typed.id) };
|
|
1838
|
+
}),
|
|
1839
|
+
"schedules.runPending": route("schedules.runPending", false, bySession, async (input) => {
|
|
1840
|
+
const port = deps.schedulesPort;
|
|
1841
|
+
if (port === void 0) throw new ServiceError("NOT_HANDLED", "schedules.* requires a worker schedules port");
|
|
1842
|
+
const typed = input;
|
|
1843
|
+
if (typeof typed?.sessionId !== "string" || typed.sessionId === "") throw new ServiceError("INVALID_INPUT", "schedules.runPending requires { sessionId }");
|
|
1844
|
+
if (typeof typed.id !== "string" || typed.id === "") throw new ServiceError("INVALID_INPUT", "schedules.runPending requires { id }");
|
|
1845
|
+
return { ran: await port.runPending?.(typed.sessionId, typed.id) ?? false };
|
|
1846
|
+
}),
|
|
1847
|
+
"schedules.dismissPending": route("schedules.dismissPending", false, bySession, async (input) => {
|
|
1848
|
+
const port = deps.schedulesPort;
|
|
1849
|
+
if (port === void 0) throw new ServiceError("NOT_HANDLED", "schedules.* requires a worker schedules port");
|
|
1850
|
+
const typed = input;
|
|
1851
|
+
if (typeof typed?.sessionId !== "string" || typed.sessionId === "") throw new ServiceError("INVALID_INPUT", "schedules.dismissPending requires { sessionId }");
|
|
1852
|
+
if (typeof typed.id !== "string" || typed.id === "") throw new ServiceError("INVALID_INPUT", "schedules.dismissPending requires { id }");
|
|
1853
|
+
return { dismissed: await port.dismissPending?.(typed.sessionId, typed.id) ?? false };
|
|
1854
|
+
}),
|
|
1855
|
+
"schedules.health": route("schedules.health", false, bySession, async (input) => {
|
|
1856
|
+
const port = deps.schedulesPort;
|
|
1857
|
+
if (port === void 0) throw new ServiceError("NOT_HANDLED", "schedules.* requires a worker schedules port");
|
|
1858
|
+
const sessionId = input?.sessionId;
|
|
1859
|
+
if (typeof sessionId !== "string" || sessionId === "") throw new ServiceError("INVALID_INPUT", "schedules.health requires { sessionId }");
|
|
1860
|
+
return await port.health?.(sessionId) ?? { unrecoverablePreTrim: false };
|
|
1861
|
+
}),
|
|
1862
|
+
"install.activation": route("install.activation", true, globalTarget, async (input) => {
|
|
1863
|
+
const ids = input?.ids;
|
|
1864
|
+
if (ids !== void 0 && (!Array.isArray(ids) || ids.some((id) => typeof id !== "string"))) throw new ServiceError("INVALID_INPUT", "install.activation ids must be string[]");
|
|
1865
|
+
return { reports: await requirePort(deps.activationPort, "install.activation").activation(ids) };
|
|
1866
|
+
}),
|
|
1867
|
+
"fold.viewState": route("fold.viewState", true, bySession, async (input) => {
|
|
1868
|
+
const sessionId = requireSessionId$1(input, "fold.viewState");
|
|
1869
|
+
const state = await requirePort(deps.foldViewStatePort, "fold.viewState").load(sessionId);
|
|
1870
|
+
return state === void 0 ? {} : { state };
|
|
1871
|
+
}),
|
|
1872
|
+
"fold.viewState.save": route("fold.viewState.save", false, bySession, async (input) => {
|
|
1873
|
+
const sessionId = requireSessionId$1(input, "fold.viewState.save");
|
|
1874
|
+
const typed = input;
|
|
1875
|
+
for (const field of ["folded", "expanded"]) {
|
|
1876
|
+
const value = typed[field];
|
|
1877
|
+
if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string")) throw new ServiceError("INVALID_INPUT", `fold.viewState.save requires { ${field}: string[] }`);
|
|
1878
|
+
}
|
|
1879
|
+
await requirePort(deps.foldViewStatePort, "fold.viewState.save").save(sessionId, {
|
|
1880
|
+
folded: typed.folded,
|
|
1881
|
+
expanded: typed.expanded
|
|
1882
|
+
});
|
|
1883
|
+
return { saved: true };
|
|
1884
|
+
}),
|
|
1885
|
+
"model.availability": route("model.availability", true, globalTarget, async () => await requirePort(deps.modelAvailabilityPort, "model.availability").snapshot()),
|
|
1886
|
+
"input.history": route("input.history", true, bySession, async (input) => {
|
|
1887
|
+
const sessionId = requireSessionId$1(input, "input.history");
|
|
1888
|
+
return { entries: await requirePort(deps.inputHistoryPort, "input.history").load(sessionId) };
|
|
1889
|
+
}),
|
|
1890
|
+
"input.history.save": route("input.history.save", false, bySession, async (input) => {
|
|
1891
|
+
const sessionId = requireSessionId$1(input, "input.history.save");
|
|
1892
|
+
const typed = input;
|
|
1893
|
+
const entries = Array.isArray(typed.entries) ? typed.entries : void 0;
|
|
1894
|
+
if (entries === void 0 || entries.some((entry) => typeof entry !== "string")) throw new ServiceError("INVALID_INPUT", "input.history.save requires { entries: string[] }");
|
|
1895
|
+
await requirePort(deps.inputHistoryPort, "input.history.save").save(sessionId, entries);
|
|
1896
|
+
return { saved: true };
|
|
1897
|
+
}),
|
|
1898
|
+
"drafts.list": route("drafts.list", true, byWorkspaceOrGlobal, async (input) => {
|
|
1899
|
+
const workspaceKey = requireName(input, "workspaceKey", "drafts.list");
|
|
1900
|
+
return { drafts: await requirePort(deps.draftsPort, "drafts.list").list(workspaceKey) };
|
|
1901
|
+
}),
|
|
1902
|
+
"drafts.save": route("drafts.save", false, byWorkspaceOrGlobal, async (input) => {
|
|
1903
|
+
const workspaceKey = requireName(input, "workspaceKey", "drafts.save");
|
|
1904
|
+
const text = input.text;
|
|
1905
|
+
if (typeof text !== "string") throw new ServiceError("INVALID_INPUT", "drafts.save requires { text }");
|
|
1906
|
+
return { draft: await requirePort(deps.draftsPort, "drafts.save").save(workspaceKey, text) };
|
|
1907
|
+
}),
|
|
1908
|
+
"drafts.remove": route("drafts.remove", false, byWorkspaceOrGlobal, async (input) => {
|
|
1909
|
+
const workspaceKey = requireName(input, "workspaceKey", "drafts.remove");
|
|
1910
|
+
const ids = input.ids;
|
|
1911
|
+
if (!Array.isArray(ids) || ids.some((id) => typeof id !== "string")) throw new ServiceError("INVALID_INPUT", "drafts.remove requires { ids: string[] }");
|
|
1912
|
+
if (ids.length > 0) await requirePort(deps.draftsPort, "drafts.remove").remove(workspaceKey, ids);
|
|
1913
|
+
return { removed: true };
|
|
1914
|
+
}),
|
|
1915
|
+
"provider.list": route("provider.list", true, globalTarget, async () => ({ providers: await requirePort(deps.providerPort, "provider.list").list() })),
|
|
1916
|
+
"install.list": route("install.list", true, globalTarget, async () => ({ items: await requirePort(deps.installPort, "install.list").list() })),
|
|
1917
|
+
"install.uninstall": route("install.uninstall", false, globalTarget, async (input) => {
|
|
1918
|
+
const id = input?.id;
|
|
1919
|
+
if (typeof id !== "string" || id === "") throw new ServiceError("INVALID_INPUT", "install.uninstall requires { id }");
|
|
1920
|
+
return await requirePort(deps.installPort, "install.uninstall").uninstall(id);
|
|
1921
|
+
}),
|
|
1922
|
+
"model.preferences": route("model.preferences", true, globalTarget, async () => await requirePort(deps.modelPreferencesPort, "model.preferences").snapshot()),
|
|
1923
|
+
"model.setEnabled": route("model.setEnabled", false, globalTarget, async (input) => {
|
|
1924
|
+
const typed = input;
|
|
1925
|
+
if (typeof typed?.modelId !== "string" || typed.modelId === "" || typeof typed.isEnabled !== "boolean") throw new ServiceError("INVALID_INPUT", "model.setEnabled requires { modelId, isEnabled }");
|
|
1926
|
+
return {
|
|
1927
|
+
ok: true,
|
|
1928
|
+
snapshot: await requirePort(deps.modelPreferencesPort, "model.setEnabled").setEnabled(typed.modelId, typed.isEnabled)
|
|
1929
|
+
};
|
|
1930
|
+
}),
|
|
1931
|
+
"model.setCapabilityOverride": route("model.setCapabilityOverride", false, globalTarget, async (input) => {
|
|
1932
|
+
const typed = input;
|
|
1933
|
+
const patch = typed?.patch;
|
|
1934
|
+
const validPatch = typeof patch === "object" && patch !== null && !Array.isArray(patch) && Object.keys(patch).length > 0 && Object.keys(patch).every((key) => key === "contextWindow" || key === "maxOutputTokens") && Object.values(patch).every((value) => typeof value === "number" && Number.isInteger(value) && value > 0);
|
|
1935
|
+
if (typeof typed?.catalogId !== "string" || typed.catalogId === "" || !validPatch) throw new ServiceError("INVALID_INPUT", "model.setCapabilityOverride requires { catalogId, patch } with positive integer capabilities");
|
|
1936
|
+
return {
|
|
1937
|
+
ok: true,
|
|
1938
|
+
snapshot: await requirePort(deps.modelPreferencesPort, "model.setCapabilityOverride").setCapabilityOverride(typed.catalogId, patch)
|
|
1939
|
+
};
|
|
1940
|
+
}),
|
|
1941
|
+
"model.clearCapabilityOverride": route("model.clearCapabilityOverride", false, globalTarget, async (input) => {
|
|
1942
|
+
const typed = input;
|
|
1943
|
+
if (typeof typed?.catalogId !== "string" || typed.catalogId === "") throw new ServiceError("INVALID_INPUT", "model.clearCapabilityOverride requires { catalogId }");
|
|
1944
|
+
return {
|
|
1945
|
+
ok: true,
|
|
1946
|
+
snapshot: await requirePort(deps.modelPreferencesPort, "model.clearCapabilityOverride").clearCapabilityOverride(typed.catalogId)
|
|
1947
|
+
};
|
|
1948
|
+
}),
|
|
1949
|
+
"model.refresh": route("model.refresh", false, globalTarget, async (input) => {
|
|
1950
|
+
const typed = input;
|
|
1951
|
+
if (typed?.providerId !== void 0 && typeof typed.providerId !== "string") throw new ServiceError("INVALID_INPUT", "model.refresh requires optional { providerId }");
|
|
1952
|
+
return await requirePort(deps.modelOperationsPort, "model.refresh").refresh(typed?.providerId);
|
|
1953
|
+
}),
|
|
1954
|
+
"model.unfreeze": route("model.unfreeze", false, globalTarget, async (input) => {
|
|
1955
|
+
const typed = input;
|
|
1956
|
+
if (typeof typed?.targetId !== "string" || typed.targetId === "") throw new ServiceError("INVALID_INPUT", "model.unfreeze requires { targetId }");
|
|
1957
|
+
return requirePort(deps.modelOperationsPort, "model.unfreeze").unfreeze(typed.targetId);
|
|
1958
|
+
}),
|
|
1959
|
+
"skill.snapshot": route("skill.snapshot", true, globalTarget, async () => await requirePort(deps.skillPort, "skill.snapshot").snapshot()),
|
|
1960
|
+
"skill.setEnabled": route("skill.setEnabled", false, globalTarget, async (input) => {
|
|
1961
|
+
const typed = await requireToggle(input, "skill.setEnabled");
|
|
1962
|
+
return await requirePort(deps.skillPort, "skill.setEnabled").setEnabled(typed.name, typed.enabled);
|
|
1963
|
+
}),
|
|
1964
|
+
"skill.reload": route("skill.reload", false, globalTarget, async () => await requirePort(deps.skillPort, "skill.reload").reload()),
|
|
1965
|
+
"mcp.snapshot": route("mcp.snapshot", true, globalTarget, async () => await requirePort(deps.mcpPort, "mcp.snapshot").snapshot()),
|
|
1966
|
+
"mcp.setEnabled": route("mcp.setEnabled", false, globalTarget, async (input) => {
|
|
1967
|
+
const typed = await requireToggle(input, "mcp.setEnabled");
|
|
1968
|
+
return await requirePort(deps.mcpPort, "mcp.setEnabled").setEnabled(typed.name, typed.enabled);
|
|
1969
|
+
}),
|
|
1970
|
+
"mcp.reload": route("mcp.reload", false, globalTarget, async () => await requirePort(deps.mcpPort, "mcp.reload").reload()),
|
|
1971
|
+
"mcp.reconnect": route("mcp.reconnect", false, globalTarget, async (input) => await requirePort(deps.mcpPort, "mcp.reconnect").reconnect(requireName(input, "name", "mcp.reconnect"))),
|
|
1972
|
+
"mcp.login": route("mcp.login", false, globalTarget, async (input) => await requirePort(deps.mcpPort, "mcp.login").login(requireName(input, "name", "mcp.login"))),
|
|
1973
|
+
"mcp.logout": route("mcp.logout", false, globalTarget, async (input) => await requirePort(deps.mcpPort, "mcp.logout").logout(requireName(input, "name", "mcp.logout")))
|
|
1974
|
+
});
|
|
1975
|
+
}
|
|
1976
|
+
|
|
1977
|
+
//#endregion
|
|
1978
|
+
//#region src/routes/session-routes.ts
|
|
1979
|
+
function parseSessionListQuery(payload) {
|
|
1980
|
+
if (payload === void 0 || payload === null) return;
|
|
1981
|
+
if (typeof payload !== "object" || Array.isArray(payload)) throw new ServiceError("INVALID_INPUT", "session.list options must be an object");
|
|
1982
|
+
const raw = payload;
|
|
1983
|
+
const query = {};
|
|
1984
|
+
if (raw.workspaceKey !== void 0) {
|
|
1985
|
+
if (typeof raw.workspaceKey !== "string" || raw.workspaceKey === "") throw new ServiceError("INVALID_INPUT", "session.list workspaceKey must be a non-empty string");
|
|
1986
|
+
query.workspaceKey = raw.workspaceKey;
|
|
1987
|
+
}
|
|
1988
|
+
if (raw.archived !== void 0) {
|
|
1989
|
+
if (raw.archived !== "exclude" && raw.archived !== "only" && raw.archived !== "include") throw new ServiceError("INVALID_INPUT", "session.list archived must be \"exclude\", \"only\" or \"include\"");
|
|
1990
|
+
query.archived = raw.archived;
|
|
1991
|
+
}
|
|
1992
|
+
if (raw.includeUnstarted !== void 0) {
|
|
1993
|
+
if (typeof raw.includeUnstarted !== "boolean") throw new ServiceError("INVALID_INPUT", "session.list includeUnstarted must be a boolean");
|
|
1994
|
+
query.includeUnstarted = raw.includeUnstarted;
|
|
1995
|
+
}
|
|
1996
|
+
if (raw.search !== void 0) {
|
|
1997
|
+
if (typeof raw.search !== "string") throw new ServiceError("INVALID_INPUT", "session.list search must be a string");
|
|
1998
|
+
query.search = raw.search;
|
|
1999
|
+
}
|
|
2000
|
+
if (raw.childrenOf !== void 0) {
|
|
2001
|
+
if (typeof raw.childrenOf !== "string" || raw.childrenOf === "") throw new ServiceError("INVALID_INPUT", "session.list childrenOf must be a non-empty string");
|
|
2002
|
+
query.childrenOf = raw.childrenOf;
|
|
2003
|
+
}
|
|
2004
|
+
if (raw.page !== void 0) {
|
|
2005
|
+
if (typeof raw.page !== "number" || !Number.isInteger(raw.page) || raw.page < 0) throw new ServiceError("INVALID_INPUT", "session.list page must be a non-negative integer");
|
|
2006
|
+
query.page = raw.page;
|
|
2007
|
+
}
|
|
2008
|
+
if (raw.pageSize !== void 0) {
|
|
2009
|
+
if (typeof raw.pageSize !== "number" || !Number.isInteger(raw.pageSize) || raw.pageSize < 1) throw new ServiceError("INVALID_INPUT", "session.list pageSize must be a positive integer");
|
|
2010
|
+
query.pageSize = raw.pageSize;
|
|
2011
|
+
}
|
|
2012
|
+
if (typeof raw === "object" && raw !== null) {
|
|
2013
|
+
const r = raw;
|
|
2014
|
+
if (r.visibility !== void 0) {
|
|
2015
|
+
if (r.visibility !== "interactive" && r.visibility !== "internal" && r.visibility !== "all") throw new ServiceError("INVALID_INPUT", "session.list visibility must be \"interactive\", \"internal\" or \"all\"");
|
|
2016
|
+
query.visibility = r.visibility;
|
|
2017
|
+
}
|
|
2018
|
+
if (r.parentSessionId !== void 0) {
|
|
2019
|
+
if (typeof r.parentSessionId !== "string" || r.parentSessionId === "") throw new ServiceError("INVALID_INPUT", "session.list parentSessionId must be a non-empty string");
|
|
2020
|
+
query.parentSessionId = r.parentSessionId;
|
|
2021
|
+
}
|
|
2022
|
+
if (query.visibility !== void 0 && query.visibility !== "interactive" && query.parentSessionId === void 0) throw new ServiceError("INVALID_INPUT", "session.list visibility \"internal\"/\"all\" requires parentSessionId");
|
|
2023
|
+
}
|
|
2024
|
+
return query;
|
|
2025
|
+
}
|
|
2026
|
+
function filterSessionEntries(entries, query) {
|
|
2027
|
+
return entries.filter((entry) => {
|
|
2028
|
+
if (query?.workspaceKey !== void 0 && entry.workspaceKey !== query.workspaceKey) return false;
|
|
2029
|
+
const visibility = query?.visibility ?? "interactive";
|
|
2030
|
+
if (effectiveSessionVisibility({
|
|
2031
|
+
...entry.visibility !== void 0 ? { visibility: entry.visibility } : {},
|
|
2032
|
+
...entry.parentSessionId !== void 0 ? { parentSessionId: entry.parentSessionId } : {},
|
|
2033
|
+
...entry.forked === true ? { forked: true } : {}
|
|
2034
|
+
}) === "internal") {
|
|
2035
|
+
if (visibility === "interactive") return false;
|
|
2036
|
+
if ((entry.lineage?.parentSessionId ?? entry.parentSessionId) !== query?.parentSessionId) return false;
|
|
2037
|
+
if (visibility === "internal") return true;
|
|
2038
|
+
} else if (visibility === "internal") return false;
|
|
2039
|
+
if (query?.childrenOf !== void 0 && (entry.lineage?.parentSessionId ?? entry.parentSessionId) !== query.childrenOf) return false;
|
|
2040
|
+
if (query?.includeUnstarted !== true && entry.conversationStarted === false) return false;
|
|
2041
|
+
if (query?.search !== void 0 && !matchesSessionSearch(query.search, entry.title, entry.id)) return false;
|
|
2042
|
+
if (query?.archived === "only") return entry.archived === true;
|
|
2043
|
+
if (query?.archived !== "include") return entry.archived !== true;
|
|
2044
|
+
return true;
|
|
2045
|
+
});
|
|
2046
|
+
}
|
|
2047
|
+
const DIAGNOSTIC_SOURCES = new Set([
|
|
2048
|
+
"hook",
|
|
2049
|
+
"persistence",
|
|
2050
|
+
"prompt-context",
|
|
2051
|
+
"provider",
|
|
2052
|
+
"guard",
|
|
2053
|
+
"install"
|
|
2054
|
+
]);
|
|
2055
|
+
const DIAGNOSTIC_SEVERITIES = new Set([
|
|
2056
|
+
"info",
|
|
2057
|
+
"warning",
|
|
2058
|
+
"error"
|
|
2059
|
+
]);
|
|
2060
|
+
function parseReconcileLostJobPayload(payload) {
|
|
2061
|
+
const sessionId = requireSessionId$1(payload, "session.reconcileLostJob");
|
|
2062
|
+
const raw = payload;
|
|
2063
|
+
if (typeof raw?.runId !== "string" || raw.runId === "") throw new ServiceError("INVALID_INPUT", "session.reconcileLostJob requires runId");
|
|
2064
|
+
if (typeof raw.resolutionId !== "string" || raw.resolutionId === "") throw new ServiceError("INVALID_INPUT", "session.reconcileLostJob requires resolutionId");
|
|
2065
|
+
for (const [key, value] of [
|
|
2066
|
+
["jobKey", raw.jobKey],
|
|
2067
|
+
["startEventId", raw.startEventId],
|
|
2068
|
+
["reason", raw.reason],
|
|
2069
|
+
["resolvedBy", raw.resolvedBy]
|
|
2070
|
+
]) if (value !== void 0 && typeof value !== "string") throw new ServiceError("INVALID_INPUT", `session.reconcileLostJob ${key} must be a string`);
|
|
2071
|
+
return {
|
|
2072
|
+
sessionId,
|
|
2073
|
+
runId: raw.runId,
|
|
2074
|
+
resolutionId: raw.resolutionId,
|
|
2075
|
+
...raw.jobKey === void 0 ? {} : { jobKey: raw.jobKey },
|
|
2076
|
+
...raw.startEventId === void 0 ? {} : { startEventId: raw.startEventId },
|
|
2077
|
+
...raw.reason === void 0 ? {} : { reason: raw.reason },
|
|
2078
|
+
...raw.resolvedBy === void 0 ? {} : { resolvedBy: raw.resolvedBy }
|
|
2079
|
+
};
|
|
2080
|
+
}
|
|
2081
|
+
function parseRecordDiagnosticPayload(payload) {
|
|
2082
|
+
const sessionId = requireSessionId$1(payload, "session.recordDiagnostic");
|
|
2083
|
+
const raw = payload;
|
|
2084
|
+
if (typeof raw?.source !== "string" || !DIAGNOSTIC_SOURCES.has(raw.source)) throw new ServiceError("INVALID_INPUT", "session.recordDiagnostic requires a known source");
|
|
2085
|
+
if (typeof raw.severity !== "string" || !DIAGNOSTIC_SEVERITIES.has(raw.severity)) throw new ServiceError("INVALID_INPUT", "session.recordDiagnostic severity must be \"info\", \"warning\" or \"error\"");
|
|
2086
|
+
if (typeof raw.code !== "string" || raw.code === "") throw new ServiceError("INVALID_INPUT", "session.recordDiagnostic requires a non-empty code");
|
|
2087
|
+
if (typeof raw.message !== "string") throw new ServiceError("INVALID_INPUT", "session.recordDiagnostic requires message");
|
|
2088
|
+
if (raw.title !== void 0 && typeof raw.title !== "string") throw new ServiceError("INVALID_INPUT", "session.recordDiagnostic title must be a string");
|
|
2089
|
+
return {
|
|
2090
|
+
sessionId,
|
|
2091
|
+
source: raw.source,
|
|
2092
|
+
severity: raw.severity,
|
|
2093
|
+
code: raw.code,
|
|
2094
|
+
message: raw.message,
|
|
2095
|
+
...raw.title === void 0 ? {} : { title: raw.title }
|
|
2096
|
+
};
|
|
2097
|
+
}
|
|
2098
|
+
function withoutSurfaceMessages(restored) {
|
|
2099
|
+
if (!("messages" in restored)) return restored;
|
|
2100
|
+
const { messages: _omitted, ...rest } = restored;
|
|
2101
|
+
return rest;
|
|
2102
|
+
}
|
|
2103
|
+
function sessionRoutes(deps) {
|
|
2104
|
+
return defineRoutes("service:session", {
|
|
2105
|
+
"session.list": route("session.list", true, sessionListTarget, async (payload) => {
|
|
2106
|
+
const query = parseSessionListQuery(payload);
|
|
2107
|
+
return filterSessionEntries(await deps.dataSource.listSessions(query), query);
|
|
2108
|
+
}),
|
|
2109
|
+
"session.counts": route("session.counts", true, sessionListTarget, async () => {
|
|
2110
|
+
const entries = await deps.dataSource.listSessions({
|
|
2111
|
+
visibility: "all",
|
|
2112
|
+
archived: "include"
|
|
2113
|
+
});
|
|
2114
|
+
const visible = entries.filter((entry) => entry.archived !== true && entry.visibility !== "internal");
|
|
2115
|
+
const resident = entries.filter((entry) => entry.residency === "resident");
|
|
2116
|
+
return {
|
|
2117
|
+
visible: visible.length,
|
|
2118
|
+
persisted: entries.length,
|
|
2119
|
+
resident: resident.length,
|
|
2120
|
+
internal: entries.length - visible.length
|
|
2121
|
+
};
|
|
2122
|
+
}),
|
|
2123
|
+
"session.create": route("session.create", false, byWorkspace, async (payload) => await deps.dataSource.createSession(payload)),
|
|
2124
|
+
"session.cwdContext": route("session.cwdContext", true, bySession, async (payload) => {
|
|
2125
|
+
const sessionId = requireSessionId$1(payload, "session.cwdContext");
|
|
2126
|
+
const workspaceKey = await deps.workspaceOf?.(sessionId);
|
|
2127
|
+
if (workspaceKey === void 0) throw new ServiceError("NOT_HANDLED", "cwd context requires a workspace for this session");
|
|
2128
|
+
const context = await deps.cwdContextOf?.(workspaceKey);
|
|
2129
|
+
if (context === void 0) throw new ServiceError("NOT_HANDLED", "cwdContext is not supported by this instance");
|
|
2130
|
+
return context;
|
|
2131
|
+
}),
|
|
2132
|
+
"session.entry": route("session.entry", true, bySession, async (payload) => {
|
|
2133
|
+
const sessionId = requireSessionId$1(payload, "session.entry");
|
|
2134
|
+
const source = await sourceForSessionAsync(deps, sessionId);
|
|
2135
|
+
if (!source.sessionEntry) throw new ServiceError("NOT_HANDLED", "sessionEntry is not supported by this data source");
|
|
2136
|
+
return source.sessionEntry(sessionId);
|
|
2137
|
+
}),
|
|
2138
|
+
"session.runtimeSnapshot": route("session.runtimeSnapshot", true, bySession, async (payload) => {
|
|
2139
|
+
const sessionId = requireSessionId$1(payload, "session.runtimeSnapshot");
|
|
2140
|
+
const source = sourceForSession(deps, sessionId);
|
|
2141
|
+
if (!source.runtimeSnapshot) throw new ServiceError("NOT_HANDLED", "runtimeSnapshot is not supported by this data source");
|
|
2142
|
+
return source.runtimeSnapshot(sessionId);
|
|
2143
|
+
}),
|
|
2144
|
+
"session.model.select": route("session.model.select", false, bySession, async (payload) => {
|
|
2145
|
+
const sessionId = requireSessionId$1(payload, "session.model.select");
|
|
2146
|
+
const raw = payload?.modelId;
|
|
2147
|
+
if (raw !== void 0 && (typeof raw !== "string" || raw.length === 0)) throw new ServiceError("INVALID_INPUT", "session.model.select modelId must be a non-empty string");
|
|
2148
|
+
const source = sourceForSession(deps, sessionId);
|
|
2149
|
+
if (!source.selectSessionModel) throw new ServiceError("NOT_HANDLED", "selectSessionModel is not supported by this data source");
|
|
2150
|
+
return await source.selectSessionModel(sessionId, raw);
|
|
2151
|
+
}),
|
|
2152
|
+
"session.effort.select": route("session.effort.select", false, bySession, async (payload) => {
|
|
2153
|
+
const sessionId = requireSessionId$1(payload, "session.effort.select");
|
|
2154
|
+
const input = payload;
|
|
2155
|
+
if (typeof input === "object" && input !== null) {
|
|
2156
|
+
for (const key of Object.keys(input)) if (key !== "sessionId" && key !== "effort") throw new ServiceError("INVALID_INPUT", `session.effort.select does not accept "${key}"; an omitted effort resets the session`);
|
|
2157
|
+
}
|
|
2158
|
+
const raw = input?.effort;
|
|
2159
|
+
if (raw !== void 0 && parseThinkingLevel(raw) === void 0) throw new ServiceError("INVALID_INPUT", `session.effort.select effort must be one of ${[...THINKING_LEVELS].join(", ")}`);
|
|
2160
|
+
const source = sourceForSession(deps, sessionId);
|
|
2161
|
+
if (!source.selectSessionEffort) throw new ServiceError("NOT_HANDLED", "selectSessionEffort is not supported by this data source");
|
|
2162
|
+
return await source.selectSessionEffort(sessionId, parseThinkingLevel(raw));
|
|
2163
|
+
}),
|
|
2164
|
+
"session.permission.select": route("session.permission.select", false, bySession, async (payload) => {
|
|
2165
|
+
const sessionId = requireSessionId$1(payload, "session.permission.select");
|
|
2166
|
+
const input = payload;
|
|
2167
|
+
const mode = input?.mode;
|
|
2168
|
+
if (mode !== void 0 && !isPermissionMode(mode)) throw new ServiceError("INVALID_INPUT", "session.permission.select mode must be a permission mode");
|
|
2169
|
+
if (mode === "bypass" && input?.confirmed !== true) throw new ServiceError("INVALID_INPUT", "session.permission.select requires confirmed=true to choose bypass");
|
|
2170
|
+
const source = sourceForSession(deps, sessionId);
|
|
2171
|
+
if (!source.selectSessionPermissionMode) throw new ServiceError("NOT_HANDLED", "selectSessionPermissionMode is not supported by this data source");
|
|
2172
|
+
return await source.selectSessionPermissionMode(sessionId, mode);
|
|
2173
|
+
}),
|
|
2174
|
+
"session.permission.mode": route("session.permission.mode", true, bySession, async (payload) => {
|
|
2175
|
+
const sessionId = requireSessionId$1(payload, "session.permission.mode");
|
|
2176
|
+
const source = sourceForSession(deps, sessionId);
|
|
2177
|
+
if (!source.sessionPermissionMode) throw new ServiceError("NOT_HANDLED", "sessionPermissionMode is not supported by this data source");
|
|
2178
|
+
return await source.sessionPermissionMode(sessionId);
|
|
2179
|
+
}),
|
|
2180
|
+
"session.rename": route("session.rename", false, bySession, async (payload) => {
|
|
2181
|
+
const sessionId = requireSessionId$1(payload, "session.rename");
|
|
2182
|
+
const title = requireTitle(payload, "session.rename");
|
|
2183
|
+
const source = sourceForSession(deps, sessionId);
|
|
2184
|
+
if (!source.renameSession) throw new ServiceError("NOT_HANDLED", "renameSession is not supported by this data source");
|
|
2185
|
+
return source.renameSession(sessionId, title);
|
|
2186
|
+
}),
|
|
2187
|
+
"session.pin": route("session.pin", false, bySession, async (payload) => {
|
|
2188
|
+
const sessionIds = requirePinTargets(payload, "session.pin");
|
|
2189
|
+
const mode = requirePinMode(payload, "session.pin");
|
|
2190
|
+
const group = optionalPinGroup(payload, "session.pin");
|
|
2191
|
+
if (mode === "toggle" && sessionIds.length > 1) throw new ServiceError("INVALID_INPUT", "session.pin toggle accepts a single target; use ensure for batches");
|
|
2192
|
+
if (!deps.dataSource.pinSessions) throw new ServiceError("NOT_HANDLED", "pinSessions is not supported by this data source");
|
|
2193
|
+
return deps.dataSource.pinSessions(sessionIds, mode, group);
|
|
2194
|
+
}),
|
|
2195
|
+
"session.archive": route("session.archive", false, bySession, async (payload) => {
|
|
2196
|
+
const sessionId = requireSessionId$1(payload, "session.archive");
|
|
2197
|
+
const source = sourceForSession(deps, sessionId);
|
|
2198
|
+
if (source.archiveSession === void 0) throw new ServiceError("NOT_HANDLED", "this runtime does not support session archive");
|
|
2199
|
+
return source.archiveSession(sessionId);
|
|
2200
|
+
}),
|
|
2201
|
+
"session.reimport": route("session.reimport", false, bySession, async (payload) => {
|
|
2202
|
+
const sessionId = requireSessionId$1(payload, "session.reimport");
|
|
2203
|
+
const source = sourceForSession(deps, sessionId);
|
|
2204
|
+
if (source.reimportSession === void 0) throw new ServiceError("NOT_HANDLED", "this runtime does not support session reimport");
|
|
2205
|
+
return source.reimportSession(sessionId);
|
|
2206
|
+
}),
|
|
2207
|
+
"session.unarchive": route("session.unarchive", false, bySession, async (payload) => {
|
|
2208
|
+
const sessionId = requireSessionId$1(payload, "session.unarchive");
|
|
2209
|
+
const source = sourceForSession(deps, sessionId);
|
|
2210
|
+
if (source.unarchiveSession === void 0) throw new ServiceError("NOT_HANDLED", "this runtime does not support session unarchive");
|
|
2211
|
+
return source.unarchiveSession(sessionId);
|
|
2212
|
+
}),
|
|
2213
|
+
"session.remove": route("session.remove", false, bySession, async (payload) => {
|
|
2214
|
+
const sessionId = requireSessionId$1(payload, "session.remove");
|
|
2215
|
+
const source = sourceForSession(deps, sessionId);
|
|
2216
|
+
if (source.removeSession === void 0) throw new ServiceError("NOT_HANDLED", "this runtime does not support session remove");
|
|
2217
|
+
return source.removeSession(sessionId);
|
|
2218
|
+
}),
|
|
2219
|
+
"session.viewport": route("session.viewport", false, bySession, async (payload) => {
|
|
2220
|
+
const sessionId = requireSessionId$1(payload, "session.viewport");
|
|
2221
|
+
const source = sourceForSession(deps, sessionId);
|
|
2222
|
+
const protectTail = payload?.protectTail;
|
|
2223
|
+
if (typeof protectTail !== "number" || !Number.isFinite(protectTail) || protectTail < 0) throw new ServiceError("INVALID_INPUT", "session.viewport requires non-negative protectTail");
|
|
2224
|
+
if (!source.setViewportProtect) throw new ServiceError("NOT_HANDLED", "setViewportProtect is not supported by this data source");
|
|
2225
|
+
return { applied: source.setViewportProtect(sessionId, protectTail) };
|
|
2226
|
+
}),
|
|
2227
|
+
"session.releaseView": route("session.releaseView", false, bySession, async (payload) => {
|
|
2228
|
+
const sessionId = requireSessionId$1(payload, "session.releaseView");
|
|
2229
|
+
const source = sourceForSession(deps, sessionId);
|
|
2230
|
+
if (source.releaseView === void 0) throw new ServiceError("NOT_HANDLED", "releaseView is not supported by this data source");
|
|
2231
|
+
source.releaseView(sessionId, optionalConnectionId(payload));
|
|
2232
|
+
}),
|
|
2233
|
+
"session.claim": route("session.claim", false, bySession, async (payload) => {
|
|
2234
|
+
const sessionId = requireSessionId$1(payload, "session.claim");
|
|
2235
|
+
const source = sourceForSession(deps, sessionId);
|
|
2236
|
+
if (source.claimSessionLease === void 0) throw new ServiceError("NOT_HANDLED", "claimSessionLease is not supported by this data source");
|
|
2237
|
+
return await source.claimSessionLease(sessionId);
|
|
2238
|
+
}),
|
|
2239
|
+
"session.restore": route("session.restore", false, bySession, async (payload) => {
|
|
2240
|
+
const sessionId = requireSessionId$1(payload, "session.restore");
|
|
2241
|
+
const source = sourceForSession(deps, sessionId);
|
|
2242
|
+
if (!source.restore) throw new ServiceError("NOT_HANDLED", "restore is not supported by this data source");
|
|
2243
|
+
const sinceSeq = payload?.sinceSeq;
|
|
2244
|
+
if (sinceSeq !== void 0 && (typeof sinceSeq !== "number" || !Number.isInteger(sinceSeq) || sinceSeq < 0)) throw new ServiceError("INVALID_INPUT", "sinceSeq must be a non-negative integer");
|
|
2245
|
+
const tailMessages = payload?.tailMessages;
|
|
2246
|
+
if (tailMessages !== void 0 && (typeof tailMessages !== "number" || !Number.isInteger(tailMessages) || tailMessages <= 0)) throw new ServiceError("INVALID_INPUT", "session.restore tailMessages must be a positive integer");
|
|
2247
|
+
return withoutSurfaceMessages(await source.restore(sessionId, {
|
|
2248
|
+
preview: payload?.preview === true,
|
|
2249
|
+
takeover: payload?.takeover === true,
|
|
2250
|
+
...sinceSeq === void 0 ? {} : { sinceSeq },
|
|
2251
|
+
...tailMessages === void 0 ? {} : { tailMessages }
|
|
2252
|
+
}));
|
|
2253
|
+
}),
|
|
2254
|
+
"session.resultObligations": route("session.resultObligations", true, bySession, async (payload) => {
|
|
2255
|
+
const sessionId = requireSessionId$1(payload, "session.resultObligations");
|
|
2256
|
+
const source = sourceForSession(deps, sessionId);
|
|
2257
|
+
if (!source.resultObligations) throw new ServiceError("NOT_HANDLED", "resultObligations is not supported by this data source");
|
|
2258
|
+
return source.resultObligations(sessionId);
|
|
2259
|
+
}),
|
|
2260
|
+
"session.discardResultObligation": route("session.discardResultObligation", false, bySession, async (payload) => {
|
|
2261
|
+
const sessionId = requireSessionId$1(payload, "session.discardResultObligation");
|
|
2262
|
+
const jobKey = requireJobKey(payload, "session.discardResultObligation");
|
|
2263
|
+
const reason = payload?.reason;
|
|
2264
|
+
const source = sourceForSession(deps, sessionId);
|
|
2265
|
+
if (!source.discardResultObligation) throw new ServiceError("NOT_HANDLED", "discardResultObligation is not supported by this data source");
|
|
2266
|
+
return source.discardResultObligation(sessionId, jobKey, typeof reason === "string" ? reason : void 0);
|
|
2267
|
+
}),
|
|
2268
|
+
"session.rearmResultObligation": route("session.rearmResultObligation", false, bySession, async (payload) => {
|
|
2269
|
+
const sessionId = requireSessionId$1(payload, "session.rearmResultObligation");
|
|
2270
|
+
const jobKey = requireJobKey(payload, "session.rearmResultObligation");
|
|
2271
|
+
const source = sourceForSession(deps, sessionId);
|
|
2272
|
+
if (!source.rearmResultObligation) throw new ServiceError("NOT_HANDLED", "rearmResultObligation is not supported by this data source");
|
|
2273
|
+
return source.rearmResultObligation(sessionId, jobKey);
|
|
2274
|
+
}),
|
|
2275
|
+
"session.confirmResultObligation": route("session.confirmResultObligation", false, bySession, async (payload) => {
|
|
2276
|
+
const sessionId = requireSessionId$1(payload, "session.confirmResultObligation");
|
|
2277
|
+
const jobKey = requireJobKey(payload, "session.confirmResultObligation");
|
|
2278
|
+
const source = sourceForSession(deps, sessionId);
|
|
2279
|
+
if (!source.confirmResultObligation) throw new ServiceError("NOT_HANDLED", "confirmResultObligation is not supported by this data source");
|
|
2280
|
+
return source.confirmResultObligation(sessionId, jobKey);
|
|
2281
|
+
}),
|
|
2282
|
+
"session.reconcileLostJob": route("session.reconcileLostJob", false, bySession, async (payload) => {
|
|
2283
|
+
const input = parseReconcileLostJobPayload(payload);
|
|
2284
|
+
if (!deps.dataSource.reconcileLostJob) throw new ServiceError("NOT_HANDLED", "reconcileLostJob is unsupported by the data source");
|
|
2285
|
+
return deps.dataSource.reconcileLostJob(input);
|
|
2286
|
+
}),
|
|
2287
|
+
"session.recordDiagnostic": route("session.recordDiagnostic", false, bySession, async (payload) => {
|
|
2288
|
+
const input = parseRecordDiagnosticPayload(payload);
|
|
2289
|
+
if (!deps.dataSource.recordDiagnostic) throw new ServiceError("NOT_HANDLED", "recordDiagnostic is unsupported by the data source");
|
|
2290
|
+
return deps.dataSource.recordDiagnostic(input);
|
|
2291
|
+
})
|
|
2292
|
+
});
|
|
2293
|
+
}
|
|
2294
|
+
|
|
2295
|
+
//#endregion
|
|
2296
|
+
//#region src/routes/session-runtime-routes.ts
|
|
2297
|
+
const DEFAULT_SURFACE_READ_LIMIT = 200;
|
|
2298
|
+
const MAX_SURFACE_READ_LIMIT = 2e3;
|
|
2299
|
+
function parseTurnToolView(payload, method) {
|
|
2300
|
+
const raw = payload?.toolView;
|
|
2301
|
+
if (raw === void 0) return void 0;
|
|
2302
|
+
if (raw === null) return null;
|
|
2303
|
+
if (typeof raw !== "object" || raw === null) throw new ServiceError("INVALID_INPUT", `${method} toolView must be an object`);
|
|
2304
|
+
const view = raw;
|
|
2305
|
+
const namesOf = (value, key) => {
|
|
2306
|
+
if (value === void 0) return void 0;
|
|
2307
|
+
if (!Array.isArray(value)) throw new ServiceError("INVALID_INPUT", `${method} toolView.${key} must be an array`);
|
|
2308
|
+
const names = value.filter((item) => typeof item === "string" && item !== "");
|
|
2309
|
+
if (names.length !== value.length) throw new ServiceError("INVALID_INPUT", `${method} toolView.${key} must contain non-empty strings`);
|
|
2310
|
+
return names;
|
|
2311
|
+
};
|
|
2312
|
+
const allow = namesOf(view.allow, "allow");
|
|
2313
|
+
const deny = namesOf(view.deny, "deny");
|
|
2314
|
+
return {
|
|
2315
|
+
...allow === void 0 ? {} : { allow },
|
|
2316
|
+
...deny === void 0 ? {} : { deny }
|
|
2317
|
+
};
|
|
2318
|
+
}
|
|
2319
|
+
function sessionRuntimeRoutes(deps) {
|
|
2320
|
+
async function resolveWorkspace(sessionId) {
|
|
2321
|
+
if (deps.workspaceOf !== void 0) return deps.workspaceOf(sessionId);
|
|
2322
|
+
return (await deps.dataSource.sessionEntry?.(sessionId))?.workspaceKey;
|
|
2323
|
+
}
|
|
2324
|
+
return defineRoutes("service:session-runtime", {
|
|
2325
|
+
"session.work.snapshot": route("session.work.snapshot", true, bySession, async (payload) => {
|
|
2326
|
+
const sessionId = requireSessionId$1(payload, "session.work.snapshot");
|
|
2327
|
+
const source = sourceForSession(deps, sessionId);
|
|
2328
|
+
if (!source.workSnapshot) throw new ServiceError("NOT_HANDLED", "work snapshot is not supported by this data source");
|
|
2329
|
+
return source.workSnapshot(sessionId);
|
|
2330
|
+
}),
|
|
2331
|
+
"session.timeline.snapshot": route("session.timeline.snapshot", true, bySession, async (payload) => {
|
|
2332
|
+
const sessionId = requireSessionId$1(payload, "session.timeline.snapshot");
|
|
2333
|
+
const source = sourceForSession(deps, sessionId);
|
|
2334
|
+
if (!source.timelineSnapshot) throw new ServiceError("NOT_HANDLED", "timeline snapshot is not supported by this data source");
|
|
2335
|
+
const input = payload;
|
|
2336
|
+
const budget = input?.budget !== void 0 ? {
|
|
2337
|
+
events: typeof input.budget.events === "number" ? input.budget.events : 100,
|
|
2338
|
+
bytes: typeof input.budget.bytes === "number" ? input.budget.bytes : 1024 * 1024
|
|
2339
|
+
} : void 0;
|
|
2340
|
+
return source.timelineSnapshot(sessionId, budget);
|
|
2341
|
+
}),
|
|
2342
|
+
"session.timeline.detail": route("session.timeline.detail", true, bySession, async (payload) => {
|
|
2343
|
+
const sessionId = requireSessionId$1(payload, "session.timeline.detail");
|
|
2344
|
+
const source = sourceForSession(deps, sessionId);
|
|
2345
|
+
if (!source.timelineDetail) throw new ServiceError("NOT_HANDLED", "timeline detail is not supported by this data source");
|
|
2346
|
+
const input = payload;
|
|
2347
|
+
const nodeIds = Array.isArray(input?.nodeIds) ? input.nodeIds : [];
|
|
2348
|
+
const budget = input?.budget !== void 0 ? {
|
|
2349
|
+
events: typeof input.budget.events === "number" ? input.budget.events : 20,
|
|
2350
|
+
bytes: typeof input.budget.bytes === "number" ? input.budget.bytes : 256 * 1024
|
|
2351
|
+
} : void 0;
|
|
2352
|
+
return source.timelineDetail(sessionId, nodeIds, budget);
|
|
2353
|
+
}),
|
|
2354
|
+
"session.contextArchive.read": route("session.contextArchive.read", true, bySession, async (payload) => {
|
|
2355
|
+
const sessionId = requireSessionId$1(payload, "session.contextArchive.read");
|
|
2356
|
+
const source = sourceForSession(deps, sessionId);
|
|
2357
|
+
if (!source.contextArchiveRead) return {
|
|
2358
|
+
kind: "unavailable",
|
|
2359
|
+
reason: "unsupported"
|
|
2360
|
+
};
|
|
2361
|
+
const input = payload;
|
|
2362
|
+
const numeric = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
|
|
2363
|
+
const budget = input.budget;
|
|
2364
|
+
return source.contextArchiveRead({
|
|
2365
|
+
sessionId,
|
|
2366
|
+
...numeric(input.recordSeq) === void 0 ? {} : { recordSeq: numeric(input.recordSeq) },
|
|
2367
|
+
...numeric(input.beforeSeq) === void 0 ? {} : { beforeSeq: numeric(input.beforeSeq) },
|
|
2368
|
+
...input.kind === "trim" || input.kind === "compaction" ? { kind: input.kind } : {},
|
|
2369
|
+
...numeric(input.offset) === void 0 ? {} : { offset: numeric(input.offset) },
|
|
2370
|
+
...budget === void 0 ? {} : { budget: {
|
|
2371
|
+
...numeric(budget.maxMessages) === void 0 ? {} : { maxMessages: numeric(budget.maxMessages) },
|
|
2372
|
+
...numeric(budget.maxEvents) === void 0 ? {} : { maxEvents: numeric(budget.maxEvents) },
|
|
2373
|
+
...numeric(budget.maxBytes) === void 0 ? {} : { maxBytes: numeric(budget.maxBytes) },
|
|
2374
|
+
...numeric(budget.deadlineMs) === void 0 ? {} : { deadlineMs: numeric(budget.deadlineMs) }
|
|
2375
|
+
} }
|
|
2376
|
+
});
|
|
2377
|
+
}),
|
|
2378
|
+
"composer.context": route("composer.context", true, bySession, async (payload) => {
|
|
2379
|
+
const sessionId = requireSessionId$1(payload, "composer.context");
|
|
2380
|
+
const source = sourceForSession(deps, sessionId);
|
|
2381
|
+
const limit = payload?.limit;
|
|
2382
|
+
if (limit !== void 0 && (typeof limit !== "number" || !Number.isFinite(limit))) throw new ServiceError("INVALID_INPUT", "composer.context limit must be a number");
|
|
2383
|
+
const read = source.readComposerContext;
|
|
2384
|
+
if (read === void 0) return {
|
|
2385
|
+
history: [],
|
|
2386
|
+
commands: [],
|
|
2387
|
+
autosuggest: "on"
|
|
2388
|
+
};
|
|
2389
|
+
const options = limit === void 0 ? void 0 : { limit };
|
|
2390
|
+
return read.call(deps.dataSource, sessionId, options);
|
|
2391
|
+
}),
|
|
2392
|
+
"session.archivedHistory": route("session.archivedHistory", true, bySession, async (payload) => {
|
|
2393
|
+
const sessionId = requireSessionId$1(payload, "session.archivedHistory");
|
|
2394
|
+
const source = sourceForSession(deps, sessionId);
|
|
2395
|
+
const limit = payload?.limit;
|
|
2396
|
+
if (limit !== void 0 && (typeof limit !== "number" || !Number.isFinite(limit))) throw new ServiceError("INVALID_INPUT", "session.archivedHistory limit must be a number");
|
|
2397
|
+
if (!source.readArchivedHistory) throw new ServiceError("NOT_HANDLED", "readArchivedHistory is not supported by this data source");
|
|
2398
|
+
return source.readArchivedHistory(sessionId, limit === void 0 ? void 0 : { limit });
|
|
2399
|
+
}),
|
|
2400
|
+
"session.surface.read": route("session.surface.read", true, bySession, async (payload) => {
|
|
2401
|
+
const sessionId = requireSessionId$1(payload, "session.surface.read");
|
|
2402
|
+
const source = sourceForSession(deps, sessionId);
|
|
2403
|
+
const limitMessages = payload?.limitMessages;
|
|
2404
|
+
if (limitMessages !== void 0 && !(typeof limitMessages === "number" && Number.isFinite(limitMessages) && limitMessages >= 0)) throw new ServiceError("INVALID_INPUT", "session.surface.read limitMessages must be a non-negative number");
|
|
2405
|
+
const beforeSeq = payload?.beforeSeq;
|
|
2406
|
+
if (beforeSeq !== void 0 && (typeof beforeSeq !== "number" || !Number.isSafeInteger(beforeSeq) || beforeSeq < 0)) throw new ServiceError("INVALID_INPUT", "session.surface.read beforeSeq must be a non-negative integer");
|
|
2407
|
+
if (!source.readSessionSurface) throw new ServiceError("NOT_HANDLED", "readSessionSurface is not supported by this data source");
|
|
2408
|
+
const effectiveLimit = limitMessages === void 0 ? 200 : Math.min(Math.floor(limitMessages), MAX_SURFACE_READ_LIMIT);
|
|
2409
|
+
return source.readSessionSurface(sessionId, {
|
|
2410
|
+
limitMessages: effectiveLimit,
|
|
2411
|
+
...beforeSeq === void 0 ? {} : { beforeSeq }
|
|
2412
|
+
});
|
|
2413
|
+
}),
|
|
2414
|
+
"session.forkPoints.list": route("session.forkPoints.list", true, bySession, async (payload) => {
|
|
2415
|
+
const sessionId = requireSessionId$1(payload, "session.forkPoints.list");
|
|
2416
|
+
const source = sourceForSession(deps, sessionId);
|
|
2417
|
+
if (!source.listForkPoints) throw new ServiceError("NOT_HANDLED", "listForkPoints is not supported by this data source");
|
|
2418
|
+
return source.listForkPoints(sessionId);
|
|
2419
|
+
}),
|
|
2420
|
+
"session.fork": route("session.fork", false, bySession, async (payload) => {
|
|
2421
|
+
const sessionId = requireSessionId$1(payload, "session.fork");
|
|
2422
|
+
const source = await sourceForSessionAsync(deps, sessionId);
|
|
2423
|
+
const input = payload;
|
|
2424
|
+
const boundarySeq = input?.boundarySeq;
|
|
2425
|
+
const childId = input?.childId;
|
|
2426
|
+
if (childId !== void 0 && (typeof childId !== "string" || childId.trim() === "")) throw new ServiceError("INVALID_INPUT", "session.fork childId must be a non-empty string");
|
|
2427
|
+
const hasValidBoundary = typeof boundarySeq === "number" && Number.isSafeInteger(boundarySeq) && boundarySeq >= 0;
|
|
2428
|
+
if (boundarySeq !== void 0 && !hasValidBoundary) throw new ServiceError("INVALID_INPUT", "session.fork boundarySeq must be a non-negative integer");
|
|
2429
|
+
const label = input?.label;
|
|
2430
|
+
if (label !== void 0 && (typeof label !== "string" || label.trim() === "")) throw new ServiceError("INVALID_INPUT", "session.fork label must be a non-empty string");
|
|
2431
|
+
if (!source.forkSession) throw new ServiceError("NOT_HANDLED", "forkSession is not supported by this data source");
|
|
2432
|
+
return source.forkSession(sessionId, {
|
|
2433
|
+
...hasValidBoundary ? { boundarySeq } : {},
|
|
2434
|
+
...typeof label === "string" ? { label: label.trim() } : {},
|
|
2435
|
+
...typeof childId === "string" ? { childId } : {}
|
|
2436
|
+
});
|
|
2437
|
+
}),
|
|
2438
|
+
"session.recovery.list": route("session.recovery.list", true, bySession, async (payload) => {
|
|
2439
|
+
const sessionId = requireSessionId$1(payload, "session.recovery.list");
|
|
2440
|
+
const source = sourceForSession(deps, sessionId);
|
|
2441
|
+
if (!source.listRecoveries) throw new ServiceError("NOT_HANDLED", "listRecoveries is not supported by this data source");
|
|
2442
|
+
return source.listRecoveries(sessionId);
|
|
2443
|
+
}),
|
|
2444
|
+
"session.recovery.get": route("session.recovery.get", true, bySession, async (payload) => {
|
|
2445
|
+
const sessionId = requireSessionId$1(payload, "session.recovery.get");
|
|
2446
|
+
const source = sourceForSession(deps, sessionId);
|
|
2447
|
+
const commitId = requireCommitId(payload, "session.recovery.get");
|
|
2448
|
+
if (!source.getRecovery) throw new ServiceError("NOT_HANDLED", "getRecovery is not supported by this data source");
|
|
2449
|
+
return source.getRecovery(sessionId, commitId);
|
|
2450
|
+
}),
|
|
2451
|
+
"session.recovery.retry": route("session.recovery.retry", false, bySession, async (payload) => {
|
|
2452
|
+
const sessionId = requireSessionId$1(payload, "session.recovery.retry");
|
|
2453
|
+
const source = sourceForSession(deps, sessionId);
|
|
2454
|
+
const commitId = requireCommitId(payload, "session.recovery.retry");
|
|
2455
|
+
if (!source.retryRecovery) throw new ServiceError("NOT_HANDLED", "retryRecovery is not supported by this data source");
|
|
2456
|
+
return source.retryRecovery(sessionId, commitId);
|
|
2457
|
+
}),
|
|
2458
|
+
"session.recovery.resolve": route("session.recovery.resolve", false, bySession, async (payload) => {
|
|
2459
|
+
const sessionId = requireSessionId$1(payload, "session.recovery.resolve");
|
|
2460
|
+
const source = sourceForSession(deps, sessionId);
|
|
2461
|
+
const commitId = requireCommitId(payload, "session.recovery.resolve");
|
|
2462
|
+
const decision = payload?.decision;
|
|
2463
|
+
if (decision !== "retry" && decision !== "drop") throw new ServiceError("INVALID_INPUT", "session.recovery.resolve decision must be \"retry\" or \"drop\"");
|
|
2464
|
+
if (!source.resolveRecovery) throw new ServiceError("NOT_HANDLED", "resolveRecovery is not supported by this data source");
|
|
2465
|
+
return source.resolveRecovery(sessionId, commitId, decision);
|
|
2466
|
+
}),
|
|
2467
|
+
"session.recovery.repair": route("session.recovery.repair", false, bySession, async (payload) => {
|
|
2468
|
+
const sessionId = requireSessionId$1(payload, "session.recovery.repair");
|
|
2469
|
+
const source = sourceForSession(deps, sessionId);
|
|
2470
|
+
if (!source.repairRecovery) throw new ServiceError("NOT_HANDLED", "repairRecovery is not supported by this data source");
|
|
2471
|
+
return source.repairRecovery(sessionId);
|
|
2472
|
+
}),
|
|
2473
|
+
"session.prepare": route("session.prepare", false, bySession, async (payload, context) => {
|
|
2474
|
+
const sessionId = requireSessionId$1(payload, "session.prepare");
|
|
2475
|
+
const source = await sourceForSessionAsync(deps, sessionId);
|
|
2476
|
+
if (!source.prepare) throw new ServiceError("NOT_HANDLED", "prepare is not supported by this data source");
|
|
2477
|
+
const turnToolView = parseTurnToolView(payload, "session.prepare");
|
|
2478
|
+
return source.prepare(sessionId, optionalConnectionId(payload), turnToolView === null ? { clear: true } : turnToolView, context.clientId);
|
|
2479
|
+
}),
|
|
2480
|
+
"session.deliver": route("session.deliver", false, bySession, async (payload) => {
|
|
2481
|
+
const request = parseSessionDeliveryRequest(payload, "session.deliver");
|
|
2482
|
+
const targetWorkspace = await resolveWorkspace(request.sessionId);
|
|
2483
|
+
const actorWorkspace = await resolveWorkspace(request.actorSessionId);
|
|
2484
|
+
if (targetWorkspace === void 0 || actorWorkspace === void 0) return {
|
|
2485
|
+
state: "rejected",
|
|
2486
|
+
reason: "unknown-workspace",
|
|
2487
|
+
requestId: request.clientRequestId,
|
|
2488
|
+
receiptConfirmed: false
|
|
2489
|
+
};
|
|
2490
|
+
if (targetWorkspace !== actorWorkspace) return {
|
|
2491
|
+
state: "rejected",
|
|
2492
|
+
reason: "cross-workspace",
|
|
2493
|
+
requestId: request.clientRequestId,
|
|
2494
|
+
receiptConfirmed: false
|
|
2495
|
+
};
|
|
2496
|
+
const source = await sourceForSessionAsync(deps, request.sessionId);
|
|
2497
|
+
if (source.deliver === void 0) throw new ServiceError("NOT_HANDLED", "deliver is not supported by this data source");
|
|
2498
|
+
return source.deliver(request);
|
|
2499
|
+
}),
|
|
2500
|
+
"recorder.pending.export": route("recorder.pending.export", true, bySession, async (payload) => {
|
|
2501
|
+
const sessionId = requireSessionId$1(payload, "recorder.pending.export");
|
|
2502
|
+
const source = sourceForSession(deps, sessionId);
|
|
2503
|
+
if (!source.exportRecorderPending) throw new ServiceError("NOT_HANDLED", "exportRecorderPending is not supported by this data source");
|
|
2504
|
+
return source.exportRecorderPending(sessionId);
|
|
2505
|
+
}),
|
|
2506
|
+
"recorder.pending.recover": route("recorder.pending.recover", false, bySession, async (payload) => {
|
|
2507
|
+
const sessionId = requireSessionId$1(payload, "recorder.pending.recover");
|
|
2508
|
+
const source = sourceForSession(deps, sessionId);
|
|
2509
|
+
const digest = payload?.digest;
|
|
2510
|
+
if (typeof digest !== "string" || digest === "") throw new ServiceError("INVALID_INPUT", "recorder.pending.recover requires digest");
|
|
2511
|
+
if (!source.recoverRecorderPending) throw new ServiceError("NOT_HANDLED", "recoverRecorderPending is not supported by this data source");
|
|
2512
|
+
return source.recoverRecorderPending(sessionId, digest);
|
|
2513
|
+
}),
|
|
2514
|
+
"session.editedFiles": route("session.editedFiles", true, bySession, async (payload) => {
|
|
2515
|
+
const sessionId = requireSessionId$1(payload, "session.editedFiles");
|
|
2516
|
+
const source = sourceForSession(deps, sessionId);
|
|
2517
|
+
if (!source.listEditedFiles) throw new ServiceError("NOT_HANDLED", "listEditedFiles is not supported by this data source");
|
|
2518
|
+
return await source.listEditedFiles(sessionId);
|
|
2519
|
+
}),
|
|
2520
|
+
"session.descendants": route("session.descendants", true, bySession, async (payload) => {
|
|
2521
|
+
const sessionId = requireSessionId$1(payload, "session.descendants");
|
|
2522
|
+
const source = await sourceForSessionAsync(deps, sessionId);
|
|
2523
|
+
if (!source.listSessionDescendants) throw new ServiceError("NOT_HANDLED", "listSessionDescendants is not supported by this data source");
|
|
2524
|
+
return await source.listSessionDescendants(sessionId);
|
|
2525
|
+
}),
|
|
2526
|
+
"plan.list": route("plan.list", true, bySession, async (payload) => {
|
|
2527
|
+
const sessionId = requireSessionId$1(payload, "plan.list");
|
|
2528
|
+
const source = sourceForSession(deps, sessionId);
|
|
2529
|
+
if (!source.listPlan) throw new ServiceError("NOT_HANDLED", "listPlan is not supported by this data source");
|
|
2530
|
+
return { items: await source.listPlan(sessionId) };
|
|
2531
|
+
}),
|
|
2532
|
+
"session.inspectSource": route("session.inspectSource", false, globalTarget, async (input) => ({ value: await requirePort(deps.sessionDiagnosticsPort, "session.inspectSource").inspectSource(requireName(input, "path", "session.inspectSource"), requireName(input, "cwd", "session.inspectSource")) })),
|
|
2533
|
+
"session.auditLogs": route("session.auditLogs", false, globalTarget, async (input) => {
|
|
2534
|
+
const typed = input;
|
|
2535
|
+
const mode = typed?.mode ?? "verify";
|
|
2536
|
+
if (mode !== "verify" && mode !== "compact" && mode !== "keep") throw new ServiceError("INVALID_INPUT", "session.auditLogs mode must be verify/compact/keep");
|
|
2537
|
+
const sessionIds = typed?.sessionIds ?? [];
|
|
2538
|
+
if (!Array.isArray(sessionIds) || sessionIds.some((id) => typeof id !== "string")) throw new ServiceError("INVALID_INPUT", "session.auditLogs sessionIds must be string[]");
|
|
2539
|
+
return { value: await requirePort(deps.sessionDiagnosticsPort, "session.auditLogs").auditLogs(mode, sessionIds) };
|
|
2540
|
+
})
|
|
2541
|
+
});
|
|
2542
|
+
}
|
|
2543
|
+
|
|
2544
|
+
//#endregion
|
|
2545
|
+
//#region src/routes/settings-routes.ts
|
|
2546
|
+
function workspaceKeyOf(input) {
|
|
2547
|
+
const value = input?.workspaceKey;
|
|
2548
|
+
if (value === void 0) return;
|
|
2549
|
+
if (typeof value !== "string" || value === "") throw new ServiceError("INVALID_INPUT", "settings.*: workspaceKey must be a non-empty string");
|
|
2550
|
+
return value;
|
|
2551
|
+
}
|
|
2552
|
+
function sourceOfKey(all, key) {
|
|
2553
|
+
return all.owners?.[key] === "project" ? "project" : "user";
|
|
2554
|
+
}
|
|
2555
|
+
function settingsRoutes(deps) {
|
|
2556
|
+
function settingsPortOrFail(input) {
|
|
2557
|
+
const workspaceKey = workspaceKeyOf(input);
|
|
2558
|
+
if (workspaceKey !== void 0 && deps.settingsPortOf === void 0 && deps.settingsPort === void 0) throw new ServiceError("NOT_HANDLED", "settings.* requires a worker settings port");
|
|
2559
|
+
if (workspaceKey !== void 0 && deps.settingsPortOf === void 0 && deps.workspaceKeyOfRuntime?.() !== workspaceKey) throw new ServiceError("WORKSPACE_NOT_FOUND", `settings.*: this runtime does not serve workspace "${workspaceKey}"`, { workspaceKey });
|
|
2560
|
+
if (workspaceKey !== void 0 && deps.settingsPortOf !== void 0) {
|
|
2561
|
+
const scoped = deps.settingsPortOf(workspaceKey);
|
|
2562
|
+
if (scoped === void 0) throw new ServiceError("WORKSPACE_NOT_FOUND", `settings.*: no workspace runtime for "${workspaceKey}"`, { workspaceKey });
|
|
2563
|
+
return scoped;
|
|
2564
|
+
}
|
|
2565
|
+
if (deps.settingsPort === void 0) throw new ServiceError("NOT_HANDLED", "settings.* requires a worker settings port");
|
|
2566
|
+
return deps.settingsPort;
|
|
2567
|
+
}
|
|
2568
|
+
return defineRoutes("service:settings", {
|
|
2569
|
+
"settings.get": route("settings.get", false, byWorkspaceOrGlobal, async (input) => {
|
|
2570
|
+
const port = settingsPortOrFail(input);
|
|
2571
|
+
const key = input?.key;
|
|
2572
|
+
if (typeof key !== "string" || key === "") throw new ServiceError("INVALID_INPUT", "settings.get requires { key }");
|
|
2573
|
+
return await port.get(key);
|
|
2574
|
+
}),
|
|
2575
|
+
"permission.mode": route("permission.mode", false, globalTarget, async () => {
|
|
2576
|
+
const settings = settingsPortOrFail();
|
|
2577
|
+
const all = await settings.getAll();
|
|
2578
|
+
const raw = all.values[PERMISSION_MODE_SETTING_KEY];
|
|
2579
|
+
const parsed = isPermissionMode(raw) ? raw : void 0;
|
|
2580
|
+
const adopted = settings.adoptedPermissionMode?.();
|
|
2581
|
+
return {
|
|
2582
|
+
mode: parsed ?? PERMISSION_MODE_FIELD_SPEC.default,
|
|
2583
|
+
offered: OFFERED_PERMISSION_MODES,
|
|
2584
|
+
source: parsed === void 0 ? "default" : sourceOfKey(all, PERMISSION_MODE_SETTING_KEY),
|
|
2585
|
+
...adopted === void 0 ? {} : { adopted }
|
|
2586
|
+
};
|
|
2587
|
+
}),
|
|
2588
|
+
"settings.getAll": route("settings.getAll", false, byWorkspaceOrGlobal, async (input) => await settingsPortOrFail(input).getAll()),
|
|
2589
|
+
"settings.set": route("settings.set", false, byWorkspaceOrGlobal, async (input) => {
|
|
2590
|
+
const port = settingsPortOrFail(input);
|
|
2591
|
+
const key = input?.key;
|
|
2592
|
+
if (typeof key !== "string" || key === "") throw new ServiceError("INVALID_INPUT", "settings.set requires { key }");
|
|
2593
|
+
const scope = optionalSettingScope(input, "settings.set");
|
|
2594
|
+
return await port.set(key, input.value, scope);
|
|
2595
|
+
}),
|
|
2596
|
+
"settings.clear": route("settings.clear", false, byWorkspaceOrGlobal, async (input) => {
|
|
2597
|
+
const port = settingsPortOrFail(input);
|
|
2598
|
+
const key = input?.key;
|
|
2599
|
+
if (typeof key !== "string" || key === "") throw new ServiceError("INVALID_INPUT", "settings.clear requires { key }");
|
|
2600
|
+
if (port.clear === void 0) throw new ServiceError("NOT_HANDLED", "settings.clear is not supported by this settings port");
|
|
2601
|
+
return await port.clear(key, optionalSettingScope(input, "settings.clear"));
|
|
2602
|
+
}),
|
|
2603
|
+
"settings.describe": route("settings.describe", false, byWorkspaceOrGlobal, async (input) => {
|
|
2604
|
+
const port = settingsPortOrFail(input);
|
|
2605
|
+
const keys = input?.keys;
|
|
2606
|
+
if (!Array.isArray(keys) || keys.some((key) => typeof key !== "string")) throw new ServiceError("INVALID_INPUT", "settings.describe requires { keys: string[] }");
|
|
2607
|
+
if (port.describe === void 0) throw new ServiceError("NOT_HANDLED", "settings.describe is not supported by this settings port");
|
|
2608
|
+
return await port.describe(keys);
|
|
2609
|
+
}),
|
|
2610
|
+
"settings.subscribe": route("settings.subscribe", false, byWorkspaceOrGlobal, async (input) => {
|
|
2611
|
+
const port = settingsPortOrFail(input);
|
|
2612
|
+
const keys = input?.keys;
|
|
2613
|
+
if (keys !== void 0 && !Array.isArray(keys)) throw new ServiceError("INVALID_INPUT", "settings.subscribe keys must be an array");
|
|
2614
|
+
return await port.subscribe(keys);
|
|
2615
|
+
})
|
|
2616
|
+
});
|
|
2617
|
+
}
|
|
2618
|
+
|
|
2619
|
+
//#endregion
|
|
2620
|
+
//#region src/resource-read.ts
|
|
2621
|
+
const RESOURCE_SCHEME_PREFIX = "otto-resource://file/";
|
|
2622
|
+
function parseResourceAddress(address) {
|
|
2623
|
+
if (!address.startsWith(RESOURCE_SCHEME_PREFIX)) throw new ServiceError("INVALID_INPUT", "resource.read address must use the otto-resource://file/ scheme");
|
|
2624
|
+
const filePath = address.slice(21);
|
|
2625
|
+
if (filePath === "" || filePath.includes("\0")) throw new ServiceError("INVALID_INPUT", "resource.read address must include a file path");
|
|
2626
|
+
return filePath;
|
|
2627
|
+
}
|
|
2628
|
+
|
|
2629
|
+
//#endregion
|
|
2630
|
+
//#region src/routes/workspace-routes.ts
|
|
2631
|
+
function optionalWorkspaceKey(payload, method) {
|
|
2632
|
+
const value = payload?.workspaceKey;
|
|
2633
|
+
if (value === void 0) return;
|
|
2634
|
+
if (typeof value !== "string" || value === "") throw new ServiceError("INVALID_INPUT", `${method}: workspaceKey must be a non-empty string`);
|
|
2635
|
+
return value;
|
|
2636
|
+
}
|
|
2637
|
+
async function workspaceOfSession(deps, sessionId) {
|
|
2638
|
+
if (deps.workspaceOf !== void 0) return await deps.workspaceOf(sessionId);
|
|
2639
|
+
return (await deps.dataSource.sessionEntry?.(sessionId))?.workspaceKey;
|
|
2640
|
+
}
|
|
2641
|
+
async function assertSessionsWithinScope(deps, context, sessionIds) {
|
|
2642
|
+
const scope = context.workspaceScope;
|
|
2643
|
+
if (scope === void 0 || scope === "*") return;
|
|
2644
|
+
for (const sessionId of sessionIds) {
|
|
2645
|
+
const workspaceKey = await workspaceOfSession(deps, sessionId);
|
|
2646
|
+
if (workspaceKey === void 0 || !scope.includes(workspaceKey)) throw new ServiceError("FORBIDDEN", `session "${sessionId}" is outside the authorized workspace scope`, { sessionId });
|
|
2647
|
+
}
|
|
2648
|
+
}
|
|
2649
|
+
async function summaryWithinScope(deps, context, summary) {
|
|
2650
|
+
const scope = context.workspaceScope;
|
|
2651
|
+
if (scope === void 0 || scope === "*") return summary;
|
|
2652
|
+
const entries = [];
|
|
2653
|
+
let totalCost = 0;
|
|
2654
|
+
for (const entry of summary.entries) {
|
|
2655
|
+
const workspaceKey = await workspaceOfSession(deps, entry.sessionId);
|
|
2656
|
+
if (workspaceKey === void 0 || !scope.includes(workspaceKey)) continue;
|
|
2657
|
+
entries.push(entry);
|
|
2658
|
+
totalCost += entry.cost;
|
|
2659
|
+
}
|
|
2660
|
+
return {
|
|
2661
|
+
totalCost: Number(totalCost.toFixed(6)),
|
|
2662
|
+
entries
|
|
2663
|
+
};
|
|
2664
|
+
}
|
|
2665
|
+
function isUiActivityFact(value) {
|
|
2666
|
+
if (typeof value !== "object" || value === null) return false;
|
|
2667
|
+
const fact = value;
|
|
2668
|
+
return typeof fact.kind === "string" && typeof fact.name === "string" && typeof fact.at === "number";
|
|
2669
|
+
}
|
|
2670
|
+
function workspaceRoutes(deps) {
|
|
2671
|
+
function jobsPortOrFail() {
|
|
2672
|
+
if (deps.jobsPort === void 0) throw new ServiceError("NOT_HANDLED", "jobs.* requires a worker jobs port");
|
|
2673
|
+
return deps.jobsPort;
|
|
2674
|
+
}
|
|
2675
|
+
return defineRoutes("service:workspace", {
|
|
2676
|
+
"workspace.list": route("workspace.list", true, globalTarget, async () => {
|
|
2677
|
+
if (!deps.dataSource.listWorkspaces) throw new ServiceError("NOT_HANDLED", "listWorkspaces is not supported by this data source");
|
|
2678
|
+
return { workspaces: await deps.dataSource.listWorkspaces() };
|
|
2679
|
+
}),
|
|
2680
|
+
"workspace.placement": route("workspace.placement", true, globalTarget, async () => ({ workers: [] })),
|
|
2681
|
+
"assembly.diagnostics": route("assembly.diagnostics", true, globalTarget, async () => {
|
|
2682
|
+
return { entries: deps.assemblyDiagnostics?.() ?? [] };
|
|
2683
|
+
}),
|
|
2684
|
+
"assembly.performanceDiagnostics": route("assembly.performanceDiagnostics", true, globalTarget, async () => {
|
|
2685
|
+
return deps.performanceDiagnostics?.() ?? void 0;
|
|
2686
|
+
}),
|
|
2687
|
+
"workspace.readiness": route("workspace.readiness", true, byWorkspace, async (payload) => {
|
|
2688
|
+
const raw = payload;
|
|
2689
|
+
if (typeof raw?.workspaceKey !== "string" || raw.workspaceKey === "") throw new ServiceError("INVALID_INPUT", "workspace.readiness requires workspaceKey");
|
|
2690
|
+
if (!deps.dataSource.listWorkspaces) throw new ServiceError("NOT_HANDLED", "listWorkspaces is not supported by this data source");
|
|
2691
|
+
if ((await deps.dataSource.listWorkspaces()).find((workspace) => workspace.key === raw.workspaceKey) === void 0) throw new ServiceError("INVALID_REQUEST", `unknown workspace "${raw.workspaceKey}"`);
|
|
2692
|
+
return {
|
|
2693
|
+
workspaceKey: raw.workspaceKey,
|
|
2694
|
+
state: deps.workspaceReadiness?.(raw.workspaceKey) ?? "loading"
|
|
2695
|
+
};
|
|
2696
|
+
}),
|
|
2697
|
+
"view.frame": route("view.frame", false, byWorkspaceWithEpoch, async (payload) => {
|
|
2698
|
+
const input = payload;
|
|
2699
|
+
if (input.workspaceKey === void 0 || input.workspaceKey === "") throw new ServiceError("INVALID_REQUEST", "view.frame requires an explicit workspaceKey");
|
|
2700
|
+
if (!deps.dataSource.viewFrame) throw new ServiceError("NOT_HANDLED", "viewFrame is not supported by this data source");
|
|
2701
|
+
return deps.dataSource.viewFrame(input);
|
|
2702
|
+
}),
|
|
2703
|
+
"view.input": route("view.input", false, byWorkspaceWithEpoch, async (payload) => {
|
|
2704
|
+
const input = payload;
|
|
2705
|
+
if (input.workspaceKey === void 0 || input.workspaceKey === "") throw new ServiceError("INVALID_REQUEST", "view.input requires an explicit workspaceKey");
|
|
2706
|
+
if (!deps.dataSource.viewInput) throw new ServiceError("NOT_HANDLED", "viewInput is not supported by this data source");
|
|
2707
|
+
return deps.dataSource.viewInput(input);
|
|
2708
|
+
}),
|
|
2709
|
+
"view.close": route("view.close", false, byWorkspaceWithEpoch, async (payload) => {
|
|
2710
|
+
const input = payload;
|
|
2711
|
+
if (input.workspaceKey === void 0 || input.workspaceKey === "") throw new ServiceError("INVALID_REQUEST", "view.close requires an explicit workspaceKey");
|
|
2712
|
+
if (!deps.dataSource.viewClose) throw new ServiceError("NOT_HANDLED", "viewClose is not supported by this data source");
|
|
2713
|
+
return deps.dataSource.viewClose(input);
|
|
2714
|
+
}),
|
|
2715
|
+
"ui.activity.record": route("ui.activity.record", false, globalTarget, async (payload) => {
|
|
2716
|
+
const fact = payload?.fact;
|
|
2717
|
+
if (!isUiActivityFact(fact)) throw new ServiceError("INVALID_INPUT", "ui.activity.record requires { fact: { kind, name, at } }");
|
|
2718
|
+
if (!deps.dataSource.recordUiActivity) throw new ServiceError("NOT_HANDLED", "recordUiActivity is not supported by this data source");
|
|
2719
|
+
return { delivered: deps.dataSource.recordUiActivity(fact) };
|
|
2720
|
+
}),
|
|
2721
|
+
"ui.catalog": route("ui.catalog", true, byWorkspaceOrGlobal, async (payload) => {
|
|
2722
|
+
const host = requireUiHost(payload, "ui.catalog");
|
|
2723
|
+
const workspaceKey = optionalWorkspaceKey(payload, "ui.catalog");
|
|
2724
|
+
if (!deps.dataSource.uiCatalog) throw new ServiceError("NOT_HANDLED", "uiCatalog is not supported by this data source");
|
|
2725
|
+
return await deps.dataSource.uiCatalog(host, workspaceKey);
|
|
2726
|
+
}),
|
|
2727
|
+
"command.catalog": route("command.catalog", true, globalTarget, async (payload) => {
|
|
2728
|
+
const input = payload;
|
|
2729
|
+
const surfaces = Array.isArray(input?.surfaces) ? input.surfaces.filter((surface) => typeof surface === "string") : void 0;
|
|
2730
|
+
if (!deps.dataSource.commandCatalog) throw new ServiceError("NOT_HANDLED", "command catalog is not supported by this data source");
|
|
2731
|
+
return await deps.dataSource.commandCatalog(surfaces === void 0 ? {} : { surfaces });
|
|
2732
|
+
}),
|
|
2733
|
+
"command.run": route("command.run", false, globalTarget, async (payload) => {
|
|
2734
|
+
const input = payload;
|
|
2735
|
+
if (!Array.isArray(input.path) || input.path.some((segment) => typeof segment !== "string")) throw new ServiceError("INVALID_INPUT", "command.run requires a path of strings");
|
|
2736
|
+
const argumentList = Array.isArray(input.argumentList) ? input.argumentList.filter((item) => typeof item === "string") : void 0;
|
|
2737
|
+
const entry = {
|
|
2738
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2739
|
+
method: "command.run",
|
|
2740
|
+
path: input.path,
|
|
2741
|
+
argumentList
|
|
2742
|
+
};
|
|
2743
|
+
const record = async (outcome) => {
|
|
2744
|
+
try {
|
|
2745
|
+
await deps.dataSource.auditCommand?.({
|
|
2746
|
+
...entry,
|
|
2747
|
+
accepted: outcome.accepted,
|
|
2748
|
+
reason: outcome.reason
|
|
2749
|
+
});
|
|
2750
|
+
} catch {}
|
|
2751
|
+
};
|
|
2752
|
+
if (!deps.dataSource.runCommand) {
|
|
2753
|
+
await record({
|
|
2754
|
+
accepted: false,
|
|
2755
|
+
reason: "not-handled"
|
|
2756
|
+
});
|
|
2757
|
+
throw new ServiceError("NOT_HANDLED", "command run is not supported by this data source");
|
|
2758
|
+
}
|
|
2759
|
+
const sessionId = typeof input.sessionId === "string" ? input.sessionId : void 0;
|
|
2760
|
+
const surface = input.surface === "tui" || input.surface === "cli" || input.surface === "web" ? input.surface : void 0;
|
|
2761
|
+
const outcome = await deps.dataSource.runCommand({
|
|
2762
|
+
path: input.path,
|
|
2763
|
+
...argumentList === void 0 ? {} : { argumentList },
|
|
2764
|
+
...sessionId === void 0 ? {} : { sessionId },
|
|
2765
|
+
...surface === void 0 ? {} : { surface }
|
|
2766
|
+
});
|
|
2767
|
+
await record(outcome);
|
|
2768
|
+
return outcome;
|
|
2769
|
+
}),
|
|
2770
|
+
"mention.search": route("mention.search", true, globalTarget, async (payload) => {
|
|
2771
|
+
const input = payload;
|
|
2772
|
+
if (typeof input.query !== "string") throw new ServiceError("INVALID_INPUT", "mention.search requires a query string");
|
|
2773
|
+
if (!deps.dataSource.mentionSearch) throw new ServiceError("NOT_HANDLED", "mention search is not supported by this data source");
|
|
2774
|
+
const kind = typeof input.kind === "string" ? input.kind : void 0;
|
|
2775
|
+
const limit = typeof input.limit === "number" ? input.limit : void 0;
|
|
2776
|
+
return await deps.dataSource.mentionSearch({
|
|
2777
|
+
query: input.query,
|
|
2778
|
+
...kind === void 0 ? {} : { kind },
|
|
2779
|
+
...limit === void 0 ? {} : { limit }
|
|
2780
|
+
});
|
|
2781
|
+
}),
|
|
2782
|
+
"env.snapshot": route("env.snapshot", false, globalTarget, async (payload) => {
|
|
2783
|
+
const input = payload;
|
|
2784
|
+
const names = Array.isArray(input?.names) ? input.names.filter((name) => typeof name === "string") : [];
|
|
2785
|
+
const snapshot = deps.envSnapshotOf?.(names);
|
|
2786
|
+
if (snapshot === void 0) throw new ServiceError("NOT_HANDLED", "env.snapshot requires an env port");
|
|
2787
|
+
return snapshot;
|
|
2788
|
+
}),
|
|
2789
|
+
"ui.preferences.get": route("ui.preferences.get", true, globalTarget, async () => {
|
|
2790
|
+
if (!deps.dataSource.uiPreferencesGet) throw new ServiceError("NOT_HANDLED", "uiPreferencesGet is not supported by this data source");
|
|
2791
|
+
return await deps.dataSource.uiPreferencesGet();
|
|
2792
|
+
}),
|
|
2793
|
+
"ui.preferences.set": route("ui.preferences.set", false, globalTarget, async (payload) => {
|
|
2794
|
+
const patch = parseWebLayoutPreferences(payload);
|
|
2795
|
+
if (patch === void 0) throw new ServiceError("INVALID_INPUT", "ui.preferences.set requires a preferences object");
|
|
2796
|
+
if (!deps.dataSource.uiPreferencesSet) throw new ServiceError("NOT_HANDLED", "uiPreferencesSet is not supported by this data source");
|
|
2797
|
+
return await deps.dataSource.uiPreferencesSet(patch);
|
|
2798
|
+
}),
|
|
2799
|
+
"perf.residency": route("perf.residency", true, globalTarget, async () => {
|
|
2800
|
+
if (!deps.dataSource.residencyPerf) throw new ServiceError("NOT_HANDLED", "residencyPerf is not supported by this data source");
|
|
2801
|
+
return await deps.dataSource.residencyPerf();
|
|
2802
|
+
}),
|
|
2803
|
+
"resource.read": route("resource.read", true, bySession, async (payload) => {
|
|
2804
|
+
const sessionId = requireSessionId$1(payload, "resource.read");
|
|
2805
|
+
const source = sourceForSession(deps, sessionId);
|
|
2806
|
+
const rawAddress = payload?.address;
|
|
2807
|
+
if (typeof rawAddress !== "string" || rawAddress === "") throw new ServiceError("INVALID_INPUT", "resource.read requires address");
|
|
2808
|
+
parseResourceAddress(rawAddress);
|
|
2809
|
+
if (!source.resourceRead) throw new ServiceError("NOT_HANDLED", "resourceRead is not supported by this data source");
|
|
2810
|
+
return await source.resourceRead({
|
|
2811
|
+
sessionId,
|
|
2812
|
+
address: rawAddress
|
|
2813
|
+
});
|
|
2814
|
+
}),
|
|
2815
|
+
"space.catalog": route("space.catalog", true, byWorkspaceOrGlobal, async (payload) => {
|
|
2816
|
+
const workspaceKey = optionalWorkspaceKey(payload, "space.catalog");
|
|
2817
|
+
if (workspaceKey !== void 0 && deps.spaceCatalogPortOf === void 0 && deps.workspaceKeyOfRuntime?.() !== workspaceKey) throw new ServiceError("WORKSPACE_NOT_FOUND", `space.catalog: this runtime does not serve workspace "${workspaceKey}"`, { workspaceKey });
|
|
2818
|
+
if (workspaceKey !== void 0 && deps.spaceCatalogPortOf !== void 0) {
|
|
2819
|
+
const scoped = deps.spaceCatalogPortOf(workspaceKey);
|
|
2820
|
+
if (scoped === void 0) throw new ServiceError("WORKSPACE_NOT_FOUND", `space.catalog: no workspace runtime for "${workspaceKey}"`, { workspaceKey });
|
|
2821
|
+
return scoped.catalog();
|
|
2822
|
+
}
|
|
2823
|
+
return requirePort(deps.spaceCatalogPort, "space.catalog").catalog();
|
|
2824
|
+
}),
|
|
2825
|
+
"provider.fallback": route("provider.fallback", false, globalTarget, async () => requirePort(deps.providerFallbackPort, "provider.fallback").state()),
|
|
2826
|
+
"memory.entries": route("memory.entries", true, globalTarget, async (input) => {
|
|
2827
|
+
const cwd = requireName(input, "cwd", "memory.entries");
|
|
2828
|
+
return { entries: await requirePort(deps.memoryEntriesPort, "memory.entries").list(cwd) };
|
|
2829
|
+
}),
|
|
2830
|
+
"memory.read": route("memory.read", true, globalTarget, async (input) => {
|
|
2831
|
+
const cwd = requireName(input, "cwd", "memory.read");
|
|
2832
|
+
const name = requireName(input, "name", "memory.read");
|
|
2833
|
+
return { content: await requirePort(deps.memoryEntriesPort, "memory.read").read(name, cwd) };
|
|
2834
|
+
}),
|
|
2835
|
+
"updates.status": route("updates.status", true, globalTarget, async () => ({ status: requirePort(deps.updatesPort, "updates.status").status() })),
|
|
2836
|
+
"updates.check": route("updates.check", false, globalTarget, async (input) => {
|
|
2837
|
+
const force = input?.force;
|
|
2838
|
+
if (force !== void 0 && typeof force !== "boolean") throw new ServiceError("INVALID_INPUT", "updates.check force must be a boolean");
|
|
2839
|
+
return { candidates: await requirePort(deps.updatesPort, "updates.check").check(force === void 0 ? void 0 : { force }) };
|
|
2840
|
+
}),
|
|
2841
|
+
"cost.summary": route("cost.summary", true, bySessionOrGlobal, async (input, context) => {
|
|
2842
|
+
const sessionId = input?.sessionId;
|
|
2843
|
+
if (sessionId !== void 0 && typeof sessionId !== "string") throw new ServiceError("INVALID_INPUT", "cost.summary sessionId must be a string");
|
|
2844
|
+
const sessionIds = input?.sessionIds;
|
|
2845
|
+
const backfill = input?.backfill;
|
|
2846
|
+
const port = requirePort(deps.costSummaryPort, "cost.summary");
|
|
2847
|
+
if (sessionIds !== void 0) {
|
|
2848
|
+
if (sessionId !== void 0) throw new ServiceError("INVALID_INPUT", "cost.summary takes sessionId or sessionIds, not both");
|
|
2849
|
+
if (!Array.isArray(sessionIds) || sessionIds.some((id) => typeof id !== "string")) throw new ServiceError("INVALID_INPUT", "cost.summary sessionIds must be a string array");
|
|
2850
|
+
if (port.summaryOf === void 0) throw new ServiceError("NOT_HANDLED", "cost.summary does not support sessionIds");
|
|
2851
|
+
await assertSessionsWithinScope(deps, context, sessionIds);
|
|
2852
|
+
return await port.summaryOf(sessionIds);
|
|
2853
|
+
}
|
|
2854
|
+
const summary = await port.summary(sessionId, { allowBackfill: context.follow !== true && backfill !== false });
|
|
2855
|
+
return sessionId === void 0 ? await summaryWithinScope(deps, context, summary) : summary;
|
|
2856
|
+
}),
|
|
2857
|
+
"trust.query": route("trust.query", false, globalTarget, async (input) => {
|
|
2858
|
+
const port = deps.trustPort;
|
|
2859
|
+
if (port === void 0) throw new ServiceError("NOT_HANDLED", "trust.query requires a worker trust port");
|
|
2860
|
+
const root = input?.root;
|
|
2861
|
+
if (typeof root !== "string" || root === "") throw new ServiceError("INVALID_INPUT", "trust.query requires { root }");
|
|
2862
|
+
const record = await port.query(root);
|
|
2863
|
+
return record === void 0 ? {} : { record };
|
|
2864
|
+
}),
|
|
2865
|
+
"jobs.list": route("jobs.list", true, globalTarget, async (input) => {
|
|
2866
|
+
const port = jobsPortOrFail();
|
|
2867
|
+
const caller = input?.caller;
|
|
2868
|
+
return { jobs: await port.list(typeof caller === "string" ? caller : void 0) };
|
|
2869
|
+
}),
|
|
2870
|
+
"jobs.read": route("jobs.read", true, globalTarget, async (input) => {
|
|
2871
|
+
const port = jobsPortOrFail();
|
|
2872
|
+
const typed = input;
|
|
2873
|
+
if (typeof typed?.id !== "string" || typed.id === "") throw new ServiceError("INVALID_INPUT", "jobs.read requires { id }");
|
|
2874
|
+
if (port.read === void 0) throw new ServiceError("NOT_HANDLED", "jobs.read is not supported by this host");
|
|
2875
|
+
return { output: await port.read(typed.id, typeof typed.caller === "string" ? typed.caller : void 0) };
|
|
2876
|
+
}),
|
|
2877
|
+
"jobs.kill": route("jobs.kill", false, globalTarget, async (input) => {
|
|
2878
|
+
const port = jobsPortOrFail();
|
|
2879
|
+
const typed = input;
|
|
2880
|
+
if (typeof typed?.id !== "string" || typed.id === "") throw new ServiceError("INVALID_INPUT", "jobs.kill requires { id }");
|
|
2881
|
+
try {
|
|
2882
|
+
await port.kill(typed.id, typeof typed.caller === "string" ? typed.caller : void 0);
|
|
2883
|
+
return { killed: true };
|
|
2884
|
+
} catch (error) {
|
|
2885
|
+
return {
|
|
2886
|
+
killed: false,
|
|
2887
|
+
error: error instanceof Error ? error.message : String(error)
|
|
2888
|
+
};
|
|
2889
|
+
}
|
|
2890
|
+
})
|
|
2891
|
+
});
|
|
2892
|
+
}
|
|
2893
|
+
|
|
2894
|
+
//#endregion
|
|
2895
|
+
//#region src/routes/worker-routes.ts
|
|
2896
|
+
function unmergedStub(method) {
|
|
2897
|
+
return async () => {
|
|
2898
|
+
throw new ServiceError("NOT_HANDLED", `no handler for type: ${method}`);
|
|
2899
|
+
};
|
|
2900
|
+
}
|
|
2901
|
+
const workerRouteSet = defineRoutes("service:worker", {
|
|
2902
|
+
"worker.lifecycle": route("worker.lifecycle", true, globalTarget, unmergedStub("worker.lifecycle")),
|
|
2903
|
+
"worker.restart.prepare": route("worker.restart.prepare", false, globalTarget, unmergedStub("worker.restart.prepare")),
|
|
2904
|
+
"worker.restart.status": route("worker.restart.status", true, globalTarget, unmergedStub("worker.restart.status")),
|
|
2905
|
+
"worker.restart.resume": route("worker.restart.resume", false, globalTarget, unmergedStub("worker.restart.resume")),
|
|
2906
|
+
"worker.restart.cancel": route("worker.restart.cancel", false, globalTarget, unmergedStub("worker.restart.cancel")),
|
|
2907
|
+
"worker.exit": route("worker.exit", false, globalTarget, unmergedStub("worker.exit"))
|
|
2908
|
+
});
|
|
2909
|
+
|
|
2910
|
+
//#endregion
|
|
2911
|
+
//#region src/routes/repository-meta.ts
|
|
2912
|
+
function repositoryMetaStub(method) {
|
|
2913
|
+
return async () => {
|
|
2914
|
+
throw new ServiceError("NOT_HANDLED", `no handler for type: ${method}`);
|
|
2915
|
+
};
|
|
2916
|
+
}
|
|
2917
|
+
const repositoryRouteSet = defineRoutes("service:repository", {
|
|
2918
|
+
"repository.capabilities": route("repository.capabilities", true, globalTarget, repositoryMetaStub("repository.capabilities")),
|
|
2919
|
+
"repository.recovery.capabilities": route("repository.recovery.capabilities", true, globalTarget, repositoryMetaStub("repository.recovery.capabilities")),
|
|
2920
|
+
"repository.recovery.save": route("repository.recovery.save", false, bySession, repositoryMetaStub("repository.recovery.save")),
|
|
2921
|
+
"repository.recovery.get": route("repository.recovery.get", true, bySession, repositoryMetaStub("repository.recovery.get")),
|
|
2922
|
+
"repository.recovery.list": route("repository.recovery.list", true, bySession, repositoryMetaStub("repository.recovery.list")),
|
|
2923
|
+
"repository.recovery.remove": route("repository.recovery.remove", false, bySession, repositoryMetaStub("repository.recovery.remove")),
|
|
2924
|
+
"repository.saveMeta": route("repository.saveMeta", false, bySavedMeta, repositoryMetaStub("repository.saveMeta")),
|
|
2925
|
+
"repository.loadMeta": route("repository.loadMeta", true, bySession, repositoryMetaStub("repository.loadMeta")),
|
|
2926
|
+
"repository.list": route("repository.list", true, byListOptions, repositoryMetaStub("repository.list")),
|
|
2927
|
+
"repository.purge": route("repository.purge", false, bySession, repositoryMetaStub("repository.purge")),
|
|
2928
|
+
"repository.appendEvents": route("repository.appendEvents", false, bySession, repositoryMetaStub("repository.appendEvents")),
|
|
2929
|
+
"repository.readEvents": route("repository.readEvents", true, bySession, repositoryMetaStub("repository.readEvents")),
|
|
2930
|
+
"repository.readArchivedEvents": route("repository.readArchivedEvents", true, bySession, repositoryMetaStub("repository.readArchivedEvents")),
|
|
2931
|
+
"repository.countEvents": route("repository.countEvents", true, bySession, repositoryMetaStub("repository.countEvents")),
|
|
2932
|
+
"repository.truncateBefore": route("repository.truncateBefore", false, bySession, repositoryMetaStub("repository.truncateBefore")),
|
|
2933
|
+
"repository.archive": route("repository.archive", false, bySession, repositoryMetaStub("repository.archive")),
|
|
2934
|
+
"repository.restoreArchived": route("repository.restoreArchived", false, bySession, repositoryMetaStub("repository.restoreArchived")),
|
|
2935
|
+
"repository.releaseCache": route("repository.releaseCache", false, bySession, repositoryMetaStub("repository.releaseCache")),
|
|
2936
|
+
"repository.readCommitted": route("repository.readCommitted", true, bySession, repositoryMetaStub("repository.readCommitted")),
|
|
2937
|
+
"repository.committedNextSeq": route("repository.committedNextSeq", true, bySession, repositoryMetaStub("repository.committedNextSeq"))
|
|
2938
|
+
});
|
|
2939
|
+
|
|
2940
|
+
//#endregion
|
|
2941
|
+
//#region src/routes/index.ts
|
|
2942
|
+
function serviceRouteSets(deps, methodNames) {
|
|
2943
|
+
return [
|
|
2944
|
+
coreRoutes(deps, methodNames),
|
|
2945
|
+
sessionRoutes(deps),
|
|
2946
|
+
sessionRuntimeRoutes(deps),
|
|
2947
|
+
chatRoutes(deps, createSendAttemptTable()),
|
|
2948
|
+
askRoutes(deps),
|
|
2949
|
+
workspaceRoutes(deps),
|
|
2950
|
+
pluginRoutes(deps),
|
|
2951
|
+
settingsRoutes(deps),
|
|
2952
|
+
authRoutes(deps),
|
|
2953
|
+
extensionRoutes(deps)
|
|
2954
|
+
];
|
|
2955
|
+
}
|
|
2956
|
+
function metaRouteSets() {
|
|
2957
|
+
return [
|
|
2958
|
+
...serviceRouteSets({}, () => []),
|
|
2959
|
+
workerRouteSet,
|
|
2960
|
+
repositoryRouteSet
|
|
2961
|
+
];
|
|
2962
|
+
}
|
|
2963
|
+
const ROUTE_METHOD_META = methodMetaOf(metaRouteSets());
|
|
2964
|
+
for (const method of SERVICE_METHODS) if (ROUTE_METHOD_META[method] === void 0) throw new Error(`route meta missing for service method: ${method}`);
|
|
2965
|
+
for (const name of Object.keys(ROUTE_METHOD_META)) if (!SERVICE_METHODS.includes(name)) throw new Error(`route meta declares unknown service method: ${name}`);
|
|
2966
|
+
for (const method of READ_ONLY_SERVICE_METHODS) if (ROUTE_METHOD_META[method]?.readOnly !== true) throw new Error(`read-only projection lists a method its route does not mark readOnly: ${method}`);
|
|
2967
|
+
for (const name of Object.keys(ROUTE_METHOD_META)) if (ROUTE_METHOD_META[name]?.readOnly === true && !READ_ONLY_SERVICE_METHODS.has(name)) throw new Error(`route is readOnly but the read-only projection omits it: ${name}`);
|
|
2968
|
+
|
|
2969
|
+
//#endregion
|
|
2970
|
+
//#region src/route-targets.ts
|
|
2971
|
+
const ROUTE_TARGETS = Object.fromEntries(Object.entries(ROUTE_METHOD_META).map(([method, meta]) => [method, meta.target]));
|
|
2972
|
+
function routeTargetOf(action, payload) {
|
|
2973
|
+
const extract = ROUTE_TARGETS[action];
|
|
2974
|
+
return extract === void 0 ? {} : extract(payload);
|
|
2975
|
+
}
|
|
2976
|
+
|
|
2977
|
+
//#endregion
|
|
2978
|
+
//#region src/attached-writers.ts
|
|
2979
|
+
function createAttachedWritersRegistry() {
|
|
2980
|
+
const bySession = /* @__PURE__ */ new Map();
|
|
2981
|
+
return {
|
|
2982
|
+
attach(sessionId, writer) {
|
|
2983
|
+
let writers = bySession.get(sessionId);
|
|
2984
|
+
if (writers === void 0) {
|
|
2985
|
+
writers = /* @__PURE__ */ new Map();
|
|
2986
|
+
bySession.set(sessionId, writers);
|
|
2987
|
+
}
|
|
2988
|
+
writers.set(writer.connectionId, writer);
|
|
2989
|
+
return () => {
|
|
2990
|
+
const current = bySession.get(sessionId);
|
|
2991
|
+
if (current === void 0) return;
|
|
2992
|
+
current.delete(writer.connectionId);
|
|
2993
|
+
if (current.size === 0) bySession.delete(sessionId);
|
|
2994
|
+
};
|
|
2995
|
+
},
|
|
2996
|
+
writersOf(sessionId) {
|
|
2997
|
+
return [...bySession.get(sessionId)?.values() ?? []];
|
|
2998
|
+
}
|
|
2999
|
+
};
|
|
3000
|
+
}
|
|
3001
|
+
|
|
3002
|
+
//#endregion
|
|
3003
|
+
//#region src/ask-validate.ts
|
|
3004
|
+
const APPROVAL_SCOPES = [
|
|
3005
|
+
"once",
|
|
3006
|
+
"session",
|
|
3007
|
+
"project",
|
|
3008
|
+
"global"
|
|
3009
|
+
];
|
|
3010
|
+
function isRecord(value) {
|
|
3011
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
3012
|
+
}
|
|
3013
|
+
function isText(value) {
|
|
3014
|
+
return typeof value === "string" && value.length > 0;
|
|
3015
|
+
}
|
|
3016
|
+
function hasExactKeys(value, keys) {
|
|
3017
|
+
return Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));
|
|
3018
|
+
}
|
|
3019
|
+
function hasAllowedKeys(value, required, optional) {
|
|
3020
|
+
if (!required.every((key) => Object.hasOwn(value, key))) return false;
|
|
3021
|
+
return Object.keys(value).every((key) => required.includes(key) || optional.includes(key));
|
|
3022
|
+
}
|
|
3023
|
+
function parseApprovalScope(value) {
|
|
3024
|
+
return APPROVAL_SCOPES.find((scope) => scope === value);
|
|
3025
|
+
}
|
|
3026
|
+
function parseAskScope(value) {
|
|
3027
|
+
if (!isRecord(value)) return void 0;
|
|
3028
|
+
if (value.kind === "session" && hasExactKeys(value, ["kind", "sessionId"]) && isText(value.sessionId)) return {
|
|
3029
|
+
kind: "session",
|
|
3030
|
+
sessionId: value.sessionId
|
|
3031
|
+
};
|
|
3032
|
+
if (value.kind === "runtime" && hasExactKeys(value, ["kind", "runtimeEpoch"]) && isText(value.runtimeEpoch)) return {
|
|
3033
|
+
kind: "runtime",
|
|
3034
|
+
runtimeEpoch: value.runtimeEpoch
|
|
3035
|
+
};
|
|
3036
|
+
}
|
|
3037
|
+
function scopeKey(scope) {
|
|
3038
|
+
return scope.kind === "session" ? `s:${scope.sessionId}` : `r:${scope.runtimeEpoch}`;
|
|
3039
|
+
}
|
|
3040
|
+
function parseAskRef(value) {
|
|
3041
|
+
if (!isRecord(value) || !hasExactKeys(value, [
|
|
3042
|
+
"runtimeEpoch",
|
|
3043
|
+
"scope",
|
|
3044
|
+
"requestId"
|
|
3045
|
+
])) return void 0;
|
|
3046
|
+
const scope = parseAskScope(value.scope);
|
|
3047
|
+
if (scope === void 0 || !isText(value.runtimeEpoch) || !isText(value.requestId)) return void 0;
|
|
3048
|
+
return {
|
|
3049
|
+
runtimeEpoch: value.runtimeEpoch,
|
|
3050
|
+
scope,
|
|
3051
|
+
requestId: value.requestId
|
|
3052
|
+
};
|
|
3053
|
+
}
|
|
3054
|
+
function parsePermissionAskRef(value) {
|
|
3055
|
+
const ref = parseAskRef(value);
|
|
3056
|
+
if (ref === void 0 || ref.scope.kind !== "session") return void 0;
|
|
3057
|
+
return {
|
|
3058
|
+
runtimeEpoch: ref.runtimeEpoch,
|
|
3059
|
+
scope: ref.scope,
|
|
3060
|
+
requestId: ref.requestId
|
|
3061
|
+
};
|
|
3062
|
+
}
|
|
3063
|
+
function parsePermissionAskResponse(value) {
|
|
3064
|
+
if (!isRecord(value)) return void 0;
|
|
3065
|
+
if (typeof value.approved !== "boolean") return void 0;
|
|
3066
|
+
if (value.scope === void 0) return hasExactKeys(value, ["approved"]) ? { approved: value.approved } : void 0;
|
|
3067
|
+
const scope = parseApprovalScope(value.scope);
|
|
3068
|
+
if (scope === void 0 || !hasExactKeys(value, ["approved", "scope"])) return void 0;
|
|
3069
|
+
return {
|
|
3070
|
+
approved: value.approved,
|
|
3071
|
+
scope
|
|
3072
|
+
};
|
|
3073
|
+
}
|
|
3074
|
+
function parseHitlAnswer(value) {
|
|
3075
|
+
if (!isRecord(value) || !hasAllowedKeys(value, ["selectedOptionLabels", "freeform"], ["selectedOptionValues"])) return;
|
|
3076
|
+
if (typeof value.freeform !== "string" || !Array.isArray(value.selectedOptionLabels)) return void 0;
|
|
3077
|
+
const labels = [];
|
|
3078
|
+
for (const label of value.selectedOptionLabels) {
|
|
3079
|
+
if (typeof label !== "string") return void 0;
|
|
3080
|
+
labels.push(label);
|
|
3081
|
+
}
|
|
3082
|
+
if (value.selectedOptionValues !== void 0) {
|
|
3083
|
+
if (!Array.isArray(value.selectedOptionValues)) return void 0;
|
|
3084
|
+
const values = [];
|
|
3085
|
+
for (const item of value.selectedOptionValues) {
|
|
3086
|
+
if (typeof item !== "string") return void 0;
|
|
3087
|
+
values.push(item);
|
|
3088
|
+
}
|
|
3089
|
+
return {
|
|
3090
|
+
selectedOptionLabels: labels,
|
|
3091
|
+
freeform: value.freeform,
|
|
3092
|
+
selectedOptionValues: values
|
|
3093
|
+
};
|
|
3094
|
+
}
|
|
3095
|
+
return {
|
|
3096
|
+
selectedOptionLabels: labels,
|
|
3097
|
+
freeform: value.freeform
|
|
3098
|
+
};
|
|
3099
|
+
}
|
|
3100
|
+
function parseHitlReply(value) {
|
|
3101
|
+
if (!isRecord(value)) return void 0;
|
|
3102
|
+
if (value.kind === "cancel") return hasExactKeys(value, ["kind"]) ? { kind: "cancel" } : void 0;
|
|
3103
|
+
if (value.kind !== "answer" || !hasExactKeys(value, ["kind", "answer"])) return void 0;
|
|
3104
|
+
const answer = parseHitlAnswer(value.answer);
|
|
3105
|
+
return answer === void 0 ? void 0 : {
|
|
3106
|
+
kind: "answer",
|
|
3107
|
+
answer
|
|
3108
|
+
};
|
|
3109
|
+
}
|
|
3110
|
+
function parseAskOpenPayload(payload) {
|
|
3111
|
+
if (!isRecord(payload) || !hasExactKeys(payload, ["scope", "answer"])) return void 0;
|
|
3112
|
+
const scope = parseAskScope(payload.scope);
|
|
3113
|
+
if (scope === void 0 || typeof payload.answer !== "boolean") return void 0;
|
|
3114
|
+
return {
|
|
3115
|
+
scope,
|
|
3116
|
+
answer: payload.answer
|
|
3117
|
+
};
|
|
3118
|
+
}
|
|
3119
|
+
function parseAskScopePayload(payload) {
|
|
3120
|
+
if (!isRecord(payload) || !hasExactKeys(payload, ["scope"])) return void 0;
|
|
3121
|
+
return parseAskScope(payload.scope);
|
|
3122
|
+
}
|
|
3123
|
+
function parseApprovalRespondPayload(payload) {
|
|
3124
|
+
if (!isRecord(payload) || !hasExactKeys(payload, ["ref", "response"])) return void 0;
|
|
3125
|
+
const ref = parsePermissionAskRef(payload.ref);
|
|
3126
|
+
const response = parsePermissionAskResponse(payload.response);
|
|
3127
|
+
if (ref === void 0 || response === void 0) return void 0;
|
|
3128
|
+
return {
|
|
3129
|
+
ref,
|
|
3130
|
+
response
|
|
3131
|
+
};
|
|
3132
|
+
}
|
|
3133
|
+
function parseHitlRespondPayload(payload) {
|
|
3134
|
+
if (!isRecord(payload) || !hasExactKeys(payload, ["ref", "reply"])) return void 0;
|
|
3135
|
+
const ref = parseAskRef(payload.ref);
|
|
3136
|
+
const reply = parseHitlReply(payload.reply);
|
|
3137
|
+
if (ref === void 0 || reply === void 0) return void 0;
|
|
3138
|
+
return {
|
|
3139
|
+
ref,
|
|
3140
|
+
reply
|
|
3141
|
+
};
|
|
3142
|
+
}
|
|
3143
|
+
|
|
3144
|
+
//#endregion
|
|
3145
|
+
//#region src/handlers.ts
|
|
3146
|
+
const WORK_IDENTITY_V2$1 = "work-identity-v2";
|
|
3147
|
+
const WORK_IDENTITY_EXECUTE_TYPES = new Set([
|
|
3148
|
+
"chat.send",
|
|
3149
|
+
"session.deliver",
|
|
3150
|
+
"chat.submitIntent",
|
|
3151
|
+
"chat.steer",
|
|
3152
|
+
"chat.retryLastRound",
|
|
3153
|
+
"chat.retryAccelerate",
|
|
3154
|
+
"chat.resumeQueue",
|
|
3155
|
+
"chat.deferAwaitingResults",
|
|
3156
|
+
"chat.queue.promote"
|
|
3157
|
+
]);
|
|
3158
|
+
const ASK_ROUTE_TYPES = new Set([
|
|
3159
|
+
"ask.open",
|
|
3160
|
+
"ask.refresh",
|
|
3161
|
+
"ask.close",
|
|
3162
|
+
"approval.respond",
|
|
3163
|
+
"hitl.respond"
|
|
3164
|
+
]);
|
|
3165
|
+
const SESSION_WRITE_METHODS = new Set([
|
|
3166
|
+
"chat.send",
|
|
3167
|
+
"chat.submitIntent",
|
|
3168
|
+
"chat.steer",
|
|
3169
|
+
"chat.retryLastRound",
|
|
3170
|
+
"chat.continueWithPending",
|
|
3171
|
+
"chat.releaseAdmission",
|
|
3172
|
+
"chat.withdraw",
|
|
3173
|
+
"chat.queue.append",
|
|
3174
|
+
"chat.queue.remove",
|
|
3175
|
+
"chat.queue.clear",
|
|
3176
|
+
"chat.queue.promote",
|
|
3177
|
+
"chat.queue.update",
|
|
3178
|
+
"chat.queue.move",
|
|
3179
|
+
"chat.resumeQueue",
|
|
3180
|
+
"chat.discardDanglingInput",
|
|
3181
|
+
"chat.clear",
|
|
3182
|
+
"chat.compact",
|
|
3183
|
+
"session.rename",
|
|
3184
|
+
"session.pin",
|
|
3185
|
+
"session.permission.select"
|
|
3186
|
+
]);
|
|
3187
|
+
function writeTargetsOf(payload) {
|
|
3188
|
+
const input = payload;
|
|
3189
|
+
const targets = [];
|
|
3190
|
+
if (typeof input?.sessionId === "string" && input.sessionId !== "") targets.push(input.sessionId);
|
|
3191
|
+
if (Array.isArray(input?.sessionIds)) {
|
|
3192
|
+
for (const sessionId of input.sessionIds) if (typeof sessionId === "string" && sessionId !== "") targets.push(sessionId);
|
|
3193
|
+
}
|
|
3194
|
+
return targets;
|
|
3195
|
+
}
|
|
3196
|
+
function withinWorkspaceScope(result, context) {
|
|
3197
|
+
const scope = context.workspaceScope;
|
|
3198
|
+
if (scope === void 0 || scope === "*" || !Array.isArray(result)) return result;
|
|
3199
|
+
return result.filter((entry) => entry.workspaceKey !== void 0 && scope.includes(entry.workspaceKey));
|
|
3200
|
+
}
|
|
3201
|
+
function createHandlers(deps) {
|
|
3202
|
+
const attachedWriters = createAttachedWritersRegistry();
|
|
3203
|
+
const attachedWritersOf = deps.attachedWritersOf ?? ((sessionId) => attachedWriters.writersOf(sessionId));
|
|
3204
|
+
let composedRoutes;
|
|
3205
|
+
const methodNames = () => Object.keys(composedRoutes);
|
|
3206
|
+
const contributedSets = deps.routeSets?.() ?? [];
|
|
3207
|
+
composedRoutes = composeRoutes([...serviceRouteSets(deps, methodNames), ...contributedSets]);
|
|
3208
|
+
function clientSupportsWorkIdentityV2(context) {
|
|
3209
|
+
if (context.transport === "in-process") return true;
|
|
3210
|
+
return context.clientFeatures?.includes(WORK_IDENTITY_V2$1) === true;
|
|
3211
|
+
}
|
|
3212
|
+
async function assertWorkIdentityExecutable(type, payload, context) {
|
|
3213
|
+
if (!WORK_IDENTITY_EXECUTE_TYPES.has(type)) return;
|
|
3214
|
+
if (deps.dataSource.workIdentityV2 === void 0) return;
|
|
3215
|
+
const target = routeTargetOf(type, payload);
|
|
3216
|
+
if (target.sessionId === void 0) return;
|
|
3217
|
+
if (!await deps.dataSource.workIdentityV2(target.sessionId)) return;
|
|
3218
|
+
if (attachedWritersOf(target.sessionId).some((writer) => !writer.capable)) throw new ServiceError("FORBIDDEN", `${type}: session has attached clients without ${WORK_IDENTITY_V2$1}; new-capable clients stay read-only`);
|
|
3219
|
+
if (clientSupportsWorkIdentityV2(context)) return;
|
|
3220
|
+
throw new ServiceError("FORBIDDEN", `${type}: session requires ${WORK_IDENTITY_V2$1} (client did not declare it)`);
|
|
3221
|
+
}
|
|
3222
|
+
async function targetOf(type, payload, context) {
|
|
3223
|
+
const target = routeTargetOf(type, payload);
|
|
3224
|
+
if (context.workspaceScope === void 0 || context.workspaceScope === "*") return target;
|
|
3225
|
+
if (target.workspaceKey !== void 0 || target.sessionId === void 0) return target;
|
|
3226
|
+
const workspaceKey = await resolveWorkspace(target.sessionId);
|
|
3227
|
+
return workspaceKey === void 0 ? target : {
|
|
3228
|
+
...target,
|
|
3229
|
+
workspaceKey
|
|
3230
|
+
};
|
|
3231
|
+
}
|
|
3232
|
+
async function resolveWorkspace(sessionId) {
|
|
3233
|
+
if (deps.workspaceOf !== void 0) return deps.workspaceOf(sessionId);
|
|
3234
|
+
return (await deps.dataSource.sessionEntry?.(sessionId))?.workspaceKey;
|
|
3235
|
+
}
|
|
3236
|
+
async function assertSessionWritable(type, payload) {
|
|
3237
|
+
if (!SESSION_WRITE_METHODS.has(type)) return;
|
|
3238
|
+
const loadEntry = deps.dataSource.sessionEntry;
|
|
3239
|
+
if (loadEntry === void 0) return;
|
|
3240
|
+
for (const sessionId of writeTargetsOf(payload)) {
|
|
3241
|
+
const entry = await loadEntry.call(deps.dataSource, sessionId);
|
|
3242
|
+
if (entry === null) continue;
|
|
3243
|
+
const parentSessionId = entry.parentSessionId ?? entry.lineage?.parentSessionId;
|
|
3244
|
+
const access = sessionAccessStateOf({
|
|
3245
|
+
...entry.archived !== void 0 ? { archived: entry.archived } : {},
|
|
3246
|
+
...entry.visibility !== void 0 ? { visibility: entry.visibility } : {},
|
|
3247
|
+
...parentSessionId !== void 0 ? { parentSessionId } : {},
|
|
3248
|
+
...entry.readonlyCap === true ? { readonlyCap: true } : {}
|
|
3249
|
+
});
|
|
3250
|
+
if (access.mode === "write") continue;
|
|
3251
|
+
throw new ServiceError("SESSION_READONLY", `session "${sessionId}" is read-only (${access.reasons.join(", ")})`, {
|
|
3252
|
+
sessionId,
|
|
3253
|
+
reasons: access.reasons
|
|
3254
|
+
});
|
|
3255
|
+
}
|
|
3256
|
+
}
|
|
3257
|
+
const base = {
|
|
3258
|
+
attachedWriters,
|
|
3259
|
+
async handle(type, payload, context = ANONYMOUS_LOCAL_CONTEXT) {
|
|
3260
|
+
await deps.authorize(context, type, payload, await targetOf(type, payload, context));
|
|
3261
|
+
await assertWorkIdentityExecutable(type, payload, context);
|
|
3262
|
+
await assertSessionWritable(type, payload);
|
|
3263
|
+
const result = await runComposedRoute(composedRoutes, type, payload, context);
|
|
3264
|
+
return type === "session.list" ? withinWorkspaceScope(result, context) : result;
|
|
3265
|
+
},
|
|
3266
|
+
listTypes() {
|
|
3267
|
+
return Object.keys(composedRoutes).filter((name) => isServiceMethod(name));
|
|
3268
|
+
}
|
|
3269
|
+
};
|
|
3270
|
+
if (deps.extension !== void 0) {
|
|
3271
|
+
base.handleExtension = deps.extension.handleExtension.bind(deps.extension);
|
|
3272
|
+
if (deps.extension.bindExtension !== void 0) base.bindExtension = deps.extension.bindExtension.bind(deps.extension);
|
|
3273
|
+
}
|
|
3274
|
+
if (deps.askHost === void 0) return base;
|
|
3275
|
+
const askHost = deps.askHost;
|
|
3276
|
+
base.bindAsk = (peer, receive, onInvalidated) => {
|
|
3277
|
+
const views = /* @__PURE__ */ new Map();
|
|
3278
|
+
const connection = askHost.connect(peer, receive, (scope, reason) => {
|
|
3279
|
+
const key = scopeKey(scope);
|
|
3280
|
+
const view = views.get(key);
|
|
3281
|
+
if (view !== void 0) {
|
|
3282
|
+
views.delete(key);
|
|
3283
|
+
view.cancelled = true;
|
|
3284
|
+
view.subscription = void 0;
|
|
3285
|
+
view.opening = void 0;
|
|
3286
|
+
}
|
|
3287
|
+
onInvalidated?.(scope, reason);
|
|
3288
|
+
});
|
|
3289
|
+
return {
|
|
3290
|
+
async handle(type, payload, context = ANONYMOUS_LOCAL_CONTEXT) {
|
|
3291
|
+
if (ASK_ROUTE_TYPES.has(type)) await deps.authorize(context, type, payload, await targetOf(type, payload, context));
|
|
3292
|
+
switch (type) {
|
|
3293
|
+
case "ask.open": {
|
|
3294
|
+
const parsed = parseAskOpenPayload(payload);
|
|
3295
|
+
if (parsed === void 0) throw new ServiceError("INVALID_INPUT", "ask.open requires { scope, answer }");
|
|
3296
|
+
const key = scopeKey(parsed.scope);
|
|
3297
|
+
const existing = views.get(key);
|
|
3298
|
+
if (existing !== void 0) {
|
|
3299
|
+
if (existing.opening !== void 0) await existing.opening;
|
|
3300
|
+
return { opened: true };
|
|
3301
|
+
}
|
|
3302
|
+
const view = {
|
|
3303
|
+
subscription: void 0,
|
|
3304
|
+
opening: void 0,
|
|
3305
|
+
cancelled: false
|
|
3306
|
+
};
|
|
3307
|
+
views.set(key, view);
|
|
3308
|
+
const opening = connection.open(parsed.scope, { answer: parsed.answer }, receive);
|
|
3309
|
+
view.opening = opening;
|
|
3310
|
+
try {
|
|
3311
|
+
const subscription = await opening;
|
|
3312
|
+
if (view.cancelled || views.get(key) !== view) {
|
|
3313
|
+
subscription.close();
|
|
3314
|
+
return { opened: false };
|
|
3315
|
+
}
|
|
3316
|
+
view.subscription = subscription;
|
|
3317
|
+
return { opened: true };
|
|
3318
|
+
} catch (error) {
|
|
3319
|
+
if (views.get(key) === view) views.delete(key);
|
|
3320
|
+
throw error;
|
|
3321
|
+
}
|
|
3322
|
+
}
|
|
3323
|
+
case "ask.refresh": {
|
|
3324
|
+
const scope = parseAskScopePayload(payload);
|
|
3325
|
+
if (scope === void 0) throw new ServiceError("INVALID_INPUT", "ask.refresh requires { scope }");
|
|
3326
|
+
await connection.refresh(scope);
|
|
3327
|
+
return { refreshed: true };
|
|
3328
|
+
}
|
|
3329
|
+
case "ask.close": {
|
|
3330
|
+
const scope = parseAskScopePayload(payload);
|
|
3331
|
+
if (scope === void 0) throw new ServiceError("INVALID_INPUT", "ask.close requires { scope }");
|
|
3332
|
+
const key = scopeKey(scope);
|
|
3333
|
+
const view = views.get(key);
|
|
3334
|
+
if (view === void 0) return { closed: askHost.revoke(peer, scope, "closed") };
|
|
3335
|
+
views.delete(key);
|
|
3336
|
+
view.cancelled = true;
|
|
3337
|
+
const subscription = view.subscription;
|
|
3338
|
+
view.subscription = void 0;
|
|
3339
|
+
view.opening = void 0;
|
|
3340
|
+
subscription?.close();
|
|
3341
|
+
return { closed: true };
|
|
3342
|
+
}
|
|
3343
|
+
case "approval.respond": {
|
|
3344
|
+
const parsed = parseApprovalRespondPayload(payload);
|
|
3345
|
+
if (parsed === void 0) throw new ServiceError("INVALID_INPUT", "approval.respond requires { ref, response }");
|
|
3346
|
+
return connection.respond({
|
|
3347
|
+
channel: "permission",
|
|
3348
|
+
ref: parsed.ref,
|
|
3349
|
+
response: parsed.response
|
|
3350
|
+
});
|
|
3351
|
+
}
|
|
3352
|
+
case "hitl.respond": {
|
|
3353
|
+
const parsed = parseHitlRespondPayload(payload);
|
|
3354
|
+
if (parsed === void 0) throw new ServiceError("INVALID_INPUT", "hitl.respond requires { ref, reply }");
|
|
3355
|
+
return connection.respond({
|
|
3356
|
+
channel: "hitl",
|
|
3357
|
+
ref: parsed.ref,
|
|
3358
|
+
reply: parsed.reply
|
|
3359
|
+
});
|
|
3360
|
+
}
|
|
3361
|
+
default: return base.handle(type, payload, context);
|
|
3362
|
+
}
|
|
3363
|
+
},
|
|
3364
|
+
listTypes() {
|
|
3365
|
+
return base.listTypes();
|
|
3366
|
+
},
|
|
3367
|
+
...base.handleExtension === void 0 ? {} : { handleExtension: base.handleExtension.bind(base) },
|
|
3368
|
+
close() {
|
|
3369
|
+
for (const view of views.values()) {
|
|
3370
|
+
if (view.cancelled) continue;
|
|
3371
|
+
view.cancelled = true;
|
|
3372
|
+
view.subscription?.close();
|
|
3373
|
+
}
|
|
3374
|
+
views.clear();
|
|
3375
|
+
connection.close();
|
|
3376
|
+
}
|
|
3377
|
+
};
|
|
3378
|
+
};
|
|
3379
|
+
return base;
|
|
3380
|
+
}
|
|
3381
|
+
|
|
3382
|
+
//#endregion
|
|
3383
|
+
//#region src/wire.ts
|
|
3384
|
+
function toWireError(error) {
|
|
3385
|
+
if (error instanceof ServiceError) return {
|
|
3386
|
+
code: error.code,
|
|
3387
|
+
message: error.message,
|
|
3388
|
+
...error.details === void 0 ? {} : { details: error.details }
|
|
3389
|
+
};
|
|
3390
|
+
const coded = codedErrorOf(error);
|
|
3391
|
+
if (coded !== void 0) return {
|
|
3392
|
+
code: coded.code,
|
|
3393
|
+
message: error instanceof Error ? error.message : String(error),
|
|
3394
|
+
...coded.details === void 0 ? {} : { details: coded.details }
|
|
3395
|
+
};
|
|
3396
|
+
return {
|
|
3397
|
+
code: "INTERNAL",
|
|
3398
|
+
message: error instanceof Error ? error.message : String(error)
|
|
3399
|
+
};
|
|
3400
|
+
}
|
|
3401
|
+
function codedErrorOf(error) {
|
|
3402
|
+
if (typeof error !== "object" || error === null) return;
|
|
3403
|
+
const code = error.code;
|
|
3404
|
+
if (typeof code !== "string" || code === "") return;
|
|
3405
|
+
const details = error.details;
|
|
3406
|
+
return details === void 0 ? { code } : {
|
|
3407
|
+
code,
|
|
3408
|
+
details
|
|
3409
|
+
};
|
|
3410
|
+
}
|
|
3411
|
+
async function handleWireRequest(handlers, type, rawBody, context, fallbackId = "http") {
|
|
3412
|
+
const invalidInput = (id, message) => ({
|
|
3413
|
+
id,
|
|
3414
|
+
ok: false,
|
|
3415
|
+
error: {
|
|
3416
|
+
code: "INVALID_INPUT",
|
|
3417
|
+
message
|
|
3418
|
+
}
|
|
3419
|
+
});
|
|
3420
|
+
let wire;
|
|
3421
|
+
try {
|
|
3422
|
+
wire = JSON.parse(rawBody);
|
|
3423
|
+
} catch {
|
|
3424
|
+
return invalidInput(fallbackId, "request body must be JSON");
|
|
3425
|
+
}
|
|
3426
|
+
if (wire === null || typeof wire !== "object") return invalidInput(fallbackId, "request body must be a JSON object");
|
|
3427
|
+
const id = typeof wire.id === "string" ? wire.id : fallbackId;
|
|
3428
|
+
if (!isServiceMethod(type)) {
|
|
3429
|
+
if (handlers.handleExtension === void 0) return invalidInput(id, `unknown request type: ${type}`);
|
|
3430
|
+
try {
|
|
3431
|
+
return {
|
|
3432
|
+
id,
|
|
3433
|
+
ok: true,
|
|
3434
|
+
payload: await handlers.handleExtension({
|
|
3435
|
+
type,
|
|
3436
|
+
payload: wire.payload,
|
|
3437
|
+
contractVersion: wire.contractVersion
|
|
3438
|
+
}, context, "service")
|
|
3439
|
+
};
|
|
3440
|
+
} catch (error) {
|
|
3441
|
+
return {
|
|
3442
|
+
id,
|
|
3443
|
+
ok: false,
|
|
3444
|
+
error: toWireError(error)
|
|
3445
|
+
};
|
|
3446
|
+
}
|
|
3447
|
+
}
|
|
3448
|
+
try {
|
|
3449
|
+
return {
|
|
3450
|
+
id,
|
|
3451
|
+
ok: true,
|
|
3452
|
+
payload: await handlers.handle(type, wire.payload, context)
|
|
3453
|
+
};
|
|
3454
|
+
} catch (error) {
|
|
3455
|
+
return {
|
|
3456
|
+
id,
|
|
3457
|
+
ok: false,
|
|
3458
|
+
error: toWireError(error)
|
|
3459
|
+
};
|
|
3460
|
+
}
|
|
3461
|
+
}
|
|
3462
|
+
|
|
3463
|
+
//#endregion
|
|
3464
|
+
//#region src/wire-stats.ts
|
|
3465
|
+
const WIRE_STATS_STATE = Symbol.for("otto.service.wireStats");
|
|
3466
|
+
function emptyStats() {
|
|
3467
|
+
return {
|
|
3468
|
+
responseBytes: 0,
|
|
3469
|
+
responseCount: 0,
|
|
3470
|
+
restoreResponseBytes: 0,
|
|
3471
|
+
restoreMessagesBytes: 0,
|
|
3472
|
+
restoreEventsBytes: 0,
|
|
3473
|
+
restoreCount: 0,
|
|
3474
|
+
eventBytes: 0,
|
|
3475
|
+
eventCount: 0,
|
|
3476
|
+
responseSendFailures: 0,
|
|
3477
|
+
eventSendFailures: 0
|
|
3478
|
+
};
|
|
3479
|
+
}
|
|
3480
|
+
function stateOf() {
|
|
3481
|
+
const store = globalThis;
|
|
3482
|
+
const current = store[WIRE_STATS_STATE];
|
|
3483
|
+
if (typeof current === "object" && current !== null) return current;
|
|
3484
|
+
const created = {
|
|
3485
|
+
stats: emptyStats(),
|
|
3486
|
+
closeReasons: /* @__PURE__ */ new Map(),
|
|
3487
|
+
isRegistered: false
|
|
3488
|
+
};
|
|
3489
|
+
store[WIRE_STATS_STATE] = created;
|
|
3490
|
+
return created;
|
|
3491
|
+
}
|
|
3492
|
+
function ensureRegistered(state) {
|
|
3493
|
+
if (state.isRegistered) return;
|
|
3494
|
+
state.isRegistered = true;
|
|
3495
|
+
registerCapacityWireStatsProbe(() => wireStatsSnapshot());
|
|
3496
|
+
}
|
|
3497
|
+
function byteLengthOfJson(value) {
|
|
3498
|
+
if (value === void 0) return 0;
|
|
3499
|
+
try {
|
|
3500
|
+
return Buffer.byteLength(JSON.stringify(value), "utf8");
|
|
3501
|
+
} catch {
|
|
3502
|
+
return 0;
|
|
3503
|
+
}
|
|
3504
|
+
}
|
|
3505
|
+
function recordResponse(type, bytes, payload, isSent) {
|
|
3506
|
+
const state = stateOf();
|
|
3507
|
+
ensureRegistered(state);
|
|
3508
|
+
if (!isSent) {
|
|
3509
|
+
state.stats.responseSendFailures += 1;
|
|
3510
|
+
return;
|
|
3511
|
+
}
|
|
3512
|
+
state.stats.responseBytes += bytes;
|
|
3513
|
+
state.stats.responseCount += 1;
|
|
3514
|
+
if (type !== "session.restore" || typeof payload !== "object" || payload === null) return;
|
|
3515
|
+
const restored = payload;
|
|
3516
|
+
state.stats.restoreCount += 1;
|
|
3517
|
+
state.stats.restoreResponseBytes += bytes;
|
|
3518
|
+
state.stats.restoreMessagesBytes += byteLengthOfJson(restored.messages);
|
|
3519
|
+
state.stats.restoreEventsBytes += byteLengthOfJson(restored.events);
|
|
3520
|
+
}
|
|
3521
|
+
function recordEventDelivery(bytes, isSent) {
|
|
3522
|
+
const state = stateOf();
|
|
3523
|
+
ensureRegistered(state);
|
|
3524
|
+
if (!isSent) {
|
|
3525
|
+
state.stats.eventSendFailures += 1;
|
|
3526
|
+
return;
|
|
3527
|
+
}
|
|
3528
|
+
state.stats.eventBytes += bytes;
|
|
3529
|
+
state.stats.eventCount += 1;
|
|
3530
|
+
}
|
|
3531
|
+
function recordConnectionClose(reason) {
|
|
3532
|
+
const state = stateOf();
|
|
3533
|
+
ensureRegistered(state);
|
|
3534
|
+
state.closeReasons.set(reason, (state.closeReasons.get(reason) ?? 0) + 1);
|
|
3535
|
+
}
|
|
3536
|
+
function wireStatsSnapshot() {
|
|
3537
|
+
const state = stateOf();
|
|
3538
|
+
return {
|
|
3539
|
+
...state.stats,
|
|
3540
|
+
closeReasons: Object.fromEntries(state.closeReasons)
|
|
3541
|
+
};
|
|
3542
|
+
}
|
|
3543
|
+
|
|
3544
|
+
//#endregion
|
|
3545
|
+
//#region src/ws.ts
|
|
3546
|
+
const WORK_IDENTITY_V2 = "work-identity-v2";
|
|
3547
|
+
function eventWithinScope(context, event) {
|
|
3548
|
+
const workspaceKey = event.workspaceKey;
|
|
3549
|
+
return typeof workspaceKey !== "string" || targetWithinScope(context, { workspaceKey });
|
|
3550
|
+
}
|
|
3551
|
+
function eventWithinSubscription(allowed, event) {
|
|
3552
|
+
return allowed === void 0 || allowed.includes(event.kind);
|
|
3553
|
+
}
|
|
3554
|
+
function clientFeaturesOf(raw) {
|
|
3555
|
+
if (!Array.isArray(raw)) return;
|
|
3556
|
+
const features = raw.filter((item) => typeof item === "string");
|
|
3557
|
+
return features.length === 0 ? void 0 : features;
|
|
3558
|
+
}
|
|
3559
|
+
const WS_CLOSE_AUTH_REQUIRED = 4001;
|
|
3560
|
+
const WS_CLOSE_AUTH_FAILED = 4003;
|
|
3561
|
+
const AUTH_FRAME_TIMEOUT_MS = 1e4;
|
|
3562
|
+
const MAX_BUFFERED_BYTES = 4 * 1024 * 1024;
|
|
3563
|
+
const SERVER_CLOSE_GRACE_MS = 1e3;
|
|
3564
|
+
function send(ws, message, serialize) {
|
|
3565
|
+
if (ws.readyState !== WebSocket.OPEN) return 0;
|
|
3566
|
+
if (ws.bufferedAmount > MAX_BUFFERED_BYTES) return -1;
|
|
3567
|
+
const text = serialize(message);
|
|
3568
|
+
ws.send(text);
|
|
3569
|
+
return Buffer.byteLength(text, "utf8");
|
|
3570
|
+
}
|
|
3571
|
+
function wireErrorCodeOf(error) {
|
|
3572
|
+
if (typeof error !== "object" || error === null) return void 0;
|
|
3573
|
+
const code = error.code;
|
|
3574
|
+
return typeof code === "string" ? code : void 0;
|
|
3575
|
+
}
|
|
3576
|
+
async function sessionIsAuthorized(handlers, sessionId, context) {
|
|
3577
|
+
const scope = context?.workspaceScope;
|
|
3578
|
+
const scoped = scope !== void 0 && scope !== "*";
|
|
3579
|
+
if (!handlers.listTypes().includes("repository.loadMeta")) {
|
|
3580
|
+
if (!scoped) return true;
|
|
3581
|
+
try {
|
|
3582
|
+
await handlers.handle("session.entry", { sessionId }, context);
|
|
3583
|
+
return true;
|
|
3584
|
+
} catch {
|
|
3585
|
+
return false;
|
|
3586
|
+
}
|
|
3587
|
+
}
|
|
3588
|
+
try {
|
|
3589
|
+
const loaded = await handlers.handle("repository.loadMeta", { sessionId }, context);
|
|
3590
|
+
return !scoped || (loaded?.meta ?? null) !== null;
|
|
3591
|
+
} catch (error) {
|
|
3592
|
+
if (wireErrorCodeOf(error) !== "FORBIDDEN") console.warn(JSON.stringify({
|
|
3593
|
+
event: "ws.session-authorization-unknown",
|
|
3594
|
+
sessionId,
|
|
3595
|
+
code: wireErrorCodeOf(error)
|
|
3596
|
+
}));
|
|
3597
|
+
return false;
|
|
3598
|
+
}
|
|
3599
|
+
}
|
|
3600
|
+
function createWebSocketManager(handlers, relay, options = {}) {
|
|
3601
|
+
const path = options.path ?? "/api/ws";
|
|
3602
|
+
const authToken = options.authToken;
|
|
3603
|
+
const principalId = options.principalId ?? "service-remote";
|
|
3604
|
+
const verify = createTokenVerifier({
|
|
3605
|
+
...authToken === void 0 ? {} : { authToken },
|
|
3606
|
+
...options.readToken === void 0 ? {} : { readToken: options.readToken },
|
|
3607
|
+
...options.ticketOf === void 0 ? {} : { ticketOf: options.ticketOf }
|
|
3608
|
+
});
|
|
3609
|
+
const heartbeatIntervalMs = options.heartbeatIntervalMs ?? 3e4;
|
|
3610
|
+
const heartbeatTimeoutMs = options.heartbeatTimeoutMs ?? 9e4;
|
|
3611
|
+
const authFrameTimeoutMs = options.authFrameTimeoutMs ?? AUTH_FRAME_TIMEOUT_MS;
|
|
3612
|
+
const wss = new WebSocketServer({ noServer: true });
|
|
3613
|
+
const connections = /* @__PURE__ */ new Map();
|
|
3614
|
+
let nextConnectionId = 0;
|
|
3615
|
+
let heartbeatTimer;
|
|
3616
|
+
const serializeForBroadcast = createSharedSerializer();
|
|
3617
|
+
function respond(ws, res, type) {
|
|
3618
|
+
const bytes = send(ws, res, serializeForBroadcast);
|
|
3619
|
+
const payload = res.ok ? res.payload : void 0;
|
|
3620
|
+
recordResponse(type ?? "", Math.max(0, bytes), payload, bytes >= 0);
|
|
3621
|
+
if (bytes < 0) {
|
|
3622
|
+
options.onResponseUndeliverable?.({
|
|
3623
|
+
type: type ?? "unknown",
|
|
3624
|
+
id: res.id
|
|
3625
|
+
});
|
|
3626
|
+
const state = connections.get(ws);
|
|
3627
|
+
if (state !== void 0) {
|
|
3628
|
+
closeState(state, "resync-required");
|
|
3629
|
+
return;
|
|
3630
|
+
}
|
|
3631
|
+
ws.close(4e3, "resync-required");
|
|
3632
|
+
}
|
|
3633
|
+
}
|
|
3634
|
+
function deliverOne(state, event) {
|
|
3635
|
+
const bytes = send(state.ws, event, serializeForBroadcast);
|
|
3636
|
+
recordEventDelivery(Math.max(0, bytes), bytes >= 0);
|
|
3637
|
+
if (bytes < 0) closeState(state, "resync-required");
|
|
3638
|
+
}
|
|
3639
|
+
function deliver(state, event) {
|
|
3640
|
+
if (!eventWithinScope(state.context, event) || !eventWithinSubscription(state.allowedEvents, event)) return;
|
|
3641
|
+
if (!isSessionMetaChangedEvent(event)) {
|
|
3642
|
+
deliverOne(state, event);
|
|
3643
|
+
return;
|
|
3644
|
+
}
|
|
3645
|
+
sessionIsAuthorized(handlers, event.targetSessionId, state.context).then((authorized) => {
|
|
3646
|
+
if (authorized) deliverOne(state, event);
|
|
3647
|
+
});
|
|
3648
|
+
}
|
|
3649
|
+
function closeState(state, reason) {
|
|
3650
|
+
state.closeReason = reason;
|
|
3651
|
+
state.bufferedAtClose = state.ws.bufferedAmount;
|
|
3652
|
+
if (state.ws.readyState === WebSocket.OPEN || state.ws.readyState === WebSocket.CONNECTING) {
|
|
3653
|
+
const code = reason === "auth-required" ? WS_CLOSE_AUTH_REQUIRED : reason === "auth-failed" ? WS_CLOSE_AUTH_FAILED : 4e3;
|
|
3654
|
+
state.ws.close(code, reason);
|
|
3655
|
+
} else state.ws.terminate();
|
|
3656
|
+
}
|
|
3657
|
+
function cleanupState(state, reason) {
|
|
3658
|
+
if (state.authTimer !== void 0) clearTimeout(state.authTimer);
|
|
3659
|
+
for (const detach of state.detachers.values()) detach();
|
|
3660
|
+
state.detachers.clear();
|
|
3661
|
+
for (const unsub of state.unsubs.values()) unsub();
|
|
3662
|
+
state.unsubs.clear();
|
|
3663
|
+
state.sessions.clear();
|
|
3664
|
+
state.extensionCleanup?.();
|
|
3665
|
+
state.extensionCleanup = void 0;
|
|
3666
|
+
state.ask?.close();
|
|
3667
|
+
connections.delete(state.ws);
|
|
3668
|
+
recordConnectionClose(reason);
|
|
3669
|
+
options.onConnectionClose?.({
|
|
3670
|
+
connectionId: state.connectionId,
|
|
3671
|
+
reason,
|
|
3672
|
+
bufferedBytes: state.bufferedAtClose,
|
|
3673
|
+
lastSeenAgoMs: Math.max(0, Date.now() - state.lastSeenAt),
|
|
3674
|
+
droppedFrames: state.droppedFrames,
|
|
3675
|
+
sessions: state.sessions.size
|
|
3676
|
+
});
|
|
3677
|
+
}
|
|
3678
|
+
function heartbeat() {
|
|
3679
|
+
if (heartbeatIntervalMs <= 0 || heartbeatTimeoutMs <= 0) return;
|
|
3680
|
+
const now = Date.now();
|
|
3681
|
+
for (const state of connections.values()) {
|
|
3682
|
+
if (now - state.lastSeenAt > heartbeatTimeoutMs) {
|
|
3683
|
+
options.onConnectionStale?.({
|
|
3684
|
+
connectionId: state.connectionId,
|
|
3685
|
+
lastSeenAt: state.lastSeenAt,
|
|
3686
|
+
now
|
|
3687
|
+
});
|
|
3688
|
+
closeState(state, "stale");
|
|
3689
|
+
continue;
|
|
3690
|
+
}
|
|
3691
|
+
if (state.ws.readyState === WebSocket.OPEN) state.ws.ping();
|
|
3692
|
+
}
|
|
3693
|
+
}
|
|
3694
|
+
function ensureHeartbeat() {
|
|
3695
|
+
if (heartbeatTimer !== void 0 || heartbeatIntervalMs <= 0 || heartbeatTimeoutMs <= 0) return;
|
|
3696
|
+
heartbeatTimer = setInterval(heartbeat, heartbeatIntervalMs);
|
|
3697
|
+
heartbeatTimer.unref?.();
|
|
3698
|
+
}
|
|
3699
|
+
function stopHeartbeat() {
|
|
3700
|
+
if (heartbeatTimer === void 0) return;
|
|
3701
|
+
clearInterval(heartbeatTimer);
|
|
3702
|
+
heartbeatTimer = void 0;
|
|
3703
|
+
}
|
|
3704
|
+
function headSeqOf(state, sessionId) {
|
|
3705
|
+
if (!handlers.listTypes().includes("repository.committedNextSeq")) return Promise.resolve(void 0);
|
|
3706
|
+
return handlers.handle("repository.committedNextSeq", { sessionId }, state.context).then((value) => {
|
|
3707
|
+
const nextSeq = value?.nextSeq;
|
|
3708
|
+
return typeof nextSeq === "number" && Number.isSafeInteger(nextSeq) && nextSeq >= 0 ? nextSeq : void 0;
|
|
3709
|
+
}, () => void 0);
|
|
3710
|
+
}
|
|
3711
|
+
function controlResponse(id, headSeq) {
|
|
3712
|
+
return {
|
|
3713
|
+
id,
|
|
3714
|
+
ok: true,
|
|
3715
|
+
payload: { headSeq: headSeq ?? null }
|
|
3716
|
+
};
|
|
3717
|
+
}
|
|
3718
|
+
async function subscribeSession(state, id, sessionId, sinceSeq) {
|
|
3719
|
+
if (!await sessionIsAuthorized(handlers, sessionId, state.context)) {
|
|
3720
|
+
respond(state.ws, {
|
|
3721
|
+
id,
|
|
3722
|
+
ok: false,
|
|
3723
|
+
error: {
|
|
3724
|
+
code: "FORBIDDEN",
|
|
3725
|
+
message: `session "${sessionId}" is outside the authorized scope`
|
|
3726
|
+
}
|
|
3727
|
+
});
|
|
3728
|
+
return;
|
|
3729
|
+
}
|
|
3730
|
+
if (state.sessions.has(sessionId)) {
|
|
3731
|
+
const existing = await readSubscriptionBackfill({
|
|
3732
|
+
handlers,
|
|
3733
|
+
sessionId,
|
|
3734
|
+
context: state.context,
|
|
3735
|
+
...sinceSeq === void 0 ? {} : { sinceSeq }
|
|
3736
|
+
});
|
|
3737
|
+
if (!existing.ok) {
|
|
3738
|
+
respond(state.ws, {
|
|
3739
|
+
id,
|
|
3740
|
+
ok: false,
|
|
3741
|
+
error: existing.error
|
|
3742
|
+
});
|
|
3743
|
+
return;
|
|
3744
|
+
}
|
|
3745
|
+
for (const event of existing.events ?? []) deliver(state, event);
|
|
3746
|
+
respond(state.ws, controlResponse(id, existing.headSeq ?? await headSeqOf(state, sessionId)));
|
|
3747
|
+
return;
|
|
3748
|
+
}
|
|
3749
|
+
const pending = [];
|
|
3750
|
+
let isBackfilling = true;
|
|
3751
|
+
const unsub = relay.subscribe(sessionId, (event) => {
|
|
3752
|
+
if (isBackfilling) {
|
|
3753
|
+
pending.push(event);
|
|
3754
|
+
return;
|
|
3755
|
+
}
|
|
3756
|
+
deliver(state, event);
|
|
3757
|
+
});
|
|
3758
|
+
state.sessions.add(sessionId);
|
|
3759
|
+
state.unsubs.set(sessionId, unsub);
|
|
3760
|
+
const backfill = await readSubscriptionBackfill({
|
|
3761
|
+
handlers,
|
|
3762
|
+
sessionId,
|
|
3763
|
+
context: state.context,
|
|
3764
|
+
...sinceSeq === void 0 ? {} : { sinceSeq }
|
|
3765
|
+
});
|
|
3766
|
+
if (!backfill.ok) {
|
|
3767
|
+
isBackfilling = false;
|
|
3768
|
+
pending.length = 0;
|
|
3769
|
+
unsub();
|
|
3770
|
+
state.sessions.delete(sessionId);
|
|
3771
|
+
state.unsubs.delete(sessionId);
|
|
3772
|
+
respond(state.ws, {
|
|
3773
|
+
id,
|
|
3774
|
+
ok: false,
|
|
3775
|
+
error: backfill.error
|
|
3776
|
+
});
|
|
3777
|
+
return;
|
|
3778
|
+
}
|
|
3779
|
+
for (const event of backfill.events ?? []) deliver(state, event);
|
|
3780
|
+
isBackfilling = false;
|
|
3781
|
+
for (const event of pending.splice(0)) deliver(state, event);
|
|
3782
|
+
const detach = state.context.follow === true ? void 0 : options.attachedWriters?.attach(sessionId, {
|
|
3783
|
+
connectionId: state.connectionId,
|
|
3784
|
+
capable: state.context.clientFeatures?.includes(WORK_IDENTITY_V2) === true
|
|
3785
|
+
});
|
|
3786
|
+
if (detach !== void 0) state.detachers.set(sessionId, detach);
|
|
3787
|
+
respond(state.ws, controlResponse(id, backfill.headSeq ?? await headSeqOf(state, sessionId)));
|
|
3788
|
+
}
|
|
3789
|
+
function handleMessage(state, data) {
|
|
3790
|
+
let message;
|
|
3791
|
+
try {
|
|
3792
|
+
message = JSON.parse(data);
|
|
3793
|
+
} catch {
|
|
3794
|
+
respond(state.ws, {
|
|
3795
|
+
id: "ws",
|
|
3796
|
+
ok: false,
|
|
3797
|
+
error: {
|
|
3798
|
+
code: "INVALID_INPUT",
|
|
3799
|
+
message: "message must be JSON"
|
|
3800
|
+
}
|
|
3801
|
+
});
|
|
3802
|
+
return;
|
|
3803
|
+
}
|
|
3804
|
+
if (typeof message !== "object" || message === null) {
|
|
3805
|
+
respond(state.ws, {
|
|
3806
|
+
id: "ws",
|
|
3807
|
+
ok: false,
|
|
3808
|
+
error: {
|
|
3809
|
+
code: "INVALID_INPUT",
|
|
3810
|
+
message: "message must be a JSON object"
|
|
3811
|
+
}
|
|
3812
|
+
});
|
|
3813
|
+
return;
|
|
3814
|
+
}
|
|
3815
|
+
const raw = message;
|
|
3816
|
+
const id = typeof raw.id === "string" ? raw.id : "ws";
|
|
3817
|
+
if (!state.authenticated) {
|
|
3818
|
+
if (raw.type !== "auth") {
|
|
3819
|
+
closeState(state, "auth-required");
|
|
3820
|
+
return;
|
|
3821
|
+
}
|
|
3822
|
+
const token = typeof raw.token === "string" ? raw.token : void 0;
|
|
3823
|
+
const verification = verify(token);
|
|
3824
|
+
if (verification === void 0) {
|
|
3825
|
+
closeState(state, "auth-failed");
|
|
3826
|
+
return;
|
|
3827
|
+
}
|
|
3828
|
+
const isReadToken = verification.channel === "read";
|
|
3829
|
+
const follow = raw.mode === "follow" || isReadToken;
|
|
3830
|
+
authenticate(state, token, follow && verification.credential.kind === "owner" ? { kind: "reader" } : verification.credential, clientFeaturesOf(raw.features), follow, isReadToken);
|
|
3831
|
+
respond(state.ws, {
|
|
3832
|
+
id,
|
|
3833
|
+
ok: true
|
|
3834
|
+
});
|
|
3835
|
+
return;
|
|
3836
|
+
}
|
|
3837
|
+
if (typeof raw.type !== "string") {
|
|
3838
|
+
respond(state.ws, {
|
|
3839
|
+
id,
|
|
3840
|
+
ok: false,
|
|
3841
|
+
error: {
|
|
3842
|
+
code: "INVALID_INPUT",
|
|
3843
|
+
message: "request.type must be a string"
|
|
3844
|
+
}
|
|
3845
|
+
});
|
|
3846
|
+
return;
|
|
3847
|
+
}
|
|
3848
|
+
if (options.requireHandshake === true && raw.type !== "service.handshake" && !state.handshaken) {
|
|
3849
|
+
respond(state.ws, {
|
|
3850
|
+
id,
|
|
3851
|
+
ok: false,
|
|
3852
|
+
error: toWireError(new RequestForbiddenError(raw.type, state.context.principalId))
|
|
3853
|
+
});
|
|
3854
|
+
return;
|
|
3855
|
+
}
|
|
3856
|
+
if (raw.type === "session.subscribe") {
|
|
3857
|
+
const sessionId = raw.payload?.sessionId;
|
|
3858
|
+
if (typeof sessionId !== "string" || sessionId === "") {
|
|
3859
|
+
respond(state.ws, {
|
|
3860
|
+
id,
|
|
3861
|
+
ok: false,
|
|
3862
|
+
error: {
|
|
3863
|
+
code: "INVALID_INPUT",
|
|
3864
|
+
message: "session.subscribe requires sessionId"
|
|
3865
|
+
}
|
|
3866
|
+
});
|
|
3867
|
+
return;
|
|
3868
|
+
}
|
|
3869
|
+
const sinceSeq = raw.payload?.sinceSeq;
|
|
3870
|
+
if (sinceSeq !== void 0 && (typeof sinceSeq !== "number" || !Number.isSafeInteger(sinceSeq) || sinceSeq < 0)) {
|
|
3871
|
+
respond(state.ws, {
|
|
3872
|
+
id,
|
|
3873
|
+
ok: false,
|
|
3874
|
+
error: {
|
|
3875
|
+
code: "INVALID_INPUT",
|
|
3876
|
+
message: "session.subscribe sinceSeq must be a non-negative integer"
|
|
3877
|
+
}
|
|
3878
|
+
});
|
|
3879
|
+
return;
|
|
3880
|
+
}
|
|
3881
|
+
subscribeSession(state, id, sessionId, sinceSeq);
|
|
3882
|
+
return;
|
|
3883
|
+
}
|
|
3884
|
+
if (raw.type === "session.unsubscribe") {
|
|
3885
|
+
const sessionId = raw.payload?.sessionId;
|
|
3886
|
+
if (typeof sessionId === "string") {
|
|
3887
|
+
state.sessions.delete(sessionId);
|
|
3888
|
+
const unsub = state.unsubs.get(sessionId);
|
|
3889
|
+
if (unsub) {
|
|
3890
|
+
unsub();
|
|
3891
|
+
state.unsubs.delete(sessionId);
|
|
3892
|
+
}
|
|
3893
|
+
state.detachers.get(sessionId)?.();
|
|
3894
|
+
state.detachers.delete(sessionId);
|
|
3895
|
+
}
|
|
3896
|
+
respond(state.ws, {
|
|
3897
|
+
id,
|
|
3898
|
+
ok: true
|
|
3899
|
+
});
|
|
3900
|
+
return;
|
|
3901
|
+
}
|
|
3902
|
+
const target = state.ask ?? handlers;
|
|
3903
|
+
if (!isServiceMethod(raw.type)) {
|
|
3904
|
+
if (target.handleExtension === void 0) {
|
|
3905
|
+
respond(state.ws, {
|
|
3906
|
+
id,
|
|
3907
|
+
ok: false,
|
|
3908
|
+
error: {
|
|
3909
|
+
code: "INVALID_INPUT",
|
|
3910
|
+
message: `unknown request type: ${raw.type}`
|
|
3911
|
+
}
|
|
3912
|
+
});
|
|
3913
|
+
return;
|
|
3914
|
+
}
|
|
3915
|
+
const extensionType = raw.type;
|
|
3916
|
+
target.handleExtension({
|
|
3917
|
+
type: extensionType,
|
|
3918
|
+
payload: raw.payload,
|
|
3919
|
+
contractVersion: raw.contractVersion
|
|
3920
|
+
}, state.context, "service").then((payload) => {
|
|
3921
|
+
respond(state.ws, {
|
|
3922
|
+
id,
|
|
3923
|
+
ok: true,
|
|
3924
|
+
payload
|
|
3925
|
+
}, extensionType);
|
|
3926
|
+
}).catch((error) => {
|
|
3927
|
+
respond(state.ws, {
|
|
3928
|
+
id,
|
|
3929
|
+
ok: false,
|
|
3930
|
+
error: toWireError(error)
|
|
3931
|
+
}, extensionType);
|
|
3932
|
+
});
|
|
3933
|
+
return;
|
|
3934
|
+
}
|
|
3935
|
+
if (!createConnectionBinding({ ...options.methodAllowList === void 0 ? {} : { methodAllowList: options.methodAllowList } }).allows(raw.type)) {
|
|
3936
|
+
respond(state.ws, {
|
|
3937
|
+
id,
|
|
3938
|
+
ok: false,
|
|
3939
|
+
error: toWireError(new RequestForbiddenError(raw.type, state.context.principalId))
|
|
3940
|
+
});
|
|
3941
|
+
return;
|
|
3942
|
+
}
|
|
3943
|
+
const method = raw.type;
|
|
3944
|
+
const payload = raw.type === "session.prepare" || raw.type === "session.releaseView" ? {
|
|
3945
|
+
...raw.payload,
|
|
3946
|
+
connectionId: state.connectionId
|
|
3947
|
+
} : raw.payload;
|
|
3948
|
+
target.handle(raw.type, payload, state.context).then((payload) => {
|
|
3949
|
+
if (raw.type === "service.handshake") state.handshaken = true;
|
|
3950
|
+
respond(state.ws, {
|
|
3951
|
+
id,
|
|
3952
|
+
ok: true,
|
|
3953
|
+
payload
|
|
3954
|
+
}, method);
|
|
3955
|
+
}).catch((error) => {
|
|
3956
|
+
respond(state.ws, {
|
|
3957
|
+
id,
|
|
3958
|
+
ok: false,
|
|
3959
|
+
error: toWireError(error)
|
|
3960
|
+
}, method);
|
|
3961
|
+
});
|
|
3962
|
+
}
|
|
3963
|
+
function authenticate(state, token, credential, clientFeatures, follow, isReadToken) {
|
|
3964
|
+
state.authenticated = true;
|
|
3965
|
+
if (state.authTimer !== void 0) {
|
|
3966
|
+
clearTimeout(state.authTimer);
|
|
3967
|
+
state.authTimer = void 0;
|
|
3968
|
+
}
|
|
3969
|
+
const readScope = typeof options.readTokenWorkspaceScope === "function" ? options.readTokenWorkspaceScope() : options.readTokenWorkspaceScope;
|
|
3970
|
+
const workspaceScope = isReadToken === true ? readScope : options.tokenWorkspaceScope;
|
|
3971
|
+
state.allowedEvents = eventsOfCredential(credential);
|
|
3972
|
+
state.context = contextFromToken(token, {
|
|
3973
|
+
transport: "ws",
|
|
3974
|
+
credential,
|
|
3975
|
+
...workspaceScope === void 0 || token === void 0 ? {} : { workspaceScope },
|
|
3976
|
+
connectionId: state.connectionId,
|
|
3977
|
+
...isReadToken === true ? {} : { principalId },
|
|
3978
|
+
...state.context.remoteAddr === void 0 ? {} : { remoteAddr: state.context.remoteAddr },
|
|
3979
|
+
...clientFeatures === void 0 || clientFeatures.length === 0 ? {} : { clientFeatures },
|
|
3980
|
+
...follow === true ? { follow: true } : {}
|
|
3981
|
+
});
|
|
3982
|
+
const peer = {
|
|
3983
|
+
connectionId: state.connectionId,
|
|
3984
|
+
principalId: state.context.principalId,
|
|
3985
|
+
transport: "ws"
|
|
3986
|
+
};
|
|
3987
|
+
options.onConnectionAuthenticated?.({
|
|
3988
|
+
connectionId: state.connectionId,
|
|
3989
|
+
isFollow: follow === true,
|
|
3990
|
+
clientFeatures: clientFeatures ?? []
|
|
3991
|
+
});
|
|
3992
|
+
try {
|
|
3993
|
+
state.extensionCleanup = handlers.bindExtension?.(peer, (frame) => {
|
|
3994
|
+
if (send(state.ws, frame, serializeForBroadcast) < 0) closeState(state, "resync-required");
|
|
3995
|
+
});
|
|
3996
|
+
} catch {
|
|
3997
|
+
state.extensionCleanup = void 0;
|
|
3998
|
+
}
|
|
3999
|
+
if (follow === true) {
|
|
4000
|
+
state.ask = void 0;
|
|
4001
|
+
return;
|
|
4002
|
+
}
|
|
4003
|
+
try {
|
|
4004
|
+
state.ask = handlers.bindAsk?.(peer, (message) => {
|
|
4005
|
+
if (send(state.ws, {
|
|
4006
|
+
stream: "ask",
|
|
4007
|
+
message
|
|
4008
|
+
}, serializeForBroadcast) < 0) {
|
|
4009
|
+
state.droppedFrames += 1;
|
|
4010
|
+
closeState(state, "resync-required");
|
|
4011
|
+
}
|
|
4012
|
+
}, (scope, reason) => {
|
|
4013
|
+
if (send(state.ws, {
|
|
4014
|
+
stream: "ask",
|
|
4015
|
+
invalidated: {
|
|
4016
|
+
scope,
|
|
4017
|
+
reason
|
|
4018
|
+
}
|
|
4019
|
+
}, serializeForBroadcast) < 0) {
|
|
4020
|
+
state.droppedFrames += 1;
|
|
4021
|
+
closeState(state, "resync-required");
|
|
4022
|
+
}
|
|
4023
|
+
});
|
|
4024
|
+
} catch {
|
|
4025
|
+
state.ask = void 0;
|
|
4026
|
+
}
|
|
4027
|
+
}
|
|
4028
|
+
wss.on("connection", (ws, req) => {
|
|
4029
|
+
const connectionId = `ws-${nextConnectionId + 1}`;
|
|
4030
|
+
const state = {
|
|
4031
|
+
id: nextConnectionId += 1,
|
|
4032
|
+
ws,
|
|
4033
|
+
sessions: /* @__PURE__ */ new Set(),
|
|
4034
|
+
unsubs: /* @__PURE__ */ new Map(),
|
|
4035
|
+
detachers: /* @__PURE__ */ new Map(),
|
|
4036
|
+
ask: void 0,
|
|
4037
|
+
context: contextFromToken(void 0, {
|
|
4038
|
+
transport: "ws",
|
|
4039
|
+
connectionId,
|
|
4040
|
+
principalId,
|
|
4041
|
+
remoteAddr: req.socket.remoteAddress
|
|
4042
|
+
}),
|
|
4043
|
+
connectionId,
|
|
4044
|
+
lastSeenAt: Date.now(),
|
|
4045
|
+
bufferedAtClose: 0,
|
|
4046
|
+
droppedFrames: 0,
|
|
4047
|
+
authenticated: false,
|
|
4048
|
+
handshaken: false
|
|
4049
|
+
};
|
|
4050
|
+
connections.set(ws, state);
|
|
4051
|
+
options.onConnectionOpen?.({ connectionId: state.connectionId });
|
|
4052
|
+
ensureHeartbeat();
|
|
4053
|
+
if (authToken === void 0) authenticate(state, void 0, { kind: "reader" });
|
|
4054
|
+
else {
|
|
4055
|
+
state.authTimer = setTimeout(() => closeState(state, "auth-required"), authFrameTimeoutMs);
|
|
4056
|
+
state.authTimer.unref?.();
|
|
4057
|
+
}
|
|
4058
|
+
ws.on("pong", () => {
|
|
4059
|
+
state.lastSeenAt = Date.now();
|
|
4060
|
+
});
|
|
4061
|
+
ws.on("message", (data) => {
|
|
4062
|
+
state.lastSeenAt = Date.now();
|
|
4063
|
+
handleMessage(state, data.toString());
|
|
4064
|
+
});
|
|
4065
|
+
ws.on("close", () => {
|
|
4066
|
+
cleanupState(state, state.closeReason ?? "client-close");
|
|
4067
|
+
});
|
|
4068
|
+
ws.on("error", () => {
|
|
4069
|
+
closeState(state, "error");
|
|
4070
|
+
});
|
|
4071
|
+
});
|
|
4072
|
+
let attachedServer;
|
|
4073
|
+
function onUpgrade(req, socket, head) {
|
|
4074
|
+
if (new URL(req.url ?? "/", "http://localhost").pathname !== path) return;
|
|
4075
|
+
const hostHeader = typeof req.headers.host === "string" ? req.headers.host : void 0;
|
|
4076
|
+
const hostAllowed = options.allowHost === void 0 ? checkHostHeaderWhenPresent(hostHeader).allowed : options.allowHost(hostHeader);
|
|
4077
|
+
const originHeader = typeof req.headers.origin === "string" ? req.headers.origin : void 0;
|
|
4078
|
+
const originAllowed = options.allowOrigin === void 0 ? checkOriginHeader(originHeader).allowed : options.allowOrigin(originHeader);
|
|
4079
|
+
if (!hostAllowed || !originAllowed) {
|
|
4080
|
+
socket.write("HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n");
|
|
4081
|
+
socket.destroy();
|
|
4082
|
+
return;
|
|
4083
|
+
}
|
|
4084
|
+
wss.handleUpgrade(req, socket, head, (ws) => {
|
|
4085
|
+
wss.emit("connection", ws, req);
|
|
4086
|
+
});
|
|
4087
|
+
}
|
|
4088
|
+
return {
|
|
4089
|
+
attach(server) {
|
|
4090
|
+
attachedServer = server;
|
|
4091
|
+
server.on("upgrade", onUpgrade);
|
|
4092
|
+
},
|
|
4093
|
+
close() {
|
|
4094
|
+
stopHeartbeat();
|
|
4095
|
+
for (const state of connections.values()) closeState(state, "server-close");
|
|
4096
|
+
attachedServer?.off("upgrade", onUpgrade);
|
|
4097
|
+
attachedServer = void 0;
|
|
4098
|
+
const graceMs = options.closeGraceMs ?? SERVER_CLOSE_GRACE_MS;
|
|
4099
|
+
const forced = setTimeout(() => {
|
|
4100
|
+
for (const socket of wss.clients) socket.terminate();
|
|
4101
|
+
}, graceMs);
|
|
4102
|
+
forced.unref?.();
|
|
4103
|
+
wss.close(() => {
|
|
4104
|
+
clearTimeout(forced);
|
|
4105
|
+
});
|
|
4106
|
+
}
|
|
4107
|
+
};
|
|
4108
|
+
}
|
|
4109
|
+
|
|
4110
|
+
//#endregion
|
|
4111
|
+
//#region src/mock.ts
|
|
4112
|
+
function defaultTurnScript(text) {
|
|
4113
|
+
const chunks = text.match(/.{1,4}/g) ?? [text];
|
|
4114
|
+
return [
|
|
4115
|
+
{
|
|
4116
|
+
kind: "prompt.start",
|
|
4117
|
+
text
|
|
4118
|
+
},
|
|
4119
|
+
{ kind: "stream.text.start" },
|
|
4120
|
+
...chunks.map((delta) => ({
|
|
4121
|
+
kind: "stream.text.delta",
|
|
4122
|
+
delta
|
|
4123
|
+
})),
|
|
4124
|
+
{ kind: "stream.text.end" },
|
|
4125
|
+
{
|
|
4126
|
+
kind: "prompt.end",
|
|
4127
|
+
model: "mock-model"
|
|
4128
|
+
}
|
|
4129
|
+
];
|
|
4130
|
+
}
|
|
4131
|
+
function sleep(ms) {
|
|
4132
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
4133
|
+
}
|
|
4134
|
+
function createMockService(options = {}) {
|
|
4135
|
+
const latency = options.latency ?? 0;
|
|
4136
|
+
const errorRate = options.errorRate ?? 0;
|
|
4137
|
+
const stepDelay = options.stepDelay ?? 0;
|
|
4138
|
+
const clock = options.clock ?? (() => Date.now());
|
|
4139
|
+
const random = options.random ?? Math.random;
|
|
4140
|
+
let seq = 0;
|
|
4141
|
+
const nextId = options.id ?? (() => `mock-${seq += 1}`);
|
|
4142
|
+
let emit = () => {};
|
|
4143
|
+
const sessions = [...options.initialSessions ?? []];
|
|
4144
|
+
const turnScript = options.turnScript ?? defaultTurnScript;
|
|
4145
|
+
async function runTurn(sessionId, text) {
|
|
4146
|
+
const steps = turnScript(text, sessionId);
|
|
4147
|
+
for (const step of steps) {
|
|
4148
|
+
await sleep(stepDelay);
|
|
4149
|
+
emit(sessionId, {
|
|
4150
|
+
sessionId,
|
|
4151
|
+
...step
|
|
4152
|
+
});
|
|
4153
|
+
}
|
|
4154
|
+
}
|
|
4155
|
+
const dataSource = {
|
|
4156
|
+
listSessions() {
|
|
4157
|
+
return [...sessions];
|
|
4158
|
+
},
|
|
4159
|
+
createSession(input) {
|
|
4160
|
+
const entry = {
|
|
4161
|
+
id: nextId(),
|
|
4162
|
+
title: typeof input?.title === "string" ? input.title : void 0,
|
|
4163
|
+
createdAt: clock()
|
|
4164
|
+
};
|
|
4165
|
+
sessions.push(entry);
|
|
4166
|
+
return entry;
|
|
4167
|
+
},
|
|
4168
|
+
submitInput(sessionId, text) {
|
|
4169
|
+
runTurn(sessionId, text);
|
|
4170
|
+
return {
|
|
4171
|
+
accepted: true,
|
|
4172
|
+
sessionId,
|
|
4173
|
+
inputId: `${sessionId}-input-${clock()}`,
|
|
4174
|
+
executionId: `${sessionId}-exec-${clock()}`
|
|
4175
|
+
};
|
|
4176
|
+
},
|
|
4177
|
+
prompt(sessionId, text) {
|
|
4178
|
+
runTurn(sessionId, text);
|
|
4179
|
+
},
|
|
4180
|
+
clear(sessionId) {
|
|
4181
|
+
emit(sessionId, {
|
|
4182
|
+
kind: "session.cleared",
|
|
4183
|
+
sessionId
|
|
4184
|
+
});
|
|
4185
|
+
return true;
|
|
4186
|
+
}
|
|
4187
|
+
};
|
|
4188
|
+
const inner = createHandlers({
|
|
4189
|
+
dataSource,
|
|
4190
|
+
authorize: createDefaultAuthorizer()
|
|
4191
|
+
});
|
|
4192
|
+
return {
|
|
4193
|
+
handlers: {
|
|
4194
|
+
async handle(type, payload) {
|
|
4195
|
+
if (errorRate > 0 && random() < errorRate) throw new ServiceError("MOCK_ERROR", `injected mock failure for ${type}`);
|
|
4196
|
+
if (latency > 0) await sleep(latency);
|
|
4197
|
+
return inner.handle(type, payload);
|
|
4198
|
+
},
|
|
4199
|
+
listTypes: inner.listTypes
|
|
4200
|
+
},
|
|
4201
|
+
dataSource,
|
|
4202
|
+
setEmit(emitEvent) {
|
|
4203
|
+
emit = emitEvent;
|
|
4204
|
+
}
|
|
4205
|
+
};
|
|
4206
|
+
}
|
|
4207
|
+
|
|
4208
|
+
//#endregion
|
|
4209
|
+
//#region src/vite.ts
|
|
4210
|
+
function readBody(req) {
|
|
4211
|
+
return new Promise((resolve, reject) => {
|
|
4212
|
+
const chunks = [];
|
|
4213
|
+
req.on("data", (chunk) => chunks.push(chunk));
|
|
4214
|
+
req.on("end", () => resolve(Buffer.concat(chunks).toString("utf-8")));
|
|
4215
|
+
req.on("error", reject);
|
|
4216
|
+
});
|
|
4217
|
+
}
|
|
4218
|
+
function respondJson(res, status, body) {
|
|
4219
|
+
res.statusCode = status;
|
|
4220
|
+
res.setHeader("content-type", "application/json");
|
|
4221
|
+
res.end(JSON.stringify(body));
|
|
4222
|
+
}
|
|
4223
|
+
function viteServiceMock(options = {}) {
|
|
4224
|
+
const relay = options.relay ?? createEventRelay();
|
|
4225
|
+
const mock = options.handlers === void 0 ? createMockService(options.mock) : void 0;
|
|
4226
|
+
if (mock) mock.setEmit((sessionId, event) => {
|
|
4227
|
+
relay.push(sessionId, event);
|
|
4228
|
+
});
|
|
4229
|
+
const handlers = options.handlers ?? mock?.handlers;
|
|
4230
|
+
if (handlers === void 0) throw new Error("viteServiceMock requires handlers or mock options");
|
|
4231
|
+
const ws = createWebSocketManager(handlers, relay, { path: options.wsPath });
|
|
4232
|
+
return {
|
|
4233
|
+
name: "x-otto-service-mock",
|
|
4234
|
+
configureServer(server) {
|
|
4235
|
+
server.middlewares.use("/api", (req, res, next) => {
|
|
4236
|
+
const path = (req.url ?? "").split("?")[0] ?? "";
|
|
4237
|
+
if (req.method === "GET" && path === "/health") {
|
|
4238
|
+
res.statusCode = 200;
|
|
4239
|
+
res.setHeader("content-type", "application/json");
|
|
4240
|
+
res.end(JSON.stringify({ ok: true }));
|
|
4241
|
+
return;
|
|
4242
|
+
}
|
|
4243
|
+
if (req.method !== "POST") {
|
|
4244
|
+
next();
|
|
4245
|
+
return;
|
|
4246
|
+
}
|
|
4247
|
+
(async () => {
|
|
4248
|
+
try {
|
|
4249
|
+
const body = await readBody(req);
|
|
4250
|
+
respondJson(res, 200, await handleWireRequest(handlers, path.replace(/^\//, ""), body, contextFromToken(void 0, {
|
|
4251
|
+
transport: "http",
|
|
4252
|
+
remoteAddr: req.socket.remoteAddress
|
|
4253
|
+
})));
|
|
4254
|
+
} catch (error) {
|
|
4255
|
+
if (!res.headersSent) respondJson(res, 200, {
|
|
4256
|
+
id: "http",
|
|
4257
|
+
ok: false,
|
|
4258
|
+
error: {
|
|
4259
|
+
code: "INVALID_INPUT",
|
|
4260
|
+
message: `request failed: ${String(error)}`
|
|
4261
|
+
}
|
|
4262
|
+
});
|
|
4263
|
+
else res.destroy();
|
|
4264
|
+
}
|
|
4265
|
+
})();
|
|
4266
|
+
});
|
|
4267
|
+
if (server.httpServer) ws.attach(server.httpServer);
|
|
4268
|
+
}
|
|
4269
|
+
};
|
|
4270
|
+
}
|
|
4271
|
+
|
|
4272
|
+
//#endregion
|
|
4273
|
+
export { viteServiceMock };
|