@celljs/ta-client 4.9.1 → 4.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.
@@ -2,16 +2,54 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.TaConnection = exports.TaRemoteError = void 0;
4
4
  const ta_protocol_1 = require("@celljs/ta-protocol");
5
- /** A failed call. `code` is set for failures the server names. */
5
+ /**
6
+ * A failed call. `code` is set for failures the server names; `rpcCode` is the code of JSON-RPC's error,
7
+ * by which a client tells a method an older ta serve does not have (`TaRemoteError.METHOD_NOT_FOUND`).
8
+ */
6
9
  class TaRemoteError extends Error {
7
- constructor(message, code, hint) {
10
+ constructor(message, code, hint, rpcCode) {
8
11
  super(message);
9
12
  this.code = code;
10
13
  this.hint = hint;
14
+ this.rpcCode = rpcCode;
11
15
  this.name = 'TaRemoteError';
12
16
  }
17
+ /** The error of a JSON-RPC answer: its code, and the code and hint of ta serve when it named the failure. */
18
+ static of(error) {
19
+ var _a;
20
+ const data = (_a = error.data) === null || _a === void 0 ? void 0 : _a.data;
21
+ return new TaRemoteError(error.message, data === null || data === void 0 ? void 0 : data.code, data === null || data === void 0 ? void 0 : data.hint, error.code);
22
+ }
23
+ /** A call that waited for a connection that did not come back. */
24
+ static notConnected() {
25
+ return new TaRemoteError(TaRemoteError.NOT_CONNECTED, ta_protocol_1.TaErrorCode.CONNECTION_LOST, 'Try again once the connection is back.');
26
+ }
27
+ /**
28
+ * Whether a failure is only that the connection was lost, which mends itself: by its code, or by its
29
+ * words in a text (a web extension shows `error.message`, often inside its own words).
30
+ */
31
+ static isConnectionLost(cause) {
32
+ if (typeof cause === 'string') {
33
+ return cause.includes(TaRemoteError.NOT_CONNECTED) || cause.includes(TaRemoteError.LOST);
34
+ }
35
+ return (cause === null || cause === void 0 ? void 0 : cause.code) === ta_protocol_1.TaErrorCode.CONNECTION_LOST;
36
+ }
37
+ /** Whether the server has no such method: a ta serve from before it was added. */
38
+ static isMethodNotFound(error) {
39
+ return error instanceof TaRemoteError && error.rpcCode === TaRemoteError.METHOD_NOT_FOUND;
40
+ }
13
41
  }
14
42
  exports.TaRemoteError = TaRemoteError;
43
+ /** JSON-RPC's code for a method the server does not have. */
44
+ TaRemoteError.METHOD_NOT_FOUND = -32601;
45
+ /** What a call says that waited for a connection that did not come back. */
46
+ TaRemoteError.NOT_CONNECTED = 'Not connected to ta serve.';
47
+ /** What a call says that was sent on a connection lost before its answer. */
48
+ TaRemoteError.LOST = 'The connection to ta serve was lost.';
49
+ /** Methods that only read: sent again after a lost connection. */
50
+ const READ_METHOD = /^(get|list|read|find)[A-Z]/;
51
+ /** Methods whose input carries a clientMessageId, by which ta serve takes a message once however often it comes. */
52
+ const MESSAGE_METHODS = new Set(['prompt', 'steer', 'followUp']);
15
53
  /**
16
54
  * A connection to `ta serve` on the `WebSocket` of the platform, with no other dependency, so that it
17
55
  * fits a browser, Electron or a mobile app. It reconnects until closed; `onOpen` runs each time, for
@@ -19,8 +57,11 @@ exports.TaRemoteError = TaRemoteError;
19
57
  * over the one WebSocket.
20
58
  *
21
59
  * A call made while the connection is down waits a little for it to come back (`waitForOpenMs`): it was
22
- * not sent. Calls that were sent when the connection was lost fail and are not sent again, because only
23
- * the caller knows whether to resend.
60
+ * not sent. Calls that were sent when the connection was lost fail, unless they are safe to send again
61
+ * (`resendable`: reads, and messages ta serve takes once by their clientMessageId), which wait for the
62
+ * next connection and go again for up to `retryForMs`: on a network that drops now and then, a read or a
63
+ * message is late rather than failed. A call that stalls while nothing comes makes it check the
64
+ * connection (`stallMs`), so that one gone without a word is not waited on for long.
24
65
  */
25
66
  class TaConnection {
26
67
  constructor(options) {
@@ -36,6 +77,7 @@ class TaConnection {
36
77
  this.gateway = this.service(ta_protocol_1.TA_GATEWAY_SERVICE);
37
78
  this.relay = this.service(ta_protocol_1.TA_RELAY_SERVICE);
38
79
  this.remote = this.service(ta_protocol_1.TA_REMOTE_SERVICE);
80
+ this.rooms = this.service(ta_protocol_1.TA_ROOM_SERVICE);
39
81
  this.closed = false;
40
82
  this.attempts = 0;
41
83
  this.nextId = 0;
@@ -45,11 +87,16 @@ class TaConnection {
45
87
  this.extensionDataListeners = new Set();
46
88
  this.authListeners = new Set();
47
89
  this.remoteListeners = new Set();
90
+ this.roomListeners = new Set();
91
+ this.sessionsListeners = new Set();
48
92
  this.openListeners = new Set();
49
93
  this.closeListeners = new Set();
50
94
  this.reconnectingListeners = new Set();
51
95
  /** The calls waiting for the connection to open: `go` once it is, `fail` when it is closed. */
52
96
  this.waiting = new Set();
97
+ /** When the last message came, on the clock of Date.now(). */
98
+ this.lastReceivedAt = 0;
99
+ this.probing = false;
53
100
  }
54
101
  /** Resolves when the first connection is open, or rejects if it cannot be made; later losses reconnect. */
55
102
  connect() {
@@ -59,6 +106,7 @@ class TaConnection {
59
106
  var _a;
60
107
  this.closed = true;
61
108
  clearTimeout(this.reconnectTimer);
109
+ clearInterval(this.stallTimer);
62
110
  for (const call of [...this.waiting]) {
63
111
  call.fail();
64
112
  }
@@ -88,6 +136,16 @@ class TaConnection {
88
136
  this.remoteListeners.add(listener);
89
137
  return () => this.remoteListeners.delete(listener);
90
138
  }
139
+ /** What happens in the rooms, once this connection called TaRoomServer.watch. */
140
+ onRoomEvent(listener) {
141
+ this.roomListeners.add(listener);
142
+ return () => this.roomListeners.delete(listener);
143
+ }
144
+ /** The open sessions as they change (TaClient.onSessions), once this connection called TaServer.watchSessions. */
145
+ onSessions(listener) {
146
+ this.sessionsListeners.add(listener);
147
+ return () => this.sessionsListeners.delete(listener);
148
+ }
91
149
  onOpen(listener) {
92
150
  this.openListeners.add(listener);
93
151
  return () => this.openListeners.delete(listener);
@@ -128,8 +186,12 @@ class TaConnection {
128
186
  return;
129
187
  }
130
188
  let answered = false;
189
+ const since = Date.now();
190
+ this.probing = true;
131
191
  const timer = setTimeout(() => {
132
- if (!answered && this.socket === socket) {
192
+ this.probing = false;
193
+ // Anything that came meanwhile says it is alive, only slow: the answer waits behind it.
194
+ if (!answered && this.socket === socket && this.lastReceivedAt <= since) {
133
195
  socket.onclose = null;
134
196
  socket.onmessage = null;
135
197
  socket.close();
@@ -137,10 +199,19 @@ class TaConnection {
137
199
  this.lost(socket, true, true);
138
200
  }
139
201
  }, timeoutMs);
140
- this.server.getServerInfo().then(() => {
202
+ const done = () => {
141
203
  answered = true;
204
+ this.probing = false;
142
205
  clearTimeout(timer);
143
- }, () => clearTimeout(timer));
206
+ };
207
+ // Any answer says the connection is alive, an error too. Asked of what answers at the front: `ta gateway`
208
+ // answers its own service while a Ta behind it is slow, and a Ta service says it has no such service.
209
+ // Sent once, not again after a loss as a read would be: it asks about this connection.
210
+ this.send(ta_protocol_1.TA_GATEWAY_SERVICE, 'getGateway', []).then(done, error => {
211
+ if (error.code !== ta_protocol_1.TaErrorCode.CONNECTION_LOST) {
212
+ done();
213
+ }
214
+ });
144
215
  }
145
216
  /** With `resolve` and `reject`: the first connection, whose failure is the caller's to handle. */
146
217
  open(resolve, reject) {
@@ -206,10 +277,11 @@ class TaConnection {
206
277
  listener(delay, this.attempts);
207
278
  }
208
279
  }
209
- /** Resolves once the connection is open, or rejects after `waitForOpenMs`, or at once when it is closed. */
210
- opened() {
211
- const { waitForOpenMs = 5000 } = this.options;
212
- const notConnected = () => new TaRemoteError('Not connected to ta serve.', ta_protocol_1.TaErrorCode.CONNECTION_LOST, 'Try again once the connection is back.');
280
+ /** Resolves once the connection is open, or rejects after `waitForOpenMs` (or `waitMs`), or at once when it is closed. */
281
+ opened(waitMs) {
282
+ const { waitForOpenMs: configured = 5000 } = this.options;
283
+ const waitForOpenMs = configured <= 0 ? 0 : (waitMs !== null && waitMs !== void 0 ? waitMs : configured);
284
+ const notConnected = () => TaRemoteError.notConnected();
213
285
  if (this.closed || waitForOpenMs <= 0) {
214
286
  return Promise.reject(notConnected());
215
287
  }
@@ -232,7 +304,7 @@ class TaConnection {
232
304
  }
233
305
  failPending() {
234
306
  for (const call of this.pending.values()) {
235
- call.reject(new TaRemoteError('The connection to ta serve was lost.', ta_protocol_1.TaErrorCode.CONNECTION_LOST, 'Send it again once the connection is back.'));
307
+ call.reject(new TaRemoteError(TaRemoteError.LOST, ta_protocol_1.TaErrorCode.CONNECTION_LOST, 'Send it again once the connection is back.'));
236
308
  }
237
309
  this.pending.clear();
238
310
  }
@@ -241,10 +313,46 @@ class TaConnection {
241
313
  get: (_target, method) => (...params) => this.call(name, method, params),
242
314
  });
243
315
  }
316
+ /**
317
+ * Whether a call may go again after a lost connection, as doing it twice does what doing it once does:
318
+ * a read, or a message with its clientMessageId (TaPromptInput), which ta serve takes once.
319
+ */
320
+ static resendable(service, method, params) {
321
+ var _a;
322
+ if (READ_METHOD.test(method)) {
323
+ return true;
324
+ }
325
+ return service === ta_protocol_1.TA_SERVER_SERVICE && MESSAGE_METHODS.has(method) && !!((_a = params[1]) === null || _a === void 0 ? void 0 : _a.clientMessageId);
326
+ }
244
327
  async call(service, method, params) {
328
+ var _a, _b;
329
+ if (!TaConnection.resendable(service, method, params)) {
330
+ if (((_a = this.socket) === null || _a === void 0 ? void 0 : _a.readyState) !== WebSocket.OPEN) {
331
+ await this.opened();
332
+ }
333
+ return this.send(service, method, params);
334
+ }
335
+ const { waitForOpenMs = 5000, retryForMs = waitForOpenMs } = this.options;
336
+ const deadline = Date.now() + Math.max(retryForMs, 1);
337
+ for (;;) {
338
+ if (((_b = this.socket) === null || _b === void 0 ? void 0 : _b.readyState) !== WebSocket.OPEN) {
339
+ await this.opened(Math.max(1, deadline - Date.now()));
340
+ }
341
+ try {
342
+ return await this.send(service, method, params);
343
+ }
344
+ catch (error) {
345
+ if (error.code !== ta_protocol_1.TaErrorCode.CONNECTION_LOST || this.closed || Date.now() >= deadline) {
346
+ throw error;
347
+ }
348
+ }
349
+ }
350
+ }
351
+ /** Sends a call on the open connection; its answer, or its failure when the connection is lost first. */
352
+ send(service, method, params) {
245
353
  var _a;
246
354
  if (((_a = this.socket) === null || _a === void 0 ? void 0 : _a.readyState) !== WebSocket.OPEN) {
247
- await this.opened();
355
+ return Promise.reject(TaRemoteError.notConnected());
248
356
  }
249
357
  const socket = this.socket;
250
358
  const id = ++this.nextId;
@@ -254,12 +362,32 @@ class TaConnection {
254
362
  length--;
255
363
  }
256
364
  return new Promise((resolve, reject) => {
257
- this.pending.set(id, { resolve, reject });
365
+ this.pending.set(id, { resolve, reject, sentAt: Date.now() });
366
+ this.watchStalls();
258
367
  socket.send(JSON.stringify({ jsonrpc: '2.0', id, method: `${service}/${method}`, params: params.slice(0, length) }));
259
368
  });
260
369
  }
370
+ /** While calls wait for answers: one that waits past `stallMs` with nothing come since makes it check the connection. */
371
+ watchStalls() {
372
+ const { stallMs = 5000 } = this.options;
373
+ if (this.stallTimer !== undefined || stallMs <= 0) {
374
+ return;
375
+ }
376
+ this.stallTimer = setInterval(() => {
377
+ const [oldest] = this.pending.values();
378
+ if (!oldest) {
379
+ clearInterval(this.stallTimer);
380
+ this.stallTimer = undefined;
381
+ return;
382
+ }
383
+ if (!this.probing && Date.now() - Math.max(oldest.sentAt, this.lastReceivedAt) >= stallMs) {
384
+ this.wake(stallMs);
385
+ }
386
+ }, Math.min(1000, stallMs));
387
+ }
261
388
  receive(text) {
262
- var _a, _b, _c, _d, _e, _f;
389
+ var _a, _b, _c, _d, _e, _f, _g;
390
+ this.lastReceivedAt = Date.now();
263
391
  const message = JSON.parse(text);
264
392
  if (message.method === `${ta_protocol_1.TA_CLIENT_SERVICE}/onEvents`) {
265
393
  const [events] = message.params;
@@ -269,13 +397,21 @@ class TaConnection {
269
397
  (_a = this.socket) === null || _a === void 0 ? void 0 : _a.send(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: null }));
270
398
  return;
271
399
  }
400
+ if (message.method === `${ta_protocol_1.TA_CLIENT_SERVICE}/onSessions`) {
401
+ const [sessions] = message.params;
402
+ for (const listener of this.sessionsListeners) {
403
+ listener(sessions);
404
+ }
405
+ (_b = this.socket) === null || _b === void 0 ? void 0 : _b.send(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: null }));
406
+ return;
407
+ }
272
408
  if (message.method === `${ta_protocol_1.TA_CLIENT_SERVICE}/onTerminalData`) {
273
409
  const [terminalId, data, exitCode] = message.params;
274
410
  for (const listener of this.terminalListeners) {
275
411
  // JSON has no undefined: a terminal still running may send null.
276
412
  listener(terminalId, data, exitCode !== null && exitCode !== void 0 ? exitCode : undefined);
277
413
  }
278
- (_b = this.socket) === null || _b === void 0 ? void 0 : _b.send(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: null }));
414
+ (_c = this.socket) === null || _c === void 0 ? void 0 : _c.send(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: null }));
279
415
  return;
280
416
  }
281
417
  if (message.method === `${ta_protocol_1.TA_CLIENT_SERVICE}/onAuthEvent`) {
@@ -283,7 +419,7 @@ class TaConnection {
283
419
  for (const listener of this.authListeners) {
284
420
  listener(loginId, event);
285
421
  }
286
- (_c = this.socket) === null || _c === void 0 ? void 0 : _c.send(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: null }));
422
+ (_d = this.socket) === null || _d === void 0 ? void 0 : _d.send(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: null }));
287
423
  return;
