@dxos/edge-client 0.10.0 → 0.11.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 (57) hide show
  1. package/dist/lib/chunk-edge-ws-muxer.mjs +322 -0
  2. package/dist/lib/chunk-edge-ws-muxer.mjs.map +1 -0
  3. package/dist/lib/cors-proxy.mjs +29 -0
  4. package/dist/lib/cors-proxy.mjs.map +1 -0
  5. package/dist/lib/edge-ws-muxer.mjs +2 -0
  6. package/dist/lib/index.mjs +1769 -0
  7. package/dist/lib/index.mjs.map +1 -0
  8. package/dist/lib/service.mjs +138 -0
  9. package/dist/lib/service.mjs.map +1 -0
  10. package/dist/lib/testing.mjs +160 -0
  11. package/dist/lib/testing.mjs.map +1 -0
  12. package/dist/types/src/base-http-client.d.ts +18 -0
  13. package/dist/types/src/base-http-client.d.ts.map +1 -1
  14. package/dist/types/src/browser-rendering.d.ts +0 -7
  15. package/dist/types/src/browser-rendering.d.ts.map +1 -1
  16. package/dist/types/src/edge-client.d.ts +22 -2
  17. package/dist/types/src/edge-client.d.ts.map +1 -1
  18. package/dist/types/src/edge-http-client.d.ts +86 -2
  19. package/dist/types/src/edge-http-client.d.ts.map +1 -1
  20. package/dist/types/src/edge-ws-connection.d.ts +19 -0
  21. package/dist/types/src/edge-ws-connection.d.ts.map +1 -1
  22. package/dist/types/src/edge-ws-connection.test.d.ts +2 -0
  23. package/dist/types/src/edge-ws-connection.test.d.ts.map +1 -0
  24. package/dist/types/src/index.d.ts +1 -0
  25. package/dist/types/src/index.d.ts.map +1 -1
  26. package/dist/types/src/protocol.d.ts +2 -1
  27. package/dist/types/src/protocol.d.ts.map +1 -1
  28. package/dist/types/src/testing/test-utils.d.ts.map +1 -1
  29. package/dist/types/tsconfig.tsbuildinfo +1 -1
  30. package/package.json +20 -20
  31. package/src/base-http-client.ts +71 -3
  32. package/src/browser-rendering.ts +0 -9
  33. package/src/edge-client.ts +21 -3
  34. package/src/edge-http-client.test.ts +121 -0
  35. package/src/edge-http-client.ts +156 -2
  36. package/src/edge-ws-connection.test.ts +219 -0
  37. package/src/edge-ws-connection.ts +97 -28
  38. package/src/index.ts +1 -0
  39. package/src/protocol.ts +11 -2
  40. package/src/testing/test-utils.ts +5 -1
  41. package/dist/lib/neutral/chunk-J5LGTIGS.mjs +0 -10
  42. package/dist/lib/neutral/chunk-J5LGTIGS.mjs.map +0 -7
  43. package/dist/lib/neutral/chunk-L5ZHLJ4B.mjs +0 -310
  44. package/dist/lib/neutral/chunk-L5ZHLJ4B.mjs.map +0 -7
  45. package/dist/lib/neutral/chunk-WQKMEZJR.mjs +0 -30
  46. package/dist/lib/neutral/chunk-WQKMEZJR.mjs.map +0 -7
  47. package/dist/lib/neutral/cors-proxy.mjs +0 -8
  48. package/dist/lib/neutral/cors-proxy.mjs.map +0 -7
  49. package/dist/lib/neutral/edge-ws-muxer.mjs +0 -12
  50. package/dist/lib/neutral/edge-ws-muxer.mjs.map +0 -7
  51. package/dist/lib/neutral/index.mjs +0 -1524
  52. package/dist/lib/neutral/index.mjs.map +0 -7
  53. package/dist/lib/neutral/meta.json +0 -1
  54. package/dist/lib/neutral/service/index.mjs +0 -134
  55. package/dist/lib/neutral/service/index.mjs.map +0 -7
  56. package/dist/lib/neutral/testing/index.mjs +0 -161
  57. package/dist/lib/neutral/testing/index.mjs.map +0 -7
