@celljs/ta-client 4.7.0 → 4.9.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/README.en.md +2 -2
- package/README.md +3 -3
- package/esm/common/session-reducer.d.ts +21 -11
- package/esm/common/session-reducer.js +55 -4
- package/esm/common/session-store.d.ts +50 -3
- package/esm/common/session-store.js +145 -15
- package/esm/common/ta-connection.d.ts +27 -2
- package/esm/common/ta-connection.js +96 -12
- package/lib/common/session-reducer.d.ts +21 -11
- package/lib/common/session-reducer.js +55 -4
- package/lib/common/session-store.d.ts +50 -3
- package/lib/common/session-store.js +145 -15
- package/lib/common/ta-connection.d.ts +27 -2
- package/lib/common/ta-connection.js +95 -11
- package/package.json +4 -3
- package/esm/common/index.js.map +0 -1
- package/esm/common/session-reducer.js.map +0 -1
- package/esm/common/session-store.js.map +0 -1
- package/esm/common/ta-connection.js.map +0 -1
- package/lib/common/index.d.ts.map +0 -1
- package/lib/common/index.js.map +0 -1
- package/lib/common/session-reducer.d.ts.map +0 -1
- package/lib/common/session-reducer.js.map +0 -1
- package/lib/common/session-reducer.spec.d.ts +0 -2
- package/lib/common/session-reducer.spec.d.ts.map +0 -1
- package/lib/common/session-reducer.spec.js +0 -100
- package/lib/common/session-reducer.spec.js.map +0 -1
- package/lib/common/session-store.d.ts.map +0 -1
- package/lib/common/session-store.js.map +0 -1
- package/lib/common/ta-connection.d.ts.map +0 -1
- package/lib/common/ta-connection.js.map +0 -1
- package/src/common/index.ts +0 -3
- package/src/common/session-reducer.spec.ts +0 -112
- package/src/common/session-reducer.ts +0 -185
- package/src/common/session-store.ts +0 -188
- package/src/common/ta-connection.ts +0 -325
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { TA_AUTH_SERVICE, TA_CLIENT_SERVICE, TA_PACKAGE_SERVICE, TA_RELAY_SERVICE, TA_REMOTE_SERVICE, TA_SERVER_SERVICE, TA_SETTINGS_SERVICE, TA_TERMINAL_SERVICE, TA_WORKSPACE_SERVICE, TaErrorCode, } from '@celljs/ta-protocol';
|
|
1
|
+
import { TA_ACCESS_SERVICE, TA_AUTH_SERVICE, TA_CLIENT_SERVICE, TA_GATEWAY_SERVICE, TA_PACKAGE_SERVICE, TA_RELAY_SERVICE, TA_REMOTE_SERVICE, TA_SERVER_SERVICE, TA_SETTINGS_SERVICE, TA_TERMINAL_SERVICE, TA_WORKSPACE_SERVICE, TaErrorCode, } from '@celljs/ta-protocol';
|
|
2
2
|
/** A failed call. `code` is set for failures the server names. */
|
|
3
3
|
export class TaRemoteError extends Error {
|
|
4
4
|
constructor(message, code, hint) {
|
|
@@ -14,7 +14,9 @@ export class TaRemoteError extends Error {
|
|
|
14
14
|
* attaching again ({@link SessionStore} does). Each service of ta serve is a property; all of them go
|
|
15
15
|
* over the one WebSocket.
|
|
16
16
|
*
|
|
17
|
-
*
|
|
17
|
+
* A call made while the connection is down waits a little for it to come back (`waitForOpenMs`): it was
|
|
18
|
+
* not sent. Calls that were sent when the connection was lost fail and are not sent again, because only
|
|
19
|
+
* the caller knows whether to resend.
|
|
18
20
|
*/
|
|
19
21
|
export class TaConnection {
|
|
20
22
|
constructor(options) {
|
|
@@ -25,6 +27,9 @@ export class TaConnection {
|
|
|
25
27
|
this.settings = this.service(TA_SETTINGS_SERVICE);
|
|
26
28
|
this.packages = this.service(TA_PACKAGE_SERVICE);
|
|
27
29
|
this.auth = this.service(TA_AUTH_SERVICE);
|
|
30
|
+
this.access = this.service(TA_ACCESS_SERVICE);
|
|
31
|
+
/** Behind `ta gateway` only: a Ta service alone does not have it. */
|
|
32
|
+
this.gateway = this.service(TA_GATEWAY_SERVICE);
|
|
28
33
|
this.relay = this.service(TA_RELAY_SERVICE);
|
|
29
34
|
this.remote = this.service(TA_REMOTE_SERVICE);
|
|
30
35
|
this.closed = false;
|
|
@@ -39,6 +44,8 @@ export class TaConnection {
|
|
|
39
44
|
this.openListeners = new Set();
|
|
40
45
|
this.closeListeners = new Set();
|
|
41
46
|
this.reconnectingListeners = new Set();
|
|
47
|
+
/** The calls waiting for the connection to open: `go` once it is, `fail` when it is closed. */
|
|
48
|
+
this.waiting = new Set();
|
|
42
49
|
}
|
|
43
50
|
/** Resolves when the first connection is open, or rejects if it cannot be made; later losses reconnect. */
|
|
44
51
|
connect() {
|
|
@@ -48,6 +55,9 @@ export class TaConnection {
|
|
|
48
55
|
var _a;
|
|
49
56
|
this.closed = true;
|
|
50
57
|
clearTimeout(this.reconnectTimer);
|
|
58
|
+
for (const call of [...this.waiting]) {
|
|
59
|
+
call.fail();
|
|
60
|
+
}
|
|
51
61
|
(_a = this.socket) === null || _a === void 0 ? void 0 : _a.close();
|
|
52
62
|
}
|
|
53
63
|
onEvents(listener) {
|
|
@@ -99,6 +109,35 @@ export class TaConnection {
|
|
|
99
109
|
this.attempts = 0;
|
|
100
110
|
this.open();
|
|
101
111
|
}
|
|
112
|
+
/**
|
|
113
|
+
* After the device slept or its network changed, when a connection may be gone without a word: one
|
|
114
|
+
* that is down is tried at once, and an open one that does not answer within `timeoutMs` is given up
|
|
115
|
+
* and made again at once, rather than when the system notices.
|
|
116
|
+
*/
|
|
117
|
+
wake(timeoutMs = 3000) {
|
|
118
|
+
const socket = this.socket;
|
|
119
|
+
if (this.closed || (socket === null || socket === void 0 ? void 0 : socket.readyState) === WebSocket.CONNECTING) {
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
if ((socket === null || socket === void 0 ? void 0 : socket.readyState) !== WebSocket.OPEN) {
|
|
123
|
+
this.reconnect();
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
let answered = false;
|
|
127
|
+
const timer = setTimeout(() => {
|
|
128
|
+
if (!answered && this.socket === socket) {
|
|
129
|
+
socket.onclose = null;
|
|
130
|
+
socket.onmessage = null;
|
|
131
|
+
socket.close();
|
|
132
|
+
this.attempts = 0;
|
|
133
|
+
this.lost(socket, true, true);
|
|
134
|
+
}
|
|
135
|
+
}, timeoutMs);
|
|
136
|
+
this.server.getServerInfo().then(() => {
|
|
137
|
+
answered = true;
|
|
138
|
+
clearTimeout(timer);
|
|
139
|
+
}, () => clearTimeout(timer));
|
|
140
|
+
}
|
|
102
141
|
/** With `resolve` and `reject`: the first connection, whose failure is the caller's to handle. */
|
|
103
142
|
open(resolve, reject) {
|
|
104
143
|
let opened = false;
|
|
@@ -108,24 +147,44 @@ export class TaConnection {
|
|
|
108
147
|
opened = true;
|
|
109
148
|
this.attempts = 0;
|
|
110
149
|
resolve === null || resolve === void 0 ? void 0 : resolve();
|
|
150
|
+
for (const call of [...this.waiting]) {
|
|
151
|
+
call.go();
|
|
152
|
+
}
|
|
111
153
|
for (const listener of this.openListeners) {
|
|
112
154
|
listener();
|
|
113
155
|
}
|
|
114
156
|
};
|
|
115
157
|
socket.onmessage = message => this.receive(String(message.data));
|
|
116
158
|
socket.onclose = () => {
|
|
117
|
-
|
|
159
|
+
// A socket given up for another (`wake`, `reconnect`) closes late: the one after it is not lost.
|
|
160
|
+
if (this.socket !== socket) {
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
118
163
|
if (reject && !opened) {
|
|
164
|
+
this.failPending();
|
|
119
165
|
reject(new TaRemoteError(`Cannot connect to ${this.options.url}.`));
|
|
120
166
|
return;
|
|
121
167
|
}
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
168
|
+
this.lost(socket, opened);
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
/** The connection on `socket` is gone: the calls sent on it fail, and another is made, `atOnce` or after the wait. */
|
|
172
|
+
lost(socket, opened, atOnce = false) {
|
|
173
|
+
this.failPending();
|
|
174
|
+
if (opened) {
|
|
175
|
+
for (const listener of this.closeListeners) {
|
|
176
|
+
listener();
|
|
126
177
|
}
|
|
178
|
+
}
|
|
179
|
+
if (this.socket !== socket || this.closed) {
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
if (atOnce) {
|
|
183
|
+
this.open();
|
|
184
|
+
}
|
|
185
|
+
else {
|
|
127
186
|
this.scheduleReconnect();
|
|
128
|
-
}
|
|
187
|
+
}
|
|
129
188
|
}
|
|
130
189
|
createWebSocket() {
|
|
131
190
|
const url = new URL(this.options.url);
|
|
@@ -143,6 +202,30 @@ export class TaConnection {
|
|
|
143
202
|
listener(delay, this.attempts);
|
|
144
203
|
}
|
|
145
204
|
}
|
|
205
|
+
/** Resolves once the connection is open, or rejects after `waitForOpenMs`, or at once when it is closed. */
|
|
206
|
+
opened() {
|
|
207
|
+
const { waitForOpenMs = 5000 } = this.options;
|
|
208
|
+
const notConnected = () => new TaRemoteError('Not connected to ta serve.', TaErrorCode.CONNECTION_LOST, 'Try again once the connection is back.');
|
|
209
|
+
if (this.closed || waitForOpenMs <= 0) {
|
|
210
|
+
return Promise.reject(notConnected());
|
|
211
|
+
}
|
|
212
|
+
return new Promise((resolve, reject) => {
|
|
213
|
+
const call = {
|
|
214
|
+
go: () => {
|
|
215
|
+
clearTimeout(timer);
|
|
216
|
+
this.waiting.delete(call);
|
|
217
|
+
resolve();
|
|
218
|
+
},
|
|
219
|
+
fail: () => {
|
|
220
|
+
clearTimeout(timer);
|
|
221
|
+
this.waiting.delete(call);
|
|
222
|
+
reject(notConnected());
|
|
223
|
+
},
|
|
224
|
+
};
|
|
225
|
+
const timer = setTimeout(call.fail, waitForOpenMs);
|
|
226
|
+
this.waiting.add(call);
|
|
227
|
+
});
|
|
228
|
+
}
|
|
146
229
|
failPending() {
|
|
147
230
|
for (const call of this.pending.values()) {
|
|
148
231
|
call.reject(new TaRemoteError('The connection to ta serve was lost.', TaErrorCode.CONNECTION_LOST, 'Send it again once the connection is back.'));
|
|
@@ -154,11 +237,12 @@ export class TaConnection {
|
|
|
154
237
|
get: (_target, method) => (...params) => this.call(name, method, params),
|
|
155
238
|
});
|
|
156
239
|
}
|
|
157
|
-
call(service, method, params) {
|
|
158
|
-
|
|
159
|
-
if ((socket === null ||
|
|
160
|
-
|
|
240
|
+
async call(service, method, params) {
|
|
241
|
+
var _a;
|
|
242
|
+
if (((_a = this.socket) === null || _a === void 0 ? void 0 : _a.readyState) !== WebSocket.OPEN) {
|
|
243
|
+
await this.opened();
|
|
161
244
|
}
|
|
245
|
+
const socket = this.socket;
|
|
162
246
|
const id = ++this.nextId;
|
|
163
247
|
// JSON has no undefined: a left-out optional argument must not arrive as null.
|
|
164
248
|
let length = params.length;
|
|
@@ -1,14 +1,6 @@
|
|
|
1
|
-
import type { RpcExtensionUIRequest, TaClientToolRequest,
|
|
2
|
-
export type SessionMessage =
|
|
3
|
-
export
|
|
4
|
-
toolName: string;
|
|
5
|
-
args: unknown;
|
|
6
|
-
/** The latest partial result while it runs, then the result. */
|
|
7
|
-
result?: unknown;
|
|
8
|
-
status: 'running' | 'done' | 'error';
|
|
9
|
-
/** Set for a call another tool made, such as a codemode script. */
|
|
10
|
-
parentToolCallId?: string;
|
|
11
|
-
}
|
|
1
|
+
import type { RpcExtensionUIRequest, TaClientToolRequest, TaEvent, TaMessage, TaToolRun } from '@celljs/ta-protocol';
|
|
2
|
+
export type SessionMessage = TaMessage;
|
|
3
|
+
export type ToolRun = TaToolRun;
|
|
12
4
|
/** A message of `notify`. */
|
|
13
5
|
export interface Notice {
|
|
14
6
|
id: string;
|
|
@@ -23,10 +15,16 @@ export interface RetryState {
|
|
|
23
15
|
errorMessage: string;
|
|
24
16
|
}
|
|
25
17
|
/** What a UI shows of a session. */
|
|
18
|
+
export interface SessionWidget {
|
|
19
|
+
lines: string[];
|
|
20
|
+
placement: 'aboveEditor' | 'belowEditor';
|
|
21
|
+
}
|
|
26
22
|
export interface SessionState {
|
|
27
23
|
/** The agent is working, from the start of a run until it has settled. */
|
|
28
24
|
working: boolean;
|
|
29
25
|
messages: SessionMessage[];
|
|
26
|
+
/** Where `messages` start in the whole conversation: those before are loaded with `SessionStore.loadEarlier`. */
|
|
27
|
+
start: number;
|
|
30
28
|
/** By tool call id. */
|
|
31
29
|
tools: Record<string, ToolRun>;
|
|
32
30
|
/** Dialogs waiting for an answer. */
|
|
@@ -37,6 +35,13 @@ export interface SessionState {
|
|
|
37
35
|
notices: Notice[];
|
|
38
36
|
/** What extensions show with `setStatus`. */
|
|
39
37
|
status: Record<string, string>;
|
|
38
|
+
/** The lines extensions show with `setWidget`, by key, above the message box or below it. */
|
|
39
|
+
widgets: Record<string, SessionWidget>;
|
|
40
|
+
/** Text an extension put in the message box (`setEditorText`): a client takes it once, by its id. */
|
|
41
|
+
editorText?: {
|
|
42
|
+
id: string;
|
|
43
|
+
text: string;
|
|
44
|
+
};
|
|
40
45
|
closed: boolean;
|
|
41
46
|
/** The index in `messages` where the run of now starts: unknown for a run that started before this client attached. */
|
|
42
47
|
runStart?: number;
|
|
@@ -49,5 +54,10 @@ export declare namespace SessionReducer {
|
|
|
49
54
|
function initial(): SessionState;
|
|
50
55
|
/** The next state; the previous one stays valid, so that UIs can compare by identity. */
|
|
51
56
|
function reduce(state: SessionState, event: TaEvent): SessionState;
|
|
57
|
+
/**
|
|
58
|
+
* The messages of `next`, with each that is the same as the one of `previous` at its place kept as it
|
|
59
|
+
* was: a conversation read again after a reconnect has new objects, which a UI would all draw again.
|
|
60
|
+
*/
|
|
61
|
+
function keep(previous: readonly SessionMessage[], next: SessionMessage[]): SessionMessage[];
|
|
52
62
|
}
|
|
53
63
|
//# sourceMappingURL=session-reducer.d.ts.map
|
|
@@ -6,7 +6,18 @@ var SessionReducer;
|
|
|
6
6
|
const DIALOGS = new Set(['select', 'confirm', 'input', 'editor']);
|
|
7
7
|
const MAX_NOTICES = 20;
|
|
8
8
|
function initial() {
|
|
9
|
-
return {
|
|
9
|
+
return {
|
|
10
|
+
working: false,
|
|
11
|
+
messages: [],
|
|
12
|
+
start: 0,
|
|
13
|
+
tools: {},
|
|
14
|
+
pendingUi: [],
|
|
15
|
+
pendingClientTools: [],
|
|
16
|
+
notices: [],
|
|
17
|
+
status: {},
|
|
18
|
+
widgets: {},
|
|
19
|
+
closed: false,
|
|
20
|
+
};
|
|
10
21
|
}
|
|
11
22
|
SessionReducer.initial = initial;
|
|
12
23
|
/** The next state; the previous one stays valid, so that UIs can compare by identity. */
|
|
@@ -39,7 +50,8 @@ var SessionReducer;
|
|
|
39
50
|
case 'ui_request_resolved':
|
|
40
51
|
return { ...state, pendingUi: state.pendingUi.filter(request => request.id !== event.id) };
|
|
41
52
|
case 'client_tool_request':
|
|
42
|
-
|
|
53
|
+
// Asked again (the client that took it left): in place of the request before.
|
|
54
|
+
return { ...state, pendingClientTools: [...state.pendingClientTools.filter(request => request.id !== event.id), event] };
|
|
43
55
|
case 'client_tool_resolved':
|
|
44
56
|
return { ...state, pendingClientTools: state.pendingClientTools.filter(request => request.id !== event.id) };
|
|
45
57
|
case 'compaction_start':
|
|
@@ -52,6 +64,8 @@ var SessionReducer;
|
|
|
52
64
|
}
|
|
53
65
|
case 'auto_retry_end':
|
|
54
66
|
return { ...state, retry: undefined };
|
|
67
|
+
case 'extension_error':
|
|
68
|
+
return withNotice(state, { id: crypto.randomUUID(), message: extensionError(event), type: 'error' });
|
|
55
69
|
case 'session_closed':
|
|
56
70
|
return { ...state, closed: true, working: false, pendingUi: [], pendingClientTools: [] };
|
|
57
71
|
default:
|
|
@@ -75,19 +89,39 @@ var SessionReducer;
|
|
|
75
89
|
function withTool(state, toolCallId, run) {
|
|
76
90
|
return { ...state, tools: { ...state.tools, [toolCallId]: run } };
|
|
77
91
|
}
|
|
92
|
+
/** What failed, as the user knows it: a command by its name. */
|
|
93
|
+
function extensionError(event) {
|
|
94
|
+
const source = event.extensionPath.startsWith('command:') ? `/${event.extensionPath.slice('command:'.length)}` : event.extensionPath;
|
|
95
|
+
return `${source}: ${event.error}`;
|
|
96
|
+
}
|
|
97
|
+
function withNotice(state, notice) {
|
|
98
|
+
return { ...state, notices: [...state.notices, notice].slice(-MAX_NOTICES) };
|
|
99
|
+
}
|
|
78
100
|
function applyUiRequest(state, request) {
|
|
79
101
|
var _a;
|
|
102
|
+
var _b, _c;
|
|
80
103
|
if (DIALOGS.has(request.method)) {
|
|
81
104
|
return { ...state, pendingUi: [...state.pendingUi, request] };
|
|
82
105
|
}
|
|
83
106
|
if (request.method === 'notify') {
|
|
84
|
-
|
|
85
|
-
return { ...state, notices: [...state.notices, notice].slice(-MAX_NOTICES) };
|
|
107
|
+
return withNotice(state, { id: request.id, message: request.message, type: (_b = request.notifyType) !== null && _b !== void 0 ? _b : 'info' });
|
|
86
108
|
}
|
|
87
109
|
if (request.method === 'setStatus') {
|
|
88
110
|
const { [request.statusKey]: _old, ...status } = state.status;
|
|
89
111
|
return { ...state, status: request.statusText === undefined ? status : { ...status, [request.statusKey]: request.statusText } };
|
|
90
112
|
}
|
|
113
|
+
if (request.method === 'setWidget') {
|
|
114
|
+
const { [request.widgetKey]: _old, ...widgets } = state.widgets;
|
|
115
|
+
return {
|
|
116
|
+
...state,
|
|
117
|
+
widgets: ((_a = request.widgetLines) === null || _a === void 0 ? void 0 : _a.length)
|
|
118
|
+
? { ...widgets, [request.widgetKey]: { lines: request.widgetLines, placement: (_c = request.widgetPlacement) !== null && _c !== void 0 ? _c : 'aboveEditor' } }
|
|
119
|
+
: widgets,
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
if (request.method === 'set_editor_text') {
|
|
123
|
+
return { ...state, editorText: { id: request.id, text: request.text } };
|
|
124
|
+
}
|
|
91
125
|
return state;
|
|
92
126
|
}
|
|
93
127
|
function applyDelta(message, delta) {
|
|
@@ -121,5 +155,22 @@ var SessionReducer;
|
|
|
121
155
|
return undefined;
|
|
122
156
|
}
|
|
123
157
|
}
|
|
158
|
+
/**
|
|
159
|
+
* The messages of `next`, with each that is the same as the one of `previous` at its place kept as it
|
|
160
|
+
* was: a conversation read again after a reconnect has new objects, which a UI would all draw again.
|
|
161
|
+
*/
|
|
162
|
+
function keep(previous, next) {
|
|
163
|
+
let same = previous.length === next.length;
|
|
164
|
+
const kept = next.map((message, index) => {
|
|
165
|
+
const before = previous[index];
|
|
166
|
+
if (before && before.role === message.role && before.timestamp === message.timestamp && JSON.stringify(before) === JSON.stringify(message)) {
|
|
167
|
+
return before;
|
|
168
|
+
}
|
|
169
|
+
same = false;
|
|
170
|
+
return message;
|
|
171
|
+
});
|
|
172
|
+
return same ? previous : kept;
|
|
173
|
+
}
|
|
174
|
+
SessionReducer.keep = keep;
|
|
124
175
|
})(SessionReducer || (exports.SessionReducer = SessionReducer = {}));
|
|
125
176
|
//# sourceMappingURL=session-reducer.js.map
|
|
@@ -1,7 +1,12 @@
|
|
|
1
|
-
import type
|
|
2
|
-
import { type SessionState } from './session-reducer';
|
|
1
|
+
import { type RpcExtensionUIResponse, type TaAttachResult, type TaClientToolDefinition, type TaClientToolRequest, type TaClientToolResult, type TaEvent, type TaEventEnvelope, type TaPromptInput, type TaPromptReceipt, type TaSessionInfo } from '@celljs/ta-protocol';
|
|
2
|
+
import { type SessionMessage, type SessionState } from './session-reducer';
|
|
3
3
|
import type { TaConnection } from './ta-connection';
|
|
4
4
|
type Listener = (state: SessionState) => void;
|
|
5
|
+
interface Taken {
|
|
6
|
+
state: SessionState;
|
|
7
|
+
applied: TaEvent[];
|
|
8
|
+
replaced: boolean;
|
|
9
|
+
}
|
|
5
10
|
/**
|
|
6
11
|
* A tool this client runs. Open the session with its `definition` in `clientTools`, and give the tool
|
|
7
12
|
* to the store, which runs each call and sends the result. Its output is what the model reads; a
|
|
@@ -14,6 +19,11 @@ export interface ClientTool {
|
|
|
14
19
|
export interface SessionStoreOptions {
|
|
15
20
|
/** The tools of the session this client runs. Other clients may run them too: the first result counts. */
|
|
16
21
|
clientTools?: ClientTool[];
|
|
22
|
+
/**
|
|
23
|
+
* Only about this many bytes of the latest messages come when it attaches, and as many more each time
|
|
24
|
+
* `loadEarlier` is called: a long conversation shows at once. None: all of it.
|
|
25
|
+
*/
|
|
26
|
+
pageBytes?: number;
|
|
17
27
|
}
|
|
18
28
|
/**
|
|
19
29
|
* The state of one open session on a client: for any UI to render and subscribe to. It catches up by
|
|
@@ -26,12 +36,18 @@ export declare class SessionStore {
|
|
|
26
36
|
protected lastSeq?: number;
|
|
27
37
|
protected readonly listeners: Set<Listener>;
|
|
28
38
|
protected readonly eventListeners: Set<(event: TaEvent) => void>;
|
|
39
|
+
protected readonly goneListeners: Set<() => void>;
|
|
29
40
|
protected readonly stop: (() => void)[];
|
|
30
41
|
protected readonly clientTools: Map<string, ClientTool>;
|
|
31
42
|
/** Calls of client tools this store is running or answering now, by id. */
|
|
32
43
|
protected readonly running: Set<string>;
|
|
33
44
|
/** Results not yet taken by the server, by call id. */
|
|
34
45
|
protected readonly results: Map<string, TaClientToolResult>;
|
|
46
|
+
/** Calls another client took, by id: tried again only when the request comes again (that client left). */
|
|
47
|
+
protected readonly declined: Map<string, TaClientToolRequest>;
|
|
48
|
+
protected readonly pageBytes?: number;
|
|
49
|
+
/** The earlier messages on their way. */
|
|
50
|
+
protected loadingEarlier?: Promise<void>;
|
|
35
51
|
constructor(connection: TaConnection, sessionId: string, options?: SessionStoreOptions);
|
|
36
52
|
get state(): SessionState;
|
|
37
53
|
/** Starts following the session. */
|
|
@@ -43,14 +59,45 @@ export declare class SessionStore {
|
|
|
43
59
|
onEvent(listener: (event: TaEvent) => void): () => void;
|
|
44
60
|
/** Sends a message with a new id; a resend after a lost connection must reuse the id. */
|
|
45
61
|
prompt(message: string, input?: Partial<TaPromptInput>): Promise<TaPromptReceipt>;
|
|
62
|
+
/**
|
|
63
|
+
* The service no longer has the session after a reconnect (it restarted, or closed the session while
|
|
64
|
+
* idle): its file stays, to open again.
|
|
65
|
+
*/
|
|
66
|
+
onGone(listener: () => void): () => void;
|
|
46
67
|
respondUi(response: RpcExtensionUIResponse): Promise<boolean>;
|
|
47
68
|
protected attachAgain(): Promise<TaAttachResult>;
|
|
69
|
+
/**
|
|
70
|
+
* The latest messages, after the earlier ones the store had if they are still the same where the
|
|
71
|
+
* latest start: a reconnect does not drop what was loaded further up.
|
|
72
|
+
*/
|
|
73
|
+
static withEarlier(current: SessionState, messages: SessionMessage[], start: number): {
|
|
74
|
+
messages: SessionMessage[];
|
|
75
|
+
start: number;
|
|
76
|
+
};
|
|
77
|
+
protected lost(error: unknown): void;
|
|
78
|
+
/**
|
|
79
|
+
* The messages before those it has, about `pageBytes` of them, put in front: once they are there, or
|
|
80
|
+
* at once when it has them all. Called again while they come, it waits for the same.
|
|
81
|
+
*/
|
|
82
|
+
loadEarlier(): Promise<void>;
|
|
83
|
+
/** All the messages of the conversation, for what needs the whole of it (an export). */
|
|
84
|
+
loadAll(): Promise<void>;
|
|
85
|
+
protected fetchEarlier(): Promise<void>;
|
|
48
86
|
protected reload(): Promise<void>;
|
|
49
87
|
protected apply(events: TaEventEnvelope[]): void;
|
|
88
|
+
/** `state` with the events of this session not taken yet. */
|
|
89
|
+
protected take(state: SessionState, events: TaEventEnvelope[]): Taken;
|
|
90
|
+
/** Once the state has the events: their listeners, and the conversation read again if it was replaced. */
|
|
91
|
+
protected applied({ applied, replaced }: Taken): void;
|
|
50
92
|
protected update(state: SessionState): void;
|
|
51
93
|
protected runClientTools(state: SessionState): void;
|
|
52
|
-
/**
|
|
94
|
+
/**
|
|
95
|
+
* Runs a call once, if this client takes it: every page of the user gets it. A result that could not be
|
|
96
|
+
* sent is sent again after a reconnect, not made again.
|
|
97
|
+
*/
|
|
53
98
|
protected answer(tool: ClientTool, request: TaClientToolRequest): Promise<void>;
|
|
99
|
+
/** 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. */
|
|
100
|
+
protected claim(request: TaClientToolRequest): Promise<boolean>;
|
|
54
101
|
protected run(tool: ClientTool, request: TaClientToolRequest): Promise<TaClientToolResult>;
|
|
55
102
|
}
|
|
56
103
|
export {};
|
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.SessionStore = void 0;
|
|
4
|
+
const ta_protocol_1 = require("@celljs/ta-protocol");
|
|
4
5
|
const session_reducer_1 = require("./session-reducer");
|
|
6
|
+
/** JSON-RPC's code for a method the server does not have. */
|
|
7
|
+
const METHOD_NOT_FOUND = -32601;
|
|
5
8
|
/**
|
|
6
9
|
* The state of one open session on a client: for any UI to render and subscribe to. It catches up by
|
|
7
10
|
* itself after a reconnect, from the events it missed or, if those are gone, from the session.
|
|
@@ -14,19 +17,23 @@ class SessionStore {
|
|
|
14
17
|
this.current = session_reducer_1.SessionReducer.initial();
|
|
15
18
|
this.listeners = new Set();
|
|
16
19
|
this.eventListeners = new Set();
|
|
20
|
+
this.goneListeners = new Set();
|
|
17
21
|
this.stop = [];
|
|
18
22
|
/** Calls of client tools this store is running or answering now, by id. */
|
|
19
23
|
this.running = new Set();
|
|
20
24
|
/** Results not yet taken by the server, by call id. */
|
|
21
25
|
this.results = new Map();
|
|
26
|
+
/** Calls another client took, by id: tried again only when the request comes again (that client left). */
|
|
27
|
+
this.declined = new Map();
|
|
22
28
|
this.clientTools = new Map(((_a = options.clientTools) !== null && _a !== void 0 ? _a : []).map(tool => [tool.definition.name, tool]));
|
|
29
|
+
this.pageBytes = options.pageBytes;
|
|
23
30
|
}
|
|
24
31
|
get state() {
|
|
25
32
|
return this.current;
|
|
26
33
|
}
|
|
27
34
|
/** Starts following the session. */
|
|
28
35
|
async attach() {
|
|
29
|
-
this.stop.push(this.connection.onEvents(events => this.apply(events)), this.connection.onOpen(() => void this.attachAgain()));
|
|
36
|
+
this.stop.push(this.connection.onEvents(events => this.apply(events)), this.connection.onOpen(() => void this.attachAgain().catch(error => this.lost(error))));
|
|
30
37
|
return (await this.attachAgain()).info;
|
|
31
38
|
}
|
|
32
39
|
/** Stops following it. The session goes on. */
|
|
@@ -49,25 +56,126 @@ class SessionStore {
|
|
|
49
56
|
prompt(message, input = {}) {
|
|
50
57
|
return this.connection.server.prompt(this.sessionId, { clientMessageId: crypto.randomUUID(), ...input, message });
|
|
51
58
|
}
|
|
59
|
+
/**
|
|
60
|
+
* The service no longer has the session after a reconnect (it restarted, or closed the session while
|
|
61
|
+
* idle): its file stays, to open again.
|
|
62
|
+
*/
|
|
63
|
+
onGone(listener) {
|
|
64
|
+
this.goneListeners.add(listener);
|
|
65
|
+
return () => this.goneListeners.delete(listener);
|
|
66
|
+
}
|
|
52
67
|
respondUi(response) {
|
|
53
68
|
return this.connection.server.respondUi(this.sessionId, response);
|
|
54
69
|
}
|
|
55
70
|
async attachAgain() {
|
|
56
|
-
|
|
71
|
+
var _a, _b;
|
|
72
|
+
const result = await this.connection.server.attach(this.sessionId, this.lastSeq, this.pageBytes ? { recentBytes: this.pageBytes } : undefined);
|
|
73
|
+
let state = this.current;
|
|
57
74
|
if (this.lastSeq === undefined || result.gap) {
|
|
58
|
-
|
|
75
|
+
// The conversation as of lastSeq, with the message being written and the calls running.
|
|
76
|
+
const conversation = (_a = result.conversation) !== null && _a !== void 0 ? _a : { ...(await this.connection.server.getMessages(this.sessionId)), tools: {} };
|
|
77
|
+
const { messages, start } = SessionStore.withEarlier(this.current, conversation.messages, (_b = conversation.start) !== null && _b !== void 0 ? _b : 0);
|
|
78
|
+
const kept = start === this.current.start ? session_reducer_1.SessionReducer.keep(this.current.messages, messages) : messages;
|
|
79
|
+
state = {
|
|
80
|
+
...this.current,
|
|
81
|
+
messages: kept,
|
|
82
|
+
tools: conversation.tools,
|
|
83
|
+
start,
|
|
84
|
+
runStart: kept === this.current.messages ? this.current.runStart : undefined,
|
|
85
|
+
};
|
|
59
86
|
this.lastSeq = result.lastSeq;
|
|
60
87
|
}
|
|
61
|
-
this.
|
|
62
|
-
|
|
88
|
+
const taken = this.take(state, result.events);
|
|
89
|
+
state = {
|
|
90
|
+
...taken.state,
|
|
91
|
+
pendingUi: result.pendingUi,
|
|
92
|
+
pendingClientTools: result.pendingClientTools,
|
|
93
|
+
working: result.info.isStreaming,
|
|
94
|
+
};
|
|
95
|
+
if (result.shownUi) {
|
|
96
|
+
// What the extensions show now, whatever events were missed.
|
|
97
|
+
state = result.shownUi.reduce(session_reducer_1.SessionReducer.reduce, { ...state, status: {}, widgets: {} });
|
|
98
|
+
}
|
|
99
|
+
// Once, however much changed: what is drawn changes in one frame.
|
|
100
|
+
this.update(state);
|
|
101
|
+
this.applied(taken);
|
|
63
102
|
return result;
|
|
64
103
|
}
|
|
104
|
+
/**
|
|
105
|
+
* The latest messages, after the earlier ones the store had if they are still the same where the
|
|
106
|
+
* latest start: a reconnect does not drop what was loaded further up.
|
|
107
|
+
*/
|
|
108
|
+
static withEarlier(current, messages, start) {
|
|
109
|
+
const at = start - current.start;
|
|
110
|
+
const had = current.messages[at];
|
|
111
|
+
const first = messages[0];
|
|
112
|
+
if (at > 0 && had && first && had.role === first.role && had.timestamp === first.timestamp) {
|
|
113
|
+
return { messages: [...current.messages.slice(0, at), ...messages], start: current.start };
|
|
114
|
+
}
|
|
115
|
+
return { messages, start };
|
|
116
|
+
}
|
|
117
|
+
lost(error) {
|
|
118
|
+
if ((error === null || error === void 0 ? void 0 : error.code) === ta_protocol_1.TaErrorCode.SESSION_NOT_FOUND) {
|
|
119
|
+
for (const listener of [...this.goneListeners]) {
|
|
120
|
+
listener();
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* The messages before those it has, about `pageBytes` of them, put in front: once they are there, or
|
|
126
|
+
* at once when it has them all. Called again while they come, it waits for the same.
|
|
127
|
+
*/
|
|
128
|
+
loadEarlier() {
|
|
129
|
+
var _a;
|
|
130
|
+
if (this.current.start === 0) {
|
|
131
|
+
return Promise.resolve();
|
|
132
|
+
}
|
|
133
|
+
(_a = this.loadingEarlier) !== null && _a !== void 0 ? _a : (this.loadingEarlier = this.fetchEarlier().finally(() => {
|
|
134
|
+
this.loadingEarlier = undefined;
|
|
135
|
+
}));
|
|
136
|
+
return this.loadingEarlier;
|
|
137
|
+
}
|
|
138
|
+
/** All the messages of the conversation, for what needs the whole of it (an export). */
|
|
139
|
+
async loadAll() {
|
|
140
|
+
while (this.current.start > 0) {
|
|
141
|
+
await this.loadEarlier();
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
async fetchEarlier() {
|
|
145
|
+
var _a;
|
|
146
|
+
const { start, messages } = this.current;
|
|
147
|
+
const first = messages[0];
|
|
148
|
+
const page = await this.connection.server.getEarlierMessages(this.sessionId, start, first === null || first === void 0 ? void 0 : first.timestamp, (_a = this.pageBytes) !== null && _a !== void 0 ? _a : 0);
|
|
149
|
+
// Loaded again meanwhile: this part may not be the one before.
|
|
150
|
+
if (this.current.messages[0] !== first) {
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
if (!page.found) {
|
|
154
|
+
await this.reload();
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
const { runStart } = this.current;
|
|
158
|
+
this.update({
|
|
159
|
+
...this.current,
|
|
160
|
+
messages: [...page.messages, ...this.current.messages],
|
|
161
|
+
start: page.start,
|
|
162
|
+
runStart: runStart === undefined ? undefined : runStart + page.messages.length,
|
|
163
|
+
});
|
|
164
|
+
}
|
|
65
165
|
async reload() {
|
|
66
|
-
const { messages } =
|
|
67
|
-
|
|
166
|
+
const { messages, start } = this.pageBytes
|
|
167
|
+
? await this.connection.server.getEarlierMessages(this.sessionId, undefined, undefined, this.pageBytes)
|
|
168
|
+
: { ...(await this.connection.server.getMessages(this.sessionId)), start: 0 };
|
|
169
|
+
this.update({ ...this.current, messages, start, tools: {}, runStart: undefined });
|
|
68
170
|
}
|
|
69
171
|
apply(events) {
|
|
70
|
-
|
|
172
|
+
const taken = this.take(this.current, events);
|
|
173
|
+
// One notification per batch: a UI renders once however many deltas arrived.
|
|
174
|
+
this.update(taken.state);
|
|
175
|
+
this.applied(taken);
|
|
176
|
+
}
|
|
177
|
+
/** `state` with the events of this session not taken yet. */
|
|
178
|
+
take(state, events) {
|
|
71
179
|
let replaced = false;
|
|
72
180
|
const applied = [];
|
|
73
181
|
for (const { sessionId, seq, event } of events) {
|
|
@@ -79,8 +187,10 @@ class SessionStore {
|
|
|
79
187
|
replaced || (replaced = event.type === 'session_replaced');
|
|
80
188
|
applied.push(event);
|
|
81
189
|
}
|
|
82
|
-
|
|
83
|
-
|
|
190
|
+
return { state, applied, replaced };
|
|
191
|
+
}
|
|
192
|
+
/** Once the state has the events: their listeners, and the conversation read again if it was replaced. */
|
|
193
|
+
applied({ applied, replaced }) {
|
|
84
194
|
for (const event of applied) {
|
|
85
195
|
for (const listener of this.eventListeners) {
|
|
86
196
|
listener(event);
|
|
@@ -102,22 +212,33 @@ class SessionStore {
|
|
|
102
212
|
runClientTools(state) {
|
|
103
213
|
for (const request of state.pendingClientTools) {
|
|
104
214
|
const tool = this.clientTools.get(request.toolName);
|
|
105
|
-
if (tool && !this.running.has(request.id)) {
|
|
215
|
+
if (tool && !this.running.has(request.id) && this.declined.get(request.id) !== request) {
|
|
106
216
|
this.running.add(request.id);
|
|
107
217
|
void this.answer(tool, request);
|
|
108
218
|
}
|
|
109
219
|
}
|
|
110
|
-
for (const
|
|
111
|
-
|
|
112
|
-
|
|
220
|
+
for (const calls of [this.results, this.declined]) {
|
|
221
|
+
for (const id of calls.keys()) {
|
|
222
|
+
if (!state.pendingClientTools.some(request => request.id === id)) {
|
|
223
|
+
calls.delete(id);
|
|
224
|
+
}
|
|
113
225
|
}
|
|
114
226
|
}
|
|
115
227
|
}
|
|
116
|
-
/**
|
|
228
|
+
/**
|
|
229
|
+
* Runs a call once, if this client takes it: every page of the user gets it. A result that could not be
|
|
230
|
+
* sent is sent again after a reconnect, not made again.
|
|
231
|
+
*/
|
|
117
232
|
async answer(tool, request) {
|
|
118
233
|
try {
|
|
119
234
|
let result = this.results.get(request.id);
|
|
120
235
|
if (!result) {
|
|
236
|
+
// Not asked again before the request comes again, also when the connection was lost: the reconnect brings it.
|
|
237
|
+
this.declined.set(request.id, request);
|
|
238
|
+
if (!(await this.claim(request))) {
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
this.declined.delete(request.id);
|
|
121
242
|
result = await this.run(tool, request);
|
|
122
243
|
this.results.set(request.id, result);
|
|
123
244
|
}
|
|
@@ -131,6 +252,15 @@ class SessionStore {
|
|
|
131
252
|
this.running.delete(request.id);
|
|
132
253
|
}
|
|
133
254
|
}
|
|
255
|
+
/** 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
|
+
claim(request) {
|
|
257
|
+
return this.connection.server.claimClientTool(this.sessionId, request.id).catch(error => {
|
|
258
|
+
if ((error === null || error === void 0 ? void 0 : error.code) === METHOD_NOT_FOUND) {
|
|
259
|
+
return true;
|
|
260
|
+
}
|
|
261
|
+
throw error;
|
|
262
|
+
});
|
|
263
|
+
}
|
|
134
264
|
async run(tool, request) {
|
|
135
265
|
try {
|
|
136
266
|
return { id: request.id, output: await tool.run(request.input, request) };
|