@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.
Files changed (56) hide show
  1. package/dist/ask-host.d.ts +18 -0
  2. package/dist/ask-validate.d.ts +47 -0
  3. package/dist/attached-writers.d.ts +9 -0
  4. package/dist/authorize.d.ts +8 -0
  5. package/dist/chat-routes.d.ts +4 -0
  6. package/dist/client-entry.d.ts +114 -0
  7. package/dist/client-entry.js +1414 -0
  8. package/dist/connection-binding.d.ts +9 -0
  9. package/dist/context.d.ts +51 -0
  10. package/dist/credential.d.ts +51 -0
  11. package/dist/errors.d.ts +11 -0
  12. package/dist/events.d.ts +21 -0
  13. package/dist/extension-approval.d.ts +41 -0
  14. package/dist/extension-rpc.d.ts +31 -0
  15. package/dist/fanout.d.ts +13 -0
  16. package/dist/handler-options.d.ts +252 -0
  17. package/dist/handlers.d.ts +23 -0
  18. package/dist/hub-capabilities.d.ts +15 -0
  19. package/dist/index.d.ts +1144 -625
  20. package/dist/index.js +8591 -44
  21. package/dist/methods.d.ts +5 -0
  22. package/dist/mock.d.ts +23 -0
  23. package/dist/resource-read.d.ts +4 -0
  24. package/dist/route-read-only.d.ts +1 -0
  25. package/dist/route-set.d.ts +22 -0
  26. package/dist/route-targets.d.ts +6 -0
  27. package/dist/route-validate.d.ts +15 -0
  28. package/dist/routes/ask-routes.d.ts +3 -0
  29. package/dist/routes/auth-routes.d.ts +3 -0
  30. package/dist/routes/core-routes.d.ts +3 -0
  31. package/dist/routes/extension-routes.d.ts +3 -0
  32. package/dist/routes/index.d.ts +6 -0
  33. package/dist/routes/plugin-routes.d.ts +3 -0
  34. package/dist/routes/repository-meta.d.ts +2 -0
  35. package/dist/routes/session-routes.d.ts +3 -0
  36. package/dist/routes/session-runtime-routes.d.ts +5 -0
  37. package/dist/routes/settings-routes.d.ts +3 -0
  38. package/dist/routes/support.d.ts +7 -0
  39. package/dist/routes/worker-routes.d.ts +2 -0
  40. package/dist/routes/workspace-routes.d.ts +3 -0
  41. package/dist/send-attempt-table.d.ts +35 -0
  42. package/dist/serialize-shared.d.ts +1 -0
  43. package/dist/source-for-session.d.ts +4 -0
  44. package/dist/subscription-backfill.d.ts +19 -0
  45. package/dist/target-extractors.d.ts +18 -0
  46. package/dist/token-verifier.d.ts +12 -0
  47. package/dist/vite.d.ts +11 -0
  48. package/dist/vite.js +4273 -0
  49. package/dist/web-host.d.ts +52 -0
  50. package/dist/wire-stats.d.ts +6 -0
  51. package/dist/wire.d.ts +12 -0
  52. package/dist/ws.d.ts +66 -0
  53. package/package.json +19 -31
  54. package/README.md +0 -135
  55. package/dist/index.d.ts.map +0 -1
  56. package/dist/index.js.map +0 -1