@@ -1,1524 +0,0 @@
1
- import {
2
- proxyFetchLegacy
3
- } from "./chunk-WQKMEZJR.mjs";
4
- import {
5
- CLOUDFLARE_MESSAGE_MAX_BYTES,
6
- CLOUDFLARE_RPC_MAX_BYTES,
7
- Protocol,
8
- WebSocketMuxer,
9
- getTypename,
10
- protocol,
11
- toUint8Array
12
- } from "./chunk-L5ZHLJ4B.mjs";
13
- import "./chunk-J5LGTIGS.mjs";
14
-
15
- // src/index.ts
16
- export * from "@dxos/protocols/buf/dxos/edge/messenger_pb";
17
-
18
- // src/auth.ts
19
- import { createCredential, createDidFromIdentityKey, signPresentation } from "@dxos/credentials";
20
- import { invariant } from "@dxos/invariant";
21
- import { Keyring } from "@dxos/keyring";
22
- import { IdentityDid, PublicKey } from "@dxos/keys";
23
- var __dxlog_file = "/__w/dxos/dxos/packages/core/mesh/edge-client/src/auth.ts";
24
- var createDeviceEdgeIdentity = async (signer, key) => {
25
- return {
26
- identityDid: await createDidFromIdentityKey(key),
27
- peerKey: key.toHex(),
28
- presentCredentials: async ({ challenge }) => {
29
- return signPresentation({
30
- presentation: {
31
- credentials: [
32
- // Verifier requires at least one credential in the presentation to establish the subject.
33
- await createCredential({
34
- assertion: {
35
- "@type": "dxos.halo.credentials.Auth"
36
- },
37
- issuer: key,
38
- subject: key,
39
- signer
40
- })
41
- ]
42
- },
43
- signer,
44
- signerKey: key,
45
- nonce: challenge
46
- });
47
- }
48
- };
49
- };
50
- var createChainEdgeIdentity = async (signer, identityKey, peerKey, chain, credentials) => {
51
- const credentialsToSign = credentials.length > 0 ? credentials : [
52
- await createCredential({
53
- assertion: {
54
- "@type": "dxos.halo.credentials.Auth"
55
- },
56
- issuer: identityKey,
57
- subject: identityKey,
58
- signer,
59
- chain,
60
- signingKey: peerKey
61
- })
62
- ];
63
- return {
64
- identityDid: await createDidFromIdentityKey(identityKey),
65
- peerKey: peerKey.toHex(),
66
- presentCredentials: async ({ challenge }) => {
67
- invariant(chain, void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 56, S: void 0, A: ["chain", ""] });
68
- return signPresentation({
69
- presentation: {
70
- credentials: credentialsToSign
71
- },
72
- signer,
73
- nonce: challenge,
74
- signerKey: peerKey,
75
- chain
76
- });
77
- }
78
- };
79
- };
80
- var createEphemeralEdgeIdentity = async () => {
81
- const keyring = new Keyring();
82
- const key = await keyring.createKey();
83
- return createDeviceEdgeIdentity(keyring, key);
84
- };
85
- var createTestHaloEdgeIdentity = async (signer, identityKey, deviceKey) => {
86
- const deviceAdmission = await createCredential({
87
- assertion: {
88
- "@type": "dxos.halo.credentials.AuthorizedDevice",
89
- deviceKey,
90
- identityKey
91
- },
92
- issuer: identityKey,
93
- subject: deviceKey,
94
- signer
95
- });
96
- return createChainEdgeIdentity(signer, identityKey, deviceKey, {
97
- credential: deviceAdmission
98
- }, [
99
- await createCredential({
100
- assertion: {
101
- "@type": "dxos.halo.credentials.Auth"
102
- },
103
- issuer: identityKey,
104
- subject: identityKey,
105
- signer
106
- })
107
- ]);
108
- };
109
- var createStubEdgeIdentity = () => {
110
- const deviceKey = PublicKey.random();
111
- return {
112
- // Random placeholder DID — the stub never authenticates or connects; a real identity replaces it.
113
- identityDid: IdentityDid.random(),
114
- peerKey: deviceKey.toHex(),
115
- presentCredentials: async () => {
116
- throw new Error("Stub identity does not support authentication.");
117
- }
118
- };
119
- };
120
-
121
- // src/edge-client.ts
122
- import { Event, PersistentLifecycle, Trigger, TriggerState, scheduleMicroTask, scheduleTaskInterval as scheduleTaskInterval2 } from "@dxos/async";
123
- import { TRACE_SPAN_ATTRIBUTE } from "@dxos/context";
124
- import { Resource as Resource2 } from "@dxos/context";
125
- import { log as log2, logInfo as logInfo2 } from "@dxos/log";
126
- import { EdgeStatus } from "@dxos/protocols/proto/dxos/client/services";
127
-
128
- // src/edge-identity.ts
129
- import { invariant as invariant2 } from "@dxos/invariant";
130
- import { schema } from "@dxos/protocols/proto";
131
- var __dxlog_file2 = "/__w/dxos/dxos/packages/core/mesh/edge-client/src/edge-identity.ts";
132
- var handleAuthChallenge = async (failedResponse, identity) => {
133
- invariant2(failedResponse.status === 401, void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 7, S: void 0, A: ["failedResponse.status === 401", ""] });
134
- const headerValue = failedResponse.headers.get("Www-Authenticate");
135
- invariant2(headerValue?.startsWith("VerifiablePresentation challenge="), void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 9, S: void 0, A: ["headerValue?.startsWith('VerifiablePresentation challenge=')", ""] });
136
- const challenge = headerValue?.slice("VerifiablePresentation challenge=".length);
137
- invariant2(challenge, void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 11, S: void 0, A: ["challenge", ""] });
138
- const presentation = await identity.presentCredentials({
139
- challenge: Buffer.from(challenge, "base64")
140
- });
141
- return schema.getCodecForType("dxos.halo.credentials.Presentation").encode(presentation);
142
- };
143
-
144
- // src/edge-ws-connection.ts
145
- import WebSocket from "isomorphic-ws";
146
- import { scheduleTask, scheduleTaskInterval } from "@dxos/async";
147
- import { Context, Resource } from "@dxos/context";
148
- import { invariant as invariant3 } from "@dxos/invariant";
149
- import { log, logInfo } from "@dxos/log";
150
- import { EdgeWebsocketProtocol } from "@dxos/protocols";
151
- import { buf } from "@dxos/protocols/buf";
152
- import { MessageSchema } from "@dxos/protocols/buf/dxos/edge/messenger_pb";
153
- var __dxlog_file3 = "/__w/dxos/dxos/packages/core/mesh/edge-client/src/edge-ws-connection.ts";
154
- function _ts_decorate(decorators, target, key, desc) {
155
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
156
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
157
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
158
- return c > 3 && r && Object.defineProperty(target, key, r), r;
159
- }
160
- var SIGNAL_KEEPALIVE_INTERVAL = 4e3;
161
- var SIGNAL_KEEPALIVE_TIMEOUT = 12e3;
162
- var EdgeWsConnection = class extends Resource {
163
- _identity;
164
- _connectionInfo;
165
- _callbacks;
166
- _inactivityTimeoutCtx;
167
- _ws;
168
- _wsMuxer;
169
- _lastReceivedMessageTimestamp = Date.now();
170
- _openTimestamp;
171
- // Latency tracking.
172
- _pingTimestamp;
173
- _rtt = 0;
174
- // Rate tracking with sliding window.
175
- _uploadRate = 0;
176
- _downloadRate = 0;
177
- _rateWindow = 1e4;
178
- _rateUpdateInterval = 1e3;
179
- _bytesSamples = [];
180
- _messagesSent = 0;
181
- _messagesReceived = 0;
182
- constructor(_identity, _connectionInfo, _callbacks) {
183
- super(), this._identity = _identity, this._connectionInfo = _connectionInfo, this._callbacks = _callbacks;
184
- }
185
- get info() {
186
- return {
187
- open: this.isOpen,
188
- identity: this._identity.identityDid,
189
- device: this._identity.peerKey
190
- };
191
- }
192
- get rtt() {
193
- return this._rtt;
194
- }
195
- get uptime() {
196
- return this._openTimestamp ? (Date.now() - this._openTimestamp) / 1e3 : 0;
197
- }
198
- get uploadRate() {
199
- return this._uploadRate;
200
- }
201
- get downloadRate() {
202
- return this._downloadRate;
203
- }
204
- get messagesSent() {
205
- return this._messagesSent;
206
- }
207
- get messagesReceived() {
208
- return this._messagesReceived;
209
- }
210
- send(message) {
211
- invariant3(this._ws, void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file3, L: 72, S: this, A: ["this._ws", ""] });
212
- invariant3(this._wsMuxer, void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file3, L: 73, S: this, A: ["this._wsMuxer", ""] });
213
- log("sending...", {
214
- peerKey: this._identity.peerKey,
215
- payload: protocol.getPayloadType(message)
216
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file3, L: 74, S: this });
217
- this._messagesSent++;
218
- if (this._ws?.protocol.includes(EdgeWebsocketProtocol.V0)) {
219
- const binary = buf.toBinary(MessageSchema, message);
220
- if (binary.length > CLOUDFLARE_MESSAGE_MAX_BYTES) {
221
- log.error("Message dropped because it was too large (>1MB).", {
222
- byteLength: binary.byteLength,
223
- serviceId: message.serviceId,
224
- payload: protocol.getPayloadType(message)
225
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file3, L: 82, S: this });
226
- return;
227
- }
228
- this._recordBytes(binary.byteLength, 0);
229
- this._ws.send(binary);
230
- } else {
231
- const binary = buf.toBinary(MessageSchema, message);
232
- this._recordBytes(binary.byteLength, 0);
233
- this._wsMuxer.send(message).catch((e) => log.catch(e, void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file3, L: 95, S: this }));
234
- }
235
- }
236
- async _open() {
237
- const baseProtocols = [
238
- ...Object.values(EdgeWebsocketProtocol)
239
- ];
240
- this._ws = new WebSocket(this._connectionInfo.url.toString(), this._connectionInfo.protocolHeader ? [
241
- ...baseProtocols,
242
- this._connectionInfo.protocolHeader
243
- ] : [
244
- ...baseProtocols
245
- ], this._connectionInfo.headers ? {
246
- headers: this._connectionInfo.headers
247
- } : void 0);
248
- const muxer = new WebSocketMuxer(this._ws);
249
- this._wsMuxer = muxer;
250
- this._ws.onopen = () => {
251
- if (this.isOpen) {
252
- log("connected", void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file3, L: 114, S: this });
253
- this._openTimestamp = Date.now();
254
- this._callbacks.onConnected();
255
- this._scheduleHeartbeats();
256
- this._scheduleRateCalculation();
257
- } else {
258
- log.verbose("connected after becoming inactive", {
259
- currentIdentity: this._identity
260
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file3, L: 120, S: this });
261
- }
262
- };
263
- this._ws.onclose = (event) => {
264
- if (this.isOpen) {
265
- log.warn("server disconnected", {
266
- code: event.code,
267
- reason: event.reason
268
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file3, L: 127, S: this });
269
- this._callbacks.onRestartRequired();
270
- muxer.destroy();
271
- }
272
- };
273
- this._ws.onerror = (event) => {
274
- if (this.isOpen) {
275
- log.warn("edge connection socket error", {
276
- error: event.error,
277
- info: event.message
278
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file3, L: 137, S: this });
279
- this._callbacks.onRestartRequired();
280
- } else {
281
- log.verbose("error ignored on closed connection", {
282
- error: event.error
283
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file3, L: 143, S: this });
284
- }
285
- };
286
- this._ws.onmessage = async (event) => {
287
- if (!this.isOpen) {
288
- log.verbose("message ignored on closed connection", {
289
- event: event.type
290
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file3, L: 152, S: this });
291
- return;
292
- }
293
- this._lastReceivedMessageTimestamp = Date.now();
294
- if (event.data === "__pong__") {
295
- if (this._pingTimestamp) {
296
- this._rtt = Date.now() - this._pingTimestamp;
297
- this._pingTimestamp = void 0;
298
- }
299
- this._rescheduleHeartbeatTimeout();
300
- return;
301
- }
302
- const bytes = await toUint8Array(event.data);
303
- this._recordBytes(0, bytes.byteLength);
304
- if (!this.isOpen) {
305
- return;
306
- }
307
- this._messagesReceived++;
308
- const message = this._ws?.protocol?.includes(EdgeWebsocketProtocol.V0) ? buf.fromBinary(MessageSchema, bytes) : muxer.receiveData(bytes);
309
- if (message) {
310
- log("received", {
311
- from: message.source,
312
- payload: protocol.getPayloadType(message)
313
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file3, L: 175, S: this });
314
- this._callbacks.onMessage(message);
315
- }
316
- };
317
- }
318
- async _close() {
319
- void this._inactivityTimeoutCtx?.dispose().catch(() => {
320
- });
321
- try {
322
- this._ws?.close();
323
- this._ws = void 0;
324
- this._wsMuxer?.destroy();
325
- this._wsMuxer = void 0;
326
- } catch (err) {
327
- if (err instanceof Error && err.message.includes("WebSocket is closed before the connection is established.")) {
328
- return;
329
- }
330
- log.warn("error closing websocket", {
331
- err
332
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file3, L: 194, S: this });
333
- }
334
- }
335
- _scheduleHeartbeats() {
336
- invariant3(this._ws, void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file3, L: 200, S: this, A: ["this._ws", ""] });
337
- scheduleTaskInterval(this._ctx, async () => {
338
- this._pingTimestamp = Date.now();
339
- this._ws?.send("__ping__");
340
- }, SIGNAL_KEEPALIVE_INTERVAL);
341
- this._pingTimestamp = Date.now();
342
- this._ws.send("__ping__");
343
- this._rescheduleHeartbeatTimeout();
344
- }
345
- _rescheduleHeartbeatTimeout() {
346
- if (!this.isOpen) {
347
- return;
348
- }
349
- void this._inactivityTimeoutCtx?.dispose();
350
- this._inactivityTimeoutCtx = new Context(void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file3, L: 216 });
351
- scheduleTask(this._inactivityTimeoutCtx, () => {
352
- if (this.isOpen) {
353
- if (Date.now() - this._lastReceivedMessageTimestamp > SIGNAL_KEEPALIVE_TIMEOUT) {
354
- log.warn("restart due to inactivity timeout", {
355
- lastReceivedMessageTimestamp: this._lastReceivedMessageTimestamp
356
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file3, L: 220, S: this });
357
- this._callbacks.onRestartRequired();
358
- } else {
359
- this._rescheduleHeartbeatTimeout();
360
- }
361
- }
362
- }, SIGNAL_KEEPALIVE_TIMEOUT);
363
- }
364
- _recordBytes(sent, received) {
365
- const now = Date.now();
366
- const currentSecond = Math.floor(now / 1e3) * 1e3;
367
- const existingSample = this._bytesSamples.find((s) => Math.floor(s.timestamp / 1e3) * 1e3 === currentSecond);
368
- if (existingSample) {
369
- existingSample.sent += sent;
370
- existingSample.received += received;
371
- } else {
372
- this._bytesSamples.push({
373
- timestamp: now,
374
- sent,
375
- received
376
- });
377
- }
378
- }
379
- _scheduleRateCalculation() {
380
- scheduleTaskInterval(this._ctx, async () => {
381
- this._calculateRates();
382
- }, this._rateUpdateInterval);
383
- this._calculateRates();
384
- }
385
- _calculateRates() {
386
- const now = Date.now();
387
- const cutoff = now - this._rateWindow;
388
- this._bytesSamples = this._bytesSamples.filter((s) => s.timestamp > cutoff);
389
- if (this._bytesSamples.length === 0) {
390
- this._uploadRate = 0;
391
- this._downloadRate = 0;
392
- return;
393
- }
394
- let totalSent = 0;
395
- let totalReceived = 0;
396
- const oldestTimestamp = Math.min(...this._bytesSamples.map((s) => s.timestamp));
397
- const timeSpan = (now - oldestTimestamp) / 1e3;
398
- for (const sample of this._bytesSamples) {
399
- totalSent += sample.sent;
400
- totalReceived += sample.received;
401
- }
402
- this._uploadRate = timeSpan > 0 ? Math.round(totalSent / timeSpan) : 0;
403
- this._downloadRate = timeSpan > 0 ? Math.round(totalReceived / timeSpan) : 0;
404
- }
405
- };
406
- _ts_decorate([
407
- logInfo
408
- ], EdgeWsConnection.prototype, "info", null);
409
-
410
- // src/errors.ts
411
- var EdgeConnectionClosedError = class extends Error {
412
- constructor() {
413
- super("Edge connection closed.");
414
- }
415
- };
416
- var EdgeIdentityChangedError = class extends Error {
417
- constructor() {
418
- super("Edge identity changed.");
419
- }
420
- };
421
-
422
- // src/utils.ts
423
- var getEdgeUrlWithProtocol = (baseUrl, protocol2) => {
424
- const isSecure = baseUrl.startsWith("https") || baseUrl.startsWith("wss");
425
- const url = new URL(baseUrl);
426
- url.protocol = protocol2 + (isSecure ? "s" : "");
427
- return url.toString();
428
- };
429
-
430
- // src/edge-client.ts
431
- var __dxlog_file4 = "/__w/dxos/dxos/packages/core/mesh/edge-client/src/edge-client.ts";
432
- function _ts_decorate2(decorators, target, key, desc) {
433
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
434
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
435
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
436
- return c > 3 && r && Object.defineProperty(target, key, r), r;
437
- }
438
- var DEFAULT_TIMEOUT = 1e4;
439
- var STATUS_REFRESH_INTERVAL = 1e3;
440
- var EdgeClient = class extends Resource2 {
441
- _identity;
442
- _config;
443
- statusChanged = new Event();
444
- _persistentLifecycle = new PersistentLifecycle({
445
- start: async () => this._connect(),
446
- stop: async (state) => this._disconnect(state)
447
- });
448
- _messageListeners = /* @__PURE__ */ new Set();
449
- _reconnectListeners = /* @__PURE__ */ new Set();
450
- _baseWsUrl;
451
- _baseHttpUrl;
452
- _currentConnection = void 0;
453
- _ready = new Trigger();
454
- constructor(_identity, _config) {
455
- super(), this._identity = _identity, this._config = _config;
456
- this._baseWsUrl = getEdgeUrlWithProtocol(_config.socketEndpoint, "ws");
457
- this._baseHttpUrl = getEdgeUrlWithProtocol(_config.socketEndpoint, "http");
458
- }
459
- get info() {
460
- return {
461
- open: this.isOpen,
462
- status: this.status,
463
- identity: this._identity.identityDid,
464
- device: this._identity.peerKey
465
- };
466
- }
467
- get status() {
468
- return {
469
- state: Boolean(this._currentConnection) && this._ready.state === TriggerState.RESOLVED ? EdgeStatus.ConnectionState.CONNECTED : EdgeStatus.ConnectionState.NOT_CONNECTED,
470
- uptime: this._currentConnection?.uptime ?? 0,
471
- rtt: this._currentConnection?.rtt ?? 0,
472
- rateBytesUp: this._currentConnection?.uploadRate ?? 0,
473
- rateBytesDown: this._currentConnection?.downloadRate ?? 0,
474
- messagesSent: this._currentConnection?.messagesSent ?? 0,
475
- messagesReceived: this._currentConnection?.messagesReceived ?? 0
476
- };
477
- }
478
- get identityDid() {
479
- return this._identity.identityDid;
480
- }
481
- get peerKey() {
482
- return this._identity.peerKey;
483
- }
484
- setIdentity(identity) {
485
- if (identity.identityDid !== this._identity.identityDid || identity.peerKey !== this._identity.peerKey) {
486
- log2("Edge identity changed", {
487
- identity,
488
- oldIdentity: this._identity
489
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 74, S: this });
490
- this._identity = identity;
491
- this._closeCurrentConnection(new EdgeIdentityChangedError());
492
- void this._persistentLifecycle.scheduleRestart();
493
- }
494
- }
495
- /**
496
- * Send message.
497
- * NOTE: The message is guaranteed to be delivered but the service must respond with a message to confirm processing.
498
- */
499
- async send(ctx, message) {
500
- if (this._ready.state !== TriggerState.RESOLVED) {
501
- log2("waiting for websocket", void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 88, S: this });
502
- await this._ready.wait({
503
- timeout: this._config.timeout ?? DEFAULT_TIMEOUT
504
- });
505
- }
506
- if (!this._currentConnection) {
507
- throw new EdgeConnectionClosedError();
508
- }
509
- if (message.source && (message.source.peerKey !== this._identity.peerKey || message.source.identityDid !== this.identityDid)) {
510
- throw new EdgeIdentityChangedError();
511
- }
512
- const traceCtx = ctx.getAttribute(TRACE_SPAN_ATTRIBUTE);
513
- if (traceCtx) {
514
- message.traceContext = {
515
- $typeName: "dxos.edge.messenger.TraceContext",
516
- traceparent: traceCtx.traceparent,
517
- tracestate: traceCtx.tracestate
518
- };
519
- }
520
- this._currentConnection.send(message);
521
- }
522
- onMessage(listener) {
523
- this._messageListeners.add(listener);
524
- return () => this._messageListeners.delete(listener);
525
- }
526
- onReconnected(listener) {
527
- this._reconnectListeners.add(listener);
528
- if (this._ready.state === TriggerState.RESOLVED) {
529
- scheduleMicroTask(this._ctx, () => {
530
- if (this._reconnectListeners.has(listener)) {
531
- try {
532
- listener();
533
- } catch (error) {
534
- log2.catch(error, void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 124, S: this });
535
- }
536
- }
537
- });
538
- }
539
- return () => this._reconnectListeners.delete(listener);
540
- }
541
- /**
542
- * Open connection to messaging service.
543
- */
544
- async _open() {
545
- log2("opening...", {
546
- info: this.info
547
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 134, S: this });
548
- this._persistentLifecycle.open().catch((err) => {
549
- log2.warn("Error while opening connection", {
550
- err
551
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 138, S: this });
552
- });
553
- scheduleTaskInterval2(this._ctx, async () => {
554
- if (!this._currentConnection) {
555
- return;
556
- }
557
- this.statusChanged.emit(this.status);
558
- }, STATUS_REFRESH_INTERVAL);
559
- }
560
- /**
561
- * Close connection and free resources.
562
- */
563
- async _close() {
564
- log2("closing...", {
565
- peerKey: this._identity.peerKey
566
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 153, S: this });
567
- this._closeCurrentConnection();
568
- await this._persistentLifecycle.close();
569
- }
570
- async _connect() {
571
- if (this._ctx.disposed) {
572
- return void 0;
573
- }
574
- const identity = this._identity;
575
- const path = `/ws/${identity.identityDid}/${identity.peerKey}`;
576
- const protocolHeader = this._config.disableAuth ? void 0 : await this._createAuthHeader(path);
577
- if (this._identity !== identity) {
578
- log2("identity changed during auth header request", void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 167, S: this });
579
- return void 0;
580
- }
581
- const restartRequired = new Trigger();
582
- const url = new URL(path, this._baseWsUrl);
583
- log2("Opening websocket", {
584
- url: url.toString(),
585
- protocolHeader
586
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 172, S: this });
587
- const connection = new EdgeWsConnection(identity, {
588
- url,
589
- protocolHeader,
590
- headers: this._config.clientTag ? {
591
- "X-DXOS-Client-Tag": this._config.clientTag
592
- } : void 0
593
- }, {
594
- onConnected: () => {
595
- if (this._isActive(connection)) {
596
- this._ready.wake();
597
- this._notifyReconnected();
598
- } else {
599
- log2.verbose("connected callback ignored, because connection is not active", void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 188, S: this });
600
- }
601
- },
602
- onRestartRequired: () => {
603
- if (this._isActive(connection)) {
604
- this._closeCurrentConnection();
605
- void this._persistentLifecycle.scheduleRestart();
606
- } else {
607
- log2.verbose("restart requested by inactive connection", void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 196, S: this });
608
- }
609
- restartRequired.wake();
610
- },
611
- onMessage: (message) => {
612
- if (this._isActive(connection)) {
613
- this._notifyMessageReceived(message);
614
- } else {
615
- log2.verbose("ignored a message on inactive connection", {
616
- from: message.source,
617
- type: message.payload?.typeUrl
618
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 204, S: this });
619
- }
620
- }
621
- });
622
- this._currentConnection = connection;
623
- await connection.open();
624
- const becameReady = await Promise.race([
625
- this._ready.wait({
626
- timeout: this._config.timeout ?? DEFAULT_TIMEOUT
627
- }).then(() => true, () => false),
628
- restartRequired.wait().then(() => false)
629
- ]);
630
- if (!becameReady) {
631
- throw new EdgeConnectionClosedError();
632
- }
633
- return connection;
634
- }
635
- async _disconnect(state) {
636
- await state.close();
637
- this.statusChanged.emit(this.status);
638
- }
639
- _closeCurrentConnection(error = new EdgeConnectionClosedError()) {
640
- this._currentConnection = void 0;
641
- this._ready.throw(error);
642
- this._ready.reset();
643
- this.statusChanged.emit(this.status);
644
- }
645
- _notifyReconnected() {
646
- this.statusChanged.emit(this.status);
647
- for (const listener of this._reconnectListeners) {
648
- try {
649
- listener();
650
- } catch (err) {
651
- log2.error("ws reconnect listener failed", {
652
- err
653
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 245, S: this });
654
- }
655
- }
656
- }
657
- _notifyMessageReceived(message) {
658
- for (const listener of this._messageListeners) {
659
- try {
660
- listener(message);
661
- } catch (err) {
662
- log2.error("ws incoming message processing failed", {
663
- err,
664
- payload: protocol.getPayloadType(message)
665
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 256, S: this });
666
- }
667
- }
668
- }
669
- async _createAuthHeader(path) {
670
- const httpUrl = new URL(path, this._baseHttpUrl);
671
- httpUrl.protocol = getEdgeUrlWithProtocol(this._baseWsUrl.toString(), "http");
672
- const response = await fetch(httpUrl, {
673
- method: "GET"
674
- });
675
- if (response.status === 401) {
676
- return encodePresentationWsAuthHeader(await handleAuthChallenge(response, this._identity));
677
- } else {
678
- log2.warn("no auth challenge from edge", {
679
- status: response.status,
680
- statusText: response.statusText
681
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 272, S: this });
682
- return void 0;
683
- }
684
- }
685
- _isActive = (connection) => connection === this._currentConnection;
686
- };
687
- _ts_decorate2([
688
- logInfo2
689
- ], EdgeClient.prototype, "info", null);
690
- var encodePresentationWsAuthHeader = (encodedPresentation) => {
691
- const encodedToken = Buffer.from(encodedPresentation).toString("base64").replace(/=*$/, "").replaceAll("/", "|");
692
- return `base64url.bearer.authorization.dxos.org.${encodedToken}`;
693
- };
694
-
695
- // src/base-http-client.ts
696
- import { sleep } from "@dxos/async";
697
- import { TRACE_SPAN_ATTRIBUTE as TRACE_SPAN_ATTRIBUTE2 } from "@dxos/context";
698
- import { invariant as invariant4 } from "@dxos/invariant";
699
- import { log as log4 } from "@dxos/log";
700
- import { EDGE_CLIENT_TAG_HEADER, EdgeAuthChallengeError, EdgeCallFailedError } from "@dxos/protocols";
701
-
702
- // src/http-client.ts
703
- import * as Context2 from "effect/Context";
704
- import * as Duration from "effect/Duration";
705
- import * as Effect from "effect/Effect";
706
- import * as Layer from "effect/Layer";
707
- import * as Schedule from "effect/Schedule";
708
- import { log as log3 } from "@dxos/log";
709
- var __dxlog_file5 = "/__w/dxos/dxos/packages/core/mesh/edge-client/src/http-client.ts";
710
- var HttpConfig = class _HttpConfig extends Context2.Tag("HttpConfig")() {
711
- static default = Layer.succeed(_HttpConfig, {
712
- timeout: Duration.millis(1e3),
713
- retryTimes: 3,
714
- retryBaseDelay: Duration.millis(1e3)
715
- });
716
- };
717
- var withRetry = (effect, { timeout: timeout2 = Duration.millis(1e3), retryBaseDelay = Duration.millis(1e3), retryTimes = 3 } = {}) => {
718
- return effect.pipe(Effect.flatMap((res) => (
719
- // Treat 500 errors as retryable?
720
- res.status === 500 ? Effect.fail(new Error(res.status.toString())) : res.json
721
- )), Effect.timeout(timeout2), Effect.retry({
722
- schedule: Schedule.exponential(retryBaseDelay).pipe(Schedule.jittered),
723
- times: retryTimes
724
- }));
725
- };
726
- var withRetryConfig = (effect) => Effect.gen(function* () {
727
- const config = yield* HttpConfig;
728
- return yield* withRetry(effect, config);
729
- });
730
- var withLogging = (effect) => effect.pipe(Effect.tap((res) => {
731
- log3.info("response", {
732
- status: res.status
733
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file5, L: 31, S: void 0 });
734
- }));
735
- var encodeAuthHeader = (challenge) => {
736
- const encodedChallenge = Buffer.from(challenge).toString("base64");
737
- return `VerifiablePresentation pb;base64,${encodedChallenge}`;
738
- };
739
-
740
- // src/base-http-client.ts
741
- var __dxlog_file6 = "/__w/dxos/dxos/packages/core/mesh/edge-client/src/base-http-client.ts";
742
- var DEFAULT_RETRY_TIMEOUT = 1500;
743
- var DEFAULT_RETRY_JITTER = 500;
744
- var DEFAULT_MAX_RETRIES_COUNT = 3;
745
- var WARNING_BODY_SIZE = 10 * 1024 * 1024;
746
- var BaseHttpClient = class {
747
- _baseUrl;
748
- _clientTag;
749
- _edgeIdentity;
750
- /** Auth header cached until next 401. */
751
- _authHeader;
752
- constructor(baseUrl, options) {
753
- this._baseUrl = getEdgeUrlWithProtocol(baseUrl, "http");
754
- this._clientTag = options?.clientTag;
755
- log4("created", {
756
- url: this._baseUrl
757
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file6, L: 24, S: this });
758
- }
759
- get baseUrl() {
760
- return this._baseUrl;
761
- }
762
- setIdentity(identity) {
763
- if (this._edgeIdentity?.identityDid !== identity.identityDid || this._edgeIdentity?.peerKey !== identity.peerKey) {
764
- this._edgeIdentity = identity;
765
- this._authHeader = void 0;
766
- }
767
- }
768
- // TODO(mykola): Extend `_call` to support streaming/raw `Response` returns so
769
- // `EdgeHttpClient.anthropicAiRequest` can be absorbed here and the auth/retry loop
770
- // stops being duplicated across the two paths.
771
- async _call(ctx, url, args) {
772
- const shouldRetry = createRetryHandler(args);
773
- log4("fetch", {
774
- url,
775
- hasBody: args.body !== void 0,
776
- bodySize: typeof args.body === "string" ? args.body.length : void 0
777
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file6, L: 43, S: this });
778
- const traceHeaders = getTraceHeaders(ctx);
779
- let handledAuth = false;
780
- const tryCount = 1;
781
- while (true) {
782
- let processingError = void 0;
783
- try {
784
- if (!this._authHeader && args.auth) {
785
- const response2 = await fetch(new URL("/auth", this._baseUrl));
786
- if (response2.status === 401) {
787
- this._authHeader = await this._handleUnauthorized(response2);
788
- }
789
- }
790
- const request = createRequest(args, this._authHeader, traceHeaders, this._clientTag);
791
- log4("call", {
792
- url,
793
- tryCount,
794
- authHeader: !!this._authHeader
795
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file6, L: 61, S: this });
796
- const response = await fetch(url, request);
797
- if (response.ok) {
798
- const contentType2 = response.headers.get("Content-Type") ?? "";
799
- if (response.status === 204 || response.headers.get("Content-Length") === "0" || !contentType2.includes("application/json")) {
800
- return void 0;
801
- }
802
- const body2 = await response.clone().json();
803
- if (typeof body2 !== "object" || body2 === null) {
804
- return body2;
805
- }
806
- if (!("success" in body2)) {
807
- return body2;
808
- }
809
- if (body2.success) {
810
- return body2.data;
811
- }
812
- } else if (response.status === 401 && response.headers.get("WWW-Authenticate") !== null && !handledAuth) {
813
- this._authHeader = await this._handleUnauthorized(response);
814
- handledAuth = true;
815
- continue;
816
- }
817
- const contentType = response.headers.get("Content-Type") ?? "";
818
- const body = contentType.startsWith("application/json") ? await response.clone().json() : void 0;
819
- invariant4(!body?.success, "Expected body to not be a failure response or undefined.", { "~LogMeta": "~LogMeta", F: __dxlog_file6, L: 92, S: this, A: ["!body?.success", "'Expected body to not be a failure response or undefined.'"] });
820
- if (body?.data?.type === "auth_challenge" && typeof body?.data?.challenge === "string") {
821
- processingError = new EdgeAuthChallengeError(body.data.challenge, body.data);
822
- } else if (body?.success === false) {
823
- processingError = EdgeCallFailedError.fromUnsuccessfulResponse(response, body);
824
- } else {
825
- invariant4(!response.ok, "Expected response to not be ok.", { "~LogMeta": "~LogMeta", F: __dxlog_file6, L: 98, S: this, A: ["!response.ok", "'Expected response to not be ok.'"] });
826
- processingError = await EdgeCallFailedError.fromHttpFailure(response);
827
- }
828
- } catch (error) {
829
- processingError = EdgeCallFailedError.fromProcessingFailureCause(error);
830
- }
831
- if (processingError?.isRetryable && await shouldRetry(ctx, processingError.retryAfterMs)) {
832
- log4.verbose("retrying request", {
833
- url,
834
- processingError
835
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file6, L: 105, S: this });
836
- } else {
837
- throw processingError;
838
- }
839
- }
840
- }
841
- async _handleUnauthorized(response) {
842
- if (!this._edgeIdentity) {
843
- log4.warn("unauthorized response received before identity was set", void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file6, L: 116, S: this });
844
- throw await EdgeCallFailedError.fromHttpFailure(response);
845
- }
846
- const challenge = await handleAuthChallenge(response, this._edgeIdentity);
847
- return encodeAuthHeader(challenge);
848
- }
849
- };
850
- var createRequest = ({ method, body, json = true }, authHeader, traceHeaders, clientTag) => {
851
- let requestBody;
852
- const headers = {};
853
- if (json) {
854
- requestBody = body === void 0 ? void 0 : JSON.stringify(body);
855
- headers["Content-Type"] = "application/json";
856
- } else {
857
- requestBody = body;
858
- }
859
- if (typeof requestBody === "string" && requestBody.length > WARNING_BODY_SIZE) {
860
- log4.warn("Request with large body", {
861
- bodySize: requestBody.length
862
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file6, L: 133, S: void 0 });
863
- }
864
- if (authHeader) {
865
- headers["Authorization"] = authHeader;
866
- }
867
- if (traceHeaders) {
868
- Object.assign(headers, traceHeaders);
869
- }
870
- if (clientTag) {
871
- headers[EDGE_CLIENT_TAG_HEADER] = clientTag;
872
- }
873
- return {
874
- method,
875
- body: requestBody,
876
- headers
877
- };
878
- };
879
- var getTraceHeaders = (ctx) => {
880
- const traceCtx = ctx.getAttribute(TRACE_SPAN_ATTRIBUTE2);
881
- if (!traceCtx) {
882
- return void 0;
883
- }
884
- const headers = {
885
- traceparent: traceCtx.traceparent
886
- };
887
- if (traceCtx.tracestate) {
888
- headers.tracestate = traceCtx.tracestate;
889
- }
890
- return headers;
891
- };
892
- var createRetryHandler = ({ retry: retry2 }) => {
893
- if (!retry2 || retry2.count < 1) {
894
- return async () => false;
895
- }
896
- let retries = 0;
897
- const maxRetries = retry2.count ?? DEFAULT_MAX_RETRIES_COUNT;
898
- const baseTimeout = retry2.timeout ?? DEFAULT_RETRY_TIMEOUT;
899
- const jitter = retry2.jitter ?? DEFAULT_RETRY_JITTER;
900
- return async (ctx, retryAfter) => {
901
- if (++retries > maxRetries || ctx.disposed) {
902
- return false;
903
- }
904
- if (retryAfter) {
905
- await sleep(retryAfter);
906
- } else {
907
- const timeout2 = baseTimeout + Math.random() * jitter;
908
- await sleep(timeout2);
909
- }
910
- return true;
911
- };
912
- };
913
-
914
- // src/edge-ai-http-client.ts
915
- import * as Headers2 from "@effect/platform/Headers";
916
- import * as HttpClient from "@effect/platform/HttpClient";
917
- import * as HttpClientError from "@effect/platform/HttpClientError";
918
- import * as HttpClientResponse from "@effect/platform/HttpClientResponse";
919
- import * as Effect2 from "effect/Effect";
920
- import * as FiberRef from "effect/FiberRef";
921
- import * as Layer2 from "effect/Layer";
922
- import * as Stream from "effect/Stream";
923
- import { BaseError } from "@dxos/errors";
924
- import { log as log5 } from "@dxos/log";
925
- import { BYOK_HEADER } from "@dxos/protocols";
926
- var __dxlog_file7 = "/__w/dxos/dxos/packages/core/mesh/edge-client/src/edge-ai-http-client.ts";
927
- var ByokError = class extends BaseError.extend("ByokError", "BYOK authentication failed") {
928
- constructor(options) {
929
- super({
930
- context: {
931
- status: options.status,
932
- provider: options.provider
933
- },
934
- ...options
935
- });
936
- }
937
- };
938
- var UsageQuotaExceededError = class extends BaseError.extend("UsageQuotaExceededError", "Usage quota exceeded") {
939
- };
940
- var requestInitTagKey = "@effect/platform/FetchHttpClient/FetchOptions";
941
- var isUserDefinedAnthropicTool = (tool) => tool.input_schema != null && typeof tool.input_schema === "object";
942
- var patchAnthropicMessagesRequestBody = (body) => {
943
- if (body == null) {
944
- return body;
945
- }
946
- const decodeBody = () => {
947
- if (typeof body === "string") {
948
- return body;
949
- }
950
- if (body instanceof Uint8Array) {
951
- return new TextDecoder().decode(body);
952
- }
953
- return void 0;
954
- };
955
- const text = decodeBody();
956
- if (text == null) {
957
- return body;
958
- }
959
- try {
960
- const payload = JSON.parse(text);
961
- if (!Array.isArray(payload.tools)) {
962
- return body;
963
- }
964
- payload.tools = payload.tools.map((tool) => isUserDefinedAnthropicTool(tool) ? {
965
- ...tool,
966
- eager_input_streaming: true
967
- } : tool);
968
- const patched = JSON.stringify(payload);
969
- return typeof body === "string" ? patched : new TextEncoder().encode(patched);
970
- } catch {
971
- return body;
972
- }
973
- };
974
- var readStreamBody = (stream) => Effect2.promise(async () => {
975
- const response = new Response(stream);
976
- return await response.text();
977
- });
978
- var EdgeAiHttpClient = class _EdgeAiHttpClient {
979
- static make = (getClient) => HttpClient.make((request, url, signal, fiber) => {
980
- const edgeClient = getClient();
981
- const context = fiber.getFiberRef(FiberRef.currentContext);
982
- const options = context.unsafeMap.get(requestInitTagKey) ?? {};
983
- const headers = options.headers ? Headers2.merge(Headers2.fromInput(options.headers), request.headers) : request.headers;
984
- const carriedByok = !!headers[BYOK_HEADER.toLowerCase()];
985
- const send = (body) => Effect2.tryPromise({
986
- try: () => edgeClient.anthropicAiRequest(new Request(url, {
987
- ...options,
988
- method: request.method,
989
- headers,
990
- body: patchAnthropicMessagesRequestBody(body),
991
- signal
992
- })),
993
- catch: (cause) => {
994
- log5.error("Failed to fetch", {
995
- cause
996
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file7, L: 106, S: this });
997
- return new HttpClientError.RequestError({
998
- request,
999
- reason: "Transport",
1000
- cause
1001
- });
1002
- }
1003
- }).pipe(Effect2.flatMap((response) => {
1004
- const httpResponse = HttpClientResponse.fromWeb(request, response);
1005
- if (carriedByok && (response.status === 401 || response.status === 403)) {
1006
- return Effect2.tryPromise({
1007
- try: () => response.clone().json(),
1008
- catch: () => void 0
1009
- }).pipe(Effect2.orElseSucceed(() => void 0), Effect2.flatMap((body2) => Effect2.fail(new HttpClientError.ResponseError({
1010
- request,
1011
- response: httpResponse,
1012
- reason: "StatusCode",
1013
- cause: new ByokError({
1014
- status: response.status,
1015
- provider: "anthropic.com",
1016
- message: body2?.error?.message ?? "Authentication failed"
1017
- })
1018
- }))));
1019
- }
1020
- if (!carriedByok && response.status === 429) {
1021
- return Effect2.tryPromise({
1022
- try: () => response.clone().json(),
1023
- catch: () => void 0
1024
- }).pipe(Effect2.orElseSucceed(() => void 0), Effect2.flatMap((body2) => Effect2.fail(new HttpClientError.ResponseError({
1025
- request,
1026
- response: httpResponse,
1027
- reason: "StatusCode",
1028
- cause: new UsageQuotaExceededError({
1029
- message: body2?.error?.message
1030
- })
1031
- }))));
1032
- }
1033
- return Effect2.succeed(httpResponse);
1034
- }));
1035
- switch (request.body._tag) {
1036
- case "Raw":
1037
- case "Uint8Array":
1038
- return send(request.body.body);
1039
- case "FormData":
1040
- return send(request.body.formData);
1041
- case "Stream":
1042
- return Stream.toReadableStreamEffect(request.body.stream).pipe(Effect2.flatMap((readable) => readStreamBody(readable)), Effect2.flatMap((text) => send(text)));
1043
- }
1044
- return send(void 0);
1045
- });
1046
- static layer = (getClient) => Layer2.succeed(HttpClient.HttpClient, _EdgeAiHttpClient.make(getClient));
1047
- };
1048
-
1049
- // src/edge-http-client.ts
1050
- import * as FetchHttpClient from "@effect/platform/FetchHttpClient";
1051
- import * as HttpClient3 from "@effect/platform/HttpClient";
1052
- import * as HttpClientRequest from "@effect/platform/HttpClientRequest";
1053
- import * as Effect3 from "effect/Effect";
1054
- import * as Function from "effect/Function";
1055
- import { EffectEx } from "@dxos/effect";
1056
- import { invariant as invariant5 } from "@dxos/invariant";
1057
- import { log as log6 } from "@dxos/log";
1058
- import { EDGE_CLIENT_TAG_HEADER as EDGE_CLIENT_TAG_HEADER2 } from "@dxos/protocols";
1059
- import { createUrl } from "@dxos/util";
1060
- var __dxlog_file8 = "/__w/dxos/dxos/packages/core/mesh/edge-client/src/edge-http-client.ts";
1061
- var EdgeHttpClient = class extends BaseHttpClient {
1062
- constructor(baseUrl, options) {
1063
- super(baseUrl, options);
1064
- log6("created", {
1065
- url: this.baseUrl
1066
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file8, L: 25, S: this });
1067
- }
1068
- //
1069
- // Status
1070
- //
1071
- async getStatus(ctx, args) {
1072
- return this._call(ctx, new URL("/status", this.baseUrl), {
1073
- ...args,
1074
- method: "GET",
1075
- auth: true
1076
- });
1077
- }
1078
- //
1079
- // Agents
1080
- //
1081
- createAgent(ctx, body, args) {
1082
- return this._call(ctx, new URL("/agents/create", this.baseUrl), {
1083
- ...args,
1084
- method: "POST",
1085
- body
1086
- });
1087
- }
1088
- getAgentStatus(ctx, request, args) {
1089
- return this._call(ctx, new URL(`/users/${request.ownerIdentityDid}/agent/status`, this.baseUrl), {
1090
- ...args,
1091
- method: "GET"
1092
- });
1093
- }
1094
- //
1095
- // Credentials
1096
- //
1097
- getCredentialsForNotarization(ctx, spaceId, args) {
1098
- return this._call(ctx, new URL(`/spaces/${spaceId}/notarization`, this.baseUrl), {
1099
- ...args,
1100
- method: "GET"
1101
- });
1102
- }
1103
- async notarizeCredentials(ctx, spaceId, body, args) {
1104
- await this._call(ctx, new URL(`/spaces/${spaceId}/notarization`, this.baseUrl), {
1105
- ...args,
1106
- body,
1107
- method: "POST"
1108
- });
1109
- }
1110
- //
1111
- // Identity
1112
- //
1113
- async recoverIdentity(ctx, body, args) {
1114
- return this._call(ctx, new URL("/identity/recover", this.baseUrl), {
1115
- ...args,
1116
- body,
1117
- method: "POST"
1118
- });
1119
- }
1120
- //
1121
- // Invitations (space join)
1122
- //
1123
- async joinSpaceByInvitation(ctx, spaceId, body, args) {
1124
- return this._call(ctx, new URL(`/spaces/${spaceId}/join`, this.baseUrl), {
1125
- ...args,
1126
- body,
1127
- method: "POST"
1128
- });
1129
- }
1130
- //
1131
- // OAuth
1132
- //
1133
- async initiateOAuthFlow(ctx, body, args) {
1134
- return this._call(ctx, new URL("/oauth/initiate", this.baseUrl), {
1135
- ...args,
1136
- body,
1137
- method: "POST"
1138
- });
1139
- }
1140
- async completeOAuthRegistration(ctx, body, args) {
1141
- return this._call(ctx, new URL("/oauth/registration/complete", this.baseUrl), {
1142
- ...args,
1143
- body,
1144
- method: "POST"
1145
- });
1146
- }
1147
- //
1148
- // Spaces
1149
- //
1150
- async createSpace(ctx, body, args) {
1151
- return this._call(ctx, new URL("/spaces/create", this.baseUrl), {
1152
- ...args,
1153
- body,
1154
- method: "POST"
1155
- });
1156
- }
1157
- //
1158
- // Queues
1159
- //
1160
- async queryQueue(ctx, subspaceTag, spaceId, query, args) {
1161
- const queueId = query.queueIds?.[0];
1162
- invariant5(queueId, "queueId required", { "~LogMeta": "~LogMeta", F: __dxlog_file8, L: 123, S: this, A: ["queueId", "'queueId required'"] });
1163
- return this._call(ctx, createUrl(new URL(`/spaces/${subspaceTag}/${spaceId}/queue/${queueId}/query`, this.baseUrl), {
1164
- after: query.after,
1165
- before: query.before,
1166
- limit: query.limit,
1167
- reverse: query.reverse,
1168
- objectIds: query.objectIds?.join(",")
1169
- }), {
1170
- ...args,
1171
- method: "GET"
1172
- });
1173
- }
1174
- async insertIntoQueue(ctx, subspaceTag, spaceId, queueId, objects, args) {
1175
- return this._call(ctx, new URL(`/spaces/${subspaceTag}/${spaceId}/queue/${queueId}`, this.baseUrl), {
1176
- ...args,
1177
- body: {
1178
- objects
1179
- },
1180
- method: "POST"
1181
- });
1182
- }
1183
- async deleteFromQueue(ctx, subspaceTag, spaceId, queueId, objectIds, args) {
1184
- return this._call(ctx, createUrl(new URL(`/spaces/${subspaceTag}/${spaceId}/queue/${queueId}`, this.baseUrl), {
1185
- ids: objectIds.join(",")
1186
- }), {
1187
- ...args,
1188
- method: "DELETE"
1189
- });
1190
- }
1191
- //
1192
- // Functions
1193
- //
1194
- async uploadFunction(ctx, pathParts, body, args) {
1195
- const formData = new FormData();
1196
- formData.append("name", body.name ?? "");
1197
- formData.append("version", body.version);
1198
- const ownerUri = this._edgeIdentity?.identityDid ?? body.ownerUri;
1199
- formData.append("ownerUri", ownerUri);
1200
- formData.append("entryPoint", body.entryPoint);
1201
- body.runtime && formData.append("runtime", body.runtime);
1202
- for (const [filename, content] of Object.entries(body.assets)) {
1203
- formData.append("assets", new Blob([
1204
- content
1205
- ], {
1206
- type: getFileMimeType(filename)
1207
- }), filename);
1208
- }
1209
- const path = [
1210
- "functions",
1211
- ...pathParts.functionId ? [
1212
- pathParts.functionId
1213
- ] : []
1214
- ].join("/");
1215
- return this._call(ctx, new URL(path, this.baseUrl), {
1216
- ...args,
1217
- body: formData,
1218
- method: "PUT",
1219
- json: false
1220
- });
1221
- }
1222
- async listFunctions(ctx, args) {
1223
- return this._call(ctx, new URL("/functions", this.baseUrl), {
1224
- ...args,
1225
- method: "GET"
1226
- });
1227
- }
1228
- async invokeFunction(ctx, params, input, args) {
1229
- const url = new URL(`/functions/${params.functionId}`, this.baseUrl);
1230
- if (params.version) {
1231
- url.searchParams.set("version", params.version);
1232
- }
1233
- if (params.spaceId) {
1234
- url.searchParams.set("spaceId", params.spaceId.toString());
1235
- }
1236
- if (params.cpuTimeLimit) {
1237
- url.searchParams.set("cpuTimeLimit", params.cpuTimeLimit.toString());
1238
- }
1239
- if (params.subrequestsLimit) {
1240
- url.searchParams.set("subrequestsLimit", params.subrequestsLimit.toString());
1241
- }
1242
- return this._call(ctx, url, {
1243
- ...args,
1244
- body: input,
1245
- method: "POST"
1246
- });
1247
- }
1248
- //
1249
- // Workflows
1250
- //
1251
- async executeWorkflow(ctx, spaceId, graphId, input, args) {
1252
- return this._call(ctx, new URL(`/workflows/${spaceId}/${graphId}`, this.baseUrl), {
1253
- ...args,
1254
- body: input,
1255
- method: "POST"
1256
- });
1257
- }
1258
- //
1259
- // Triggers
1260
- //
1261
- async getCronTriggers(ctx, spaceId) {
1262
- return this._call(ctx, new URL(`/functions/${spaceId}/triggers/crons`, this.baseUrl), {
1263
- method: "GET"
1264
- });
1265
- }
1266
- async getTriggersDispatcherStatus(ctx, spaceId, args) {
1267
- return this._call(ctx, new URL(`/triggers/${spaceId}/status`, this.baseUrl), {
1268
- ...args,
1269
- method: "GET",
1270
- auth: true
1271
- });
1272
- }
1273
- async forceRunCronTrigger(ctx, spaceId, triggerId) {
1274
- return this._call(ctx, new URL(`/functions/${spaceId}/triggers/crons/${triggerId}/run`, this.baseUrl), {
1275
- method: "POST"
1276
- });
1277
- }
1278
- //
1279
- // Query
1280
- //
1281
- async execQuery(ctx, spaceId, body, args) {
1282
- return this._call(ctx, new URL(`/spaces/${spaceId}/exec-query`, this.baseUrl), {
1283
- ...args,
1284
- body,
1285
- method: "POST"
1286
- });
1287
- }
1288
- //
1289
- // Registry
1290
- //
1291
- async getRegistryPlugins(ctx, args) {
1292
- return this._call(ctx, new URL("/registry/plugins", this.baseUrl), {
1293
- ...args,
1294
- method: "GET"
1295
- });
1296
- }
1297
- /**
1298
- * Uploads a built plugin bundle to the registry's R2-backed hosting. Authenticated
1299
- * with the caller's hub identity (verifiable presentation) — `setIdentity` must
1300
- * have been called. Returns the canonical `moduleUrl` (the hosted `manifest.json`).
1301
- */
1302
- async uploadPluginBundle(ctx, request, args) {
1303
- return this._call(ctx, new URL("/registry/upload", this.baseUrl), {
1304
- body: request,
1305
- method: "POST",
1306
- auth: true,
1307
- ...args
1308
- });
1309
- }
1310
- //
1311
- // Import/Export
1312
- //
1313
- async importBundle(ctx, spaceId, body, args) {
1314
- return this._call(ctx, new URL(`/spaces/${spaceId}/import`, this.baseUrl), {
1315
- ...args,
1316
- body,
1317
- method: "PUT"
1318
- });
1319
- }
1320
- async exportBundle(ctx, spaceId, body, args) {
1321
- return this._call(ctx, new URL(`/spaces/${spaceId}/export`, this.baseUrl), {
1322
- ...args,
1323
- body,
1324
- method: "POST"
1325
- });
1326
- }
1327
- //
1328
- // Proxy
1329
- //
1330
- /**
1331
- * Fetch through the edge proxy for third-party REST APIs.
1332
- * TEMPORARY: currently routes through legacy open proxy. See https://github.com/dxos/edge/pull/576.
1333
- */
1334
- async proxyFetch(target, init = {}) {
1335
- return proxyFetchLegacy(target, init, this._clientTag);
1336
- }
1337
- //
1338
- // AI service.
1339
- //
1340
- /**
1341
- * Issue an authenticated request to the EDGE AI route (`/ai/generate/anthropic/*`), which
1342
- * proxies to the AI service. Used as the backend HTTP client for the Anthropic AI provider
1343
- * (see {@link EdgeAiHttpClient}).
1344
- *
1345
- * Returns the raw `Response` so streaming bodies are forwarded unchanged to `@effect/ai`.
1346
- * Requires an identity to have been set via {@link setIdentity}.
1347
- */
1348
- // TODO(mykola): Merge into `BaseHttpClient._call` once it can return a streaming/raw `Response`;
1349
- // the auth/retry loop below duplicates the one in `_call`.
1350
- async anthropicAiRequest(request) {
1351
- const incoming = new URL(request.url);
1352
- const base = this.baseUrl.replace(/\/$/, "");
1353
- const target = new URL(`${base}/ai/generate/anthropic${incoming.pathname}${incoming.search}`);
1354
- const method = request.method;
1355
- const body = method === "GET" || method === "HEAD" ? void 0 : await request.arrayBuffer();
1356
- let handledAuth = false;
1357
- while (true) {
1358
- if (!this._authHeader) {
1359
- const authResponse = await fetch(new URL("/auth", this.baseUrl));
1360
- if (authResponse.status === 401) {
1361
- this._authHeader = await this._handleUnauthorized(authResponse);
1362
- }
1363
- }
1364
- const headers = new Headers(request.headers);
1365
- if (this._authHeader) {
1366
- headers.set("Authorization", this._authHeader);
1367
- }
1368
- if (this._clientTag) {
1369
- headers.set(EDGE_CLIENT_TAG_HEADER2, this._clientTag);
1370
- }
1371
- const response = await fetch(target, {
1372
- method,
1373
- headers,
1374
- body,
1375
- signal: request.signal
1376
- });
1377
- if (response.status === 401 && response.headers.get("WWW-Authenticate") !== null && !handledAuth) {
1378
- this._authHeader = await this._handleUnauthorized(response);
1379
- handledAuth = true;
1380
- continue;
1381
- }
1382
- return response;
1383
- }
1384
- }
1385
- //
1386
- // Internal (Effect-based, used by tests)
1387
- //
1388
- async _fetch(url, _args) {
1389
- return Function.pipe(HttpClient3.execute(HttpClientRequest.make(_args.method)(url.toString())), withLogging, withRetryConfig, Effect3.provide(FetchHttpClient.layer), Effect3.provide(HttpConfig.default), Effect3.withSpan("EdgeHttpClient"), EffectEx.runAndForwardErrors);
1390
- }
1391
- };
1392
- var getFileMimeType = (filename) => [
1393
- ".js",
1394
- ".mjs"
1395
- ].some((ext) => filename.endsWith(ext)) ? "application/javascript+module" : filename.endsWith(".wasm") ? "application/wasm" : "application/octet-stream";
1396
-
1397
- // src/hub-http-client.ts
1398
- import { createUrl as createUrl2 } from "@dxos/util";
1399
- var HubHttpClient = class extends BaseHttpClient {
1400
- constructor(hubUrl, options) {
1401
- super(hubUrl, options);
1402
- }
1403
- //
1404
- // Public (unauthenticated) endpoints
1405
- //
1406
- async checkEmailExists(ctx, body, args) {
1407
- return this._call(ctx, new URL("/account/email/exists", this.baseUrl), {
1408
- ...args,
1409
- body,
1410
- method: "POST"
1411
- });
1412
- }
1413
- async validateInvitationCode(ctx, body, args) {
1414
- return this._call(ctx, new URL("/account/invitation-code/validate", this.baseUrl), {
1415
- ...args,
1416
- body,
1417
- method: "POST"
1418
- });
1419
- }
1420
- async redeemInvitationCode(ctx, body, args) {
1421
- return this._call(ctx, new URL("/account/invitation-code/redeem", this.baseUrl), {
1422
- ...args,
1423
- body,
1424
- method: "POST"
1425
- });
1426
- }
1427
- /**
1428
- * Existing-account email login. Server inlines `token` for test emails; regular
1429
- * emails are delivered out-of-band. Response is identical for unknown emails
1430
- * (enumeration-safe).
1431
- */
1432
- async login(ctx, body, args) {
1433
- return this._call(ctx, new URL("/account/login", this.baseUrl), {
1434
- ...args,
1435
- body,
1436
- method: "POST"
1437
- });
1438
- }
1439
- async requestAccess(ctx, body, args) {
1440
- return this._call(ctx, new URL("/account/request-access", this.baseUrl), {
1441
- ...args,
1442
- body,
1443
- method: "POST"
1444
- });
1445
- }
1446
- //
1447
- // Authenticated (VP) endpoints
1448
- //
1449
- async getAccount(ctx, args) {
1450
- return this._call(ctx, new URL("/account/me", this.baseUrl), {
1451
- ...args,
1452
- method: "GET"
1453
- });
1454
- }
1455
- async deleteAccount(ctx, args) {
1456
- return this._call(ctx, new URL("/account/me", this.baseUrl), {
1457
- ...args,
1458
- method: "DELETE"
1459
- });
1460
- }
1461
- async listAccountInvitations(ctx, args) {
1462
- return this._call(ctx, new URL("/account/invitation", this.baseUrl), {
1463
- ...args,
1464
- method: "GET"
1465
- });
1466
- }
1467
- async issueAccountInvitation(ctx, args) {
1468
- return this._call(ctx, new URL("/account/invitation/issue", this.baseUrl), {
1469
- ...args,
1470
- method: "POST"
1471
- });
1472
- }
1473
- async resendVerificationEmail(ctx, args) {
1474
- return this._call(ctx, new URL("/account/email/resend-verification", this.baseUrl), {
1475
- ...args,
1476
- method: "POST"
1477
- });
1478
- }
1479
- /**
1480
- * Rolling-window usage and effective limits for the authenticated identity.
1481
- * Served from the per-user metering DO; optional `windowSeconds` defaults to the largest limit window.
1482
- */
1483
- async getProfileUsage(ctx, query, args) {
1484
- return this._call(ctx, createUrl2(new URL("/api/metering/profile/usage", this.baseUrl), {
1485
- windowSeconds: query?.windowSeconds
1486
- }), {
1487
- ...args,
1488
- method: "GET"
1489
- });
1490
- }
1491
- };
1492
- export {
1493
- BaseHttpClient,
1494
- ByokError,
1495
- CLOUDFLARE_MESSAGE_MAX_BYTES,
1496
- CLOUDFLARE_RPC_MAX_BYTES,
1497
- EdgeAiHttpClient,
1498
- EdgeClient,
1499
- EdgeConnectionClosedError,
1500
- EdgeHttpClient,
1501
- EdgeIdentityChangedError,
1502
- HttpConfig,
1503
- HubHttpClient,
1504
- Protocol,
1505
- UsageQuotaExceededError,
1506
- WebSocketMuxer,
1507
- createChainEdgeIdentity,
1508
- createDeviceEdgeIdentity,
1509
- createEphemeralEdgeIdentity,
1510
- createStubEdgeIdentity,
1511
- createTestHaloEdgeIdentity,
1512
- encodeAuthHeader,
1513
- getTypename,
1514
- handleAuthChallenge,
1515
- patchAnthropicMessagesRequestBody,
1516
- protocol,
1517
- proxyFetchLegacy,
1518
- requestInitTagKey,
1519
- toUint8Array,
1520
- withLogging,
1521
- withRetry,
1522
- withRetryConfig
1523
- };
1524
- //# sourceMappingURL=index.mjs.map