288
424
  }
289
425
  if (message.method === `${ta_protocol_1.TA_CLIENT_SERVICE}/onRemoteEvent`) {
@@ -291,7 +427,15 @@ class TaConnection {
291
427
  for (const listener of this.remoteListeners) {
292
428
  listener(event);
293
429
  }
294
- (_d = this.socket) === null || _d === void 0 ? void 0 : _d.send(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: null }));
430
+ (_e = this.socket) === null || _e === void 0 ? void 0 : _e.send(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: null }));
431
+ return;
432
+ }
433
+ if (message.method === `${ta_protocol_1.TA_CLIENT_SERVICE}/onRoomEvent`) {
434
+ const [event] = message.params;
435
+ for (const listener of this.roomListeners) {
436
+ listener(event);
437
+ }
438
+ (_f = this.socket) === null || _f === void 0 ? void 0 : _f.send(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: null }));
295
439
  return;
296
440
  }
297
441
  if (message.method === `${ta_protocol_1.TA_CLIENT_SERVICE}/onExtensionData`) {
@@ -299,7 +443,7 @@ class TaConnection {
299
443
  for (const listener of this.extensionDataListeners) {
300
444
  listener(name, keys, cwd !== null && cwd !== void 0 ? cwd : undefined);
301
445
  }
302
- (_e = this.socket) === null || _e === void 0 ? void 0 : _e.send(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: null }));
446
+ (_g = this.socket) === null || _g === void 0 ? void 0 : _g.send(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: null }));
303
447
  return;