@@ -0,0 +1,1414 @@
1
+ import "@x-otto/kernel";
2
+ import { isSandboxMode } from "@x-otto/kernel/sandbox";
3
+
4
+ //#region src/fanout.ts
5
+ function createEventFanout(options = {}) {
6
+ const subscriptions = /* @__PURE__ */ new Map();
7
+ function makeDisposer(sessionId, handler, entry, token) {
8
+ return () => {
9
+ if (token.released) return;
10
+ token.released = true;
11
+ if (subscriptions.get(sessionId) !== entry) return;
12
+ const count = entry.handlers.get(handler);
13
+ if (count === void 0) return;
14
+ if (count > 1) {
15
+ entry.handlers.set(handler, count - 1);
16
+ return;
17
+ }
18
+ entry.handlers.delete(handler);
19
+ if (entry.handlers.size === 0) {
20
+ subscriptions.delete(sessionId);
21
+ options.onLastSubscriberRemoved?.(sessionId);
22
+ }
23
+ };
24
+ }
25
+ return {
26
+ add(sessionId, handler) {
27
+ const token = { released: false };
28
+ const existing = subscriptions.get(sessionId);
29
+ if (existing) {
30
+ existing.handlers.set(handler, (existing.handlers.get(handler) ?? 0) + 1);
31
+ return makeDisposer(sessionId, handler, existing, token);
32
+ }
33
+ const entry = { handlers: new Map([[handler, 1]]) };
34
+ subscriptions.set(sessionId, entry);
35
+ try {
36
+ options.onFirstSubscriber?.(sessionId);
37
+ } catch (error) {
38
+ entry.handlers.clear();
39
+ if (subscriptions.get(sessionId) === entry) subscriptions.delete(sessionId);
40
+ throw error;
41
+ }
42
+ return makeDisposer(sessionId, handler, entry, token);
43
+ },
44
+ deliver(sessionId, deliver) {
45
+ const entry = subscriptions.get(sessionId);
46
+ if (!entry) return;
47
+ for (const handler of Array.from(entry.handlers.keys())) try {
48
+ deliver(handler);
49
+ } catch {}
50
+ },
51
+ clear() {
52
+ const sessionIds = Array.from(subscriptions.keys());
53
+ subscriptions.clear();
54
+ const failures = [];
55
+ for (const sessionId of sessionIds) try {
56
+ options.onLastSubscriberRemoved?.(sessionId);
57
+ } catch (error) {
58
+ failures.push(error);
59
+ }
60
+ if (failures.length > 0) throw failures[0];
61
+ },
62
+ sessionCount() {
63
+ return subscriptions.size;
64
+ }
65
+ };
66
+ }
67
+
68
+ //#endregion
69
+ //#region src/errors.ts
70
+ var ServiceError = class extends Error {
71
+ constructor(code, message, details) {
72
+ super(message);
73
+ this.code = code;
74
+ this.details = details;
75
+ this.name = "ServiceError";
76
+ }
77
+ };
78
+ function isServiceError(error) {
79
+ if (error instanceof ServiceError) return true;
80
+ if (!(error instanceof Error) || typeof error.code !== "string") return false;
81
+ for (let proto = Object.getPrototypeOf(error); proto !== null; proto = Object.getPrototypeOf(proto)) if (proto.constructor?.name === "ServiceError") return true;
82
+ return false;
83
+ }
84
+ var RequestForbiddenError = class extends ServiceError {
85
+ constructor(action, principalId) {
86
+ super("FORBIDDEN", `principal "${principalId}" is not authorized for ${action}`, {
87
+ action,
88
+ principalId
89
+ });
90
+ this.action = action;
91
+ this.principalId = principalId;
92
+ this.name = "RequestForbiddenError";
93
+ }
94
+ };
95
+
96
+ //#endregion
97
+ //#region src/events.ts
98
+ const GLOBAL_EVENTS_CHANNEL = "__global__";
99
+ const PRIVATE_ASK_EVENT_KINDS = new Set([
100
+ "approval.respond",
101
+ "approval.opened",
102
+ "approval.closed",
103
+ "hitl.request",
104
+ "hitl.respond",
105
+ "hitl.cancelled"
106
+ ]);
107
+ const PER_SESSION_ONLY_EVENT_KINDS = /* @__PURE__ */ new Set();
108
+ function isPrivateAskEvent(event) {
109
+ if (typeof event !== "object" || event === null) return false;
110
+ const kind = event.kind;
111
+ return typeof kind === "string" && PRIVATE_ASK_EVENT_KINDS.has(kind);
112
+ }
113
+ function isPerSessionOnlyEvent(event) {
114
+ if (typeof event !== "object" || event === null) return false;
115
+ const kind = event.kind;
116
+ return typeof kind === "string" && PER_SESSION_ONLY_EVENT_KINDS.has(kind);
117
+ }
118
+ const filteredHandlers = /* @__PURE__ */ new WeakMap();
119
+ function filterPrivateAskEvents(handler) {
120
+ const existing = filteredHandlers.get(handler);
121
+ if (existing !== void 0) return existing;
122
+ const next = (event) => {
123
+ if (isPrivateAskEvent(event)) return;
124
+ handler(event);
125
+ };
126
+ filteredHandlers.set(handler, next);
127
+ return next;
128
+ }
129
+
130
+ //#endregion
131
+ //#region src/ask-validate.ts
132
+ const APPROVAL_SCOPES = [
133
+ "once",
134
+ "session",
135
+ "project",
136
+ "global"
137
+ ];
138
+ const SANDBOX_BACKENDS = ["seatbelt", "bubblewrap"];
139
+ const ASK_INVALIDATION_REASONS = [
140
+ "disconnected",
141
+ "scope-denied",
142
+ "stale-runtime",
143
+ "closed"
144
+ ];
145
+ function isRecord(value) {
146
+ return typeof value === "object" && value !== null && !Array.isArray(value);
147
+ }
148
+ function isText(value) {
149
+ return typeof value === "string" && value.length > 0;
150
+ }
151
+ function hasExactKeys(value, keys) {
152
+ return Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));
153
+ }
154
+ function hasAllowedKeys(value, required, optional) {
155
+ if (!required.every((key) => Object.hasOwn(value, key))) return false;
156
+ return Object.keys(value).every((key) => required.includes(key) || optional.includes(key));
157
+ }
158
+ function isRevision(value) {
159
+ return typeof value === "number" && Number.isInteger(value) && value >= 0;
160
+ }
161
+ function parseApprovalScope(value) {
162
+ return APPROVAL_SCOPES.find((scope) => scope === value);
163
+ }
164
+ function parseApprovalScopes(value) {
165
+ if (!Array.isArray(value) || value.length === 0) return void 0;
166
+ const scopes = [];
167
+ for (const item of value) {
168
+ const scope = parseApprovalScope(item);
169
+ if (scope === void 0) return void 0;
170
+ scopes.push(scope);
171
+ }
172
+ return scopes;
173
+ }
174
+ function parseNetworkHosts(value) {
175
+ if (!isRecord(value) || !hasExactKeys(value, ["hosts"])) return void 0;
176
+ if (!Array.isArray(value.hosts) || value.hosts.length === 0) return void 0;
177
+ const hosts = [];
178
+ for (const host of value.hosts) {
179
+ if (!isText(host)) return void 0;
180
+ hosts.push(host);
181
+ }
182
+ return hosts;
183
+ }
184
+ function parseAskScope(value) {
185
+ if (!isRecord(value)) return void 0;
186
+ if (value.kind === "session" && hasExactKeys(value, ["kind", "sessionId"]) && isText(value.sessionId)) return {
187
+ kind: "session",
188
+ sessionId: value.sessionId
189
+ };
190
+ if (value.kind === "runtime" && hasExactKeys(value, ["kind", "runtimeEpoch"]) && isText(value.runtimeEpoch)) return {
191
+ kind: "runtime",
192
+ runtimeEpoch: value.runtimeEpoch
193
+ };
194
+ }
195
+ function scopeKey(scope) {
196
+ return scope.kind === "session" ? `s:${scope.sessionId}` : `r:${scope.runtimeEpoch}`;
197
+ }
198
+ function parseAskRef(value) {
199
+ if (!isRecord(value) || !hasExactKeys(value, [
200
+ "runtimeEpoch",
201
+ "scope",
202
+ "requestId"
203
+ ])) return void 0;
204
+ const scope = parseAskScope(value.scope);
205
+ if (scope === void 0 || !isText(value.runtimeEpoch) || !isText(value.requestId)) return void 0;
206
+ return {
207
+ runtimeEpoch: value.runtimeEpoch,
208
+ scope,
209
+ requestId: value.requestId
210
+ };
211
+ }
212
+ function parsePermissionAskRef(value) {
213
+ const ref = parseAskRef(value);
214
+ if (ref === void 0 || ref.scope.kind !== "session") return void 0;
215
+ return {
216
+ runtimeEpoch: ref.runtimeEpoch,
217
+ scope: ref.scope,
218
+ requestId: ref.requestId
219
+ };
220
+ }
221
+ function parsePermissionAskResponse(value) {
222
+ if (!isRecord(value)) return void 0;
223
+ if (typeof value.approved !== "boolean") return void 0;
224
+ if (value.scope === void 0) return hasExactKeys(value, ["approved"]) ? { approved: value.approved } : void 0;
225
+ const scope = parseApprovalScope(value.scope);
226
+ if (scope === void 0 || !hasExactKeys(value, ["approved", "scope"])) return void 0;
227
+ return {
228
+ approved: value.approved,
229
+ scope
230
+ };
231
+ }
232
+ function parseHitlAnswer(value) {
233
+ if (!isRecord(value) || !hasAllowedKeys(value, ["selectedOptionLabels", "freeform"], ["selectedOptionValues"])) return;
234
+ if (typeof value.freeform !== "string" || !Array.isArray(value.selectedOptionLabels)) return void 0;
235
+ const labels = [];
236
+ for (const label of value.selectedOptionLabels) {
237
+ if (typeof label !== "string") return void 0;
238
+ labels.push(label);
239
+ }
240
+ if (value.selectedOptionValues !== void 0) {
241
+ if (!Array.isArray(value.selectedOptionValues)) return void 0;
242
+ const values = [];
243
+ for (const item of value.selectedOptionValues) {
244
+ if (typeof item !== "string") return void 0;
245
+ values.push(item);
246
+ }
247
+ return {
248
+ selectedOptionLabels: labels,
249
+ freeform: value.freeform,
250
+ selectedOptionValues: values
251
+ };
252
+ }
253
+ return {
254
+ selectedOptionLabels: labels,
255
+ freeform: value.freeform
256
+ };
257
+ }
258
+ function parsePermissionAskRequest(value) {
259
+ if (!isRecord(value)) return void 0;
260
+ const common = [
261
+ "kind",
262
+ "sessionId",
263
+ "toolCallId",
264
+ "toolName",
265
+ "argumentList",
266
+ "offeredScopes"
267
+ ];
268
+ const offeredScopes = parseApprovalScopes(value.offeredScopes);
269
+ if (offeredScopes === void 0) return void 0;
270
+ if (!isRecord(value.argumentList)) return void 0;
271
+ if (!isText(value.sessionId) || !isText(value.toolCallId) || !isText(value.toolName)) return void 0;
272
+ if (value.kind === "tool") {
273
+ if (!hasAllowedKeys(value, [...common, "reason"], [
274
+ "grantKey",
275
+ "ruleName",
276
+ "exactCommandGrant",
277
+ "network"
278
+ ])) return;
279
+ if (!isText(value.reason)) return void 0;
280
+ if (value.grantKey !== void 0 && !isText(value.grantKey)) return void 0;
281
+ if (value.ruleName !== void 0 && !isText(value.ruleName)) return void 0;
282
+ if (value.exactCommandGrant !== void 0 && typeof value.exactCommandGrant !== "boolean") return void 0;
283
+ if (value.exactCommandGrant === true && value.toolName !== "bash") return void 0;
284
+ if (value.exactCommandGrant === true && !isText(value.argumentList["command"])) return void 0;
285
+ const hosts = value.network === void 0 ? void 0 : parseNetworkHosts(value.network);
286
+ if (value.network !== void 0 && hosts === void 0) return void 0;
287
+ return {
288
+ kind: "tool",
289
+ sessionId: value.sessionId,
290
+ toolCallId: value.toolCallId,
291
+ toolName: value.toolName,
292
+ argumentList: value.argumentList,
293
+ reason: value.reason,
294
+ offeredScopes,
295
+ ...value.grantKey === void 0 ? {} : { grantKey: value.grantKey },
296
+ ...value.ruleName === void 0 ? {} : { ruleName: value.ruleName },
297
+ ...value.exactCommandGrant === void 0 ? {} : { exactCommandGrant: value.exactCommandGrant },
298
+ ...hosts === void 0 ? {} : { network: { hosts } }
299
+ };
300
+ }
301
+ if (value.kind !== "sandbox") return void 0;
302
+ if (!hasAllowedKeys(value, [
303
+ ...common,
304
+ "from",
305
+ "to",
306
+ "justification",
307
+ "backend"
308
+ ], ["denialReason"])) return;
309
+ if (!isText(value.justification)) return void 0;
310
+ if (value.denialReason !== void 0 && !isText(value.denialReason)) return void 0;
311
+ if (!isSandboxMode(value.from) || !isSandboxMode(value.to)) return void 0;
312
+ const backend = SANDBOX_BACKENDS.find((item) => item === value.backend);
313
+ if (backend === void 0) return void 0;
314
+ if (offeredScopes.length !== 2 || offeredScopes[0] !== "once" || offeredScopes[1] !== "session") return;
315
+ return {
316
+ kind: "sandbox",
317
+ sessionId: value.sessionId,
318
+ toolCallId: value.toolCallId,
319
+ toolName: value.toolName,
320
+ argumentList: value.argumentList,
321
+ offeredScopes: ["once", "session"],
322
+ from: value.from,
323
+ to: value.to,
324
+ justification: value.justification,
325
+ backend,
326
+ ...value.denialReason === void 0 ? {} : { denialReason: value.denialReason }
327
+ };
328
+ }
329
+ function readOptionalText(value) {
330
+ if (value === void 0 || value === "") return { kind: "absent" };
331
+ if (typeof value !== "string") return { kind: "invalid" };
332
+ return {
333
+ kind: "text",
334
+ text: value
335
+ };
336
+ }
337
+ function parseHitlAskRequest(value) {
338
+ if (!isRecord(value)) return void 0;
339
+ if (!hasAllowedKeys(value, ["question"], [
340
+ "sessionId",
341
+ "header",
342
+ "background",
343
+ "recommendation",
344
+ "options",
345
+ "allowFreeform",
346
+ "multiSelect",
347
+ "evidence"
348
+ ])) return void 0;
349
+ if (!isText(value.question)) return void 0;
350
+ const header = readOptionalText(value.header);
351
+ const recommendation = readOptionalText(value.recommendation);
352
+ if (header.kind === "invalid" || recommendation.kind === "invalid") return void 0;
353
+ if (value.sessionId !== void 0 && !isText(value.sessionId)) return void 0;
354
+ if (value.background !== void 0 && typeof value.background !== "string") return void 0;
355
+ if (value.allowFreeform !== void 0 && typeof value.allowFreeform !== "boolean") return void 0;
356
+ if (value.multiSelect !== void 0 && typeof value.multiSelect !== "boolean") return void 0;
357
+ const options = parseHitlOptions(value.options);
358
+ if (value.options !== void 0 && options === void 0) return void 0;
359
+ const evidence = parseStringArray(value.evidence);
360
+ if (value.evidence !== void 0 && evidence === void 0) return void 0;
361
+ return {
362
+ question: value.question,
363
+ ...value.sessionId === void 0 ? {} : { sessionId: value.sessionId },
364
+ ...header.kind === "text" ? { header: header.text } : {},
365
+ ...value.background === void 0 ? {} : { background: value.background },
366
+ ...recommendation.kind === "text" ? { recommendation: recommendation.text } : {},
367
+ ...options === void 0 ? {} : { options },
368
+ ...value.allowFreeform === void 0 ? {} : { allowFreeform: value.allowFreeform },
369
+ ...value.multiSelect === void 0 ? {} : { multiSelect: value.multiSelect },
370
+ ...evidence === void 0 ? {} : { evidence }
371
+ };
372
+ }
373
+ function parseHitlOptions(value) {
374
+ if (!Array.isArray(value)) return void 0;
375
+ const options = [];
376
+ for (const item of value) {
377
+ if (!isRecord(item) || !hasAllowedKeys(item, ["label"], [
378
+ "rationale",
379
+ "recommended",
380
+ "preview",
381
+ "value"
382
+ ])) return;
383
+ if (!isText(item.label)) return void 0;
384
+ if (item.rationale !== void 0 && typeof item.rationale !== "string") return void 0;
385
+ if (item.preview !== void 0 && typeof item.preview !== "string") return void 0;
386
+ if (item.recommended !== void 0 && typeof item.recommended !== "boolean") return void 0;
387
+ if (item.value !== void 0 && typeof item.value !== "string") return void 0;
388
+ options.push({
389
+ label: item.label,
390
+ ...item.rationale === void 0 ? {} : { rationale: item.rationale },
391
+ ...item.recommended === void 0 ? {} : { recommended: item.recommended },
392
+ ...item.preview === void 0 ? {} : { preview: item.preview },
393
+ ...item.value === void 0 ? {} : { value: item.value }
394
+ });
395
+ }
396
+ return options;
397
+ }
398
+ function parseStringArray(value) {
399
+ if (!Array.isArray(value)) return void 0;
400
+ const items = [];
401
+ for (const item of value) {
402
+ if (typeof item !== "string") return void 0;
403
+ items.push(item);
404
+ }
405
+ return items;
406
+ }
407
+ function parseOutcome(value, parseValue) {
408
+ if (!isRecord(value) || typeof value.status !== "string") return void 0;
409
+ if (value.status === "answered") {
410
+ if (!hasExactKeys(value, [
411
+ "status",
412
+ "value",
413
+ "by"
414
+ ]) || value.by !== "human") return void 0;
415
+ const parsed = parseValue(value.value);
416
+ if (parsed === void 0) return void 0;
417
+ return {
418
+ status: "answered",
419
+ value: parsed,
420
+ by: "human"
421
+ };
422
+ }
423
+ if (value.status === "cancelled" || value.status === "timed-out" || value.status === "unavailable") return hasExactKeys(value, ["status"]) ? { status: value.status } : void 0;
424
+ }
425
+ function parsePendingAsk(value) {
426
+ if (!isRecord(value) || !hasExactKeys(value, [
427
+ "channel",
428
+ "ref",
429
+ "request"
430
+ ])) return void 0;
431
+ if (value.channel === "permission") {
432
+ const ref = parsePermissionAskRef(value.ref);
433
+ const request = parsePermissionAskRequest(value.request);
434
+ if (ref === void 0 || request === void 0) return void 0;
435
+ return {
436
+ channel: "permission",
437
+ ref,
438
+ request
439
+ };
440
+ }
441
+ if (value.channel === "hitl") {
442
+ const ref = parseAskRef(value.ref);
443
+ const request = parseHitlAskRequest(value.request);
444
+ if (ref === void 0 || request === void 0) return void 0;
445
+ return {
446
+ channel: "hitl",
447
+ ref,
448
+ request
449
+ };
450
+ }
451
+ }
452
+ function parseAskViewMessage(value) {
453
+ if (!isRecord(value) || typeof value.kind !== "string") return void 0;
454
+ if (value.kind === "ask.snapshot") {
455
+ if (!hasExactKeys(value, [
456
+ "kind",
457
+ "runtimeEpoch",
458
+ "revision",
459
+ "scope",
460
+ "pending"
461
+ ])) return void 0;
462
+ if (!isText(value.runtimeEpoch) || !isRevision(value.revision) || !Array.isArray(value.pending)) return;
463
+ const scope = parseAskScope(value.scope);
464
+ if (scope === void 0) return void 0;
465
+ const pending = [];
466
+ for (const entry of value.pending) {
467
+ const parsed = parsePendingAsk(entry);
468
+ if (parsed === void 0) return void 0;
469
+ pending.push(parsed);
470
+ }
471
+ return {
472
+ kind: "ask.snapshot",
473
+ runtimeEpoch: value.runtimeEpoch,
474
+ revision: value.revision,
475
+ scope,
476
+ pending
477
+ };
478
+ }
479
+ if (value.kind === "approval.opened") {
480
+ if (!hasExactKeys(value, [
481
+ "kind",
482
+ "revision",
483
+ "ref",
484
+ "request"
485
+ ]) || !isRevision(value.revision)) return void 0;
486
+ const ref = parsePermissionAskRef(value.ref);
487
+ const request = parsePermissionAskRequest(value.request);
488
+ if (ref === void 0 || request === void 0) return void 0;
489
+ return {
490
+ kind: "approval.opened",
491
+ revision: value.revision,
492
+ ref,
493
+ request
494
+ };
495
+ }
496
+ if (value.kind === "approval.closed") {
497
+ if (!hasExactKeys(value, [
498
+ "kind",
499
+ "revision",
500
+ "ref",
501
+ "outcome"
502
+ ]) || !isRevision(value.revision)) return void 0;
503
+ const ref = parsePermissionAskRef(value.ref);
504
+ const outcome = parseOutcome(value.outcome, parsePermissionAskResponse);
505
+ if (ref === void 0 || outcome === void 0) return void 0;
506
+ return {
507
+ kind: "approval.closed",
508
+ revision: value.revision,
509
+ ref,
510
+ outcome
511
+ };
512
+ }
513
+ if (value.kind === "hitl.opened") {
514
+ if (!hasExactKeys(value, [
515
+ "kind",
516
+ "revision",
517
+ "ref",
518
+ "request"
519
+ ]) || !isRevision(value.revision)) return void 0;
520
+ const ref = parseAskRef(value.ref);
521
+ const request = parseHitlAskRequest(value.request);
522
+ if (ref === void 0 || request === void 0) return void 0;
523
+ return {
524
+ kind: "hitl.opened",
525
+ revision: value.revision,
526
+ ref,
527
+ request
528
+ };
529
+ }
530
+ if (value.kind === "hitl.closed") {
531
+ if (!hasExactKeys(value, [
532
+ "kind",
533
+ "revision",
534
+ "ref",
535
+ "outcome"
536
+ ]) || !isRevision(value.revision)) return void 0;
537
+ const ref = parseAskRef(value.ref);
538
+ const outcome = parseOutcome(value.outcome, parseHitlAnswer);
539
+ if (ref === void 0 || outcome === void 0) return void 0;
540
+ return {
541
+ kind: "hitl.closed",
542
+ revision: value.revision,
543
+ ref,
544
+ outcome
545
+ };
546
+ }
547
+ }
548
+ function viewMessageScope(message) {
549
+ return message.kind === "ask.snapshot" ? message.scope : message.ref.scope;
550
+ }
551
+ function parseAskInvalidated(value) {
552
+ if (!isRecord(value) || !hasExactKeys(value, ["scope", "reason"])) return void 0;
553
+ const scope = parseAskScope(value.scope);
554
+ const reason = ASK_INVALIDATION_REASONS.find((item) => item === value.reason);
555
+ if (scope === void 0 || reason === void 0) return void 0;
556
+ return {
557
+ scope,
558
+ reason
559
+ };
560
+ }
561
+ function parseAskFrame(value) {
562
+ if (!isRecord(value) || value.stream !== "ask") return void 0;
563
+ if (Object.hasOwn(value, "message")) {
564
+ if (!hasExactKeys(value, ["stream", "message"])) return void 0;
565
+ const message = parseAskViewMessage(value.message);
566
+ return message === void 0 ? void 0 : {
567
+ kind: "message",
568
+ message
569
+ };
570
+ }
571
+ if (Object.hasOwn(value, "invalidated")) {
572
+ if (!hasExactKeys(value, ["stream", "invalidated"])) return void 0;
573
+ const invalidated = parseAskInvalidated(value.invalidated);
574
+ return invalidated === void 0 ? void 0 : {
575
+ kind: "invalidated",
576
+ ...invalidated
577
+ };
578
+ }
579
+ }
580
+
581
+ //#endregion
582
+ //#region src/client.ts
583
+ function respondPayload(command) {
584
+ return command.channel === "permission" ? {
585
+ ref: command.ref,
586
+ response: command.response
587
+ } : {
588
+ ref: command.ref,
589
+ reply: command.reply
590
+ };
591
+ }
592
+ function respondType(command) {
593
+ return command.channel === "permission" ? "approval.respond" : "hitl.respond";
594
+ }
595
+ function createHttpWsClient(transport) {
596
+ let closed = false;
597
+ const fanout = createEventFanout({
598
+ onFirstSubscriber: (sessionId) => transport.subscribe(sessionId),
599
+ onLastSubscriberRemoved: (sessionId) => {
600
+ if (!closed) transport.unsubscribe(sessionId);
601
+ }
602
+ });
603
+ const pending = /* @__PURE__ */ new Map();
604
+ const extensionListeners = /* @__PURE__ */ new Set();
605
+ const catalogSubscriptions = /* @__PURE__ */ new Map();
606
+ const extensionSubscriptions = /* @__PURE__ */ new Map();
607
+ let seq = 0;
608
+ transport.onResponse((res) => {
609
+ const entry = pending.get(res.id);
610
+ if (!entry) return;
611
+ pending.delete(res.id);
612
+ if (res.ok) entry.resolve(res.payload);
613
+ else entry.reject(new ServiceError(res.error?.code ?? "UNKNOWN", res.error?.message ?? "unknown error", res.error?.details));
614
+ });
615
+ const emitExtension = (frame) => {
616
+ for (const listener of [...extensionListeners]) listener(frame);
617
+ };
618
+ transport.onEvent((event) => {
619
+ if (isPrivateAskEvent(event)) return;
620
+ fanout.deliver(event.sessionId, (handler) => handler(event));
621
+ });
622
+ transport.onExtension?.((frame) => {
623
+ if (frame.kind === "extension.catalog.closed") catalogSubscriptions.delete(frame.subscriptionId);
624
+ if (frame.kind === "extension.subscription.closed") extensionSubscriptions.delete(frame.subscriptionId);
625
+ emitExtension(frame);
626
+ });
627
+ transport.onClose((info) => {
628
+ const remote = info?.reason === "remote";
629
+ const code = remote ? "CONNECTION_LOST" : "CONNECTION_CLOSED";
630
+ const message = remote ? "connection lost before a response arrived; the request may still be executing on the server" : "connection closed";
631
+ for (const [subscriptionId, epoch] of catalogSubscriptions) emitExtension({
632
+ kind: "extension.catalog.closed",
633
+ subscriptionId,
634
+ reason: remote ? "disconnected" : "closed",
635
+ epoch
636
+ });
637
+ catalogSubscriptions.clear();
638
+ for (const [subscriptionId, epoch] of extensionSubscriptions) emitExtension({
639
+ kind: "extension.subscription.closed",
640
+ subscriptionId,
641
+ reason: remote ? "disconnected" : "closed",
642
+ epoch
643
+ });
644
+ extensionSubscriptions.clear();
645
+ for (const entry of pending.values()) entry.reject(new ServiceError(code, message));
646
+ pending.clear();
647
+ if (!(remote && info?.reconnecting === true)) {
648
+ closed = true;
649
+ fanout.clear();
650
+ extensionListeners.clear();
651
+ }
652
+ });
653
+ function request(type, ...payload) {
654
+ const id = `req-${seq += 1}`;
655
+ return new Promise((resolve, reject) => {
656
+ pending.set(id, {
657
+ resolve,
658
+ reject
659
+ });
660
+ try {
661
+ const frame = payload.length === 0 ? {
662
+ id,
663
+ type
664
+ } : {
665
+ id,
666
+ type,
667
+ payload: payload[0]
668
+ };
669
+ transport.send(frame);
670
+ } catch (error) {
671
+ pending.delete(id);
672
+ reject(new ServiceError("TRANSPORT_ERROR", error instanceof Error ? error.message : String(error)));
673
+ }
674
+ });
675
+ }
676
+ function requestExtension(type, payload, contractVersion, access) {
677
+ const id = `req-${seq += 1}`;
678
+ return new Promise((resolve, reject) => {
679
+ pending.set(id, {
680
+ resolve,
681
+ reject
682
+ });
683
+ try {
684
+ transport.send({
685
+ id,
686
+ type,
687
+ payload,
688
+ contractVersion
689
+ }, access === void 0 ? void 0 : { access });
690
+ } catch (error) {
691
+ pending.delete(id);
692
+ reject(new ServiceError("TRANSPORT_ERROR", error instanceof Error ? error.message : String(error)));
693
+ }
694
+ }).then((value) => {
695
+ const result = typeof value === "object" && value !== null ? value : void 0;
696
+ if (type === "extension.catalog.subscribe" && typeof result?.subscriptionId === "string" && typeof result.epoch === "string") catalogSubscriptions.set(result.subscriptionId, result.epoch);
697
+ if (type === "extension.catalog.unsubscribe" && typeof payload.subscriptionId === "string") catalogSubscriptions.delete(payload.subscriptionId);
698
+ if (type === "extension.subscribe" && typeof result?.subscriptionId === "string" && typeof result.epoch === "string") extensionSubscriptions.set(result.subscriptionId, result.epoch);
699
+ if (type === "extension.unsubscribe" && typeof payload.subscriptionId === "string") extensionSubscriptions.delete(payload.subscriptionId);
700
+ return value;
701
+ });
702
+ }
703
+ const asks = createTransportAskConnection(transport, request);
704
+ return {
705
+ request,
706
+ requestExtension,
707
+ subscribe(sessionId, handler) {
708
+ return fanout.add(sessionId, filterPrivateAskEvents(handler));
709
+ },
710
+ onReconnected(handler) {
711
+ if (transport.onReconnected === void 0) return () => void 0;
712
+ const detach = transport.onReconnected(handler);
713
+ return () => {
714
+ detach?.();
715
+ };
716
+ },
717
+ onExtension(handler) {
718
+ extensionListeners.add(handler);
719
+ return () => extensionListeners.delete(handler);
720
+ },
721
+ subscribeAwaited(sessionId) {
722
+ return transport.subscribeAwaited?.(sessionId) ?? Promise.resolve();
723
+ },
724
+ ...asks === void 0 ? {} : { asks },
725
+ close() {
726
+ asks?.close();
727
+ transport.close();
728
+ }
729
+ };
730
+ }
731
+ function createTransportAskConnection(transport, request) {
732
+ const onAskView = transport.onAskView;
733
+ const askOpen = transport.askOpen;
734
+ if (onAskView === void 0 || askOpen === void 0) return void 0;
735
+ const bindings = /* @__PURE__ */ new Map();
736
+ const invalidatedHandlers = /* @__PURE__ */ new Set();
737
+ function clearBinding(scope) {
738
+ const key = scopeKey(scope);
739
+ const entry = bindings.get(key);
740
+ if (entry === void 0) return;
741
+ bindings.delete(key);
742
+ entry.cancelled = true;
743
+ entry.subscription = void 0;
744
+ entry.opening = void 0;
745
+ }
746
+ function closeScope(scope) {
747
+ const key = scopeKey(scope);
748
+ const entry = bindings.get(key);
749
+ if (entry === void 0 || entry.cancelled) return;
750
+ entry.cancelled = true;
751
+ bindings.delete(key);
752
+ entry.subscription = void 0;
753
+ entry.opening = void 0;
754
+ transport.askClose?.(scope);
755
+ }
756
+ onAskView((message) => {
757
+ bindings.get(scopeKey(viewMessageScope(message)))?.receive(message);
758
+ });
759
+ transport.onAskInvalidated?.((scope, reason) => {
760
+ if (reason !== "disconnected") {
761
+ clearBinding(scope);
762
+ transport.askClose?.(scope);
763
+ } else {
764
+ const entry = bindings.get(scopeKey(scope));
765
+ if (entry !== void 0) entry.subscription = void 0;
766
+ }
767
+ for (const handler of invalidatedHandlers) handler(scope, reason);
768
+ });
769
+ return {
770
+ async open(scope, openOptions, receive) {
771
+ const key = scopeKey(scope);
772
+ const existing = bindings.get(key);
773
+ if (existing !== void 0 && !existing.cancelled) {
774
+ if (existing.opening !== void 0) return existing.opening;
775
+ if (existing.subscription !== void 0) return existing.subscription;
776
+ }
777
+ const entry = {
778
+ receive,
779
+ subscription: void 0,
780
+ opening: void 0,
781
+ cancelled: false
782
+ };
783
+ bindings.set(key, entry);
784
+ const opening = (async () => {
785
+ await askOpen.call(transport, scope, { answer: openOptions?.answer === true });
786
+ if (entry.cancelled) {
787
+ transport.askClose?.(scope);
788
+ throw new ServiceError("SCOPE_DENIED", "ask scope was closed while opening");
789
+ }
790
+ const subscription = { close: () => closeScope(scope) };
791
+ entry.subscription = subscription;
792
+ return subscription;
793
+ })();
794
+ entry.opening = opening;
795
+ try {
796
+ const subscription = await opening;
797
+ if (entry.opening === opening) entry.opening = void 0;
798
+ return subscription;
799
+ } catch (error) {
800
+ if (entry.opening === opening) entry.opening = void 0;
801
+ clearBinding(scope);
802
+ throw error;
803
+ }
804
+ },
805
+ async refresh(scope) {
806
+ await transport.askRefresh?.(scope);
807
+ },
808
+ async respond(command) {
809
+ return request(respondType(command), respondPayload(command));
810
+ },
811
+ onInvalidated(handler) {
812
+ invalidatedHandlers.add(handler);
813
+ return () => invalidatedHandlers.delete(handler);
814
+ },
815
+ close() {
816
+ for (const entry of bindings.values()) {
817
+ if (entry.subscription !== void 0) {
818
+ entry.subscription.close();
819
+ continue;
820
+ }
821
+ entry.cancelled = true;
822
+ }
823
+ bindings.clear();
824
+ }
825
+ };
826
+ }
827
+
828
+ //#endregion
829
+ //#region src/route-read-only.ts
830
+ const READ_ONLY_SERVICE_METHODS = new Set([
831
+ "ask.descendants",
832
+ "assembly.diagnostics",
833
+ "assembly.performanceDiagnostics",
834
+ "auth.status",
835
+ "chat.attempt.status",
836
+ "chat.executionStatus",
837
+ "chat.queue.list",
838
+ "command.catalog",
839
+ "composer.context",
840
+ "cost.summary",
841
+ "drafts.list",
842
+ "extension.permissions",
843
+ "fold.viewState",
844
+ "input.history",
845
+ "install.activation",
846
+ "install.list",
847
+ "jobs.list",
848
+ "jobs.read",
849
+ "mcp.snapshot",
850
+ "memory.entries",
851
+ "memory.read",
852
+ "mention.search",
853
+ "model.availability",
854
+ "model.list",
855
+ "model.preferences",
856
+ "perf.residency",
857
+ "plan.list",
858
+ "plugin.list",
859
+ "provider.list",
860
+ "recorder.pending.export",
861
+ "repository.capabilities",
862
+ "repository.committedNextSeq",
863
+ "repository.countEvents",
864
+ "repository.list",
865
+ "repository.loadMeta",
866
+ "repository.readArchivedEvents",
867
+ "repository.readCommitted",
868
+ "repository.readEvents",
869
+ "repository.recovery.capabilities",
870
+ "repository.recovery.get",
871
+ "repository.recovery.list",
872
+ "resource.read",
873
+ "runtime.askScope",
874
+ "schedules.list",
875
+ "service.handshake",
876
+ "session.archivedHistory",
877
+ "session.contextArchive.read",
878
+ "session.cwdContext",
879
+ "session.descendants",
880
+ "session.editedFiles",
881
+ "session.entry",
882
+ "session.permission.mode",
883
+ "session.forkPoints.list",
884
+ "session.list",
885
+ "session.counts",
886
+ "session.recovery.get",
887
+ "session.recovery.list",
888
+ "session.resultObligations",
889
+ "session.runtimeSnapshot",
890
+ "session.surface.read",
891
+ "session.timeline.detail",
892
+ "session.timeline.snapshot",
893
+ "session.work.snapshot",
894
+ "skill.snapshot",
895
+ "space.catalog",
896
+ "ui.catalog",
897
+ "ui.preferences.get",
898
+ "updates.status",
899
+ "worker.lifecycle",
900
+ "worker.restart.status",
901
+ "workspace.list",
902
+ "workspace.placement",
903
+ "workspace.readiness"
904
+ ]);
905
+
906
+ //#endregion
907
+ //#region src/authorize.ts
908
+ function isReadOnlyMethod(action) {
909
+ return READ_ONLY_SERVICE_METHODS.has(action);
910
+ }
911
+
912
+ //#endregion
913
+ //#region src/transport.ts
914
+ function isResponse(message) {
915
+ return typeof message === "object" && message !== null && "id" in message && "ok" in message;
916
+ }
917
+ function isExtensionFrame(message) {
918
+ if (typeof message !== "object" || message === null) return false;
919
+ const frame = message;
920
+ if (frame.kind === "extension.catalog.closed" || frame.kind === "extension.subscription.closed") return typeof frame.subscriptionId === "string" && typeof frame.epoch === "string" && (frame.reason === "closed" || frame.reason === "disconnected");
921
+ if (frame.kind === "extension.event") return typeof frame.subscriptionId === "string" && typeof frame.extensionId === "string" && typeof frame.workspaceKey === "string" && typeof frame.topic === "string" && typeof frame.contractVersion === "number" && Number.isInteger(frame.contractVersion) && frame.contractVersion > 0 && typeof frame.epoch === "string" && typeof frame.generation === "number" && typeof frame.sequence === "number" && Object.hasOwn(frame, "payload");
922
+ return frame.kind === "extension.catalog" && typeof frame.subscriptionId === "string" && typeof frame.workspaceKey === "string" && typeof frame.epoch === "string" && typeof frame.generation === "number" && (frame.reason === "changed" || frame.reason === "unavailable");
923
+ }
924
+ function isEvent(message) {
925
+ return typeof message === "object" && message !== null && "sessionId" in message && "kind" in message;
926
+ }
927
+ const AUTH_FRAME_ID = "__auth__";
928
+ function isAllowedWhileBlocked(type, access) {
929
+ return type === "session.subscribe" || type === "session.unsubscribe" || type.startsWith("ask.") || isReadOnlyMethod(type) || access === "read";
930
+ }
931
+ const AUTH_CLOSE_CODES = new Set([4001, 4003]);
932
+ const DEFAULT_BACKOFF_MS = 100;
933
+ function createWebSocketTransport(url, options = {}) {
934
+ const socketFactory = options.socketFactory ?? ((target) => new WebSocket(target));
935
+ const reconnect = options.reconnect;
936
+ const queue = [];
937
+ const subscribed = /* @__PURE__ */ new Set();
938
+ const subscribeIds = /* @__PURE__ */ new Map();
939
+ const lastSeqBySession = /* @__PURE__ */ new Map();
940
+ const askScopes = /* @__PURE__ */ new Map();
941
+ const askRequests = /* @__PURE__ */ new Map();
942
+ let askSeq = 0;
943
+ let socket;
944
+ let pendingAuth;
945
+ let state = { kind: "connecting" };
946
+ let generation = 0;
947
+ const generationHandlers = /* @__PURE__ */ new Set();
948
+ let lastCloseReason;
949
+ let resolveReady = () => {};
950
+ let rejectReady = () => {};
951
+ const ready = new Promise((resolve, reject) => {
952
+ resolveReady = resolve;
953
+ rejectReady = reject;
954
+ });
955
+ const handlers = {};
956
+ const resumeHandlers = /* @__PURE__ */ new Set();
957
+ const closeListeners = [];
958
+ function emitClose(info) {
959
+ for (const listener of [...closeListeners]) try {
960
+ listener(info);
961
+ } catch {
962
+ continue;
963
+ }
964
+ }
965
+ const subscribeWaiters = /* @__PURE__ */ new Map();
966
+ function settleSubscribeWaiters(sessionId, error) {
967
+ const waiters = subscribeWaiters.get(sessionId);
968
+ if (waiters === void 0) return;
969
+ subscribeWaiters.delete(sessionId);
970
+ for (const waiter of waiters) if (error === void 0) waiter.resolve();
971
+ else waiter.reject(error);
972
+ }
973
+ function rawSend(request) {
974
+ socket?.send(JSON.stringify(request));
975
+ }
976
+ function closeReasonOf(event) {
977
+ const reason = typeof event === "object" && event !== null ? String(event.reason ?? "") : "";
978
+ if (reason === "stale") return "stale";
979
+ if (reason === "resync-required") return "resync-required";
980
+ return "remote";
981
+ }
982
+ function flushQueue() {
983
+ for (const request of queue.splice(0)) rawSend(request);
984
+ }
985
+ function queueAskRequest(kind, scope, answer, replay) {
986
+ const id = `ask-${kind}-${askSeq += 1}`;
987
+ askRequests.set(id, {
988
+ scope,
989
+ kind,
990
+ replay
991
+ });
992
+ if (kind === "open") transport.send({
993
+ id,
994
+ type: "ask.open",
995
+ payload: {
996
+ scope,
997
+ answer
998
+ }
999
+ });
1000
+ else transport.send({
1001
+ id,
1002
+ type: "ask.refresh",
1003
+ payload: { scope }
1004
+ });
1005
+ return id;
1006
+ }
1007
+ function replayAskScopes() {
1008
+ const replays = [...askScopes.values()].map(({ scope, answer }) => new Promise((resolve) => {
1009
+ const id = `ask-open-${askSeq += 1}`;
1010
+ askRequests.set(id, {
1011
+ scope,
1012
+ kind: "open",
1013
+ replay: true,
1014
+ resolve
1015
+ });
1016
+ rawSend({
1017
+ id,
1018
+ type: "ask.open",
1019
+ payload: {
1020
+ scope,
1021
+ answer
1022
+ }
1023
+ });
1024
+ }));
1025
+ return Promise.all(replays);
1026
+ }
1027
+ function awaitAskRequest(id, scope, kind) {
1028
+ return new Promise((resolve, reject) => {
1029
+ const entry = askRequests.get(id);
1030
+ if (entry === void 0) {
1031
+ reject(new ServiceError("TRANSPORT_ERROR", "ask request was not queued"));
1032
+ return;
1033
+ }
1034
+ entry.resolve = resolve;
1035
+ entry.reject = (error) => {
1036
+ if (kind === "open") askScopes.delete(scopeKey(scope));
1037
+ reject(error);
1038
+ };
1039
+ });
1040
+ }
1041
+ function invokeInvalidated(scope, reason) {
1042
+ handlers.onAskInvalidated?.(scope, reason);
1043
+ }
1044
+ function reasonForError(error) {
1045
+ if (error.code === "SCOPE_DENIED") return "scope-denied";
1046
+ if (error.code === "STALE_RUNTIME") return "stale-runtime";
1047
+ if (error.code === "ROUTE_NOT_READY") return "disconnected";
1048
+ return "closed";
1049
+ }
1050
+ function settleAskRequest(res) {
1051
+ const entry = res.id === void 0 ? void 0 : askRequests.get(res.id);
1052
+ if (entry === void 0 || res.id === void 0) return;
1053
+ askRequests.delete(res.id);
1054
+ if (res.ok) {
1055
+ entry.resolve?.();
1056
+ return;
1057
+ }
1058
+ const error = new ServiceError(res.error?.code ?? "UNKNOWN", res.error?.message ?? "ask request failed");
1059
+ if (!entry.replay) {
1060
+ askScopes.delete(scopeKey(entry.scope));
1061
+ entry.reject?.(error);
1062
+ return;
1063
+ }
1064
+ askScopes.delete(scopeKey(entry.scope));
1065
+ invokeInvalidated(entry.scope, reasonForError(error));
1066
+ entry.resolve?.();
1067
+ }
1068
+ function failAskRequests() {
1069
+ for (const [id, entry] of askRequests) {
1070
+ askRequests.delete(id);
1071
+ if (!entry.replay) entry.reject?.(new ServiceError("CONNECTION_LOST", "connection lost before the ask request completed"));
1072
+ else entry.resolve?.();
1073
+ }
1074
+ }
1075
+ function sendSubscribe(sessionId) {
1076
+ const lastSeq = lastSeqBySession.get(sessionId);
1077
+ const request = {
1078
+ id: `sub-${sessionId}`,
1079
+ type: "session.subscribe",
1080
+ payload: lastSeq === void 0 ? { sessionId } : {
1081
+ sessionId,
1082
+ sinceSeq: lastSeq
1083
+ }
1084
+ };
1085
+ if (state.kind !== "closed") subscribeIds.set(request.id, sessionId);
1086
+ transport.send(request);
1087
+ }
1088
+ function recordHeadSeq(sessionId, payload) {
1089
+ if (typeof payload !== "object" || payload === null) return;
1090
+ const headSeq = payload.headSeq;
1091
+ if (typeof headSeq !== "number" || !Number.isSafeInteger(headSeq) || headSeq < 0) return;
1092
+ if (headSeq > (lastSeqBySession.get(sessionId) ?? -1)) lastSeqBySession.set(sessionId, headSeq);
1093
+ }
1094
+ function settleSubscribeResponse(message) {
1095
+ const sessionId = message.id === void 0 ? void 0 : subscribeIds.get(message.id);
1096
+ if (message.id === void 0 || sessionId === void 0) return false;
1097
+ subscribeIds.delete(message.id);
1098
+ if (message.ok) {
1099
+ recordHeadSeq(sessionId, message.payload);
1100
+ settleSubscribeWaiters(sessionId);
1101
+ return true;
1102
+ }
1103
+ subscribed.delete(sessionId);
1104
+ settleSubscribeWaiters(sessionId, new ServiceError(message.error?.code ?? "SUBSCRIPTION_REJECTED", message.error?.message ?? `session "${sessionId}" subscription was rejected`));
1105
+ handlers.onEvent?.({
1106
+ kind: "error",
1107
+ sessionId,
1108
+ code: message.error?.code ?? "SUBSCRIPTION_REJECTED",
1109
+ message: message.error?.message ?? `session "${sessionId}" subscription was rejected`
1110
+ });
1111
+ return true;
1112
+ }
1113
+ function invalidateAskScopes(reason) {
1114
+ for (const entry of askScopes.values()) invokeInvalidated(entry.scope, reason);
1115
+ }
1116
+ function beginReconnect(nextAttempt) {
1117
+ if (reconnect === void 0 || nextAttempt > reconnect.maxAttempts) return false;
1118
+ state = {
1119
+ kind: "reconnecting",
1120
+ attempt: nextAttempt
1121
+ };
1122
+ const linearDelay = (reconnect.backoffMs ?? DEFAULT_BACKOFF_MS) * nextAttempt;
1123
+ const delay = Math.min(linearDelay, reconnect.maxBackoffMs ?? Number.POSITIVE_INFINITY);
1124
+ setTimeout(() => {
1125
+ if (state.kind === "reconnecting" && state.attempt === nextAttempt) connect();
1126
+ }, delay);
1127
+ return true;
1128
+ }
1129
+ function failAuthentication() {
1130
+ if (state.kind === "closed") return;
1131
+ queue.length = 0;
1132
+ lastCloseReason = "auth-failed";
1133
+ state = {
1134
+ kind: "closed",
1135
+ reason: "auth-failed"
1136
+ };
1137
+ failAskRequests();
1138
+ invalidateAskScopes("closed");
1139
+ rejectReady(/* @__PURE__ */ new Error("websocket authentication failed"));
1140
+ emitClose({
1141
+ reason: "remote",
1142
+ reconnecting: false
1143
+ });
1144
+ socket?.close();
1145
+ }
1146
+ function connect() {
1147
+ const ws = socketFactory(url);
1148
+ socket = ws;
1149
+ ws.addEventListener("open", () => {
1150
+ if (socket !== ws || state.kind === "closed") return;
1151
+ const wasReconnect = state.kind === "reconnecting";
1152
+ if (options.authToken !== void 0) {
1153
+ pendingAuth = { wasReconnect };
1154
+ ws.send(JSON.stringify({
1155
+ id: AUTH_FRAME_ID,
1156
+ type: "auth",
1157
+ token: options.authToken,
1158
+ ...options.mode === void 0 ? {} : { mode: options.mode },
1159
+ ...options.features === void 0 || options.features.length === 0 ? {} : { features: [...options.features] }
1160
+ }));
1161
+ return;
1162
+ }
1163
+ markOpen(wasReconnect);
1164
+ });
1165
+ async function markOpen(wasReconnect) {
1166
+ if (wasReconnect) try {
1167
+ for (const handler of [...resumeHandlers]) await handler();
1168
+ } catch {
1169
+ if (state.kind === "closed" || socket !== ws) return;
1170
+ lastCloseReason = "resync-required";
1171
+ state = {
1172
+ kind: "closed",
1173
+ reason: "resync-required"
1174
+ };
1175
+ queue.length = 0;
1176
+ failAskRequests();
1177
+ invalidateAskScopes("closed");
1178
+ ws.close();
1179
+ emitClose({
1180
+ reason: "remote",
1181
+ reconnecting: false
1182
+ });
1183
+ return;
1184
+ }
1185
+ if (wasReconnect) await replayAskScopes();
1186
+ if (state.kind === "closed" || socket !== ws) return;
1187
+ state = { kind: "open" };
1188
+ generation += 1;
1189
+ if (wasReconnect) for (const sessionId of subscribed) sendSubscribe(sessionId);
1190
+ for (const handler of [...generationHandlers]) handler(generation);
1191
+ flushQueue();
1192
+ resolveReady();
1193
+ }
1194
+ ws.addEventListener("message", (event) => {
1195
+ if (socket !== ws) return;
1196
+ let message;
1197
+ try {
1198
+ message = JSON.parse(String(event.data));
1199
+ } catch {
1200
+ return;
1201
+ }
1202
+ if (isExtensionFrame(message)) {
1203
+ handlers.onExtension?.(message);
1204
+ return;
1205
+ }
1206
+ const frame = parseAskFrame(message);
1207
+ if (frame !== void 0) {
1208
+ if (frame.kind === "message") handlers.onAskView?.(frame.message);
1209
+ else handlers.onAskInvalidated?.(frame.scope, frame.reason);
1210
+ return;
1211
+ }
1212
+ if (pendingAuth !== void 0 && isResponse(message) && message.id === AUTH_FRAME_ID) {
1213
+ const { wasReconnect } = pendingAuth;
1214
+ pendingAuth = void 0;
1215
+ if (message.ok === true) markOpen(wasReconnect);
1216
+ else failAuthentication();
1217
+ return;
1218
+ }
1219
+ if (isResponse(message)) {
1220
+ if ((message.id === void 0 ? void 0 : askRequests.get(message.id)) !== void 0) {
1221
+ settleAskRequest(message);
1222
+ return;
1223
+ }
1224
+ if (settleSubscribeResponse(message)) return;
1225
+ handlers.onResponse?.(message);
1226
+ } else if (isEvent(message)) handlers.onEvent?.(message);
1227
+ });
1228
+ let settled = false;
1229
+ const onGone = (event) => {
1230
+ if (socket !== ws || settled) return;
1231
+ settled = true;
1232
+ pendingAuth = void 0;
1233
+ if (state.kind === "closed") return;
1234
+ const code = typeof event === "object" && event !== null ? event.code : void 0;
1235
+ if (typeof code === "number" && AUTH_CLOSE_CODES.has(code)) {
1236
+ failAuthentication();
1237
+ return;
1238
+ }
1239
+ queue.length = 0;
1240
+ if (state.kind === "connecting") {
1241
+ lastCloseReason = "exhausted";
1242
+ state = {
1243
+ kind: "closed",
1244
+ reason: "exhausted"
1245
+ };
1246
+ failAskRequests();
1247
+ rejectReady(/* @__PURE__ */ new Error("websocket connection failed"));
1248
+ emitClose({
1249
+ reason: "remote",
1250
+ reconnecting: false
1251
+ });
1252
+ return;
1253
+ }
1254
+ const reconnecting = beginReconnect(state.kind === "reconnecting" ? state.attempt + 1 : 1);
1255
+ const remoteReason = closeReasonOf(event);
1256
+ if (!reconnecting) {
1257
+ lastCloseReason = remoteReason === "stale" ? "stale" : "exhausted";
1258
+ state = {
1259
+ kind: "closed",
1260
+ reason: lastCloseReason
1261
+ };
1262
+ }
1263
+ failAskRequests();
1264
+ invalidateAskScopes(reconnecting ? "disconnected" : "closed");
1265
+ emitClose({
1266
+ reason: "remote",
1267
+ reconnecting
1268
+ });
1269
+ };
1270
+ ws.addEventListener("error", () => {
1271
+ if (state.kind !== "open") onGone();
1272
+ });
1273
+ ws.addEventListener("close", onGone);
1274
+ }
1275
+ const transport = {
1276
+ send(request, sendOptions) {
1277
+ if (state.kind === "closed") throw new Error("transport closed");
1278
+ if (options.writeGate !== void 0 && !options.writeGate() && !isAllowedWhileBlocked(request.type, sendOptions?.access)) throw new ServiceError("TRANSPORT_ERROR", "connection is not writable");
1279
+ if (state.kind === "open") rawSend(request);
1280
+ else queue.push(request);
1281
+ },
1282
+ subscribe(sessionId) {
1283
+ if (state.kind === "closed") return;
1284
+ subscribed.add(sessionId);
1285
+ if (state.kind === "reconnecting") return;
1286
+ sendSubscribe(sessionId);
1287
+ },
1288
+ subscribeAwaited(sessionId) {
1289
+ if (state.kind === "closed") return Promise.reject(new ServiceError("CONNECTION_CLOSED", "transport closed"));
1290
+ return new Promise((resolve, reject) => {
1291
+ const waiters = subscribeWaiters.get(sessionId) ?? [];
1292
+ waiters.push({
1293
+ resolve,
1294
+ reject
1295
+ });
1296
+ subscribeWaiters.set(sessionId, waiters);
1297
+ if (!subscribed.has(sessionId)) this.subscribe(sessionId);
1298
+ });
1299
+ },
1300
+ unsubscribe(sessionId) {
1301
+ subscribed.delete(sessionId);
1302
+ subscribeIds.delete(`sub-${sessionId}`);
1303
+ lastSeqBySession.delete(sessionId);
1304
+ if (state.kind !== "open") {
1305
+ const subscribeId = `sub-${sessionId}`;
1306
+ for (let i = queue.length - 1; i >= 0; i--) if (queue[i]?.id === subscribeId) queue.splice(i, 1);
1307
+ return;
1308
+ }
1309
+ this.send({
1310
+ id: `unsub-${sessionId}`,
1311
+ type: "session.unsubscribe",
1312
+ payload: { sessionId }
1313
+ });
1314
+ },
1315
+ onResponse(handler) {
1316
+ handlers.onResponse = handler;
1317
+ },
1318
+ onEvent(handler) {
1319
+ handlers.onEvent = handler;
1320
+ },
1321
+ onExtension(handler) {
1322
+ handlers.onExtension = handler;
1323
+ },
1324
+ onClose(handler) {
1325
+ closeListeners.push(handler);
1326
+ },
1327
+ onGeneration(handler) {
1328
+ generationHandlers.add(handler);
1329
+ return () => {
1330
+ generationHandlers.delete(handler);
1331
+ };
1332
+ },
1333
+ onReconnected(handler) {
1334
+ if (typeof handler !== "function") return () => void 0;
1335
+ resumeHandlers.add(handler);
1336
+ return () => {
1337
+ resumeHandlers.delete(handler);
1338
+ };
1339
+ },
1340
+ onAskView(handler) {
1341
+ handlers.onAskView = handler;
1342
+ },
1343
+ onAskInvalidated(handler) {
1344
+ handlers.onAskInvalidated = handler;
1345
+ },
1346
+ askOpen(scope, { answer }) {
1347
+ if (state.kind === "closed") return Promise.reject(new ServiceError("CONNECTION_CLOSED", "transport closed"));
1348
+ askScopes.set(scopeKey(scope), {
1349
+ scope,
1350
+ answer
1351
+ });
1352
+ let id;
1353
+ try {
1354
+ id = queueAskRequest("open", scope, answer, false);
1355
+ } catch (error) {
1356
+ askScopes.delete(scopeKey(scope));
1357
+ return Promise.reject(new ServiceError("TRANSPORT_ERROR", error instanceof Error ? error.message : String(error)));
1358
+ }
1359
+ return awaitAskRequest(id, scope, "open");
1360
+ },
1361
+ askRefresh(scope) {
1362
+ if (state.kind === "closed") return Promise.reject(new ServiceError("CONNECTION_CLOSED", "transport closed"));
1363
+ let id;
1364
+ try {
1365
+ id = queueAskRequest("refresh", scope, false, false);
1366
+ } catch (error) {
1367
+ return Promise.reject(new ServiceError("TRANSPORT_ERROR", error instanceof Error ? error.message : String(error)));
1368
+ }
1369
+ return awaitAskRequest(id, scope, "refresh");
1370
+ },
1371
+ askClose(scope) {
1372
+ if (!askScopes.delete(scopeKey(scope))) return;
1373
+ try {
1374
+ this.send({
1375
+ id: `ask-close-${askSeq += 1}`,
1376
+ type: "ask.close",
1377
+ payload: { scope }
1378
+ });
1379
+ } catch {
1380
+ return;
1381
+ }
1382
+ },
1383
+ close() {
1384
+ if (state.kind === "closed") return;
1385
+ if (state.kind === "connecting") rejectReady(new ServiceError("CONNECTION_CLOSED", "transport closed before connection opened"));
1386
+ lastCloseReason = "local";
1387
+ state = {
1388
+ kind: "closed",
1389
+ reason: "local"
1390
+ };
1391
+ queue.length = 0;
1392
+ subscribeIds.clear();
1393
+ for (const sessionId of [...subscribeWaiters.keys()]) settleSubscribeWaiters(sessionId, new ServiceError("CONNECTION_CLOSED", "transport closed before subscribe was acknowledged"));
1394
+ failAskRequests();
1395
+ invalidateAskScopes("closed");
1396
+ socket?.close();
1397
+ emitClose({
1398
+ reason: "local",
1399
+ reconnecting: false
1400
+ });
1401
+ }
1402
+ };
1403
+ connect();
1404
+ return {
1405
+ transport,
1406
+ ready,
1407
+ close: () => transport.close(),
1408
+ closeReason: () => lastCloseReason,
1409
+ generation: () => generation
1410
+ };
1411
+ }
1412
+
1413
+ //#endregion
1414
+ export { GLOBAL_EVENTS_CHANNEL, RequestForbiddenError, ServiceError, createEventFanout, createHttpWsClient, createWebSocketTransport, filterPrivateAskEvents, isPerSessionOnlyEvent, isPrivateAskEvent, isServiceError };