@celljs/ta-client 4.5.1 → 4.6.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.md +16 -3
- package/esm/common/session-reducer.d.ts +26 -1
- package/esm/common/session-reducer.js +44 -9
- package/esm/common/session-reducer.js.map +1 -1
- package/esm/common/session-store.d.ts +27 -2
- package/esm/common/session-store.js +62 -2
- package/esm/common/session-store.js.map +1 -1
- package/esm/common/ta-connection.d.ts +54 -5
- package/esm/common/ta-connection.js +104 -17
- package/esm/common/ta-connection.js.map +1 -1
- package/lib/common/session-reducer.d.ts +26 -1
- package/lib/common/session-reducer.d.ts.map +1 -1
- package/lib/common/session-reducer.js +44 -9
- package/lib/common/session-reducer.js.map +1 -1
- package/lib/common/session-reducer.spec.js +37 -0
- package/lib/common/session-reducer.spec.js.map +1 -1
- package/lib/common/session-store.d.ts +27 -2
- package/lib/common/session-store.d.ts.map +1 -1
- package/lib/common/session-store.js +62 -2
- package/lib/common/session-store.js.map +1 -1
- package/lib/common/ta-connection.d.ts +54 -5
- package/lib/common/ta-connection.d.ts.map +1 -1
- package/lib/common/ta-connection.js +103 -16
- package/lib/common/ta-connection.js.map +1 -1
- package/package.json +2 -2
- package/src/common/session-reducer.spec.ts +42 -0
- package/src/common/session-reducer.ts +72 -9
- package/src/common/session-store.ts +92 -3
- package/src/common/ta-connection.ts +156 -20
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { RpcExtensionUIRequest, TaCommandResult, TaEvent } from '@celljs/ta-protocol';
|
|
1
|
+
import type { RpcExtensionUIRequest, TaClientToolRequest, TaCommandResult, TaEvent } from '@celljs/ta-protocol';
|
|
2
2
|
|
|
3
3
|
export type SessionMessage = TaCommandResult<'get_messages'>['messages'][number];
|
|
4
4
|
|
|
@@ -8,6 +8,23 @@ export interface ToolRun {
|
|
|
8
8
|
/** The latest partial result while it runs, then the result. */
|
|
9
9
|
result?: unknown;
|
|
10
10
|
status: 'running' | 'done' | 'error';
|
|
11
|
+
/** Set for a call another tool made, such as a codemode script. */
|
|
12
|
+
parentToolCallId?: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** A message of `notify`. */
|
|
16
|
+
export interface Notice {
|
|
17
|
+
id: string;
|
|
18
|
+
message: string;
|
|
19
|
+
type: 'info' | 'warning' | 'error';
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** pi retries a failed request of the model by itself: `auto_retry_start`. */
|
|
23
|
+
export interface RetryState {
|
|
24
|
+
attempt: number;
|
|
25
|
+
maxAttempts: number;
|
|
26
|
+
delayMs: number;
|
|
27
|
+
errorMessage: string;
|
|
11
28
|
}
|
|
12
29
|
|
|
13
30
|
/** What a UI shows of a session. */
|
|
@@ -19,9 +36,19 @@ export interface SessionState {
|
|
|
19
36
|
tools: Record<string, ToolRun>;
|
|
20
37
|
/** Dialogs waiting for an answer. */
|
|
21
38
|
pendingUi: RpcExtensionUIRequest[];
|
|
39
|
+
/** Calls of client tools waiting for a result. */
|
|
40
|
+
pendingClientTools: TaClientToolRequest[];
|
|
41
|
+
/** The latest messages of `notify`, oldest first. */
|
|
42
|
+
notices: Notice[];
|
|
22
43
|
/** What extensions show with `setStatus`. */
|
|
23
44
|
status: Record<string, string>;
|
|
24
45
|
closed: boolean;
|
|
46
|
+
/** The index in `messages` where the run of now starts: unknown for a run that started before this client attached. */
|
|
47
|
+
runStart?: number;
|
|
48
|
+
/** pi compacts the conversation, for this reason. */
|
|
49
|
+
compacting?: 'manual' | 'threshold' | 'overflow';
|
|
50
|
+
/** pi waits to retry a failed request of the model. */
|
|
51
|
+
retry?: RetryState;
|
|
25
52
|
}
|
|
26
53
|
|
|
27
54
|
interface ContentBlock {
|
|
@@ -30,29 +57,37 @@ interface ContentBlock {
|
|
|
30
57
|
}
|
|
31
58
|
|
|
32
59
|
type StreamDelta = { type: string; contentIndex?: number; delta?: string; id?: string; toolName?: string };
|
|
60
|
+
type Retry = { attempt: number; maxAttempts: number; delayMs: number; errorMessage: string };
|
|
33
61
|
|
|
34
62
|
export namespace SessionReducer {
|
|
35
63
|
const DIALOGS = new Set(['select', 'confirm', 'input', 'editor']);
|
|
64
|
+
const MAX_NOTICES = 20;
|
|
36
65
|
|
|
37
66
|
export function initial(): SessionState {
|
|
38
|
-
return { working: false, messages: [], tools: {}, pendingUi: [], status: {}, closed: false };
|
|
67
|
+
return { working: false, messages: [], tools: {}, pendingUi: [], pendingClientTools: [], notices: [], status: {}, closed: false };
|
|
39
68
|
}
|
|
40
69
|
|
|
41
70
|
/** The next state; the previous one stays valid, so that UIs can compare by identity. */
|
|
42
71
|
export function reduce(state: SessionState, event: TaEvent): SessionState {
|
|
43
72
|
switch (event.type) {
|
|
44
73
|
case 'agent_start':
|
|
45
|
-
return { ...state, working: true };
|
|
74
|
+
return { ...state, working: true, runStart: state.messages.length };
|
|
46
75
|
case 'agent_settled':
|
|
47
|
-
return { ...state, working: false };
|
|
76
|
+
return { ...state, working: false, retry: undefined };
|
|
48
77
|
case 'message_start':
|
|
49
78
|
return { ...state, messages: [...state.messages, event.message] };
|
|
50
|
-
case 'message_update':
|
|
51
|
-
|
|
79
|
+
case 'message_update': {
|
|
80
|
+
// The usage so far: some APIs count while they stream, others only at the end.
|
|
81
|
+
const { usage } = event as { usage?: unknown };
|
|
82
|
+
return withLastMessage(state, message => withUsage(applyDelta(message, event.assistantMessageEvent as StreamDelta), usage));
|
|
83
|
+
}
|
|
52
84
|
case 'message_end':
|
|
53
85
|
return withLastMessage(state, () => event.message);
|
|
54
|
-
case 'tool_execution_start':
|
|
55
|
-
|
|
86
|
+
case 'tool_execution_start': {
|
|
87
|
+
const { parentToolCallId } = event as { parentToolCallId?: string };
|
|
88
|
+
const run: ToolRun = { toolName: event.toolName, args: event.args, status: 'running' };
|
|
89
|
+
return withTool(state, event.toolCallId, parentToolCallId ? { ...run, parentToolCallId } : run);
|
|
90
|
+
}
|
|
56
91
|
case 'tool_execution_update':
|
|
57
92
|
return withTool(state, event.toolCallId, { ...state.tools[event.toolCallId], result: event.partialResult });
|
|
58
93
|
case 'tool_execution_end':
|
|
@@ -61,8 +96,22 @@ export namespace SessionReducer {
|
|
|
61
96
|
return applyUiRequest(state, event);
|
|
62
97
|
case 'ui_request_resolved':
|
|
63
98
|
return { ...state, pendingUi: state.pendingUi.filter(request => request.id !== event.id) };
|
|
99
|
+
case 'client_tool_request':
|
|
100
|
+
return { ...state, pendingClientTools: [...state.pendingClientTools, event] };
|
|
101
|
+
case 'client_tool_resolved':
|
|
102
|
+
return { ...state, pendingClientTools: state.pendingClientTools.filter(request => request.id !== event.id) };
|
|
103
|
+
case 'compaction_start':
|
|
104
|
+
return { ...state, compacting: event.reason };
|
|
105
|
+
case 'compaction_end':
|
|
106
|
+
return { ...state, compacting: undefined };
|
|
107
|
+
case 'auto_retry_start': {
|
|
108
|
+
const { attempt, maxAttempts, delayMs, errorMessage } = event as Retry;
|
|
109
|
+
return { ...state, retry: { attempt, maxAttempts, delayMs, errorMessage } };
|
|
110
|
+
}
|
|
111
|
+
case 'auto_retry_end':
|
|
112
|
+
return { ...state, retry: undefined };
|
|
64
113
|
case 'session_closed':
|
|
65
|
-
return { ...state, closed: true, working: false, pendingUi: [] };
|
|
114
|
+
return { ...state, closed: true, working: false, pendingUi: [], pendingClientTools: [] };
|
|
66
115
|
default:
|
|
67
116
|
return state;
|
|
68
117
|
}
|
|
@@ -76,6 +125,13 @@ export namespace SessionReducer {
|
|
|
76
125
|
return { ...state, messages: [...state.messages.slice(0, last), update(state.messages[last])] };
|
|
77
126
|
}
|
|
78
127
|
|
|
128
|
+
function withUsage(message: SessionMessage, usage: unknown): SessionMessage {
|
|
129
|
+
if (!usage || message.role !== 'assistant' || (message as { usage?: unknown }).usage === usage) {
|
|
130
|
+
return message;
|
|
131
|
+
}
|
|
132
|
+
return { ...message, usage } as SessionMessage;
|
|
133
|
+
}
|
|
134
|
+
|
|
79
135
|
function withTool(state: SessionState, toolCallId: string, run: ToolRun): SessionState {
|
|
80
136
|
return { ...state, tools: { ...state.tools, [toolCallId]: run } };
|
|
81
137
|
}
|
|
@@ -84,6 +140,10 @@ export namespace SessionReducer {
|
|
|
84
140
|
if (DIALOGS.has(request.method)) {
|
|
85
141
|
return { ...state, pendingUi: [...state.pendingUi, request] };
|
|
86
142
|
}
|
|
143
|
+
if (request.method === 'notify') {
|
|
144
|
+
const notice: Notice = { id: request.id, message: request.message, type: request.notifyType ?? 'info' };
|
|
145
|
+
return { ...state, notices: [...state.notices, notice].slice(-MAX_NOTICES) };
|
|
146
|
+
}
|
|
87
147
|
if (request.method === 'setStatus') {
|
|
88
148
|
const { [request.statusKey]: _old, ...status } = state.status;
|
|
89
149
|
return { ...state, status: request.statusText === undefined ? status : { ...status, [request.statusKey]: request.statusText } };
|
|
@@ -115,6 +175,9 @@ export namespace SessionReducer {
|
|
|
115
175
|
return block && { ...block, text: `${block.text ?? ''}${delta.delta}` };
|
|
116
176
|
case 'thinking_delta':
|
|
117
177
|
return block && { ...block, thinking: `${block.thinking ?? ''}${delta.delta}` };
|
|
178
|
+
case 'toolcall_delta':
|
|
179
|
+
// The arguments as they come, JSON not yet whole: what the model has written so far.
|
|
180
|
+
return block && { ...block, partialJson: `${block.partialJson ?? ''}${delta.delta}` };
|
|
118
181
|
default:
|
|
119
182
|
return undefined;
|
|
120
183
|
}
|
|
@@ -1,9 +1,35 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type {
|
|
2
|
+
RpcExtensionUIResponse,
|
|
3
|
+
TaAttachResult,
|
|
4
|
+
TaClientToolDefinition,
|
|
5
|
+
TaClientToolRequest,
|
|
6
|
+
TaClientToolResult,
|
|
7
|
+
TaEvent,
|
|
8
|
+
TaEventEnvelope,
|
|
9
|
+
TaPromptInput,
|
|
10
|
+
TaPromptReceipt,
|
|
11
|
+
TaSessionInfo,
|
|
12
|
+
} from '@celljs/ta-protocol';
|
|
2
13
|
import { SessionReducer, type SessionState } from './session-reducer';
|
|
3
14
|
import type { TaConnection } from './ta-connection';
|
|
4
15
|
|
|
5
16
|
type Listener = (state: SessionState) => void;
|
|
6
17
|
|
|
18
|
+
/**
|
|
19
|
+
* A tool this client runs. Open the session with its `definition` in `clientTools`, and give the tool
|
|
20
|
+
* to the store, which runs each call and sends the result. Its output is what the model reads; a
|
|
21
|
+
* thrown error becomes a failed call.
|
|
22
|
+
*/
|
|
23
|
+
export interface ClientTool {
|
|
24
|
+
definition: TaClientToolDefinition;
|
|
25
|
+
run(input: unknown, request: TaClientToolRequest): Promise<string> | string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface SessionStoreOptions {
|
|
29
|
+
/** The tools of the session this client runs. Other clients may run them too: the first result counts. */
|
|
30
|
+
clientTools?: ClientTool[];
|
|
31
|
+
}
|
|
32
|
+
|
|
7
33
|
/**
|
|
8
34
|
* The state of one open session on a client: for any UI to render and subscribe to. It catches up by
|
|
9
35
|
* itself after a reconnect, from the events it missed or, if those are gone, from the session.
|
|
@@ -12,12 +38,21 @@ export class SessionStore {
|
|
|
12
38
|
protected current = SessionReducer.initial();
|
|
13
39
|
protected lastSeq?: number;
|
|
14
40
|
protected readonly listeners = new Set<Listener>();
|
|
41
|
+
protected readonly eventListeners = new Set<(event: TaEvent) => void>();
|
|
15
42
|
protected readonly stop: (() => void)[] = [];
|
|
43
|
+
protected readonly clientTools: Map<string, ClientTool>;
|
|
44
|
+
/** Calls of client tools this store is running or answering now, by id. */
|
|
45
|
+
protected readonly running = new Set<string>();
|
|
46
|
+
/** Results not yet taken by the server, by call id. */
|
|
47
|
+
protected readonly results = new Map<string, TaClientToolResult>();
|
|
16
48
|
|
|
17
49
|
constructor(
|
|
18
50
|
protected readonly connection: TaConnection,
|
|
19
51
|
readonly sessionId: string,
|
|
20
|
-
|
|
52
|
+
options: SessionStoreOptions = {},
|
|
53
|
+
) {
|
|
54
|
+
this.clientTools = new Map((options.clientTools ?? []).map(tool => [tool.definition.name, tool]));
|
|
55
|
+
}
|
|
21
56
|
|
|
22
57
|
get state(): SessionState {
|
|
23
58
|
return this.current;
|
|
@@ -45,6 +80,12 @@ export class SessionStore {
|
|
|
45
80
|
return () => this.listeners.delete(listener);
|
|
46
81
|
}
|
|
47
82
|
|
|
83
|
+
/** Each new event of the session, once the state has taken it in. */
|
|
84
|
+
onEvent(listener: (event: TaEvent) => void): () => void {
|
|
85
|
+
this.eventListeners.add(listener);
|
|
86
|
+
return () => this.eventListeners.delete(listener);
|
|
87
|
+
}
|
|
88
|
+
|
|
48
89
|
/** Sends a message with a new id; a resend after a lost connection must reuse the id. */
|
|
49
90
|
prompt(message: string, input: Partial<TaPromptInput> = {}): Promise<TaPromptReceipt> {
|
|
50
91
|
return this.connection.server.prompt(this.sessionId, { clientMessageId: crypto.randomUUID(), ...input, message });
|
|
@@ -61,7 +102,7 @@ export class SessionStore {
|
|
|
61
102
|
this.lastSeq = result.lastSeq;
|
|
62
103
|
}
|
|
63
104
|
this.apply(result.events);
|
|
64
|
-
this.update({ ...this.current, pendingUi: result.pendingUi, working: result.info.isStreaming });
|
|
105
|
+
this.update({ ...this.current, pendingUi: result.pendingUi, pendingClientTools: result.pendingClientTools, working: result.info.isStreaming });
|
|
65
106
|
return result;
|
|
66
107
|
}
|
|
67
108
|
|
|
@@ -73,6 +114,7 @@ export class SessionStore {
|
|
|
73
114
|
protected apply(events: TaEventEnvelope[]): void {
|
|
74
115
|
let state = this.current;
|
|
75
116
|
let replaced = false;
|
|
117
|
+
const applied: TaEvent[] = [];
|
|
76
118
|
for (const { sessionId, seq, event } of events) {
|
|
77
119
|
if (sessionId !== this.sessionId || (this.lastSeq !== undefined && seq <= this.lastSeq)) {
|
|
78
120
|
continue;
|
|
@@ -80,9 +122,15 @@ export class SessionStore {
|
|
|
80
122
|
this.lastSeq = seq;
|
|
81
123
|
state = SessionReducer.reduce(state, event);
|
|
82
124
|
replaced ||= event.type === 'session_replaced';
|
|
125
|
+
applied.push(event);
|
|
83
126
|
}
|
|
84
127
|
// One notification per batch: a UI renders once however many deltas arrived.
|
|
85
128
|
this.update(state);
|
|
129
|
+
for (const event of applied) {
|
|
130
|
+
for (const listener of this.eventListeners) {
|
|
131
|
+
listener(event);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
86
134
|
if (replaced) {
|
|
87
135
|
void this.reload();
|
|
88
136
|
}
|
|
@@ -94,6 +142,47 @@ export class SessionStore {
|
|
|
94
142
|
for (const listener of this.listeners) {
|
|
95
143
|
listener(state);
|
|
96
144
|
}
|
|
145
|
+
this.runClientTools(state);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
protected runClientTools(state: SessionState): void {
|
|
150
|
+
for (const request of state.pendingClientTools) {
|
|
151
|
+
const tool = this.clientTools.get(request.toolName);
|
|
152
|
+
if (tool && !this.running.has(request.id)) {
|
|
153
|
+
this.running.add(request.id);
|
|
154
|
+
void this.answer(tool, request);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
for (const id of this.results.keys()) {
|
|
158
|
+
if (!state.pendingClientTools.some(request => request.id === id)) {
|
|
159
|
+
this.results.delete(id);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Runs a call once: a result that could not be sent is sent again after a reconnect, not made again. */
|
|
165
|
+
protected async answer(tool: ClientTool, request: TaClientToolRequest): Promise<void> {
|
|
166
|
+
try {
|
|
167
|
+
let result = this.results.get(request.id);
|
|
168
|
+
if (!result) {
|
|
169
|
+
result = await this.run(tool, request);
|
|
170
|
+
this.results.set(request.id, result);
|
|
171
|
+
}
|
|
172
|
+
await this.connection.server.respondClientTool(this.sessionId, result);
|
|
173
|
+
this.results.delete(request.id);
|
|
174
|
+
} catch {
|
|
175
|
+
// The connection was lost; the reconnect sends the result if the call still waits.
|
|
176
|
+
} finally {
|
|
177
|
+
this.running.delete(request.id);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
protected async run(tool: ClientTool, request: TaClientToolRequest): Promise<TaClientToolResult> {
|
|
182
|
+
try {
|
|
183
|
+
return { id: request.id, output: await tool.run(request.input, request) };
|
|
184
|
+
} catch (error) {
|
|
185
|
+
return { id: request.id, output: error instanceof Error ? error.message : String(error), isError: true };
|
|
97
186
|
}
|
|
98
187
|
}
|
|
99
188
|
}
|
|
@@ -1,4 +1,24 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
TA_AUTH_SERVICE,
|
|
3
|
+
TA_CLIENT_SERVICE,
|
|
4
|
+
TA_PACKAGE_SERVICE,
|
|
5
|
+
TA_RELAY_SERVICE,
|
|
6
|
+
TA_SERVER_SERVICE,
|
|
7
|
+
TA_SETTINGS_SERVICE,
|
|
8
|
+
TA_TERMINAL_SERVICE,
|
|
9
|
+
TA_WORKSPACE_SERVICE,
|
|
10
|
+
type TaAuthEvent,
|
|
11
|
+
type TaAuthServer,
|
|
12
|
+
TaErrorCode,
|
|
13
|
+
type TaErrorData,
|
|
14
|
+
type TaEventEnvelope,
|
|
15
|
+
type TaPackageServer,
|
|
16
|
+
type TaRelayServer,
|
|
17
|
+
type TaServer,
|
|
18
|
+
type TaSettingsServer,
|
|
19
|
+
type TaTerminalServer,
|
|
20
|
+
type TaWorkspaceServer,
|
|
21
|
+
} from '@celljs/ta-protocol';
|
|
2
22
|
|
|
3
23
|
/** A failed call. `code` is set for failures the server names. */
|
|
4
24
|
export class TaRemoteError extends Error {
|
|
@@ -21,6 +41,22 @@ export interface TaConnectionOptions {
|
|
|
21
41
|
reconnectDelayMs?: number;
|
|
22
42
|
/** Default 10000. */
|
|
23
43
|
maxReconnectDelayMs?: number;
|
|
44
|
+
/**
|
|
45
|
+
* Another way to ta serve than a WebSocket to `url`, such as a relay (RelaySocket of @celljs/ta-relay):
|
|
46
|
+
* a new socket for each connection, which takes care of access itself.
|
|
47
|
+
*/
|
|
48
|
+
createSocket?: () => TaSocket;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** What TaConnection uses of a WebSocket. */
|
|
52
|
+
export interface TaSocket {
|
|
53
|
+
readonly readyState: number;
|
|
54
|
+
onopen: ((event?: unknown) => void) | null;
|
|
55
|
+
onmessage: ((message: { data: unknown }) => void) | null;
|
|
56
|
+
onclose: ((event?: unknown) => void) | null;
|
|
57
|
+
onerror?: ((event?: unknown) => void) | null;
|
|
58
|
+
send(text: string): void;
|
|
59
|
+
close(): void;
|
|
24
60
|
}
|
|
25
61
|
|
|
26
62
|
interface PendingCall {
|
|
@@ -37,30 +73,43 @@ interface RpcMessage {
|
|
|
37
73
|
}
|
|
38
74
|
|
|
39
75
|
type EventsListener = (events: TaEventEnvelope[]) => void;
|
|
76
|
+
type TerminalListener = (terminalId: string, data: string, exitCode?: number) => void;
|
|
77
|
+
type ExtensionDataListener = (name: string, keys: string[], cwd?: string) => void;
|
|
78
|
+
type AuthEventListener = (loginId: string, event: TaAuthEvent) => void;
|
|
40
79
|
type OpenListener = () => void;
|
|
80
|
+
type CloseListener = () => void;
|
|
81
|
+
type ReconnectingListener = (delayMs: number, attempt: number) => void;
|
|
41
82
|
|
|
42
83
|
/**
|
|
43
84
|
* A connection to `ta serve` on the `WebSocket` of the platform, with no other dependency, so that it
|
|
44
85
|
* fits a browser, Electron or a mobile app. It reconnects until closed; `onOpen` runs each time, for
|
|
45
|
-
* attaching again ({@link SessionStore} does).
|
|
86
|
+
* attaching again ({@link SessionStore} does). Each service of ta serve is a property; all of them go
|
|
87
|
+
* over the one WebSocket.
|
|
88
|
+
*
|
|
89
|
+
* Calls fail when the connection is down; they are not queued, because only the caller knows whether to resend.
|
|
46
90
|
*/
|
|
47
91
|
export class TaConnection {
|
|
48
|
-
|
|
49
|
-
readonly
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
protected socket?:
|
|
92
|
+
readonly server = this.service<TaServer>(TA_SERVER_SERVICE);
|
|
93
|
+
readonly workspace = this.service<TaWorkspaceServer>(TA_WORKSPACE_SERVICE);
|
|
94
|
+
readonly terminals = this.service<TaTerminalServer>(TA_TERMINAL_SERVICE);
|
|
95
|
+
readonly settings = this.service<TaSettingsServer>(TA_SETTINGS_SERVICE);
|
|
96
|
+
readonly packages = this.service<TaPackageServer>(TA_PACKAGE_SERVICE);
|
|
97
|
+
readonly auth = this.service<TaAuthServer>(TA_AUTH_SERVICE);
|
|
98
|
+
readonly relay = this.service<TaRelayServer>(TA_RELAY_SERVICE);
|
|
99
|
+
|
|
100
|
+
protected socket?: TaSocket;
|
|
57
101
|
protected closed = false;
|
|
58
102
|
protected attempts = 0;
|
|
59
103
|
protected reconnectTimer?: ReturnType<typeof setTimeout>;
|
|
60
104
|
protected nextId = 0;
|
|
61
105
|
protected readonly pending = new Map<number, PendingCall>();
|
|
62
106
|
protected readonly eventListeners = new Set<EventsListener>();
|
|
107
|
+
protected readonly terminalListeners = new Set<TerminalListener>();
|
|
108
|
+
protected readonly extensionDataListeners = new Set<ExtensionDataListener>();
|
|
109
|
+
protected readonly authListeners = new Set<AuthEventListener>();
|
|
63
110
|
protected readonly openListeners = new Set<OpenListener>();
|
|
111
|
+
protected readonly closeListeners = new Set<CloseListener>();
|
|
112
|
+
protected readonly reconnectingListeners = new Set<ReconnectingListener>();
|
|
64
113
|
|
|
65
114
|
constructor(protected readonly options: TaConnectionOptions) {}
|
|
66
115
|
|
|
@@ -80,17 +129,56 @@ export class TaConnection {
|
|
|
80
129
|
return () => this.eventListeners.delete(listener);
|
|
81
130
|
}
|
|
82
131
|
|
|
132
|
+
/** Output of the terminals of this connection (TaTerminalServer.openTerminal). */
|
|
133
|
+
onTerminalData(listener: TerminalListener): () => void {
|
|
134
|
+
this.terminalListeners.add(listener);
|
|
135
|
+
return () => this.terminalListeners.delete(listener);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Keys of the data of packages that changed (TaClient.onExtensionData), for the data this connection read; `cwd` for a key of a directory. */
|
|
139
|
+
onExtensionData(listener: ExtensionDataListener): () => void {
|
|
140
|
+
this.extensionDataListeners.add(listener);
|
|
141
|
+
return () => this.extensionDataListeners.delete(listener);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** What happens during the sign-ins of this connection (TaAuthServer.login). */
|
|
145
|
+
onAuthEvent(listener: AuthEventListener): () => void {
|
|
146
|
+
this.authListeners.add(listener);
|
|
147
|
+
return () => this.authListeners.delete(listener);
|
|
148
|
+
}
|
|
149
|
+
|
|
83
150
|
onOpen(listener: OpenListener): () => void {
|
|
84
151
|
this.openListeners.add(listener);
|
|
85
152
|
return () => this.openListeners.delete(listener);
|
|
86
153
|
}
|
|
87
154
|
|
|
155
|
+
/** Runs each time an open connection is lost; it reconnects unless closed. */
|
|
156
|
+
onClose(listener: CloseListener): () => void {
|
|
157
|
+
this.closeListeners.add(listener);
|
|
158
|
+
return () => this.closeListeners.delete(listener);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Runs each time it waits to try again: how long, and which try it is (1 for the first after a loss). */
|
|
162
|
+
onReconnecting(listener: ReconnectingListener): () => void {
|
|
163
|
+
this.reconnectingListeners.add(listener);
|
|
164
|
+
return () => this.reconnectingListeners.delete(listener);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** While the connection is down, tries again now rather than at the end of the wait, which starts over; otherwise does nothing. */
|
|
168
|
+
reconnect(): void {
|
|
169
|
+
const state = this.socket?.readyState;
|
|
170
|
+
if (this.closed || state === WebSocket.OPEN || state === WebSocket.CONNECTING) {
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
clearTimeout(this.reconnectTimer);
|
|
174
|
+
this.attempts = 0;
|
|
175
|
+
this.open();
|
|
176
|
+
}
|
|
177
|
+
|
|
88
178
|
/** With `resolve` and `reject`: the first connection, whose failure is the caller's to handle. */
|
|
89
179
|
protected open(resolve?: () => void, reject?: (error: Error) => void): void {
|
|
90
180
|
let opened = false;
|
|
91
|
-
const
|
|
92
|
-
url.searchParams.set('token', this.options.token);
|
|
93
|
-
const socket = new WebSocket(url);
|
|
181
|
+
const socket = this.options.createSocket ? this.options.createSocket() : this.createWebSocket();
|
|
94
182
|
this.socket = socket;
|
|
95
183
|
socket.onopen = () => {
|
|
96
184
|
opened = true;
|
|
@@ -105,12 +193,23 @@ export class TaConnection {
|
|
|
105
193
|
this.failPending();
|
|
106
194
|
if (reject && !opened) {
|
|
107
195
|
reject(new TaRemoteError(`Cannot connect to ${this.options.url}.`));
|
|
108
|
-
|
|
109
|
-
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
if (opened) {
|
|
199
|
+
for (const listener of this.closeListeners) {
|
|
200
|
+
listener();
|
|
201
|
+
}
|
|
110
202
|
}
|
|
203
|
+
this.scheduleReconnect();
|
|
111
204
|
};
|
|
112
205
|
}
|
|
113
206
|
|
|
207
|
+
protected createWebSocket(): TaSocket {
|
|
208
|
+
const url = new URL(this.options.url);
|
|
209
|
+
url.searchParams.set('token', this.options.token);
|
|
210
|
+
return new WebSocket(url);
|
|
211
|
+
}
|
|
212
|
+
|
|
114
213
|
protected scheduleReconnect(): void {
|
|
115
214
|
if (this.closed) {
|
|
116
215
|
return;
|
|
@@ -118,19 +217,31 @@ export class TaConnection {
|
|
|
118
217
|
const { reconnectDelayMs = 250, maxReconnectDelayMs = 10000 } = this.options;
|
|
119
218
|
const delay = Math.min(reconnectDelayMs * 2 ** this.attempts++, maxReconnectDelayMs);
|
|
120
219
|
this.reconnectTimer = setTimeout(() => this.open(), delay);
|
|
220
|
+
for (const listener of this.reconnectingListeners) {
|
|
221
|
+
listener(delay, this.attempts);
|
|
222
|
+
}
|
|
121
223
|
}
|
|
122
224
|
|
|
123
225
|
protected failPending(): void {
|
|
124
226
|
for (const call of this.pending.values()) {
|
|
125
|
-
call.reject(new TaRemoteError('The connection to ta serve was lost.'));
|
|
227
|
+
call.reject(new TaRemoteError('The connection to ta serve was lost.', TaErrorCode.CONNECTION_LOST, 'Send it again once the connection is back.'));
|
|
126
228
|
}
|
|
127
229
|
this.pending.clear();
|
|
128
230
|
}
|
|
129
231
|
|
|
130
|
-
protected
|
|
232
|
+
protected service<T extends object>(name: string): T {
|
|
233
|
+
return new Proxy({} as T, {
|
|
234
|
+
get:
|
|
235
|
+
(_target, method: string) =>
|
|
236
|
+
(...params: unknown[]) =>
|
|
237
|
+
this.call(name, method, params),
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
protected call(service: string, method: string, params: unknown[]): Promise<unknown> {
|
|
131
242
|
const socket = this.socket;
|
|
132
243
|
if (socket?.readyState !== WebSocket.OPEN) {
|
|
133
|
-
return Promise.reject(new TaRemoteError('Not connected to ta serve.'));
|
|
244
|
+
return Promise.reject(new TaRemoteError('Not connected to ta serve.', TaErrorCode.CONNECTION_LOST, 'Try again once the connection is back.'));
|
|
134
245
|
}
|
|
135
246
|
const id = ++this.nextId;
|
|
136
247
|
// JSON has no undefined: a left-out optional argument must not arrive as null.
|
|
@@ -140,7 +251,7 @@ export class TaConnection {
|
|
|
140
251
|
}
|
|
141
252
|
return new Promise((resolve, reject) => {
|
|
142
253
|
this.pending.set(id, { resolve, reject });
|
|
143
|
-
socket.send(JSON.stringify({ jsonrpc: '2.0', id, method: `${
|
|
254
|
+
socket.send(JSON.stringify({ jsonrpc: '2.0', id, method: `${service}/${method}`, params: params.slice(0, length) }));
|
|
144
255
|
});
|
|
145
256
|
}
|
|
146
257
|
|
|
@@ -154,6 +265,31 @@ export class TaConnection {
|
|
|
154
265
|
this.socket?.send(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: null }));
|
|
155
266
|
return;
|
|
156
267
|
}
|
|
268
|
+
if (message.method === `${TA_CLIENT_SERVICE}/onTerminalData`) {
|
|
269
|
+
const [terminalId, data, exitCode] = message.params as [string, string, number | null | undefined];
|
|
270
|
+
for (const listener of this.terminalListeners) {
|
|
271
|
+
// JSON has no undefined: a terminal still running may send null.
|
|
272
|
+
listener(terminalId, data, exitCode ?? undefined);
|
|
273
|
+
}
|
|
274
|
+
this.socket?.send(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: null }));
|
|
275
|
+
return;
|
|
276
|
+
}
|
|
277
|
+
if (message.method === `${TA_CLIENT_SERVICE}/onAuthEvent`) {
|
|
278
|
+
const [loginId, event] = message.params as [string, TaAuthEvent];
|
|
279
|
+
for (const listener of this.authListeners) {
|
|
280
|
+
listener(loginId, event);
|
|
281
|
+
}
|
|
282
|
+
this.socket?.send(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: null }));
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
if (message.method === `${TA_CLIENT_SERVICE}/onExtensionData`) {
|
|
286
|
+
const [name, keys, cwd] = message.params as [string, string[], string | null | undefined];
|
|
287
|
+
for (const listener of this.extensionDataListeners) {
|
|
288
|
+
listener(name, keys, cwd ?? undefined);
|
|
289
|
+
}
|
|
290
|
+
this.socket?.send(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: null }));
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
157
293
|
const call = this.pending.get(message.id as number);
|
|
158
294
|
if (!call) {
|
|
159
295
|
return;
|