@agent-relay/sdk 2.3.4 → 2.3.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +1 -29
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -38
- package/dist/index.js.map +1 -1
- package/package.json +4 -25
- package/dist/browser-client.d.ts +0 -212
- package/dist/browser-client.d.ts.map +0 -1
- package/dist/browser-client.js +0 -750
- package/dist/browser-client.js.map +0 -1
- package/dist/browser-framing.d.ts +0 -46
- package/dist/browser-framing.d.ts.map +0 -1
- package/dist/browser-framing.js +0 -122
- package/dist/browser-framing.js.map +0 -1
- package/dist/standalone.d.ts +0 -89
- package/dist/standalone.d.ts.map +0 -1
- package/dist/standalone.js +0 -131
- package/dist/standalone.js.map +0 -1
- package/dist/transports/index.d.ts +0 -92
- package/dist/transports/index.d.ts.map +0 -1
- package/dist/transports/index.js +0 -129
- package/dist/transports/index.js.map +0 -1
- package/dist/transports/socket-transport.d.ts +0 -30
- package/dist/transports/socket-transport.d.ts.map +0 -1
- package/dist/transports/socket-transport.js +0 -94
- package/dist/transports/socket-transport.js.map +0 -1
- package/dist/transports/types.d.ts +0 -69
- package/dist/transports/types.d.ts.map +0 -1
- package/dist/transports/types.js +0 -10
- package/dist/transports/types.js.map +0 -1
- package/dist/transports/websocket-transport.d.ts +0 -55
- package/dist/transports/websocket-transport.d.ts.map +0 -1
- package/dist/transports/websocket-transport.js +0 -180
- package/dist/transports/websocket-transport.js.map +0 -1
package/dist/browser-client.js
DELETED
|
@@ -1,750 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* BrowserRelayClient - Browser-compatible Agent Relay SDK Client
|
|
3
|
-
* @agent-relay/sdk
|
|
4
|
-
*
|
|
5
|
-
* A client designed for browser environments using WebSocket transport.
|
|
6
|
-
* Can also be used in Node.js with the WebSocket transport.
|
|
7
|
-
*
|
|
8
|
-
* Key differences from RelayClient:
|
|
9
|
-
* - Uses transport abstraction instead of direct socket access
|
|
10
|
-
* - No Node.js-specific dependencies (node:net, node:crypto)
|
|
11
|
-
* - Uses browser-compatible APIs (crypto.randomUUID, etc.)
|
|
12
|
-
*/
|
|
13
|
-
import { createAutoTransport, } from './transports/index.js';
|
|
14
|
-
import { PROTOCOL_VERSION, } from '@agent-relay/protocol';
|
|
15
|
-
import { encodeFrameLegacyBrowser, BrowserFrameParser } from './browser-framing.js';
|
|
16
|
-
const DEFAULT_CONFIG = {
|
|
17
|
-
agentName: 'agent',
|
|
18
|
-
quiet: false,
|
|
19
|
-
reconnect: true,
|
|
20
|
-
maxReconnectAttempts: 10,
|
|
21
|
-
reconnectDelayMs: 1000,
|
|
22
|
-
reconnectMaxDelayMs: 30000,
|
|
23
|
-
};
|
|
24
|
-
// Simple ID generator (browser-compatible)
|
|
25
|
-
let idCounter = 0;
|
|
26
|
-
function generateId() {
|
|
27
|
-
return `${Date.now().toString(36)}-${(++idCounter).toString(36)}`;
|
|
28
|
-
}
|
|
29
|
-
// Browser-compatible UUID generator
|
|
30
|
-
function generateUUID() {
|
|
31
|
-
// Use crypto.randomUUID if available (modern browsers)
|
|
32
|
-
if (typeof crypto !== 'undefined' && crypto.randomUUID) {
|
|
33
|
-
return crypto.randomUUID();
|
|
34
|
-
}
|
|
35
|
-
// Fallback: simple UUID v4 implementation
|
|
36
|
-
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
|
|
37
|
-
const r = (Math.random() * 16) | 0;
|
|
38
|
-
const v = c === 'x' ? r : (r & 0x3) | 0x8;
|
|
39
|
-
return v.toString(16);
|
|
40
|
-
});
|
|
41
|
-
}
|
|
42
|
-
/**
|
|
43
|
-
* Circular buffer for O(1) deduplication with bounded memory.
|
|
44
|
-
*/
|
|
45
|
-
class CircularDedupeCache {
|
|
46
|
-
ids = new Set();
|
|
47
|
-
ring;
|
|
48
|
-
head = 0;
|
|
49
|
-
capacity;
|
|
50
|
-
constructor(capacity = 2000) {
|
|
51
|
-
this.capacity = capacity;
|
|
52
|
-
this.ring = new Array(capacity);
|
|
53
|
-
}
|
|
54
|
-
check(id) {
|
|
55
|
-
if (this.ids.has(id))
|
|
56
|
-
return true;
|
|
57
|
-
if (this.ids.size >= this.capacity) {
|
|
58
|
-
const oldest = this.ring[this.head];
|
|
59
|
-
if (oldest)
|
|
60
|
-
this.ids.delete(oldest);
|
|
61
|
-
}
|
|
62
|
-
this.ring[this.head] = id;
|
|
63
|
-
this.ids.add(id);
|
|
64
|
-
this.head = (this.head + 1) % this.capacity;
|
|
65
|
-
return false;
|
|
66
|
-
}
|
|
67
|
-
clear() {
|
|
68
|
-
this.ids.clear();
|
|
69
|
-
this.ring = new Array(this.capacity);
|
|
70
|
-
this.head = 0;
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
/**
|
|
74
|
-
* BrowserRelayClient - A browser-compatible relay client.
|
|
75
|
-
*
|
|
76
|
-
* Uses WebSocket transport by default, making it compatible with browsers.
|
|
77
|
-
* Can also be used in Node.js for WebSocket-based connections.
|
|
78
|
-
*
|
|
79
|
-
* @example Browser usage
|
|
80
|
-
* ```typescript
|
|
81
|
-
* import { BrowserRelayClient } from '@agent-relay/sdk/browser';
|
|
82
|
-
*
|
|
83
|
-
* const client = new BrowserRelayClient({
|
|
84
|
-
* agentName: 'MyAgent',
|
|
85
|
-
* transport: {
|
|
86
|
-
* wsUrl: 'wss://relay.example.com/ws',
|
|
87
|
-
* },
|
|
88
|
-
* });
|
|
89
|
-
*
|
|
90
|
-
* await client.connect();
|
|
91
|
-
*
|
|
92
|
-
* client.onMessage = (from, payload) => {
|
|
93
|
-
* console.log(`Message from ${from}: ${payload.body}`);
|
|
94
|
-
* };
|
|
95
|
-
*
|
|
96
|
-
* client.sendMessage('OtherAgent', 'Hello!');
|
|
97
|
-
* ```
|
|
98
|
-
*/
|
|
99
|
-
export class BrowserRelayClient {
|
|
100
|
-
config;
|
|
101
|
-
transport;
|
|
102
|
-
parser;
|
|
103
|
-
_state = 'DISCONNECTED';
|
|
104
|
-
sessionId;
|
|
105
|
-
resumeToken;
|
|
106
|
-
reconnectAttempts = 0;
|
|
107
|
-
reconnectDelay;
|
|
108
|
-
reconnectTimer;
|
|
109
|
-
_destroyed = false;
|
|
110
|
-
dedupeCache = new CircularDedupeCache(2000);
|
|
111
|
-
writeQueue = [];
|
|
112
|
-
writeScheduled = false;
|
|
113
|
-
pendingSyncAcks = new Map();
|
|
114
|
-
pendingRequests = new Map();
|
|
115
|
-
// Event handlers
|
|
116
|
-
onMessage;
|
|
117
|
-
onChannelMessage;
|
|
118
|
-
onStateChange;
|
|
119
|
-
onError;
|
|
120
|
-
constructor(config) {
|
|
121
|
-
this.config = { ...DEFAULT_CONFIG, ...config };
|
|
122
|
-
this.parser = new BrowserFrameParser(); // Always uses legacy mode (4-byte header, JSON only)
|
|
123
|
-
this.reconnectDelay = this.config.reconnectDelayMs ?? DEFAULT_CONFIG.reconnectDelayMs;
|
|
124
|
-
}
|
|
125
|
-
get state() {
|
|
126
|
-
return this._state;
|
|
127
|
-
}
|
|
128
|
-
get agentName() {
|
|
129
|
-
return this.config.agentName;
|
|
130
|
-
}
|
|
131
|
-
get currentSessionId() {
|
|
132
|
-
return this.sessionId;
|
|
133
|
-
}
|
|
134
|
-
/**
|
|
135
|
-
* Connect to the relay daemon.
|
|
136
|
-
*/
|
|
137
|
-
async connect() {
|
|
138
|
-
if (this._state !== 'DISCONNECTED' && this._state !== 'BACKOFF') {
|
|
139
|
-
return;
|
|
140
|
-
}
|
|
141
|
-
this.setState('CONNECTING');
|
|
142
|
-
// Create transport if not provided
|
|
143
|
-
if (!this.transport) {
|
|
144
|
-
if (this.config.transportInstance) {
|
|
145
|
-
this.transport = this.config.transportInstance;
|
|
146
|
-
}
|
|
147
|
-
else if (this.config.transport) {
|
|
148
|
-
this.transport = createAutoTransport(this.config.transport);
|
|
149
|
-
}
|
|
150
|
-
else {
|
|
151
|
-
throw new Error('Transport configuration required. Provide either transport options or transportInstance.');
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
// Set up transport events
|
|
155
|
-
this.transport.setEvents({
|
|
156
|
-
onConnect: () => {
|
|
157
|
-
this.setState('HANDSHAKING');
|
|
158
|
-
this.sendHello();
|
|
159
|
-
},
|
|
160
|
-
onData: (data) => this.handleData(data),
|
|
161
|
-
onClose: () => this.handleDisconnect(),
|
|
162
|
-
onError: (err) => this.handleError(err),
|
|
163
|
-
});
|
|
164
|
-
try {
|
|
165
|
-
await this.transport.connect();
|
|
166
|
-
// Wait for READY state
|
|
167
|
-
await new Promise((resolve, reject) => {
|
|
168
|
-
let checkReady;
|
|
169
|
-
const cleanup = () => {
|
|
170
|
-
clearInterval(checkReady);
|
|
171
|
-
clearTimeout(timeout);
|
|
172
|
-
};
|
|
173
|
-
const timeout = setTimeout(() => {
|
|
174
|
-
cleanup();
|
|
175
|
-
reject(new Error('Connection handshake timeout'));
|
|
176
|
-
}, 5000);
|
|
177
|
-
checkReady = setInterval(() => {
|
|
178
|
-
if (this._state === 'READY') {
|
|
179
|
-
cleanup();
|
|
180
|
-
resolve();
|
|
181
|
-
}
|
|
182
|
-
else if (this._state === 'DISCONNECTED') {
|
|
183
|
-
cleanup();
|
|
184
|
-
reject(new Error('Connection failed'));
|
|
185
|
-
}
|
|
186
|
-
}, 10);
|
|
187
|
-
});
|
|
188
|
-
}
|
|
189
|
-
catch (err) {
|
|
190
|
-
this.setState('DISCONNECTED');
|
|
191
|
-
throw err;
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
/**
|
|
195
|
-
* Disconnect from the relay daemon.
|
|
196
|
-
*/
|
|
197
|
-
disconnect() {
|
|
198
|
-
if (this.reconnectTimer) {
|
|
199
|
-
clearTimeout(this.reconnectTimer);
|
|
200
|
-
this.reconnectTimer = undefined;
|
|
201
|
-
}
|
|
202
|
-
if (this.transport) {
|
|
203
|
-
// Send BYE message
|
|
204
|
-
this.send({
|
|
205
|
-
v: PROTOCOL_VERSION,
|
|
206
|
-
type: 'BYE',
|
|
207
|
-
id: generateId(),
|
|
208
|
-
ts: Date.now(),
|
|
209
|
-
payload: {},
|
|
210
|
-
});
|
|
211
|
-
this.transport.disconnect();
|
|
212
|
-
this.transport = undefined;
|
|
213
|
-
}
|
|
214
|
-
this.setState('DISCONNECTED');
|
|
215
|
-
}
|
|
216
|
-
/**
|
|
217
|
-
* Permanently destroy the client.
|
|
218
|
-
*/
|
|
219
|
-
destroy() {
|
|
220
|
-
this._destroyed = true;
|
|
221
|
-
this.disconnect();
|
|
222
|
-
}
|
|
223
|
-
/**
|
|
224
|
-
* Send a message to another agent.
|
|
225
|
-
*/
|
|
226
|
-
sendMessage(to, body, kind = 'message', data, thread, meta) {
|
|
227
|
-
if (this._state !== 'READY') {
|
|
228
|
-
return false;
|
|
229
|
-
}
|
|
230
|
-
const envelope = {
|
|
231
|
-
v: PROTOCOL_VERSION,
|
|
232
|
-
type: 'SEND',
|
|
233
|
-
id: generateId(),
|
|
234
|
-
ts: Date.now(),
|
|
235
|
-
to,
|
|
236
|
-
payload: {
|
|
237
|
-
kind,
|
|
238
|
-
body,
|
|
239
|
-
data,
|
|
240
|
-
thread,
|
|
241
|
-
},
|
|
242
|
-
payload_meta: meta,
|
|
243
|
-
};
|
|
244
|
-
return this.send(envelope);
|
|
245
|
-
}
|
|
246
|
-
/**
|
|
247
|
-
* Send an ACK for a delivered message.
|
|
248
|
-
*/
|
|
249
|
-
sendAck(payload) {
|
|
250
|
-
if (this._state !== 'READY') {
|
|
251
|
-
return false;
|
|
252
|
-
}
|
|
253
|
-
const envelope = {
|
|
254
|
-
v: PROTOCOL_VERSION,
|
|
255
|
-
type: 'ACK',
|
|
256
|
-
id: generateId(),
|
|
257
|
-
ts: Date.now(),
|
|
258
|
-
payload,
|
|
259
|
-
};
|
|
260
|
-
return this.send(envelope);
|
|
261
|
-
}
|
|
262
|
-
/**
|
|
263
|
-
* Send a request to another agent and wait for their response.
|
|
264
|
-
*/
|
|
265
|
-
async request(to, body, options = {}) {
|
|
266
|
-
if (this._state !== 'READY') {
|
|
267
|
-
throw new Error('Client not ready');
|
|
268
|
-
}
|
|
269
|
-
const correlationId = generateUUID();
|
|
270
|
-
const timeoutMs = options.timeout ?? 30000;
|
|
271
|
-
const kind = options.kind ?? 'message';
|
|
272
|
-
return new Promise((resolve, reject) => {
|
|
273
|
-
const timeoutHandle = setTimeout(() => {
|
|
274
|
-
this.pendingRequests.delete(correlationId);
|
|
275
|
-
reject(new Error(`Request timeout after ${timeoutMs}ms waiting for response from ${to}`));
|
|
276
|
-
}, timeoutMs);
|
|
277
|
-
this.pendingRequests.set(correlationId, {
|
|
278
|
-
resolve,
|
|
279
|
-
reject,
|
|
280
|
-
timeoutHandle,
|
|
281
|
-
targetAgent: to,
|
|
282
|
-
});
|
|
283
|
-
const envelope = {
|
|
284
|
-
v: PROTOCOL_VERSION,
|
|
285
|
-
type: 'SEND',
|
|
286
|
-
id: generateId(),
|
|
287
|
-
ts: Date.now(),
|
|
288
|
-
to,
|
|
289
|
-
payload: {
|
|
290
|
-
kind,
|
|
291
|
-
body,
|
|
292
|
-
data: {
|
|
293
|
-
...options.data,
|
|
294
|
-
_correlationId: correlationId,
|
|
295
|
-
},
|
|
296
|
-
thread: options.thread,
|
|
297
|
-
},
|
|
298
|
-
payload_meta: {
|
|
299
|
-
replyTo: correlationId,
|
|
300
|
-
},
|
|
301
|
-
};
|
|
302
|
-
const sent = this.send(envelope);
|
|
303
|
-
if (!sent) {
|
|
304
|
-
clearTimeout(timeoutHandle);
|
|
305
|
-
this.pendingRequests.delete(correlationId);
|
|
306
|
-
reject(new Error('Failed to send request'));
|
|
307
|
-
}
|
|
308
|
-
});
|
|
309
|
-
}
|
|
310
|
-
/**
|
|
311
|
-
* Respond to a request from another agent.
|
|
312
|
-
*/
|
|
313
|
-
respond(correlationId, to, body, data) {
|
|
314
|
-
if (this._state !== 'READY') {
|
|
315
|
-
return false;
|
|
316
|
-
}
|
|
317
|
-
const envelope = {
|
|
318
|
-
v: PROTOCOL_VERSION,
|
|
319
|
-
type: 'SEND',
|
|
320
|
-
id: generateId(),
|
|
321
|
-
ts: Date.now(),
|
|
322
|
-
to,
|
|
323
|
-
payload: {
|
|
324
|
-
kind: 'message',
|
|
325
|
-
body,
|
|
326
|
-
data: {
|
|
327
|
-
...data,
|
|
328
|
-
_correlationId: correlationId,
|
|
329
|
-
_isResponse: true,
|
|
330
|
-
},
|
|
331
|
-
},
|
|
332
|
-
payload_meta: {
|
|
333
|
-
replyTo: correlationId,
|
|
334
|
-
},
|
|
335
|
-
};
|
|
336
|
-
return this.send(envelope);
|
|
337
|
-
}
|
|
338
|
-
/**
|
|
339
|
-
* Broadcast a message to all agents.
|
|
340
|
-
*/
|
|
341
|
-
broadcast(body, kind = 'message', data) {
|
|
342
|
-
return this.sendMessage('*', body, kind, data);
|
|
343
|
-
}
|
|
344
|
-
/**
|
|
345
|
-
* Bind as a shadow to a primary agent.
|
|
346
|
-
*/
|
|
347
|
-
bindAsShadow(primaryAgent, options = {}) {
|
|
348
|
-
if (this._state !== 'READY')
|
|
349
|
-
return false;
|
|
350
|
-
return this.send({
|
|
351
|
-
v: PROTOCOL_VERSION,
|
|
352
|
-
type: 'SHADOW_BIND',
|
|
353
|
-
id: generateId(),
|
|
354
|
-
ts: Date.now(),
|
|
355
|
-
payload: {
|
|
356
|
-
primaryAgent,
|
|
357
|
-
speakOn: options.speakOn,
|
|
358
|
-
receiveIncoming: options.receiveIncoming,
|
|
359
|
-
receiveOutgoing: options.receiveOutgoing,
|
|
360
|
-
},
|
|
361
|
-
});
|
|
362
|
-
}
|
|
363
|
-
/**
|
|
364
|
-
* Unbind from a primary agent.
|
|
365
|
-
*/
|
|
366
|
-
unbindAsShadow(primaryAgent) {
|
|
367
|
-
if (this._state !== 'READY')
|
|
368
|
-
return false;
|
|
369
|
-
return this.send({
|
|
370
|
-
v: PROTOCOL_VERSION,
|
|
371
|
-
type: 'SHADOW_UNBIND',
|
|
372
|
-
id: generateId(),
|
|
373
|
-
ts: Date.now(),
|
|
374
|
-
payload: {
|
|
375
|
-
primaryAgent,
|
|
376
|
-
},
|
|
377
|
-
});
|
|
378
|
-
}
|
|
379
|
-
/**
|
|
380
|
-
* Send log output to the daemon.
|
|
381
|
-
*/
|
|
382
|
-
sendLog(data) {
|
|
383
|
-
if (this._state !== 'READY') {
|
|
384
|
-
return false;
|
|
385
|
-
}
|
|
386
|
-
const envelope = {
|
|
387
|
-
v: PROTOCOL_VERSION,
|
|
388
|
-
type: 'LOG',
|
|
389
|
-
id: generateId(),
|
|
390
|
-
ts: Date.now(),
|
|
391
|
-
payload: {
|
|
392
|
-
data,
|
|
393
|
-
timestamp: Date.now(),
|
|
394
|
-
},
|
|
395
|
-
};
|
|
396
|
-
return this.send(envelope);
|
|
397
|
-
}
|
|
398
|
-
// =============================================================================
|
|
399
|
-
// Channel Operations
|
|
400
|
-
// =============================================================================
|
|
401
|
-
/**
|
|
402
|
-
* Join a channel.
|
|
403
|
-
*/
|
|
404
|
-
joinChannel(channel, displayName) {
|
|
405
|
-
if (this._state !== 'READY') {
|
|
406
|
-
return false;
|
|
407
|
-
}
|
|
408
|
-
const envelope = {
|
|
409
|
-
v: PROTOCOL_VERSION,
|
|
410
|
-
type: 'CHANNEL_JOIN',
|
|
411
|
-
id: generateId(),
|
|
412
|
-
ts: Date.now(),
|
|
413
|
-
payload: {
|
|
414
|
-
channel,
|
|
415
|
-
displayName,
|
|
416
|
-
},
|
|
417
|
-
};
|
|
418
|
-
return this.send(envelope);
|
|
419
|
-
}
|
|
420
|
-
/**
|
|
421
|
-
* Leave a channel.
|
|
422
|
-
*/
|
|
423
|
-
leaveChannel(channel, reason) {
|
|
424
|
-
if (this._state !== 'READY')
|
|
425
|
-
return false;
|
|
426
|
-
const envelope = {
|
|
427
|
-
v: PROTOCOL_VERSION,
|
|
428
|
-
type: 'CHANNEL_LEAVE',
|
|
429
|
-
id: generateId(),
|
|
430
|
-
ts: Date.now(),
|
|
431
|
-
payload: {
|
|
432
|
-
channel,
|
|
433
|
-
reason,
|
|
434
|
-
},
|
|
435
|
-
};
|
|
436
|
-
return this.send(envelope);
|
|
437
|
-
}
|
|
438
|
-
/**
|
|
439
|
-
* Send a message to a channel.
|
|
440
|
-
*/
|
|
441
|
-
sendChannelMessage(channel, body, options) {
|
|
442
|
-
if (this._state !== 'READY') {
|
|
443
|
-
return false;
|
|
444
|
-
}
|
|
445
|
-
const envelope = {
|
|
446
|
-
v: PROTOCOL_VERSION,
|
|
447
|
-
type: 'CHANNEL_MESSAGE',
|
|
448
|
-
id: generateId(),
|
|
449
|
-
ts: Date.now(),
|
|
450
|
-
payload: {
|
|
451
|
-
channel,
|
|
452
|
-
body,
|
|
453
|
-
thread: options?.thread,
|
|
454
|
-
mentions: options?.mentions,
|
|
455
|
-
attachments: options?.attachments,
|
|
456
|
-
data: options?.data,
|
|
457
|
-
},
|
|
458
|
-
};
|
|
459
|
-
return this.send(envelope);
|
|
460
|
-
}
|
|
461
|
-
// =============================================================================
|
|
462
|
-
// Private Methods
|
|
463
|
-
// =============================================================================
|
|
464
|
-
setState(state) {
|
|
465
|
-
this._state = state;
|
|
466
|
-
if (this.onStateChange) {
|
|
467
|
-
this.onStateChange(state);
|
|
468
|
-
}
|
|
469
|
-
}
|
|
470
|
-
sendHello() {
|
|
471
|
-
const hello = {
|
|
472
|
-
v: PROTOCOL_VERSION,
|
|
473
|
-
type: 'HELLO',
|
|
474
|
-
id: generateId(),
|
|
475
|
-
ts: Date.now(),
|
|
476
|
-
payload: {
|
|
477
|
-
agent: this.config.agentName,
|
|
478
|
-
entityType: this.config.entityType,
|
|
479
|
-
cli: this.config.cli,
|
|
480
|
-
displayName: this.config.displayName,
|
|
481
|
-
avatarUrl: this.config.avatarUrl,
|
|
482
|
-
capabilities: {
|
|
483
|
-
ack: true,
|
|
484
|
-
resume: true,
|
|
485
|
-
max_inflight: 256,
|
|
486
|
-
supports_topics: true,
|
|
487
|
-
},
|
|
488
|
-
session: this.resumeToken ? { resume_token: this.resumeToken } : undefined,
|
|
489
|
-
},
|
|
490
|
-
};
|
|
491
|
-
this.send(hello);
|
|
492
|
-
}
|
|
493
|
-
send(envelope) {
|
|
494
|
-
if (!this.transport || this.transport.state !== 'connected') {
|
|
495
|
-
return false;
|
|
496
|
-
}
|
|
497
|
-
try {
|
|
498
|
-
const frame = encodeFrameLegacyBrowser(envelope);
|
|
499
|
-
this.writeQueue.push(frame);
|
|
500
|
-
if (!this.writeScheduled) {
|
|
501
|
-
this.writeScheduled = true;
|
|
502
|
-
// Use setTimeout(0) for browser compatibility (instead of setImmediate)
|
|
503
|
-
setTimeout(() => this.flushWrites(), 0);
|
|
504
|
-
}
|
|
505
|
-
return true;
|
|
506
|
-
}
|
|
507
|
-
catch (err) {
|
|
508
|
-
this.handleError(err);
|
|
509
|
-
return false;
|
|
510
|
-
}
|
|
511
|
-
}
|
|
512
|
-
flushWrites() {
|
|
513
|
-
this.writeScheduled = false;
|
|
514
|
-
if (this.writeQueue.length === 0 || !this.transport)
|
|
515
|
-
return;
|
|
516
|
-
// Concatenate all buffers
|
|
517
|
-
const totalLength = this.writeQueue.reduce((sum, buf) => sum + buf.length, 0);
|
|
518
|
-
const combined = new Uint8Array(totalLength);
|
|
519
|
-
let offset = 0;
|
|
520
|
-
for (const buf of this.writeQueue) {
|
|
521
|
-
combined.set(buf, offset);
|
|
522
|
-
offset += buf.length;
|
|
523
|
-
}
|
|
524
|
-
this.transport.send(combined);
|
|
525
|
-
this.writeQueue = [];
|
|
526
|
-
}
|
|
527
|
-
handleData(data) {
|
|
528
|
-
try {
|
|
529
|
-
const frames = this.parser.push(data);
|
|
530
|
-
for (const frame of frames) {
|
|
531
|
-
this.processFrame(frame);
|
|
532
|
-
}
|
|
533
|
-
}
|
|
534
|
-
catch (err) {
|
|
535
|
-
this.handleError(err);
|
|
536
|
-
}
|
|
537
|
-
}
|
|
538
|
-
processFrame(envelope) {
|
|
539
|
-
switch (envelope.type) {
|
|
540
|
-
case 'WELCOME':
|
|
541
|
-
this.handleWelcome(envelope);
|
|
542
|
-
break;
|
|
543
|
-
case 'DELIVER':
|
|
544
|
-
this.handleDeliver(envelope);
|
|
545
|
-
break;
|
|
546
|
-
case 'CHANNEL_MESSAGE':
|
|
547
|
-
this.handleChannelMessage(envelope);
|
|
548
|
-
break;
|
|
549
|
-
case 'PING':
|
|
550
|
-
this.handlePing(envelope);
|
|
551
|
-
break;
|
|
552
|
-
case 'ACK':
|
|
553
|
-
this.handleAck(envelope);
|
|
554
|
-
break;
|
|
555
|
-
case 'ERROR':
|
|
556
|
-
this.handleErrorFrame(envelope);
|
|
557
|
-
break;
|
|
558
|
-
case 'BUSY':
|
|
559
|
-
if (!this.config.quiet) {
|
|
560
|
-
console.warn('[sdk] Server busy, backing off');
|
|
561
|
-
}
|
|
562
|
-
break;
|
|
563
|
-
}
|
|
564
|
-
}
|
|
565
|
-
handleWelcome(envelope) {
|
|
566
|
-
this.sessionId = envelope.payload.session_id;
|
|
567
|
-
this.resumeToken = envelope.payload.resume_token;
|
|
568
|
-
this.reconnectAttempts = 0;
|
|
569
|
-
this.reconnectDelay = this.config.reconnectDelayMs ?? DEFAULT_CONFIG.reconnectDelayMs;
|
|
570
|
-
this.setState('READY');
|
|
571
|
-
if (!this.config.quiet) {
|
|
572
|
-
console.log(`[sdk] Connected as ${this.config.agentName} (session: ${this.sessionId})`);
|
|
573
|
-
}
|
|
574
|
-
}
|
|
575
|
-
handleDeliver(envelope) {
|
|
576
|
-
// Send ACK
|
|
577
|
-
this.send({
|
|
578
|
-
v: PROTOCOL_VERSION,
|
|
579
|
-
type: 'ACK',
|
|
580
|
-
id: generateId(),
|
|
581
|
-
ts: Date.now(),
|
|
582
|
-
payload: {
|
|
583
|
-
ack_id: envelope.id,
|
|
584
|
-
seq: envelope.delivery.seq,
|
|
585
|
-
},
|
|
586
|
-
});
|
|
587
|
-
const duplicate = this.dedupeCache.check(envelope.id);
|
|
588
|
-
if (duplicate) {
|
|
589
|
-
return;
|
|
590
|
-
}
|
|
591
|
-
// Check if this is a response to a pending request
|
|
592
|
-
const correlationId = this.extractCorrelationId(envelope);
|
|
593
|
-
if (correlationId && envelope.from) {
|
|
594
|
-
const pending = this.pendingRequests.get(correlationId);
|
|
595
|
-
if (pending) {
|
|
596
|
-
clearTimeout(pending.timeoutHandle);
|
|
597
|
-
this.pendingRequests.delete(correlationId);
|
|
598
|
-
pending.resolve({
|
|
599
|
-
from: envelope.from,
|
|
600
|
-
body: envelope.payload.body,
|
|
601
|
-
data: envelope.payload.data,
|
|
602
|
-
correlationId,
|
|
603
|
-
thread: envelope.payload.thread,
|
|
604
|
-
payload: envelope.payload,
|
|
605
|
-
});
|
|
606
|
-
}
|
|
607
|
-
}
|
|
608
|
-
if (this.onMessage && envelope.from) {
|
|
609
|
-
this.onMessage(envelope.from, envelope.payload, envelope.id, envelope.payload_meta, envelope.delivery.originalTo);
|
|
610
|
-
}
|
|
611
|
-
}
|
|
612
|
-
extractCorrelationId(envelope) {
|
|
613
|
-
if (envelope.payload_meta?.replyTo) {
|
|
614
|
-
return envelope.payload_meta.replyTo;
|
|
615
|
-
}
|
|
616
|
-
if (envelope.payload.data && typeof envelope.payload.data._correlationId === 'string') {
|
|
617
|
-
return envelope.payload.data._correlationId;
|
|
618
|
-
}
|
|
619
|
-
return undefined;
|
|
620
|
-
}
|
|
621
|
-
handleChannelMessage(envelope) {
|
|
622
|
-
const duplicate = this.dedupeCache.check(envelope.id);
|
|
623
|
-
if (duplicate) {
|
|
624
|
-
return;
|
|
625
|
-
}
|
|
626
|
-
if (this.onChannelMessage && envelope.from) {
|
|
627
|
-
this.onChannelMessage(envelope.from, envelope.payload.channel, envelope.payload.body, envelope);
|
|
628
|
-
}
|
|
629
|
-
// Also call onMessage for backwards compatibility
|
|
630
|
-
if (this.onMessage && envelope.from) {
|
|
631
|
-
const sendPayload = {
|
|
632
|
-
kind: 'message',
|
|
633
|
-
body: envelope.payload.body,
|
|
634
|
-
data: {
|
|
635
|
-
_isChannelMessage: true,
|
|
636
|
-
_channel: envelope.payload.channel,
|
|
637
|
-
_mentions: envelope.payload.mentions,
|
|
638
|
-
},
|
|
639
|
-
thread: envelope.payload.thread,
|
|
640
|
-
};
|
|
641
|
-
this.onMessage(envelope.from, sendPayload, envelope.id, undefined, envelope.payload.channel);
|
|
642
|
-
}
|
|
643
|
-
}
|
|
644
|
-
handleAck(envelope) {
|
|
645
|
-
const correlationId = envelope.payload.correlationId;
|
|
646
|
-
if (!correlationId)
|
|
647
|
-
return;
|
|
648
|
-
const pending = this.pendingSyncAcks.get(correlationId);
|
|
649
|
-
if (!pending)
|
|
650
|
-
return;
|
|
651
|
-
clearTimeout(pending.timeoutHandle);
|
|
652
|
-
this.pendingSyncAcks.delete(correlationId);
|
|
653
|
-
pending.resolve(envelope.payload);
|
|
654
|
-
}
|
|
655
|
-
handlePing(envelope) {
|
|
656
|
-
this.send({
|
|
657
|
-
v: PROTOCOL_VERSION,
|
|
658
|
-
type: 'PONG',
|
|
659
|
-
id: generateId(),
|
|
660
|
-
ts: Date.now(),
|
|
661
|
-
payload: envelope.payload ?? {},
|
|
662
|
-
});
|
|
663
|
-
}
|
|
664
|
-
handleErrorFrame(envelope) {
|
|
665
|
-
if (!this.config.quiet) {
|
|
666
|
-
console.error('[sdk] Server error:', envelope.payload);
|
|
667
|
-
}
|
|
668
|
-
if (envelope.payload.code === 'RESUME_TOO_OLD') {
|
|
669
|
-
this.resumeToken = undefined;
|
|
670
|
-
this.sessionId = undefined;
|
|
671
|
-
}
|
|
672
|
-
if (envelope.payload.fatal) {
|
|
673
|
-
if (!this.config.quiet) {
|
|
674
|
-
console.error('[sdk] Fatal error received, will not reconnect:', envelope.payload.message);
|
|
675
|
-
}
|
|
676
|
-
this._destroyed = true;
|
|
677
|
-
}
|
|
678
|
-
}
|
|
679
|
-
handleDisconnect() {
|
|
680
|
-
this.parser.reset();
|
|
681
|
-
this.transport = undefined;
|
|
682
|
-
this.rejectPendingSyncAcks(new Error('Disconnected while awaiting ACK'));
|
|
683
|
-
this.rejectPendingRequests(new Error('Disconnected while awaiting request response'));
|
|
684
|
-
if (this._destroyed) {
|
|
685
|
-
this.setState('DISCONNECTED');
|
|
686
|
-
return;
|
|
687
|
-
}
|
|
688
|
-
if (this.config.reconnect && this.reconnectAttempts < (this.config.maxReconnectAttempts ?? DEFAULT_CONFIG.maxReconnectAttempts)) {
|
|
689
|
-
this.scheduleReconnect();
|
|
690
|
-
}
|
|
691
|
-
else {
|
|
692
|
-
this.setState('DISCONNECTED');
|
|
693
|
-
if (this.reconnectAttempts >= (this.config.maxReconnectAttempts ?? DEFAULT_CONFIG.maxReconnectAttempts) && !this.config.quiet) {
|
|
694
|
-
console.error(`[sdk] Max reconnect attempts reached (${this.config.maxReconnectAttempts}), giving up`);
|
|
695
|
-
}
|
|
696
|
-
}
|
|
697
|
-
}
|
|
698
|
-
handleError(error) {
|
|
699
|
-
if (!this.config.quiet) {
|
|
700
|
-
console.error('[sdk] Error:', error.message);
|
|
701
|
-
}
|
|
702
|
-
if (this.onError) {
|
|
703
|
-
this.onError(error);
|
|
704
|
-
}
|
|
705
|
-
}
|
|
706
|
-
rejectPendingSyncAcks(error) {
|
|
707
|
-
for (const [correlationId, pending] of this.pendingSyncAcks.entries()) {
|
|
708
|
-
clearTimeout(pending.timeoutHandle);
|
|
709
|
-
pending.reject(error);
|
|
710
|
-
this.pendingSyncAcks.delete(correlationId);
|
|
711
|
-
}
|
|
712
|
-
}
|
|
713
|
-
rejectPendingRequests(error) {
|
|
714
|
-
for (const [correlationId, pending] of this.pendingRequests.entries()) {
|
|
715
|
-
clearTimeout(pending.timeoutHandle);
|
|
716
|
-
pending.reject(error);
|
|
717
|
-
this.pendingRequests.delete(correlationId);
|
|
718
|
-
}
|
|
719
|
-
}
|
|
720
|
-
scheduleReconnect() {
|
|
721
|
-
// Cannot reconnect when using transportInstance - we can't recreate an
|
|
722
|
-
// externally-provided transport. Users must handle reconnection themselves
|
|
723
|
-
// or use transport options instead.
|
|
724
|
-
if (!this.config.transport && this.config.transportInstance) {
|
|
725
|
-
if (!this.config.quiet) {
|
|
726
|
-
console.warn('[sdk] Cannot auto-reconnect with transportInstance. ' +
|
|
727
|
-
'Use transport options instead, or handle reconnection manually.');
|
|
728
|
-
}
|
|
729
|
-
this.setState('DISCONNECTED');
|
|
730
|
-
return;
|
|
731
|
-
}
|
|
732
|
-
this.setState('BACKOFF');
|
|
733
|
-
this.reconnectAttempts++;
|
|
734
|
-
const jitter = Math.random() * 0.3 + 0.85;
|
|
735
|
-
const maxDelay = this.config.reconnectMaxDelayMs ?? DEFAULT_CONFIG.reconnectMaxDelayMs;
|
|
736
|
-
const delay = Math.min(this.reconnectDelay * jitter, maxDelay);
|
|
737
|
-
this.reconnectDelay *= 2;
|
|
738
|
-
if (!this.config.quiet) {
|
|
739
|
-
console.log(`[sdk] Reconnecting in ${Math.round(delay)}ms (attempt ${this.reconnectAttempts})`);
|
|
740
|
-
}
|
|
741
|
-
this.reconnectTimer = setTimeout(() => {
|
|
742
|
-
// Re-create transport for reconnection
|
|
743
|
-
if (this.config.transport) {
|
|
744
|
-
this.transport = createAutoTransport(this.config.transport);
|
|
745
|
-
}
|
|
746
|
-
this.connect().catch(() => { });
|
|
747
|
-
}, delay);
|
|
748
|
-
}
|
|
749
|
-
}
|
|
750
|
-
//# sourceMappingURL=browser-client.js.map
|