304
448
  }
305
449
  const call = this.pending.get(message.id);
@@ -308,8 +452,7 @@ class TaConnection {
308
452
  }
309
453
  this.pending.delete(message.id);
310
454
  if (message.error) {
311
- const data = (_f = message.error.data) === null || _f === void 0 ? void 0 : _f.data;
312
- call.reject(new TaRemoteError(message.error.message, data === null || data === void 0 ? void 0 : data.code, data === null || data === void 0 ? void 0 : data.hint));
455
+ call.reject(TaRemoteError.of(message.error));
313
456
  }
314
457
  else {
315
458
  call.resolve(message.result);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@celljs/ta-client",
3
- "version": "4.9.1",
3
+ "version": "4.11.0",
4
4
  "description": "A client of ta serve for any JavaScript runtime: connection and UI-independent session state",
5
5
  "homepage": "https://github.com/cellbang/cell",
6
6
  "bugs": {
@@ -29,11 +29,11 @@
29
29
  "watch": "tsc -b -w --preserveWatchOutput"
30
30
  },
31
31
  "dependencies": {
32
- "@celljs/ta-protocol": "4.9.1"
32
+ "@celljs/ta-protocol": "4.11.0"
33
33
  },
34
34
  "devDependencies": {
35
- "@earendil-works/pi-ai": "^1.5.0",
36
- "@earendil-works/pi-coding-agent": "^1.5.0"
35
+ "@earendil-works/pi-ai": "^1.5.2",
36
+ "@earendil-works/pi-coding-agent": "^1.5.2"
37
37
  },
38
38
  "publishConfig": {
39
39
  "access": "public"