@celljs/ta-client 4.9.0 → 4.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/esm/common/session-reducer.d.ts +15 -1
- package/esm/common/session-reducer.js +8 -4
- package/esm/common/session-store.d.ts +80 -5
- package/esm/common/session-store.js +226 -11
- package/esm/common/ta-connection.d.ts +65 -7
- package/esm/common/ta-connection.js +131 -17
- package/lib/common/session-reducer.d.ts +15 -1
- package/lib/common/session-reducer.js +8 -4
- package/lib/common/session-store.d.ts +80 -5
- package/lib/common/session-store.js +227 -12
- package/lib/common/ta-connection.d.ts +65 -7
- package/lib/common/ta-connection.js +131 -17
- package/package.json +4 -4
|
@@ -1,20 +1,25 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.SessionStore = void 0;
|
|
3
|
+
exports.SessionStore = exports.HOLD_MS = void 0;
|
|
4
4
|
const ta_protocol_1 = require("@celljs/ta-protocol");
|
|
5
5
|
const session_reducer_1 = require("./session-reducer");
|
|
6
|
-
|
|
7
|
-
|
|
6
|
+
const ta_connection_1 = require("./ta-connection");
|
|
7
|
+
/** How long a message the connection could not take waits for it, on its way, before it shows as failed. */
|
|
8
|
+
exports.HOLD_MS = 60000;
|
|
8
9
|
/**
|
|
9
10
|
* The state of one open session on a client: for any UI to render and subscribe to. It catches up by
|
|
10
11
|
* itself after a reconnect, from the events it missed or, if those are gone, from the session.
|
|
11
12
|
*/
|
|
12
13
|
class SessionStore {
|
|
13
14
|
constructor(connection, sessionId, options = {}) {
|
|
14
|
-
var _a;
|
|
15
|
+
var _a, _b;
|
|
15
16
|
this.connection = connection;
|
|
16
17
|
this.sessionId = sessionId;
|
|
18
|
+
/** The session as the service told it. */
|
|
17
19
|
this.current = session_reducer_1.SessionReducer.initial();
|
|
20
|
+
/** `current` with the messages sent from here on their way: what UIs get. */
|
|
21
|
+
this.shown = this.current;
|
|
22
|
+
this.sent = [];
|
|
18
23
|
this.listeners = new Set();
|
|
19
24
|
this.eventListeners = new Set();
|
|
20
25
|
this.goneListeners = new Set();
|
|
@@ -25,11 +30,18 @@ class SessionStore {
|
|
|
25
30
|
this.results = new Map();
|
|
26
31
|
/** Calls another client took, by id: tried again only when the request comes again (that client left). */
|
|
27
32
|
this.declined = new Map();
|
|
33
|
+
/** The messages held that are being sent again now. */
|
|
34
|
+
this.resending = new Set();
|
|
28
35
|
this.clientTools = new Map(((_a = options.clientTools) !== null && _a !== void 0 ? _a : []).map(tool => [tool.definition.name, tool]));
|
|
29
36
|
this.pageBytes = options.pageBytes;
|
|
37
|
+
this.holdMs = (_b = options.holdMs) !== null && _b !== void 0 ? _b : exports.HOLD_MS;
|
|
38
|
+
if (options.initial) {
|
|
39
|
+
const { messages, start, tools } = options.initial;
|
|
40
|
+
this.current = this.shown = { ...this.current, messages, start, tools };
|
|
41
|
+
}
|
|
30
42
|
}
|
|
31
43
|
get state() {
|
|
32
|
-
return this.
|
|
44
|
+
return this.shown;
|
|
33
45
|
}
|
|
34
46
|
/** Starts following the session. */
|
|
35
47
|
async attach() {
|
|
@@ -52,9 +64,194 @@ class SessionStore {
|
|
|
52
64
|
this.eventListeners.add(listener);
|
|
53
65
|
return () => this.eventListeners.delete(listener);
|
|
54
66
|
}
|
|
55
|
-
/**
|
|
67
|
+
/**
|
|
68
|
+
* Sends a message with a new id; a resend after a lost connection must reuse the id. Sent while the
|
|
69
|
+
* agent is idle, it shows at once at the end of the conversation, with the agent at work, until the
|
|
70
|
+
* session has it (a command, which may add none, does not).
|
|
71
|
+
*/
|
|
56
72
|
prompt(message, input = {}) {
|
|
57
|
-
return this.
|
|
73
|
+
return this.deliver(message, input, false);
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* As `prompt`, for what the user typed: a message that fails to go stays in the conversation, marked
|
|
77
|
+
* failed, to send again (`resend`) or take back (`discard`), and this resolves without a receipt. One
|
|
78
|
+
* the connection could not take is not failed: it stays on its way and goes once the store is attached
|
|
79
|
+
* again, as a chat app sends what was typed without network once it is back; only after `holdMs`
|
|
80
|
+
* without a connection does it show as failed.
|
|
81
|
+
*/
|
|
82
|
+
async send(message, input = {}) {
|
|
83
|
+
try {
|
|
84
|
+
return await this.deliver(message, input, true);
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
if (this.sent.some(sent => (sent.failed || sent.heldAt) && sent.text === message)) {
|
|
88
|
+
return undefined;
|
|
89
|
+
}
|
|
90
|
+
throw error;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
/** Sends again a message that failed, with its id: one that reached the service after all runs once. */
|
|
94
|
+
async resend(id) {
|
|
95
|
+
const sent = this.sent.find(candidate => candidate.id === id && candidate.failed);
|
|
96
|
+
if (!sent) {
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
this.sent = this.sent.filter(other => other !== sent);
|
|
100
|
+
await this.send(sent.text, { ...sent.input, clientMessageId: sent.id }).catch(() => undefined);
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Takes on the messages that failed to go from another store of the same conversation (one that showed
|
|
104
|
+
* it before this one attached, without the computer), to send again from here.
|
|
105
|
+
*/
|
|
106
|
+
carry(from) {
|
|
107
|
+
const failed = from.sent.filter(sent => (sent.failed || sent.heldAt) && !this.sent.some(other => other.id === sent.id));
|
|
108
|
+
if (failed.length) {
|
|
109
|
+
this.sent = [...this.sent, ...failed];
|
|
110
|
+
this.show();
|
|
111
|
+
if (this.lastSeq !== undefined) {
|
|
112
|
+
this.sendHeld();
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
/** Takes back a message that failed. */
|
|
117
|
+
discard(id) {
|
|
118
|
+
const sent = this.sent.find(candidate => candidate.id === id);
|
|
119
|
+
if (sent) {
|
|
120
|
+
this.unsend(sent);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
deliver(message, input, keep) {
|
|
124
|
+
const full = { clientMessageId: crypto.randomUUID(), ...input, message };
|
|
125
|
+
const sent = this.current.working || message.startsWith('/') ? undefined : this.add(full);
|
|
126
|
+
if (!sent) {
|
|
127
|
+
return this.connection.server.prompt(this.sessionId, full);
|
|
128
|
+
}
|
|
129
|
+
return this.go(sent, full, keep);
|
|
130
|
+
}
|
|
131
|
+
/** Sends a message shown as sent, and settles it by the answer. */
|
|
132
|
+
go(sent, full, keep) {
|
|
133
|
+
return this.connection.server.prompt(this.sessionId, full).then(result => {
|
|
134
|
+
sent.heldAt = undefined;
|
|
135
|
+
if (result.status === 'accepted') {
|
|
136
|
+
sent.accepted = true;
|
|
137
|
+
}
|
|
138
|
+
else {
|
|
139
|
+
// Queued after another run, sent before, or taken by an extension: no message of it comes now.
|
|
140
|
+
this.unsend(sent);
|
|
141
|
+
}
|
|
142
|
+
return result;
|
|
143
|
+
}, error => {
|
|
144
|
+
if (keep && ta_connection_1.TaRemoteError.isConnectionLost(error) && this.hold(sent)) {
|
|
145
|
+
throw error;
|
|
146
|
+
}
|
|
147
|
+
if (keep) {
|
|
148
|
+
this.fail(sent, error);
|
|
149
|
+
}
|
|
150
|
+
else {
|
|
151
|
+
this.unsend(sent);
|
|
152
|
+
}
|
|
153
|
+
throw error;
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
add(input) {
|
|
157
|
+
var _a;
|
|
158
|
+
const message = { role: 'user', content: [{ type: 'text', text: input.message }, ...((_a = input.images) !== null && _a !== void 0 ? _a : [])], timestamp: Date.now() };
|
|
159
|
+
const { message: _text, clientMessageId: _id, ...rest } = input;
|
|
160
|
+
const sent = { id: input.clientMessageId, message, text: input.message, input: rest, accepted: false };
|
|
161
|
+
this.sent = [...this.sent, sent];
|
|
162
|
+
this.show();
|
|
163
|
+
return sent;
|
|
164
|
+
}
|
|
165
|
+
/** Keeps a message the connection could not take on its way, unless it waited `holdMs` already. */
|
|
166
|
+
hold(sent) {
|
|
167
|
+
var _a, _b;
|
|
168
|
+
if (!this.sent.includes(sent)) {
|
|
169
|
+
return false;
|
|
170
|
+
}
|
|
171
|
+
(_a = sent.heldAt) !== null && _a !== void 0 ? _a : (sent.heldAt = Date.now());
|
|
172
|
+
if (Date.now() - sent.heldAt >= this.holdMs) {
|
|
173
|
+
return false;
|
|
174
|
+
}
|
|
175
|
+
(_b = this.holdTimer) !== null && _b !== void 0 ? _b : (this.holdTimer = setTimeout(() => this.expireHeld(), sent.heldAt + this.holdMs - Date.now()));
|
|
176
|
+
return true;
|
|
177
|
+
}
|
|
178
|
+
/** The messages held `holdMs` that are not going now show as failed. */
|
|
179
|
+
expireHeld() {
|
|
180
|
+
this.holdTimer = undefined;
|
|
181
|
+
const now = Date.now();
|
|
182
|
+
let next = Number.POSITIVE_INFINITY;
|
|
183
|
+
for (const sent of this.sent) {
|
|
184
|
+
if (sent.heldAt === undefined || sent.failed || this.resending.has(sent)) {
|
|
185
|
+
continue;
|
|
186
|
+
}
|
|
187
|
+
if (now - sent.heldAt >= this.holdMs) {
|
|
188
|
+
this.fail(sent, ta_connection_1.TaRemoteError.notConnected());
|
|
189
|
+
}
|
|
190
|
+
else {
|
|
191
|
+
next = Math.min(next, sent.heldAt + this.holdMs - now);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
if (next !== Number.POSITIVE_INFINITY) {
|
|
195
|
+
this.holdTimer = setTimeout(() => this.expireHeld(), next);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
/** Attached again: the messages held go now, with their ids, so that one the service had after all runs once. */
|
|
199
|
+
sendHeld() {
|
|
200
|
+
for (const sent of this.sent) {
|
|
201
|
+
if (sent.heldAt === undefined || sent.failed || this.resending.has(sent)) {
|
|
202
|
+
continue;
|
|
203
|
+
}
|
|
204
|
+
this.resending.add(sent);
|
|
205
|
+
void this.go(sent, { ...sent.input, clientMessageId: sent.id, message: sent.text }, true)
|
|
206
|
+
.catch(() => undefined)
|
|
207
|
+
.finally(() => this.resending.delete(sent));
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
fail(sent, error) {
|
|
211
|
+
if (this.sent.includes(sent)) {
|
|
212
|
+
const failed = { ...sent, failed: error instanceof Error ? error.message : String(error) };
|
|
213
|
+
this.sent = this.sent.map(other => (other === sent ? failed : other));
|
|
214
|
+
this.show();
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
unsend(sent) {
|
|
218
|
+
if (this.sent.includes(sent)) {
|
|
219
|
+
this.sent = this.sent.filter(other => other !== sent);
|
|
220
|
+
this.show();
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
/** The message sent, once the session has a message of the user: the one of the same text, else the first. */
|
|
224
|
+
arrived(message) {
|
|
225
|
+
var _a;
|
|
226
|
+
const waiting = this.sent.filter(sent => !sent.failed);
|
|
227
|
+
const text = SessionStore.textOf(message);
|
|
228
|
+
const sent = (_a = waiting.find(candidate => candidate.text === text)) !== null && _a !== void 0 ? _a : waiting[0];
|
|
229
|
+
this.sent = this.sent.filter(other => other !== sent);
|
|
230
|
+
}
|
|
231
|
+
static textOf(message) {
|
|
232
|
+
const { content } = message;
|
|
233
|
+
if (typeof content === 'string') {
|
|
234
|
+
return content;
|
|
235
|
+
}
|
|
236
|
+
const first = Array.isArray(content) ? content[0] : undefined;
|
|
237
|
+
return (first === null || first === void 0 ? void 0 : first.type) === 'text' ? first.text : undefined;
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* `state` with the messages sent from here after it (`outbox` says which they are), and the agent at
|
|
241
|
+
* work for those on their way.
|
|
242
|
+
*/
|
|
243
|
+
static withSent(state, sent) {
|
|
244
|
+
if (!sent.length) {
|
|
245
|
+
return state;
|
|
246
|
+
}
|
|
247
|
+
const going = sent.some(message => !message.failed);
|
|
248
|
+
return {
|
|
249
|
+
...state,
|
|
250
|
+
messages: [...state.messages, ...sent.map(message => message.message)],
|
|
251
|
+
outbox: sent,
|
|
252
|
+
working: state.working || going,
|
|
253
|
+
runStart: state.working || !going ? state.runStart : state.messages.length,
|
|
254
|
+
};
|
|
58
255
|
}
|
|
59
256
|
/**
|
|
60
257
|
* The service no longer has the session after a reconnect (it restarted, or closed the session while
|
|
@@ -75,7 +272,7 @@ class SessionStore {
|
|
|
75
272
|
// The conversation as of lastSeq, with the message being written and the calls running.
|
|
76
273
|
const conversation = (_a = result.conversation) !== null && _a !== void 0 ? _a : { ...(await this.connection.server.getMessages(this.sessionId)), tools: {} };
|
|
77
274
|
const { messages, start } = SessionStore.withEarlier(this.current, conversation.messages, (_b = conversation.start) !== null && _b !== void 0 ? _b : 0);
|
|
78
|
-
const kept =
|
|
275
|
+
const kept = session_reducer_1.SessionReducer.keep(this.current.messages, messages, start - this.current.start);
|
|
79
276
|
state = {
|
|
80
277
|
...this.current,
|
|
81
278
|
messages: kept,
|
|
@@ -84,6 +281,8 @@ class SessionStore {
|
|
|
84
281
|
runStart: kept === this.current.messages ? this.current.runStart : undefined,
|
|
85
282
|
};
|
|
86
283
|
this.lastSeq = result.lastSeq;
|
|
284
|
+
// The conversation of the service has those it took.
|
|
285
|
+
this.sent = this.sent.filter(sent => !sent.accepted);
|
|
87
286
|
}
|
|
88
287
|
const taken = this.take(state, result.events);
|
|
89
288
|
state = {
|
|
@@ -99,6 +298,7 @@ class SessionStore {
|
|
|
99
298
|
// Once, however much changed: what is drawn changes in one frame.
|
|
100
299
|
this.update(state);
|
|
101
300
|
this.applied(taken);
|
|
301
|
+
this.sendHeld();
|
|
102
302
|
return result;
|
|
103
303
|
}
|
|
104
304
|
/**
|
|
@@ -184,6 +384,15 @@ class SessionStore {
|
|
|
184
384
|
}
|
|
185
385
|
this.lastSeq = seq;
|
|
186
386
|
state = session_reducer_1.SessionReducer.reduce(state, event);
|
|
387
|
+
if (this.sent.length) {
|
|
388
|
+
if (event.type === 'message_start' && event.message.role === 'user') {
|
|
389
|
+
this.arrived(event.message);
|
|
390
|
+
}
|
|
391
|
+
else if (event.type === 'agent_settled') {
|
|
392
|
+
// Its run ended without it as sent (an extension changed it): it no longer waits.
|
|
393
|
+
this.sent = this.sent.filter(sent => !sent.accepted);
|
|
394
|
+
}
|
|
395
|
+
}
|
|
187
396
|
replaced || (replaced = event.type === 'session_replaced');
|
|
188
397
|
applied.push(event);
|
|
189
398
|
}
|
|
@@ -203,12 +412,18 @@ class SessionStore {
|
|
|
203
412
|
update(state) {
|
|
204
413
|
if (state !== this.current) {
|
|
205
414
|
this.current = state;
|
|
206
|
-
|
|
207
|
-
listener(state);
|
|
208
|
-
}
|
|
415
|
+
this.show();
|
|
209
416
|
this.runClientTools(state);
|
|
210
417
|
}
|
|
211
418
|
}
|
|
419
|
+
/** UIs get the state with the messages sent, when either changed. */
|
|
420
|
+
show() {
|
|
421
|
+
const shown = SessionStore.withSent(this.current, this.sent.map(({ id, message, failed }) => (failed ? { id, message, failed } : { id, message })));
|
|
422
|
+
this.shown = shown;
|
|
423
|
+
for (const listener of this.listeners) {
|
|
424
|
+
listener(shown);
|
|
425
|
+
}
|
|
426
|
+
}
|
|
212
427
|
runClientTools(state) {
|
|
213
428
|
for (const request of state.pendingClientTools) {
|
|
214
429
|
const tool = this.clientTools.get(request.toolName);
|
|
@@ -255,7 +470,7 @@ class SessionStore {
|
|
|
255
470
|
/** Whether this client runs the call; a Ta service from before claims (a computer not updated yet, reached from a phone) lets every client run it, as it did. */
|
|
256
471
|
claim(request) {
|
|
257
472
|
return this.connection.server.claimClientTool(this.sessionId, request.id).catch(error => {
|
|
258
|
-
if ((error
|
|
473
|
+
if (ta_connection_1.TaRemoteError.isMethodNotFound(error)) {
|
|
259
474
|
return true;
|
|
260
475
|
}
|
|
261
476
|
throw error;
|
|
@@ -1,9 +1,36 @@
|
|
|
1
|
-
import { type TaAccessServer, type TaAuthEvent, type TaAuthServer, TaErrorCode, type TaEventEnvelope, type TaGatewayServer, type TaPackageServer, type TaRelayServer, type TaRemoteEvent, type TaRemoteServer, type TaServer, type TaSettingsServer, type TaTerminalServer, type TaWorkspaceServer } from '@celljs/ta-protocol';
|
|
2
|
-
/**
|
|
1
|
+
import { type TaAccessServer, type TaAuthEvent, type TaAuthServer, TaErrorCode, type TaErrorData, type TaEventEnvelope, type TaGatewayServer, type TaPackageServer, type TaRelayServer, type TaRemoteEvent, type TaRemoteServer, type TaServer, type TaSettingsServer, type TaTerminalServer, type TaWorkspaceServer } from '@celljs/ta-protocol';
|
|
2
|
+
/**
|
|
3
|
+
* A failed call. `code` is set for failures the server names; `rpcCode` is the code of JSON-RPC's error,
|
|
4
|
+
* by which a client tells a method an older ta serve does not have (`TaRemoteError.METHOD_NOT_FOUND`).
|
|
5
|
+
*/
|
|
3
6
|
export declare class TaRemoteError extends Error {
|
|
4
7
|
readonly code?: TaErrorCode | undefined;
|
|
5
8
|
readonly hint?: string | undefined;
|
|
6
|
-
|
|
9
|
+
readonly rpcCode?: number | undefined;
|
|
10
|
+
/** JSON-RPC's code for a method the server does not have. */
|
|
11
|
+
static readonly METHOD_NOT_FOUND = -32601;
|
|
12
|
+
constructor(message: string, code?: TaErrorCode | undefined, hint?: string | undefined, rpcCode?: number | undefined);
|
|
13
|
+
/** The error of a JSON-RPC answer: its code, and the code and hint of ta serve when it named the failure. */
|
|
14
|
+
static of(error: {
|
|
15
|
+
message: string;
|
|
16
|
+
code?: number;
|
|
17
|
+
data?: {
|
|
18
|
+
data?: TaErrorData;
|
|
19
|
+
};
|
|
20
|
+
}): TaRemoteError;
|
|
21
|
+
/** What a call says that waited for a connection that did not come back. */
|
|
22
|
+
static readonly NOT_CONNECTED = "Not connected to ta serve.";
|
|
23
|
+
/** What a call says that was sent on a connection lost before its answer. */
|
|
24
|
+
static readonly LOST = "The connection to ta serve was lost.";
|
|
25
|
+
/** A call that waited for a connection that did not come back. */
|
|
26
|
+
static notConnected(): TaRemoteError;
|
|
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: unknown): boolean;
|
|
32
|
+
/** Whether the server has no such method: a ta serve from before it was added. */
|
|
33
|
+
static isMethodNotFound(error: unknown): boolean;
|
|
7
34
|
}
|
|
8
35
|
export interface TaConnectionOptions {
|
|
9
36
|
/** The `url` of serve.json. */
|
|
@@ -19,6 +46,18 @@ export interface TaConnectionOptions {
|
|
|
19
46
|
* that a short drop goes unnoticed. Default 5000; 0 fails at once.
|
|
20
47
|
*/
|
|
21
48
|
waitForOpenMs?: number;
|
|
49
|
+
/**
|
|
50
|
+
* How long a call that is safe to send again (`TaConnection.resendable`: a read, a message with its
|
|
51
|
+
* clientMessageId) keeps trying across lost connections, waiting for each to come back, before it
|
|
52
|
+
* fails: a drop mended within it goes unseen. Default `waitForOpenMs`.
|
|
53
|
+
*/
|
|
54
|
+
retryForMs?: number;
|
|
55
|
+
/**
|
|
56
|
+
* A call unanswered this long while nothing at all came over the connection makes it check that the
|
|
57
|
+
* connection is alive (`wake`): one gone without a word is made again in seconds, not when the system
|
|
58
|
+
* notices; the check waits as long for its answer. Default 5000; 0 never checks.
|
|
59
|
+
*/
|
|
60
|
+
stallMs?: number;
|
|
22
61
|
/**
|
|
23
62
|
* Another way to ta serve than a WebSocket to `url`, such as a relay (RelaySocket of @celljs/ta-relay):
|
|
24
63
|
* a new socket for each connection, which takes care of access itself.
|
|
@@ -40,6 +79,8 @@ export interface TaSocket {
|
|
|
40
79
|
interface PendingCall {
|
|
41
80
|
resolve(result: unknown): void;
|
|
42
81
|
reject(error: Error): void;
|
|
82
|
+
/** When it was sent, on the clock of Date.now(). */
|
|
83
|
+
sentAt: number;
|
|
43
84
|
}
|
|
44
85
|
type EventsListener = (events: TaEventEnvelope[]) => void;
|
|
45
86
|
type TerminalListener = (terminalId: string, data: string, exitCode?: number) => void;
|
|
@@ -56,8 +97,11 @@ type ReconnectingListener = (delayMs: number, attempt: number) => void;
|
|
|
56
97
|
* over the one WebSocket.
|
|
57
98
|
*
|
|
58
99
|
* A call made while the connection is down waits a little for it to come back (`waitForOpenMs`): it was
|
|
59
|
-
* not sent. Calls that were sent when the connection was lost fail
|
|
60
|
-
*
|
|
100
|
+
* not sent. Calls that were sent when the connection was lost fail, unless they are safe to send again
|
|
101
|
+
* (`resendable`: reads, and messages ta serve takes once by their clientMessageId), which wait for the
|
|
102
|
+
* next connection and go again for up to `retryForMs`: on a network that drops now and then, a read or a
|
|
103
|
+
* message is late rather than failed. A call that stalls while nothing comes makes it check the
|
|
104
|
+
* connection (`stallMs`), so that one gone without a word is not waited on for long.
|
|
61
105
|
*/
|
|
62
106
|
export declare class TaConnection {
|
|
63
107
|
protected readonly options: TaConnectionOptions;
|
|
@@ -91,6 +135,11 @@ export declare class TaConnection {
|
|
|
91
135
|
go(): void;
|
|
92
136
|
fail(): void;
|
|
93
137
|
}>;
|
|
138
|
+
/** When the last message came, on the clock of Date.now(). */
|
|
139
|
+
protected lastReceivedAt: number;
|
|
140
|
+
/** Checks the calls for a stall while some wait for answers. */
|
|
141
|
+
protected stallTimer?: ReturnType<typeof setInterval>;
|
|
142
|
+
protected probing: boolean;
|
|
94
143
|
constructor(options: TaConnectionOptions);
|
|
95
144
|
/** Resolves when the first connection is open, or rejects if it cannot be made; later losses reconnect. */
|
|
96
145
|
connect(): Promise<void>;
|
|
@@ -123,11 +172,20 @@ export declare class TaConnection {
|
|
|
123
172
|
protected lost(socket: TaSocket, opened: boolean, atOnce?: boolean): void;
|
|
124
173
|
protected createWebSocket(): TaSocket;
|
|
125
174
|
protected scheduleReconnect(): void;
|
|
126
|
-
/** Resolves once the connection is open, or rejects after `waitForOpenMs
|
|
127
|
-
protected opened(): Promise<void>;
|
|
175
|
+
/** Resolves once the connection is open, or rejects after `waitForOpenMs` (or `waitMs`), or at once when it is closed. */
|
|
176
|
+
protected opened(waitMs?: number): Promise<void>;
|
|
128
177
|
protected failPending(): void;
|
|
129
178
|
protected service<T extends object>(name: string): T;
|
|
179
|
+
/**
|
|
180
|
+
* Whether a call may go again after a lost connection, as doing it twice does what doing it once does:
|
|
181
|
+
* a read, or a message with its clientMessageId (TaPromptInput), which ta serve takes once.
|
|
182
|
+
*/
|
|
183
|
+
static resendable(service: string, method: string, params: readonly unknown[]): boolean;
|
|
130
184
|
protected call(service: string, method: string, params: unknown[]): Promise<unknown>;
|
|
185
|
+
/** Sends a call on the open connection; its answer, or its failure when the connection is lost first. */
|
|
186
|
+
protected send(service: string, method: string, params: unknown[]): Promise<unknown>;
|
|
187
|
+
/** While calls wait for answers: one that waits past `stallMs` with nothing come since makes it check the connection. */
|
|
188
|
+
protected watchStalls(): void;
|
|
131
189
|
protected receive(text: string): void;
|
|
132
190
|
}
|
|
133
191
|
export {};
|
|
@@ -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
|
-
/**
|
|
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
|
|
23
|
-
*
|
|
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) {
|
|
@@ -50,6 +91,9 @@ class TaConnection {
|
|
|
50
91
|
this.reconnectingListeners = new Set();
|
|
51
92
|
/** The calls waiting for the connection to open: `go` once it is, `fail` when it is closed. */
|
|
52
93
|
this.waiting = new Set();
|
|
94
|
+
/** When the last message came, on the clock of Date.now(). */
|
|
95
|
+
this.lastReceivedAt = 0;
|
|
96
|
+
this.probing = false;
|
|
53
97
|
}
|
|
54
98
|
/** Resolves when the first connection is open, or rejects if it cannot be made; later losses reconnect. */
|
|
55
99
|
connect() {
|
|
@@ -59,6 +103,7 @@ class TaConnection {
|
|
|
59
103
|
var _a;
|
|
60
104
|
this.closed = true;
|
|
61
105
|
clearTimeout(this.reconnectTimer);
|
|
106
|
+
clearInterval(this.stallTimer);
|
|
62
107
|
for (const call of [...this.waiting]) {
|
|
63
108
|
call.fail();
|
|
64
109
|
}
|
|
@@ -128,8 +173,12 @@ class TaConnection {
|
|
|
128
173
|
return;
|
|
129
174
|
}
|
|
130
175
|
let answered = false;
|
|
176
|
+
const since = Date.now();
|
|
177
|
+
this.probing = true;
|
|
131
178
|
const timer = setTimeout(() => {
|
|
132
|
-
|
|
179
|
+
this.probing = false;
|
|
180
|
+
// Anything that came meanwhile says it is alive, only slow: the answer waits behind it.
|
|
181
|
+
if (!answered && this.socket === socket && this.lastReceivedAt <= since) {
|
|
133
182
|
socket.onclose = null;
|
|
134
183
|
socket.onmessage = null;
|
|
135
184
|
socket.close();
|
|
@@ -137,10 +186,19 @@ class TaConnection {
|
|
|
137
186
|
this.lost(socket, true, true);
|
|
138
187
|
}
|
|
139
188
|
}, timeoutMs);
|
|
140
|
-
|
|
189
|
+
const done = () => {
|
|
141
190
|
answered = true;
|
|
191
|
+
this.probing = false;
|
|
142
192
|
clearTimeout(timer);
|
|
143
|
-
}
|
|
193
|
+
};
|
|
194
|
+
// Any answer says the connection is alive, an error too. Asked of what answers at the front: `ta gateway`
|
|
195
|
+
// answers its own service while a Ta behind it is slow, and a Ta service says it has no such service.
|
|
196
|
+
// Sent once, not again after a loss as a read would be: it asks about this connection.
|
|
197
|
+
this.send(ta_protocol_1.TA_GATEWAY_SERVICE, 'getGateway', []).then(done, error => {
|
|
198
|
+
if (error.code !== ta_protocol_1.TaErrorCode.CONNECTION_LOST) {
|
|
199
|
+
done();
|
|
200
|
+
}
|
|
201
|
+
});
|
|
144
202
|
}
|
|
145
203
|
/** With `resolve` and `reject`: the first connection, whose failure is the caller's to handle. */
|
|
146
204
|
open(resolve, reject) {
|
|
@@ -206,10 +264,11 @@ class TaConnection {
|
|
|
206
264
|
listener(delay, this.attempts);
|
|
207
265
|
}
|
|
208
266
|
}
|
|
209
|
-
/** Resolves once the connection is open, or rejects after `waitForOpenMs
|
|
210
|
-
opened() {
|
|
211
|
-
const { waitForOpenMs = 5000 } = this.options;
|
|
212
|
-
const
|
|
267
|
+
/** Resolves once the connection is open, or rejects after `waitForOpenMs` (or `waitMs`), or at once when it is closed. */
|
|
268
|
+
opened(waitMs) {
|
|
269
|
+
const { waitForOpenMs: configured = 5000 } = this.options;
|
|
270
|
+
const waitForOpenMs = configured <= 0 ? 0 : (waitMs !== null && waitMs !== void 0 ? waitMs : configured);
|
|
271
|
+
const notConnected = () => TaRemoteError.notConnected();
|
|
213
272
|
if (this.closed || waitForOpenMs <= 0) {
|
|
214
273
|
return Promise.reject(notConnected());
|
|
215
274
|
}
|
|
@@ -232,7 +291,7 @@ class TaConnection {
|
|
|
232
291
|
}
|
|
233
292
|
failPending() {
|
|
234
293
|
for (const call of this.pending.values()) {
|
|
235
|
-
call.reject(new TaRemoteError(
|
|
294
|
+
call.reject(new TaRemoteError(TaRemoteError.LOST, ta_protocol_1.TaErrorCode.CONNECTION_LOST, 'Send it again once the connection is back.'));
|
|
236
295
|
}
|
|
237
296
|
this.pending.clear();
|
|
238
297
|
}
|
|
@@ -241,10 +300,46 @@ class TaConnection {
|
|
|
241
300
|
get: (_target, method) => (...params) => this.call(name, method, params),
|
|
242
301
|
});
|
|
243
302
|
}
|
|
303
|
+
/**
|
|
304
|
+
* Whether a call may go again after a lost connection, as doing it twice does what doing it once does:
|
|
305
|
+
* a read, or a message with its clientMessageId (TaPromptInput), which ta serve takes once.
|
|
306
|
+
*/
|
|
307
|
+
static resendable(service, method, params) {
|
|
308
|
+
var _a;
|
|
309
|
+
if (READ_METHOD.test(method)) {
|
|
310
|
+
return true;
|
|
311
|
+
}
|
|
312
|
+
return service === ta_protocol_1.TA_SERVER_SERVICE && MESSAGE_METHODS.has(method) && !!((_a = params[1]) === null || _a === void 0 ? void 0 : _a.clientMessageId);
|
|
313
|
+
}
|
|
244
314
|
async call(service, method, params) {
|
|
315
|
+
var _a, _b;
|
|
316
|
+
if (!TaConnection.resendable(service, method, params)) {
|
|
317
|
+
if (((_a = this.socket) === null || _a === void 0 ? void 0 : _a.readyState) !== WebSocket.OPEN) {
|
|
318
|
+
await this.opened();
|
|
319
|
+
}
|
|
320
|
+
return this.send(service, method, params);
|
|
321
|
+
}
|
|
322
|
+
const { waitForOpenMs = 5000, retryForMs = waitForOpenMs } = this.options;
|
|
323
|
+
const deadline = Date.now() + Math.max(retryForMs, 1);
|
|
324
|
+
for (;;) {
|
|
325
|
+
if (((_b = this.socket) === null || _b === void 0 ? void 0 : _b.readyState) !== WebSocket.OPEN) {
|
|
326
|
+
await this.opened(Math.max(1, deadline - Date.now()));
|
|
327
|
+
}
|
|
328
|
+
try {
|
|
329
|
+
return await this.send(service, method, params);
|
|
330
|
+
}
|
|
331
|
+
catch (error) {
|
|
332
|
+
if (error.code !== ta_protocol_1.TaErrorCode.CONNECTION_LOST || this.closed || Date.now() >= deadline) {
|
|
333
|
+
throw error;
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
/** Sends a call on the open connection; its answer, or its failure when the connection is lost first. */
|
|
339
|
+
send(service, method, params) {
|
|
245
340
|
var _a;
|
|
246
341
|
if (((_a = this.socket) === null || _a === void 0 ? void 0 : _a.readyState) !== WebSocket.OPEN) {
|
|
247
|
-
|
|
342
|
+
return Promise.reject(TaRemoteError.notConnected());
|
|
248
343
|
}
|
|
249
344
|
const socket = this.socket;
|
|
250
345
|
const id = ++this.nextId;
|
|
@@ -254,12 +349,32 @@ class TaConnection {
|
|
|
254
349
|
length--;
|
|
255
350
|
}
|
|
256
351
|
return new Promise((resolve, reject) => {
|
|
257
|
-
this.pending.set(id, { resolve, reject });
|
|
352
|
+
this.pending.set(id, { resolve, reject, sentAt: Date.now() });
|
|
353
|
+
this.watchStalls();
|
|
258
354
|
socket.send(JSON.stringify({ jsonrpc: '2.0', id, method: `${service}/${method}`, params: params.slice(0, length) }));
|
|
259
355
|
});
|
|
260
356
|
}
|
|
357
|
+
/** While calls wait for answers: one that waits past `stallMs` with nothing come since makes it check the connection. */
|
|
358
|
+
watchStalls() {
|
|
359
|
+
const { stallMs = 5000 } = this.options;
|
|
360
|
+
if (this.stallTimer !== undefined || stallMs <= 0) {
|
|
361
|
+
return;
|
|
362
|
+
}
|
|
363
|
+
this.stallTimer = setInterval(() => {
|
|
364
|
+
const [oldest] = this.pending.values();
|
|
365
|
+
if (!oldest) {
|
|
366
|
+
clearInterval(this.stallTimer);
|
|
367
|
+
this.stallTimer = undefined;
|
|
368
|
+
return;
|
|
369
|
+
}
|
|
370
|
+
if (!this.probing && Date.now() - Math.max(oldest.sentAt, this.lastReceivedAt) >= stallMs) {
|
|
371
|
+
this.wake(stallMs);
|
|
372
|
+
}
|
|
373
|
+
}, Math.min(1000, stallMs));
|
|
374
|
+
}
|
|
261
375
|
receive(text) {
|
|
262
|
-
var _a, _b, _c, _d, _e
|
|
376
|
+
var _a, _b, _c, _d, _e;
|
|
377
|
+
this.lastReceivedAt = Date.now();
|
|
263
378
|
const message = JSON.parse(text);
|
|
264
379
|
if (message.method === `${ta_protocol_1.TA_CLIENT_SERVICE}/onEvents`) {
|
|
265
380
|
const [events] = message.params;
|
|
@@ -308,8 +423,7 @@ class TaConnection {
|
|
|
308
423
|
}
|
|
309
424
|
this.pending.delete(message.id);
|
|
310
425
|
if (message.error) {
|
|
311
|
-
|
|
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));
|
|
426
|
+
call.reject(TaRemoteError.of(message.error));
|
|
313
427
|
}
|
|
314
428
|
else {
|
|
315
429
|
call.resolve(message.result);
|