@celljs/ta-client 4.9.1 → 4.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/esm/common/session-reducer.d.ts +15 -1
- package/esm/common/session-reducer.js +8 -4
- package/esm/common/session-store.d.ts +88 -8
- package/esm/common/session-store.js +241 -17
- package/esm/common/ta-connection.d.ts +74 -7
- package/esm/common/ta-connection.js +165 -22
- package/lib/common/session-reducer.d.ts +15 -1
- package/lib/common/session-reducer.js +8 -4
- package/lib/common/session-store.d.ts +88 -8
- package/lib/common/session-store.js +242 -18
- package/lib/common/ta-connection.d.ts +74 -7
- package/lib/common/ta-connection.js +164 -21
- package/package.json +4 -4
|
@@ -1,12 +1,24 @@
|
|
|
1
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
|
-
import type
|
|
2
|
+
import { type OutboxMessage, type SessionMessage, type SessionState } from './session-reducer';
|
|
3
|
+
import { type TaConnection } from './ta-connection';
|
|
4
4
|
type Listener = (state: SessionState) => void;
|
|
5
5
|
interface Taken {
|
|
6
6
|
state: SessionState;
|
|
7
7
|
applied: TaEvent[];
|
|
8
8
|
replaced: boolean;
|
|
9
9
|
}
|
|
10
|
+
/** A message sent from this client that the session has not shown yet. */
|
|
11
|
+
interface Sent extends OutboxMessage {
|
|
12
|
+
text: string;
|
|
13
|
+
/** How it was sent, but its text and id: to send it again the same. */
|
|
14
|
+
input: Partial<TaPromptInput>;
|
|
15
|
+
/** The service took it: the conversation it gives from now on has it. */
|
|
16
|
+
accepted: boolean;
|
|
17
|
+
/** When the connection first could not take it: it waits for the next, shown as on its way, until `holdMs`. */
|
|
18
|
+
heldAt?: number;
|
|
19
|
+
}
|
|
20
|
+
/** How long a message the connection could not take waits for it, on its way, before it shows as failed. */
|
|
21
|
+
export declare const HOLD_MS = 60000;
|
|
10
22
|
/**
|
|
11
23
|
* A tool this client runs. Open the session with its `definition` in `clientTools`, and give the tool
|
|
12
24
|
* to the store, which runs each call and sends the result. Its output is what the model reads; a
|
|
@@ -16,6 +28,10 @@ export interface ClientTool {
|
|
|
16
28
|
definition: TaClientToolDefinition;
|
|
17
29
|
run(input: unknown, request: TaClientToolRequest): Promise<string> | string;
|
|
18
30
|
}
|
|
31
|
+
/** What a store uses of its connection: a TaConnection, or something that stands for one before there is one. */
|
|
32
|
+
export type SessionConnection = Pick<TaConnection, 'server' | 'onEvents' | 'onOpen'>;
|
|
33
|
+
/** What a store shows before it attaches: the conversation as a client kept it (its messages from `start`, and its tool calls). */
|
|
34
|
+
export type SessionSnapshot = Pick<SessionState, 'messages' | 'start' | 'tools'>;
|
|
19
35
|
export interface SessionStoreOptions {
|
|
20
36
|
/** The tools of the session this client runs. Other clients may run them too: the first result counts. */
|
|
21
37
|
clientTools?: ClientTool[];
|
|
@@ -24,15 +40,27 @@ export interface SessionStoreOptions {
|
|
|
24
40
|
* `loadEarlier` is called: a long conversation shows at once. None: all of it.
|
|
25
41
|
*/
|
|
26
42
|
pageBytes?: number;
|
|
43
|
+
/**
|
|
44
|
+
* Shown from the start, before it attaches (and without a connection): the conversation as it was last
|
|
45
|
+
* seen. Attached, the messages of the session that are the same keep their objects, so that a UI draws
|
|
46
|
+
* again only what changed.
|
|
47
|
+
*/
|
|
48
|
+
initial?: SessionSnapshot;
|
|
49
|
+
/** How long a message the user sent waits for a lost connection to come back (HOLD_MS). */
|
|
50
|
+
holdMs?: number;
|
|
27
51
|
}
|
|
28
52
|
/**
|
|
29
53
|
* The state of one open session on a client: for any UI to render and subscribe to. It catches up by
|
|
30
54
|
* itself after a reconnect, from the events it missed or, if those are gone, from the session.
|
|
31
55
|
*/
|
|
32
56
|
export declare class SessionStore {
|
|
33
|
-
protected readonly connection:
|
|
57
|
+
protected readonly connection: SessionConnection;
|
|
34
58
|
readonly sessionId: string;
|
|
59
|
+
/** The session as the service told it. */
|
|
35
60
|
protected current: SessionState;
|
|
61
|
+
/** `current` with the messages sent from here on their way: what UIs get. */
|
|
62
|
+
protected shown: SessionState;
|
|
63
|
+
protected sent: Sent[];
|
|
36
64
|
protected lastSeq?: number;
|
|
37
65
|
protected readonly listeners: Set<Listener>;
|
|
38
66
|
protected readonly eventListeners: Set<(event: TaEvent) => void>;
|
|
@@ -48,24 +76,74 @@ export declare class SessionStore {
|
|
|
48
76
|
protected readonly pageBytes?: number;
|
|
49
77
|
/** The earlier messages on their way. */
|
|
50
78
|
protected loadingEarlier?: Promise<void>;
|
|
51
|
-
|
|
79
|
+
protected readonly holdMs: number;
|
|
80
|
+
protected holdTimer?: ReturnType<typeof setTimeout>;
|
|
81
|
+
/** The messages held that are being sent again now. */
|
|
82
|
+
protected readonly resending: Set<Sent>;
|
|
83
|
+
constructor(connection: SessionConnection, sessionId: string, options?: SessionStoreOptions);
|
|
52
84
|
get state(): SessionState;
|
|
53
|
-
/**
|
|
54
|
-
|
|
85
|
+
/** The conversation as the session has it, without the messages sent from here on their way: for another store of it to start from. */
|
|
86
|
+
get snapshot(): SessionSnapshot;
|
|
87
|
+
/**
|
|
88
|
+
* Starts following the session; `attached`: what opening it attached already (TaOpenedSession.attached),
|
|
89
|
+
* taken at once, in the same turn of the event loop as its answer, so that no event after it is missed.
|
|
90
|
+
*/
|
|
91
|
+
attach(attached?: TaAttachResult): Promise<TaSessionInfo>;
|
|
55
92
|
/** Stops following it. The session goes on. */
|
|
56
93
|
detach(): Promise<void>;
|
|
57
94
|
subscribe(listener: Listener): () => void;
|
|
58
95
|
/** Each new event of the session, once the state has taken it in. */
|
|
59
96
|
onEvent(listener: (event: TaEvent) => void): () => void;
|
|
60
|
-
/**
|
|
97
|
+
/**
|
|
98
|
+
* Sends a message with a new id; a resend after a lost connection must reuse the id. Sent while the
|
|
99
|
+
* agent is idle, it shows at once at the end of the conversation, with the agent at work, until the
|
|
100
|
+
* session has it (a command, which may add none, does not).
|
|
101
|
+
*/
|
|
61
102
|
prompt(message: string, input?: Partial<TaPromptInput>): Promise<TaPromptReceipt>;
|
|
103
|
+
/**
|
|
104
|
+
* As `prompt`, for what the user typed: a message that fails to go stays in the conversation, marked
|
|
105
|
+
* failed, to send again (`resend`) or take back (`discard`), and this resolves without a receipt. One
|
|
106
|
+
* the connection could not take is not failed: it stays on its way and goes once the store is attached
|
|
107
|
+
* again, as a chat app sends what was typed without network once it is back; only after `holdMs`
|
|
108
|
+
* without a connection does it show as failed.
|
|
109
|
+
*/
|
|
110
|
+
send(message: string, input?: Partial<TaPromptInput>): Promise<TaPromptReceipt | undefined>;
|
|
111
|
+
/** Sends again a message that failed, with its id: one that reached the service after all runs once. */
|
|
112
|
+
resend(id: string): Promise<void>;
|
|
113
|
+
/**
|
|
114
|
+
* Takes on the messages that failed to go from another store of the same conversation (one that showed
|
|
115
|
+
* it before this one attached, without the computer), to send again from here.
|
|
116
|
+
*/
|
|
117
|
+
carry(from: SessionStore): void;
|
|
118
|
+
/** Takes back a message that failed. */
|
|
119
|
+
discard(id: string): void;
|
|
120
|
+
protected deliver(message: string, input: Partial<TaPromptInput>, keep: boolean): Promise<TaPromptReceipt>;
|
|
121
|
+
/** Sends a message shown as sent, and settles it by the answer. */
|
|
122
|
+
protected go(sent: Sent, full: TaPromptInput, keep: boolean): Promise<TaPromptReceipt>;
|
|
123
|
+
protected add(input: TaPromptInput): Sent;
|
|
124
|
+
/** Keeps a message the connection could not take on its way, unless it waited `holdMs` already. */
|
|
125
|
+
protected hold(sent: Sent): boolean;
|
|
126
|
+
/** The messages held `holdMs` that are not going now show as failed. */
|
|
127
|
+
protected expireHeld(): void;
|
|
128
|
+
/** Attached again: the messages held go now, with their ids, so that one the service had after all runs once. */
|
|
129
|
+
protected sendHeld(): void;
|
|
130
|
+
protected fail(sent: Sent, error: unknown): void;
|
|
131
|
+
protected unsend(sent: Sent): void;
|
|
132
|
+
/** The message sent, once the session has a message of the user: the one of the same text, else the first. */
|
|
133
|
+
protected arrived(message: SessionMessage): void;
|
|
134
|
+
protected static textOf(message: SessionMessage): string | undefined;
|
|
135
|
+
/**
|
|
136
|
+
* `state` with the messages sent from here after it (`outbox` says which they are), and the agent at
|
|
137
|
+
* work for those on their way.
|
|
138
|
+
*/
|
|
139
|
+
static withSent(state: SessionState, sent: readonly OutboxMessage[]): SessionState;
|
|
62
140
|
/**
|
|
63
141
|
* The service no longer has the session after a reconnect (it restarted, or closed the session while
|
|
64
142
|
* idle): its file stays, to open again.
|
|
65
143
|
*/
|
|
66
144
|
onGone(listener: () => void): () => void;
|
|
67
145
|
respondUi(response: RpcExtensionUIResponse): Promise<boolean>;
|
|
68
|
-
protected attachAgain(): Promise<TaAttachResult>;
|
|
146
|
+
protected attachAgain(attached?: TaAttachResult): Promise<TaAttachResult>;
|
|
69
147
|
/**
|
|
70
148
|
* The latest messages, after the earlier ones the store had if they are still the same where the
|
|
71
149
|
* latest start: a reconnect does not drop what was loaded further up.
|
|
@@ -90,6 +168,8 @@ export declare class SessionStore {
|
|
|
90
168
|
/** Once the state has the events: their listeners, and the conversation read again if it was replaced. */
|
|
91
169
|
protected applied({ applied, replaced }: Taken): void;
|
|
92
170
|
protected update(state: SessionState): void;
|
|
171
|
+
/** UIs get the state with the messages sent, when either changed. */
|
|
172
|
+
protected show(): void;
|
|
93
173
|
protected runClientTools(state: SessionState): void;
|
|
94
174
|
/**
|
|
95
175
|
* Runs a call once, if this client takes it: every page of the user gets it. A result that could not be
|
|
@@ -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,16 +30,31 @@ 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
|
-
/**
|
|
35
|
-
|
|
46
|
+
/** The conversation as the session has it, without the messages sent from here on their way: for another store of it to start from. */
|
|
47
|
+
get snapshot() {
|
|
48
|
+
const { messages, start, tools } = this.current;
|
|
49
|
+
return { messages, start, tools };
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Starts following the session; `attached`: what opening it attached already (TaOpenedSession.attached),
|
|
53
|
+
* taken at once, in the same turn of the event loop as its answer, so that no event after it is missed.
|
|
54
|
+
*/
|
|
55
|
+
async attach(attached) {
|
|
36
56
|
this.stop.push(this.connection.onEvents(events => this.apply(events)), this.connection.onOpen(() => void this.attachAgain().catch(error => this.lost(error))));
|
|
37
|
-
return (await this.attachAgain()).info;
|
|
57
|
+
return (await this.attachAgain(attached)).info;
|
|
38
58
|
}
|
|
39
59
|
/** Stops following it. The session goes on. */
|
|
40
60
|
async detach() {
|
|
@@ -52,9 +72,194 @@ class SessionStore {
|
|
|
52
72
|
this.eventListeners.add(listener);
|
|
53
73
|
return () => this.eventListeners.delete(listener);
|
|
54
74
|
}
|
|
55
|
-
/**
|
|
75
|
+
/**
|
|
76
|
+
* Sends a message with a new id; a resend after a lost connection must reuse the id. Sent while the
|
|
77
|
+
* agent is idle, it shows at once at the end of the conversation, with the agent at work, until the
|
|
78
|
+
* session has it (a command, which may add none, does not).
|
|
79
|
+
*/
|
|
56
80
|
prompt(message, input = {}) {
|
|
57
|
-
return this.
|
|
81
|
+
return this.deliver(message, input, false);
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* As `prompt`, for what the user typed: a message that fails to go stays in the conversation, marked
|
|
85
|
+
* failed, to send again (`resend`) or take back (`discard`), and this resolves without a receipt. One
|
|
86
|
+
* the connection could not take is not failed: it stays on its way and goes once the store is attached
|
|
87
|
+
* again, as a chat app sends what was typed without network once it is back; only after `holdMs`
|
|
88
|
+
* without a connection does it show as failed.
|
|
89
|
+
*/
|
|
90
|
+
async send(message, input = {}) {
|
|
91
|
+
try {
|
|
92
|
+
return await this.deliver(message, input, true);
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
if (this.sent.some(sent => (sent.failed || sent.heldAt) && sent.text === message)) {
|
|
96
|
+
return undefined;
|
|
97
|
+
}
|
|
98
|
+
throw error;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
/** Sends again a message that failed, with its id: one that reached the service after all runs once. */
|
|
102
|
+
async resend(id) {
|
|
103
|
+
const sent = this.sent.find(candidate => candidate.id === id && candidate.failed);
|
|
104
|
+
if (!sent) {
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
this.sent = this.sent.filter(other => other !== sent);
|
|
108
|
+
await this.send(sent.text, { ...sent.input, clientMessageId: sent.id }).catch(() => undefined);
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Takes on the messages that failed to go from another store of the same conversation (one that showed
|
|
112
|
+
* it before this one attached, without the computer), to send again from here.
|
|
113
|
+
*/
|
|
114
|
+
carry(from) {
|
|
115
|
+
const failed = from.sent.filter(sent => (sent.failed || sent.heldAt) && !this.sent.some(other => other.id === sent.id));
|
|
116
|
+
if (failed.length) {
|
|
117
|
+
this.sent = [...this.sent, ...failed];
|
|
118
|
+
this.show();
|
|
119
|
+
if (this.lastSeq !== undefined) {
|
|
120
|
+
this.sendHeld();
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
/** Takes back a message that failed. */
|
|
125
|
+
discard(id) {
|
|
126
|
+
const sent = this.sent.find(candidate => candidate.id === id);
|
|
127
|
+
if (sent) {
|
|
128
|
+
this.unsend(sent);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
deliver(message, input, keep) {
|
|
132
|
+
const full = { clientMessageId: crypto.randomUUID(), ...input, message };
|
|
133
|
+
const sent = this.current.working || message.startsWith('/') ? undefined : this.add(full);
|
|
134
|
+
if (!sent) {
|
|
135
|
+
return this.connection.server.prompt(this.sessionId, full);
|
|
136
|
+
}
|
|
137
|
+
return this.go(sent, full, keep);
|
|
138
|
+
}
|
|
139
|
+
/** Sends a message shown as sent, and settles it by the answer. */
|
|
140
|
+
go(sent, full, keep) {
|
|
141
|
+
return this.connection.server.prompt(this.sessionId, full).then(result => {
|
|
142
|
+
sent.heldAt = undefined;
|
|
143
|
+
if (result.status === 'accepted') {
|
|
144
|
+
sent.accepted = true;
|
|
145
|
+
}
|
|
146
|
+
else {
|
|
147
|
+
// Queued after another run, sent before, or taken by an extension: no message of it comes now.
|
|
148
|
+
this.unsend(sent);
|
|
149
|
+
}
|
|
150
|
+
return result;
|
|
151
|
+
}, error => {
|
|
152
|
+
if (keep && ta_connection_1.TaRemoteError.isConnectionLost(error) && this.hold(sent)) {
|
|
153
|
+
throw error;
|
|
154
|
+
}
|
|
155
|
+
if (keep) {
|
|
156
|
+
this.fail(sent, error);
|
|
157
|
+
}
|
|
158
|
+
else {
|
|
159
|
+
this.unsend(sent);
|
|
160
|
+
}
|
|
161
|
+
throw error;
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
add(input) {
|
|
165
|
+
var _a;
|
|
166
|
+
const message = { role: 'user', content: [{ type: 'text', text: input.message }, ...((_a = input.images) !== null && _a !== void 0 ? _a : [])], timestamp: Date.now() };
|
|
167
|
+
const { message: _text, clientMessageId: _id, ...rest } = input;
|
|
168
|
+
const sent = { id: input.clientMessageId, message, text: input.message, input: rest, accepted: false };
|
|
169
|
+
this.sent = [...this.sent, sent];
|
|
170
|
+
this.show();
|
|
171
|
+
return sent;
|
|
172
|
+
}
|
|
173
|
+
/** Keeps a message the connection could not take on its way, unless it waited `holdMs` already. */
|
|
174
|
+
hold(sent) {
|
|
175
|
+
var _a, _b;
|
|
176
|
+
if (!this.sent.includes(sent)) {
|
|
177
|
+
return false;
|
|
178
|
+
}
|
|
179
|
+
(_a = sent.heldAt) !== null && _a !== void 0 ? _a : (sent.heldAt = Date.now());
|
|
180
|
+
if (Date.now() - sent.heldAt >= this.holdMs) {
|
|
181
|
+
return false;
|
|
182
|
+
}
|
|
183
|
+
(_b = this.holdTimer) !== null && _b !== void 0 ? _b : (this.holdTimer = setTimeout(() => this.expireHeld(), sent.heldAt + this.holdMs - Date.now()));
|
|
184
|
+
return true;
|
|
185
|
+
}
|
|
186
|
+
/** The messages held `holdMs` that are not going now show as failed. */
|
|
187
|
+
expireHeld() {
|
|
188
|
+
this.holdTimer = undefined;
|
|
189
|
+
const now = Date.now();
|
|
190
|
+
let next = Number.POSITIVE_INFINITY;
|
|
191
|
+
for (const sent of this.sent) {
|
|
192
|
+
if (sent.heldAt === undefined || sent.failed || this.resending.has(sent)) {
|
|
193
|
+
continue;
|
|
194
|
+
}
|
|
195
|
+
if (now - sent.heldAt >= this.holdMs) {
|
|
196
|
+
this.fail(sent, ta_connection_1.TaRemoteError.notConnected());
|
|
197
|
+
}
|
|
198
|
+
else {
|
|
199
|
+
next = Math.min(next, sent.heldAt + this.holdMs - now);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
if (next !== Number.POSITIVE_INFINITY) {
|
|
203
|
+
this.holdTimer = setTimeout(() => this.expireHeld(), next);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
/** Attached again: the messages held go now, with their ids, so that one the service had after all runs once. */
|
|
207
|
+
sendHeld() {
|
|
208
|
+
for (const sent of this.sent) {
|
|
209
|
+
if (sent.heldAt === undefined || sent.failed || this.resending.has(sent)) {
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
this.resending.add(sent);
|
|
213
|
+
void this.go(sent, { ...sent.input, clientMessageId: sent.id, message: sent.text }, true)
|
|
214
|
+
.catch(() => undefined)
|
|
215
|
+
.finally(() => this.resending.delete(sent));
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
fail(sent, error) {
|
|
219
|
+
if (this.sent.includes(sent)) {
|
|
220
|
+
const failed = { ...sent, failed: error instanceof Error ? error.message : String(error) };
|
|
221
|
+
this.sent = this.sent.map(other => (other === sent ? failed : other));
|
|
222
|
+
this.show();
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
unsend(sent) {
|
|
226
|
+
if (this.sent.includes(sent)) {
|
|
227
|
+
this.sent = this.sent.filter(other => other !== sent);
|
|
228
|
+
this.show();
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
/** The message sent, once the session has a message of the user: the one of the same text, else the first. */
|
|
232
|
+
arrived(message) {
|
|
233
|
+
var _a;
|
|
234
|
+
const waiting = this.sent.filter(sent => !sent.failed);
|
|
235
|
+
const text = SessionStore.textOf(message);
|
|
236
|
+
const sent = (_a = waiting.find(candidate => candidate.text === text)) !== null && _a !== void 0 ? _a : waiting[0];
|
|
237
|
+
this.sent = this.sent.filter(other => other !== sent);
|
|
238
|
+
}
|
|
239
|
+
static textOf(message) {
|
|
240
|
+
const { content } = message;
|
|
241
|
+
if (typeof content === 'string') {
|
|
242
|
+
return content;
|
|
243
|
+
}
|
|
244
|
+
const first = Array.isArray(content) ? content[0] : undefined;
|
|
245
|
+
return (first === null || first === void 0 ? void 0 : first.type) === 'text' ? first.text : undefined;
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* `state` with the messages sent from here after it (`outbox` says which they are), and the agent at
|
|
249
|
+
* work for those on their way.
|
|
250
|
+
*/
|
|
251
|
+
static withSent(state, sent) {
|
|
252
|
+
if (!sent.length) {
|
|
253
|
+
return state;
|
|
254
|
+
}
|
|
255
|
+
const going = sent.some(message => !message.failed);
|
|
256
|
+
return {
|
|
257
|
+
...state,
|
|
258
|
+
messages: [...state.messages, ...sent.map(message => message.message)],
|
|
259
|
+
outbox: sent,
|
|
260
|
+
working: state.working || going,
|
|
261
|
+
runStart: state.working || !going ? state.runStart : state.messages.length,
|
|
262
|
+
};
|
|
58
263
|
}
|
|
59
264
|
/**
|
|
60
265
|
* The service no longer has the session after a reconnect (it restarted, or closed the session while
|
|
@@ -67,15 +272,16 @@ class SessionStore {
|
|
|
67
272
|
respondUi(response) {
|
|
68
273
|
return this.connection.server.respondUi(this.sessionId, response);
|
|
69
274
|
}
|
|
70
|
-
async attachAgain() {
|
|
275
|
+
async attachAgain(attached) {
|
|
71
276
|
var _a, _b;
|
|
72
|
-
const result = await this.connection.server.attach(this.sessionId, this.lastSeq, this.pageBytes ? { recentBytes: this.pageBytes } : undefined);
|
|
277
|
+
const result = attached !== null && attached !== void 0 ? attached : (await this.connection.server.attach(this.sessionId, this.lastSeq, this.pageBytes ? { recentBytes: this.pageBytes } : undefined));
|
|
73
278
|
let state = this.current;
|
|
74
|
-
|
|
279
|
+
// A conversation given (one attached as it opened) is the session's from scratch, whatever this store had.
|
|
280
|
+
if (this.lastSeq === undefined || result.gap || (attached === null || attached === void 0 ? void 0 : attached.conversation)) {
|
|
75
281
|
// The conversation as of lastSeq, with the message being written and the calls running.
|
|
76
282
|
const conversation = (_a = result.conversation) !== null && _a !== void 0 ? _a : { ...(await this.connection.server.getMessages(this.sessionId)), tools: {} };
|
|
77
283
|
const { messages, start } = SessionStore.withEarlier(this.current, conversation.messages, (_b = conversation.start) !== null && _b !== void 0 ? _b : 0);
|
|
78
|
-
const kept =
|
|
284
|
+
const kept = session_reducer_1.SessionReducer.keep(this.current.messages, messages, start - this.current.start);
|
|
79
285
|
state = {
|
|
80
286
|
...this.current,
|
|
81
287
|
messages: kept,
|
|
@@ -84,6 +290,8 @@ class SessionStore {
|
|
|
84
290
|
runStart: kept === this.current.messages ? this.current.runStart : undefined,
|
|
85
291
|
};
|
|
86
292
|
this.lastSeq = result.lastSeq;
|
|
293
|
+
// The conversation of the service has those it took.
|
|
294
|
+
this.sent = this.sent.filter(sent => !sent.accepted);
|
|
87
295
|
}
|
|
88
296
|
const taken = this.take(state, result.events);
|
|
89
297
|
state = {
|
|
@@ -99,6 +307,7 @@ class SessionStore {
|
|
|
99
307
|
// Once, however much changed: what is drawn changes in one frame.
|
|
100
308
|
this.update(state);
|
|
101
309
|
this.applied(taken);
|
|
310
|
+
this.sendHeld();
|
|
102
311
|
return result;
|
|
103
312
|
}
|
|
104
313
|
/**
|
|
@@ -184,6 +393,15 @@ class SessionStore {
|
|
|
184
393
|
}
|
|
185
394
|
this.lastSeq = seq;
|
|
186
395
|
state = session_reducer_1.SessionReducer.reduce(state, event);
|
|
396
|
+
if (this.sent.length) {
|
|
397
|
+
if (event.type === 'message_start' && event.message.role === 'user') {
|
|
398
|
+
this.arrived(event.message);
|
|
399
|
+
}
|
|
400
|
+
else if (event.type === 'agent_settled') {
|
|
401
|
+
// Its run ended without it as sent (an extension changed it): it no longer waits.
|
|
402
|
+
this.sent = this.sent.filter(sent => !sent.accepted);
|
|
403
|
+
}
|
|
404
|
+
}
|
|
187
405
|
replaced || (replaced = event.type === 'session_replaced');
|
|
188
406
|
applied.push(event);
|
|
189
407
|
}
|
|
@@ -203,12 +421,18 @@ class SessionStore {
|
|
|
203
421
|
update(state) {
|
|
204
422
|
if (state !== this.current) {
|
|
205
423
|
this.current = state;
|
|
206
|
-
|
|
207
|
-
listener(state);
|
|
208
|
-
}
|
|
424
|
+
this.show();
|
|
209
425
|
this.runClientTools(state);
|
|
210
426
|
}
|
|
211
427
|
}
|
|
428
|
+
/** UIs get the state with the messages sent, when either changed. */
|
|
429
|
+
show() {
|
|
430
|
+
const shown = SessionStore.withSent(this.current, this.sent.map(({ id, message, failed }) => (failed ? { id, message, failed } : { id, message })));
|
|
431
|
+
this.shown = shown;
|
|
432
|
+
for (const listener of this.listeners) {
|
|
433
|
+
listener(shown);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
212
436
|
runClientTools(state) {
|
|
213
437
|
for (const request of state.pendingClientTools) {
|
|
214
438
|
const tool = this.clientTools.get(request.toolName);
|
|
@@ -255,7 +479,7 @@ class SessionStore {
|
|
|
255
479
|
/** 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
480
|
claim(request) {
|
|
257
481
|
return this.connection.server.claimClientTool(this.sessionId, request.id).catch(error => {
|
|
258
|
-
if ((error
|
|
482
|
+
if (ta_connection_1.TaRemoteError.isMethodNotFound(error)) {
|
|
259
483
|
return true;
|
|
260
484
|
}
|
|
261
485
|
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 TaRoomEvent, type TaRoomServer, type TaServer, type TaSessionInfo, 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,12 +79,16 @@ 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;
|
|
46
87
|
type ExtensionDataListener = (name: string, keys: string[], cwd?: string) => void;
|
|
47
88
|
type AuthEventListener = (loginId: string, event: TaAuthEvent) => void;
|
|
48
89
|
type RemoteEventListener = (event: TaRemoteEvent) => void;
|
|
90
|
+
type RoomEventListener = (event: TaRoomEvent) => void;
|
|
91
|
+
type SessionsListener = (sessions: TaSessionInfo[]) => void;
|
|
49
92
|
type OpenListener = () => void;
|
|
50
93
|
type CloseListener = () => void;
|
|
51
94
|
type ReconnectingListener = (delayMs: number, attempt: number) => void;
|
|
@@ -56,8 +99,11 @@ type ReconnectingListener = (delayMs: number, attempt: number) => void;
|
|
|
56
99
|
* over the one WebSocket.
|
|
57
100
|
*
|
|
58
101
|
* 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
|
-
*
|
|
102
|
+
* not sent. Calls that were sent when the connection was lost fail, unless they are safe to send again
|
|
103
|
+
* (`resendable`: reads, and messages ta serve takes once by their clientMessageId), which wait for the
|
|
104
|
+
* next connection and go again for up to `retryForMs`: on a network that drops now and then, a read or a
|
|
105
|
+
* message is late rather than failed. A call that stalls while nothing comes makes it check the
|
|
106
|
+
* connection (`stallMs`), so that one gone without a word is not waited on for long.
|
|
61
107
|
*/
|
|
62
108
|
export declare class TaConnection {
|
|
63
109
|
protected readonly options: TaConnectionOptions;
|
|
@@ -72,6 +118,7 @@ export declare class TaConnection {
|
|
|
72
118
|
readonly gateway: TaGatewayServer;
|
|
73
119
|
readonly relay: TaRelayServer;
|
|
74
120
|
readonly remote: TaRemoteServer;
|
|
121
|
+
readonly rooms: TaRoomServer;
|
|
75
122
|
protected socket?: TaSocket;
|
|
76
123
|
protected closed: boolean;
|
|
77
124
|
protected attempts: number;
|
|
@@ -83,6 +130,8 @@ export declare class TaConnection {
|
|
|
83
130
|
protected readonly extensionDataListeners: Set<ExtensionDataListener>;
|
|
84
131
|
protected readonly authListeners: Set<AuthEventListener>;
|
|
85
132
|
protected readonly remoteListeners: Set<RemoteEventListener>;
|
|
133
|
+
protected readonly roomListeners: Set<RoomEventListener>;
|
|
134
|
+
protected readonly sessionsListeners: Set<SessionsListener>;
|
|
86
135
|
protected readonly openListeners: Set<OpenListener>;
|
|
87
136
|
protected readonly closeListeners: Set<CloseListener>;
|
|
88
137
|
protected readonly reconnectingListeners: Set<ReconnectingListener>;
|
|
@@ -91,6 +140,11 @@ export declare class TaConnection {
|
|
|
91
140
|
go(): void;
|
|
92
141
|
fail(): void;
|
|
93
142
|
}>;
|
|
143
|
+
/** When the last message came, on the clock of Date.now(). */
|
|
144
|
+
protected lastReceivedAt: number;
|
|
145
|
+
/** Checks the calls for a stall while some wait for answers. */
|
|
146
|
+
protected stallTimer?: ReturnType<typeof setInterval>;
|
|
147
|
+
protected probing: boolean;
|
|
94
148
|
constructor(options: TaConnectionOptions);
|
|
95
149
|
/** Resolves when the first connection is open, or rejects if it cannot be made; later losses reconnect. */
|
|
96
150
|
connect(): Promise<void>;
|
|
@@ -104,6 +158,10 @@ export declare class TaConnection {
|
|
|
104
158
|
onAuthEvent(listener: AuthEventListener): () => void;
|
|
105
159
|
/** What happens with the remote machines, once this connection called TaRemoteServer.watch. */
|
|
106
160
|
onRemoteEvent(listener: RemoteEventListener): () => void;
|
|
161
|
+
/** What happens in the rooms, once this connection called TaRoomServer.watch. */
|
|
162
|
+
onRoomEvent(listener: RoomEventListener): () => void;
|
|
163
|
+
/** The open sessions as they change (TaClient.onSessions), once this connection called TaServer.watchSessions. */
|
|
164
|
+
onSessions(listener: SessionsListener): () => void;
|
|
107
165
|
onOpen(listener: OpenListener): () => void;
|
|
108
166
|
/** Runs each time an open connection is lost; it reconnects unless closed. */
|
|
109
167
|
onClose(listener: CloseListener): () => void;
|
|
@@ -123,11 +181,20 @@ export declare class TaConnection {
|
|
|
123
181
|
protected lost(socket: TaSocket, opened: boolean, atOnce?: boolean): void;
|
|
124
182
|
protected createWebSocket(): TaSocket;
|
|
125
183
|
protected scheduleReconnect(): void;
|
|
126
|
-
/** Resolves once the connection is open, or rejects after `waitForOpenMs
|
|
127
|
-
protected opened(): Promise<void>;
|
|
184
|
+
/** Resolves once the connection is open, or rejects after `waitForOpenMs` (or `waitMs`), or at once when it is closed. */
|
|
185
|
+
protected opened(waitMs?: number): Promise<void>;
|
|
128
186
|
protected failPending(): void;
|
|
129
187
|
protected service<T extends object>(name: string): T;
|
|
188
|
+
/**
|
|
189
|
+
* Whether a call may go again after a lost connection, as doing it twice does what doing it once does:
|
|
190
|
+
* a read, or a message with its clientMessageId (TaPromptInput), which ta serve takes once.
|
|
191
|
+
*/
|
|
192
|
+
static resendable(service: string, method: string, params: readonly unknown[]): boolean;
|
|
130
193
|
protected call(service: string, method: string, params: unknown[]): Promise<unknown>;
|
|
194
|
+
/** Sends a call on the open connection; its answer, or its failure when the connection is lost first. */
|
|
195
|
+
protected send(service: string, method: string, params: unknown[]): Promise<unknown>;
|
|
196
|
+
/** While calls wait for answers: one that waits past `stallMs` with nothing come since makes it check the connection. */
|
|
197
|
+
protected watchStalls(): void;
|
|
131
198
|
protected receive(text: string): void;
|
|
132
199
|
}
|
|
133
200
|
export {};
|