@celljs/ta-client 4.9.0 → 4.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/esm/common/session-reducer.d.ts +15 -1
- package/esm/common/session-reducer.js +8 -4
- package/esm/common/session-store.d.ts +80 -5
- package/esm/common/session-store.js +226 -11
- package/esm/common/ta-connection.d.ts +65 -7
- package/esm/common/ta-connection.js +131 -17
- package/lib/common/session-reducer.d.ts +15 -1
- package/lib/common/session-reducer.js +8 -4
- package/lib/common/session-store.d.ts +80 -5
- package/lib/common/session-store.js +227 -12
- package/lib/common/ta-connection.d.ts +65 -7
- package/lib/common/ta-connection.js +131 -17
- package/package.json +4 -4
|
@@ -19,6 +19,14 @@ export interface SessionWidget {
|
|
|
19
19
|
lines: string[];
|
|
20
20
|
placement: 'aboveEditor' | 'belowEditor';
|
|
21
21
|
}
|
|
22
|
+
/** A message sent from this client that the session does not have yet: on its way, or `failed` to go. */
|
|
23
|
+
export interface OutboxMessage {
|
|
24
|
+
/** Its clientMessageId. */
|
|
25
|
+
id: string;
|
|
26
|
+
message: SessionMessage;
|
|
27
|
+
/** Why it did not go. */
|
|
28
|
+
failed?: string;
|
|
29
|
+
}
|
|
22
30
|
export interface SessionState {
|
|
23
31
|
/** The agent is working, from the start of a run until it has settled. */
|
|
24
32
|
working: boolean;
|
|
@@ -49,6 +57,10 @@ export interface SessionState {
|
|
|
49
57
|
compacting?: 'manual' | 'threshold' | 'overflow';
|
|
50
58
|
/** pi waits to retry a failed request of the model. */
|
|
51
59
|
retry?: RetryState;
|
|
60
|
+
/** What an extension says the agent does while it works (pi's `setWorkingMessage`). */
|
|
61
|
+
workingMessage?: string;
|
|
62
|
+
/** Which of the last `messages` this client sent that the session does not have yet (SessionStore.send). */
|
|
63
|
+
outbox?: readonly OutboxMessage[];
|
|
52
64
|
}
|
|
53
65
|
export declare namespace SessionReducer {
|
|
54
66
|
function initial(): SessionState;
|
|
@@ -57,6 +69,8 @@ export declare namespace SessionReducer {
|
|
|
57
69
|
/**
|
|
58
70
|
* The messages of `next`, with each that is the same as the one of `previous` at its place kept as it
|
|
59
71
|
* was: a conversation read again after a reconnect has new objects, which a UI would all draw again.
|
|
72
|
+
* `offset`: where `next` starts in `previous` (the difference of their `start`), for a part of the
|
|
73
|
+
* conversation that begins elsewhere, such as one kept on the device that was cut shorter.
|
|
60
74
|
*/
|
|
61
|
-
function keep(previous: readonly SessionMessage[], next: SessionMessage[]): SessionMessage[];
|
|
75
|
+
function keep(previous: readonly SessionMessage[], next: SessionMessage[], offset?: number): SessionMessage[];
|
|
62
76
|
}
|
|
@@ -23,7 +23,9 @@ export var SessionReducer;
|
|
|
23
23
|
case 'agent_start':
|
|
24
24
|
return { ...state, working: true, runStart: state.messages.length };
|
|
25
25
|
case 'agent_settled':
|
|
26
|
-
return { ...state, working: false, retry: undefined };
|
|
26
|
+
return { ...state, working: false, retry: undefined, workingMessage: undefined };
|
|
27
|
+
case 'working_message':
|
|
28
|
+
return { ...state, workingMessage: event.message };
|
|
27
29
|
case 'message_start':
|
|
28
30
|
return { ...state, messages: [...state.messages, event.message] };
|
|
29
31
|
case 'message_update': {
|
|
@@ -155,11 +157,13 @@ export var SessionReducer;
|
|
|
155
157
|
/**
|
|
156
158
|
* The messages of `next`, with each that is the same as the one of `previous` at its place kept as it
|
|
157
159
|
* was: a conversation read again after a reconnect has new objects, which a UI would all draw again.
|
|
160
|
+
* `offset`: where `next` starts in `previous` (the difference of their `start`), for a part of the
|
|
161
|
+
* conversation that begins elsewhere, such as one kept on the device that was cut shorter.
|
|
158
162
|
*/
|
|
159
|
-
function keep(previous, next) {
|
|
160
|
-
let same = previous.length === next.length;
|
|
163
|
+
function keep(previous, next, offset = 0) {
|
|
164
|
+
let same = offset === 0 && previous.length === next.length;
|
|
161
165
|
const kept = next.map((message, index) => {
|
|
162
|
-
const before = previous[index];
|
|
166
|
+
const before = previous[index + offset];
|
|
163
167
|
if (before && before.role === message.role && before.timestamp === message.timestamp && JSON.stringify(before) === JSON.stringify(message)) {
|
|
164
168
|
return before;
|
|
165
169
|
}
|
|
@@ -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.js';
|
|
3
|
-
import type
|
|
2
|
+
import { type OutboxMessage, type SessionMessage, type SessionState } from './session-reducer.js';
|
|
3
|
+
import { type TaConnection } from './ta-connection.js';
|
|
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,7 +76,11 @@ 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
85
|
/** Starts following the session. */
|
|
54
86
|
attach(): Promise<TaSessionInfo>;
|
|
@@ -57,8 +89,49 @@ export declare class SessionStore {
|
|
|
57
89
|
subscribe(listener: Listener): () => void;
|
|
58
90
|
/** Each new event of the session, once the state has taken it in. */
|
|
59
91
|
onEvent(listener: (event: TaEvent) => void): () => void;
|
|
60
|
-
/**
|
|
92
|
+
/**
|
|
93
|
+
* Sends a message with a new id; a resend after a lost connection must reuse the id. Sent while the
|
|
94
|
+
* agent is idle, it shows at once at the end of the conversation, with the agent at work, until the
|
|
95
|
+
* session has it (a command, which may add none, does not).
|
|
96
|
+
*/
|
|
61
97
|
prompt(message: string, input?: Partial<TaPromptInput>): Promise<TaPromptReceipt>;
|
|
98
|
+
/**
|
|
99
|
+
* As `prompt`, for what the user typed: a message that fails to go stays in the conversation, marked
|
|
100
|
+
* failed, to send again (`resend`) or take back (`discard`), and this resolves without a receipt. One
|
|
101
|
+
* the connection could not take is not failed: it stays on its way and goes once the store is attached
|
|
102
|
+
* again, as a chat app sends what was typed without network once it is back; only after `holdMs`
|
|
103
|
+
* without a connection does it show as failed.
|
|
104
|
+
*/
|
|
105
|
+
send(message: string, input?: Partial<TaPromptInput>): Promise<TaPromptReceipt | undefined>;
|
|
106
|
+
/** Sends again a message that failed, with its id: one that reached the service after all runs once. */
|
|
107
|
+
resend(id: string): Promise<void>;
|
|
108
|
+
/**
|
|
109
|
+
* Takes on the messages that failed to go from another store of the same conversation (one that showed
|
|
110
|
+
* it before this one attached, without the computer), to send again from here.
|
|
111
|
+
*/
|
|
112
|
+
carry(from: SessionStore): void;
|
|
113
|
+
/** Takes back a message that failed. */
|
|
114
|
+
discard(id: string): void;
|
|
115
|
+
protected deliver(message: string, input: Partial<TaPromptInput>, keep: boolean): Promise<TaPromptReceipt>;
|
|
116
|
+
/** Sends a message shown as sent, and settles it by the answer. */
|
|
117
|
+
protected go(sent: Sent, full: TaPromptInput, keep: boolean): Promise<TaPromptReceipt>;
|
|
118
|
+
protected add(input: TaPromptInput): Sent;
|
|
119
|
+
/** Keeps a message the connection could not take on its way, unless it waited `holdMs` already. */
|
|
120
|
+
protected hold(sent: Sent): boolean;
|
|
121
|
+
/** The messages held `holdMs` that are not going now show as failed. */
|
|
122
|
+
protected expireHeld(): void;
|
|
123
|
+
/** Attached again: the messages held go now, with their ids, so that one the service had after all runs once. */
|
|
124
|
+
protected sendHeld(): void;
|
|
125
|
+
protected fail(sent: Sent, error: unknown): void;
|
|
126
|
+
protected unsend(sent: Sent): void;
|
|
127
|
+
/** The message sent, once the session has a message of the user: the one of the same text, else the first. */
|
|
128
|
+
protected arrived(message: SessionMessage): void;
|
|
129
|
+
protected static textOf(message: SessionMessage): string | undefined;
|
|
130
|
+
/**
|
|
131
|
+
* `state` with the messages sent from here after it (`outbox` says which they are), and the agent at
|
|
132
|
+
* work for those on their way.
|
|
133
|
+
*/
|
|
134
|
+
static withSent(state: SessionState, sent: readonly OutboxMessage[]): SessionState;
|
|
62
135
|
/**
|
|
63
136
|
* The service no longer has the session after a reconnect (it restarted, or closed the session while
|
|
64
137
|
* idle): its file stays, to open again.
|
|
@@ -90,6 +163,8 @@ export declare class SessionStore {
|
|
|
90
163
|
/** Once the state has the events: their listeners, and the conversation read again if it was replaced. */
|
|
91
164
|
protected applied({ applied, replaced }: Taken): void;
|
|
92
165
|
protected update(state: SessionState): void;
|
|
166
|
+
/** UIs get the state with the messages sent, when either changed. */
|
|
167
|
+
protected show(): void;
|
|
93
168
|
protected runClientTools(state: SessionState): void;
|
|
94
169
|
/**
|
|
95
170
|
* Runs a call once, if this client takes it: every page of the user gets it. A result that could not be
|
|
@@ -1,17 +1,22 @@
|
|
|
1
1
|
import { TaErrorCode, } from '@celljs/ta-protocol';
|
|
2
2
|
import { SessionReducer } from './session-reducer.js';
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
import { TaRemoteError } from './ta-connection.js';
|
|
4
|
+
/** How long a message the connection could not take waits for it, on its way, before it shows as failed. */
|
|
5
|
+
export const HOLD_MS = 60000;
|
|
5
6
|
/**
|
|
6
7
|
* The state of one open session on a client: for any UI to render and subscribe to. It catches up by
|
|
7
8
|
* itself after a reconnect, from the events it missed or, if those are gone, from the session.
|
|
8
9
|
*/
|
|
9
10
|
export class SessionStore {
|
|
10
11
|
constructor(connection, sessionId, options = {}) {
|
|
11
|
-
var _a;
|
|
12
|
+
var _a, _b;
|
|
12
13
|
this.connection = connection;
|
|
13
14
|
this.sessionId = sessionId;
|
|
15
|
+
/** The session as the service told it. */
|
|
14
16
|
this.current = SessionReducer.initial();
|
|
17
|
+
/** `current` with the messages sent from here on their way: what UIs get. */
|
|
18
|
+
this.shown = this.current;
|
|
19
|
+
this.sent = [];
|
|
15
20
|
this.listeners = new Set();
|
|
16
21
|
this.eventListeners = new Set();
|
|
17
22
|
this.goneListeners = new Set();
|
|
@@ -22,11 +27,18 @@ export class SessionStore {
|
|
|
22
27
|
this.results = new Map();
|
|
23
28
|
/** Calls another client took, by id: tried again only when the request comes again (that client left). */
|
|
24
29
|
this.declined = new Map();
|
|
30
|
+
/** The messages held that are being sent again now. */
|
|
31
|
+
this.resending = new Set();
|
|
25
32
|
this.clientTools = new Map(((_a = options.clientTools) !== null && _a !== void 0 ? _a : []).map(tool => [tool.definition.name, tool]));
|
|
26
33
|
this.pageBytes = options.pageBytes;
|
|
34
|
+
this.holdMs = (_b = options.holdMs) !== null && _b !== void 0 ? _b : HOLD_MS;
|
|
35
|
+
if (options.initial) {
|
|
36
|
+
const { messages, start, tools } = options.initial;
|
|
37
|
+
this.current = this.shown = { ...this.current, messages, start, tools };
|
|
38
|
+
}
|
|
27
39
|
}
|
|
28
40
|
get state() {
|
|
29
|
-
return this.
|
|
41
|
+
return this.shown;
|
|
30
42
|
}
|
|
31
43
|
/** Starts following the session. */
|
|
32
44
|
async attach() {
|
|
@@ -49,9 +61,194 @@ export class SessionStore {
|
|
|
49
61
|
this.eventListeners.add(listener);
|
|
50
62
|
return () => this.eventListeners.delete(listener);
|
|
51
63
|
}
|
|
52
|
-
/**
|
|
64
|
+
/**
|
|
65
|
+
* Sends a message with a new id; a resend after a lost connection must reuse the id. Sent while the
|
|
66
|
+
* agent is idle, it shows at once at the end of the conversation, with the agent at work, until the
|
|
67
|
+
* session has it (a command, which may add none, does not).
|
|
68
|
+
*/
|
|
53
69
|
prompt(message, input = {}) {
|
|
54
|
-
return this.
|
|
70
|
+
return this.deliver(message, input, false);
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* As `prompt`, for what the user typed: a message that fails to go stays in the conversation, marked
|
|
74
|
+
* failed, to send again (`resend`) or take back (`discard`), and this resolves without a receipt. One
|
|
75
|
+
* the connection could not take is not failed: it stays on its way and goes once the store is attached
|
|
76
|
+
* again, as a chat app sends what was typed without network once it is back; only after `holdMs`
|
|
77
|
+
* without a connection does it show as failed.
|
|
78
|
+
*/
|
|
79
|
+
async send(message, input = {}) {
|
|
80
|
+
try {
|
|
81
|
+
return await this.deliver(message, input, true);
|
|
82
|
+
}
|
|
83
|
+
catch (error) {
|
|
84
|
+
if (this.sent.some(sent => (sent.failed || sent.heldAt) && sent.text === message)) {
|
|
85
|
+
return undefined;
|
|
86
|
+
}
|
|
87
|
+
throw error;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/** Sends again a message that failed, with its id: one that reached the service after all runs once. */
|
|
91
|
+
async resend(id) {
|
|
92
|
+
const sent = this.sent.find(candidate => candidate.id === id && candidate.failed);
|
|
93
|
+
if (!sent) {
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
this.sent = this.sent.filter(other => other !== sent);
|
|
97
|
+
await this.send(sent.text, { ...sent.input, clientMessageId: sent.id }).catch(() => undefined);
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Takes on the messages that failed to go from another store of the same conversation (one that showed
|
|
101
|
+
* it before this one attached, without the computer), to send again from here.
|
|
102
|
+
*/
|
|
103
|
+
carry(from) {
|
|
104
|
+
const failed = from.sent.filter(sent => (sent.failed || sent.heldAt) && !this.sent.some(other => other.id === sent.id));
|
|
105
|
+
if (failed.length) {
|
|
106
|
+
this.sent = [...this.sent, ...failed];
|
|
107
|
+
this.show();
|
|
108
|
+
if (this.lastSeq !== undefined) {
|
|
109
|
+
this.sendHeld();
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
/** Takes back a message that failed. */
|
|
114
|
+
discard(id) {
|
|
115
|
+
const sent = this.sent.find(candidate => candidate.id === id);
|
|
116
|
+
if (sent) {
|
|
117
|
+
this.unsend(sent);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
deliver(message, input, keep) {
|
|
121
|
+
const full = { clientMessageId: crypto.randomUUID(), ...input, message };
|
|
122
|
+
const sent = this.current.working || message.startsWith('/') ? undefined : this.add(full);
|
|
123
|
+
if (!sent) {
|
|
124
|
+
return this.connection.server.prompt(this.sessionId, full);
|
|
125
|
+
}
|
|
126
|
+
return this.go(sent, full, keep);
|
|
127
|
+
}
|
|
128
|
+
/** Sends a message shown as sent, and settles it by the answer. */
|
|
129
|
+
go(sent, full, keep) {
|
|
130
|
+
return this.connection.server.prompt(this.sessionId, full).then(result => {
|
|
131
|
+
sent.heldAt = undefined;
|
|
132
|
+
if (result.status === 'accepted') {
|
|
133
|
+
sent.accepted = true;
|
|
134
|
+
}
|
|
135
|
+
else {
|
|
136
|
+
// Queued after another run, sent before, or taken by an extension: no message of it comes now.
|
|
137
|
+
this.unsend(sent);
|
|
138
|
+
}
|
|
139
|
+
return result;
|
|
140
|
+
}, error => {
|
|
141
|
+
if (keep && TaRemoteError.isConnectionLost(error) && this.hold(sent)) {
|
|
142
|
+
throw error;
|
|
143
|
+
}
|
|
144
|
+
if (keep) {
|
|
145
|
+
this.fail(sent, error);
|
|
146
|
+
}
|
|
147
|
+
else {
|
|
148
|
+
this.unsend(sent);
|
|
149
|
+
}
|
|
150
|
+
throw error;
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
add(input) {
|
|
154
|
+
var _a;
|
|
155
|
+
const message = { role: 'user', content: [{ type: 'text', text: input.message }, ...((_a = input.images) !== null && _a !== void 0 ? _a : [])], timestamp: Date.now() };
|
|
156
|
+
const { message: _text, clientMessageId: _id, ...rest } = input;
|
|
157
|
+
const sent = { id: input.clientMessageId, message, text: input.message, input: rest, accepted: false };
|
|
158
|
+
this.sent = [...this.sent, sent];
|
|
159
|
+
this.show();
|
|
160
|
+
return sent;
|
|
161
|
+
}
|
|
162
|
+
/** Keeps a message the connection could not take on its way, unless it waited `holdMs` already. */
|
|
163
|
+
hold(sent) {
|
|
164
|
+
var _a, _b;
|
|
165
|
+
if (!this.sent.includes(sent)) {
|
|
166
|
+
return false;
|
|
167
|
+
}
|
|
168
|
+
(_a = sent.heldAt) !== null && _a !== void 0 ? _a : (sent.heldAt = Date.now());
|
|
169
|
+
if (Date.now() - sent.heldAt >= this.holdMs) {
|
|
170
|
+
return false;
|
|
171
|
+
}
|
|
172
|
+
(_b = this.holdTimer) !== null && _b !== void 0 ? _b : (this.holdTimer = setTimeout(() => this.expireHeld(), sent.heldAt + this.holdMs - Date.now()));
|
|
173
|
+
return true;
|
|
174
|
+
}
|
|
175
|
+
/** The messages held `holdMs` that are not going now show as failed. */
|
|
176
|
+
expireHeld() {
|
|
177
|
+
this.holdTimer = undefined;
|
|
178
|
+
const now = Date.now();
|
|
179
|
+
let next = Number.POSITIVE_INFINITY;
|
|
180
|
+
for (const sent of this.sent) {
|
|
181
|
+
if (sent.heldAt === undefined || sent.failed || this.resending.has(sent)) {
|
|
182
|
+
continue;
|
|
183
|
+
}
|
|
184
|
+
if (now - sent.heldAt >= this.holdMs) {
|
|
185
|
+
this.fail(sent, TaRemoteError.notConnected());
|
|
186
|
+
}
|
|
187
|
+
else {
|
|
188
|
+
next = Math.min(next, sent.heldAt + this.holdMs - now);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
if (next !== Number.POSITIVE_INFINITY) {
|
|
192
|
+
this.holdTimer = setTimeout(() => this.expireHeld(), next);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
/** Attached again: the messages held go now, with their ids, so that one the service had after all runs once. */
|
|
196
|
+
sendHeld() {
|
|
197
|
+
for (const sent of this.sent) {
|
|
198
|
+
if (sent.heldAt === undefined || sent.failed || this.resending.has(sent)) {
|
|
199
|
+
continue;
|
|
200
|
+
}
|
|
201
|
+
this.resending.add(sent);
|
|
202
|
+
void this.go(sent, { ...sent.input, clientMessageId: sent.id, message: sent.text }, true)
|
|
203
|
+
.catch(() => undefined)
|
|
204
|
+
.finally(() => this.resending.delete(sent));
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
fail(sent, error) {
|
|
208
|
+
if (this.sent.includes(sent)) {
|
|
209
|
+
const failed = { ...sent, failed: error instanceof Error ? error.message : String(error) };
|
|
210
|
+
this.sent = this.sent.map(other => (other === sent ? failed : other));
|
|
211
|
+
this.show();
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
unsend(sent) {
|
|
215
|
+
if (this.sent.includes(sent)) {
|
|
216
|
+
this.sent = this.sent.filter(other => other !== sent);
|
|
217
|
+
this.show();
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
/** The message sent, once the session has a message of the user: the one of the same text, else the first. */
|
|
221
|
+
arrived(message) {
|
|
222
|
+
var _a;
|
|
223
|
+
const waiting = this.sent.filter(sent => !sent.failed);
|
|
224
|
+
const text = SessionStore.textOf(message);
|
|
225
|
+
const sent = (_a = waiting.find(candidate => candidate.text === text)) !== null && _a !== void 0 ? _a : waiting[0];
|
|
226
|
+
this.sent = this.sent.filter(other => other !== sent);
|
|
227
|
+
}
|
|
228
|
+
static textOf(message) {
|
|
229
|
+
const { content } = message;
|
|
230
|
+
if (typeof content === 'string') {
|
|
231
|
+
return content;
|
|
232
|
+
}
|
|
233
|
+
const first = Array.isArray(content) ? content[0] : undefined;
|
|
234
|
+
return (first === null || first === void 0 ? void 0 : first.type) === 'text' ? first.text : undefined;
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* `state` with the messages sent from here after it (`outbox` says which they are), and the agent at
|
|
238
|
+
* work for those on their way.
|
|
239
|
+
*/
|
|
240
|
+
static withSent(state, sent) {
|
|
241
|
+
if (!sent.length) {
|
|
242
|
+
return state;
|
|
243
|
+
}
|
|
244
|
+
const going = sent.some(message => !message.failed);
|
|
245
|
+
return {
|
|
246
|
+
...state,
|
|
247
|
+
messages: [...state.messages, ...sent.map(message => message.message)],
|
|
248
|
+
outbox: sent,
|
|
249
|
+
working: state.working || going,
|
|
250
|
+
runStart: state.working || !going ? state.runStart : state.messages.length,
|
|
251
|
+
};
|
|
55
252
|
}
|
|
56
253
|
/**
|
|
57
254
|
* The service no longer has the session after a reconnect (it restarted, or closed the session while
|
|
@@ -72,7 +269,7 @@ export class SessionStore {
|
|
|
72
269
|
// The conversation as of lastSeq, with the message being written and the calls running.
|
|
73
270
|
const conversation = (_a = result.conversation) !== null && _a !== void 0 ? _a : { ...(await this.connection.server.getMessages(this.sessionId)), tools: {} };
|
|
74
271
|
const { messages, start } = SessionStore.withEarlier(this.current, conversation.messages, (_b = conversation.start) !== null && _b !== void 0 ? _b : 0);
|
|
75
|
-
const kept =
|
|
272
|
+
const kept = SessionReducer.keep(this.current.messages, messages, start - this.current.start);
|
|
76
273
|
state = {
|
|
77
274
|
...this.current,
|
|
78
275
|
messages: kept,
|
|
@@ -81,6 +278,8 @@ export class SessionStore {
|
|
|
81
278
|
runStart: kept === this.current.messages ? this.current.runStart : undefined,
|
|
82
279
|
};
|
|
83
280
|
this.lastSeq = result.lastSeq;
|
|
281
|
+
// The conversation of the service has those it took.
|
|
282
|
+
this.sent = this.sent.filter(sent => !sent.accepted);
|
|
84
283
|
}
|
|
85
284
|
const taken = this.take(state, result.events);
|
|
86
285
|
state = {
|
|
@@ -96,6 +295,7 @@ export class SessionStore {
|
|
|
96
295
|
// Once, however much changed: what is drawn changes in one frame.
|
|
97
296
|
this.update(state);
|
|
98
297
|
this.applied(taken);
|
|
298
|
+
this.sendHeld();
|
|
99
299
|
return result;
|
|
100
300
|
}
|
|
101
301
|
/**
|
|
@@ -181,6 +381,15 @@ export class SessionStore {
|
|
|
181
381
|
}
|
|
182
382
|
this.lastSeq = seq;
|
|
183
383
|
state = SessionReducer.reduce(state, event);
|
|
384
|
+
if (this.sent.length) {
|
|
385
|
+
if (event.type === 'message_start' && event.message.role === 'user') {
|
|
386
|
+
this.arrived(event.message);
|
|
387
|
+
}
|
|
388
|
+
else if (event.type === 'agent_settled') {
|
|
389
|
+
// Its run ended without it as sent (an extension changed it): it no longer waits.
|
|
390
|
+
this.sent = this.sent.filter(sent => !sent.accepted);
|
|
391
|
+
}
|
|
392
|
+
}
|
|
184
393
|
replaced || (replaced = event.type === 'session_replaced');
|
|
185
394
|
applied.push(event);
|
|
186
395
|
}
|
|
@@ -200,12 +409,18 @@ export class SessionStore {
|
|
|
200
409
|
update(state) {
|
|
201
410
|
if (state !== this.current) {
|
|
202
411
|
this.current = state;
|
|
203
|
-
|
|
204
|
-
listener(state);
|
|
205
|
-
}
|
|
412
|
+
this.show();
|
|
206
413
|
this.runClientTools(state);
|
|
207
414
|
}
|
|
208
415
|
}
|
|
416
|
+
/** UIs get the state with the messages sent, when either changed. */
|
|
417
|
+
show() {
|
|
418
|
+
const shown = SessionStore.withSent(this.current, this.sent.map(({ id, message, failed }) => (failed ? { id, message, failed } : { id, message })));
|
|
419
|
+
this.shown = shown;
|
|
420
|
+
for (const listener of this.listeners) {
|
|
421
|
+
listener(shown);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
209
424
|
runClientTools(state) {
|
|
210
425
|
for (const request of state.pendingClientTools) {
|
|
211
426
|
const tool = this.clientTools.get(request.toolName);
|
|
@@ -252,7 +467,7 @@ export class SessionStore {
|
|
|
252
467
|
/** 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. */
|
|
253
468
|
claim(request) {
|
|
254
469
|
return this.connection.server.claimClientTool(this.sessionId, request.id).catch(error => {
|
|
255
|
-
if ((error
|
|
470
|
+
if (TaRemoteError.isMethodNotFound(error)) {
|
|
256
471
|
return true;
|
|
257
472
|
}
|
|
258
473
|
throw error;
|
|
@@ -1,9 +1,36 @@
|
|
|
1
|
-
import { type TaAccessServer, type TaAuthEvent, type TaAuthServer, TaErrorCode, type TaEventEnvelope, type TaGatewayServer, type TaPackageServer, type TaRelayServer, type TaRemoteEvent, type TaRemoteServer, type TaServer, type TaSettingsServer, type TaTerminalServer, type TaWorkspaceServer } from '@celljs/ta-protocol';
|
|
2
|
-
/**
|
|
1
|
+
import { type TaAccessServer, type TaAuthEvent, type TaAuthServer, TaErrorCode, type TaErrorData, type TaEventEnvelope, type TaGatewayServer, type TaPackageServer, type TaRelayServer, type TaRemoteEvent, type TaRemoteServer, type TaServer, type TaSettingsServer, type TaTerminalServer, type TaWorkspaceServer } from '@celljs/ta-protocol';
|
|
2
|
+
/**
|
|
3
|
+
* A failed call. `code` is set for failures the server names; `rpcCode` is the code of JSON-RPC's error,
|
|
4
|
+
* by which a client tells a method an older ta serve does not have (`TaRemoteError.METHOD_NOT_FOUND`).
|
|
5
|
+
*/
|
|
3
6
|
export declare class TaRemoteError extends Error {
|
|
4
7
|
readonly code?: TaErrorCode | undefined;
|
|
5
8
|
readonly hint?: string | undefined;
|
|
6
|
-
|
|
9
|
+
readonly rpcCode?: number | undefined;
|
|
10
|
+
/** JSON-RPC's code for a method the server does not have. */
|
|
11
|
+
static readonly METHOD_NOT_FOUND = -32601;
|
|
12
|
+
constructor(message: string, code?: TaErrorCode | undefined, hint?: string | undefined, rpcCode?: number | undefined);
|
|
13
|
+
/** The error of a JSON-RPC answer: its code, and the code and hint of ta serve when it named the failure. */
|
|
14
|
+
static of(error: {
|
|
15
|
+
message: string;
|
|
16
|
+
code?: number;
|
|
17
|
+
data?: {
|
|
18
|
+
data?: TaErrorData;
|
|
19
|
+
};
|
|
20
|
+
}): TaRemoteError;
|
|
21
|
+
/** What a call says that waited for a connection that did not come back. */
|
|
22
|
+
static readonly NOT_CONNECTED = "Not connected to ta serve.";
|
|
23
|
+
/** What a call says that was sent on a connection lost before its answer. */
|
|
24
|
+
static readonly LOST = "The connection to ta serve was lost.";
|
|
25
|
+
/** A call that waited for a connection that did not come back. */
|
|
26
|
+
static notConnected(): TaRemoteError;
|
|
27
|
+
/**
|
|
28
|
+
* Whether a failure is only that the connection was lost, which mends itself: by its code, or by its
|
|
29
|
+
* words in a text (a web extension shows `error.message`, often inside its own words).
|
|
30
|
+
*/
|
|
31
|
+
static isConnectionLost(cause: unknown): boolean;
|
|
32
|
+
/** Whether the server has no such method: a ta serve from before it was added. */
|
|
33
|
+
static isMethodNotFound(error: unknown): boolean;
|
|
7
34
|
}
|
|
8
35
|
export interface TaConnectionOptions {
|
|
9
36
|
/** The `url` of serve.json. */
|
|
@@ -19,6 +46,18 @@ export interface TaConnectionOptions {
|
|
|
19
46
|
* that a short drop goes unnoticed. Default 5000; 0 fails at once.
|
|
20
47
|
*/
|
|
21
48
|
waitForOpenMs?: number;
|
|
49
|
+
/**
|
|
50
|
+
* How long a call that is safe to send again (`TaConnection.resendable`: a read, a message with its
|
|
51
|
+
* clientMessageId) keeps trying across lost connections, waiting for each to come back, before it
|
|
52
|
+
* fails: a drop mended within it goes unseen. Default `waitForOpenMs`.
|
|
53
|
+
*/
|
|
54
|
+
retryForMs?: number;
|
|
55
|
+
/**
|
|
56
|
+
* A call unanswered this long while nothing at all came over the connection makes it check that the
|
|
57
|
+
* connection is alive (`wake`): one gone without a word is made again in seconds, not when the system
|
|
58
|
+
* notices; the check waits as long for its answer. Default 5000; 0 never checks.
|
|
59
|
+
*/
|
|
60
|
+
stallMs?: number;
|
|
22
61
|
/**
|
|
23
62
|
* Another way to ta serve than a WebSocket to `url`, such as a relay (RelaySocket of @celljs/ta-relay):
|
|
24
63
|
* a new socket for each connection, which takes care of access itself.
|
|
@@ -40,6 +79,8 @@ export interface TaSocket {
|
|
|
40
79
|
interface PendingCall {
|
|
41
80
|
resolve(result: unknown): void;
|
|
42
81
|
reject(error: Error): void;
|
|
82
|
+
/** When it was sent, on the clock of Date.now(). */
|
|
83
|
+
sentAt: number;
|
|
43
84
|
}
|
|
44
85
|
type EventsListener = (events: TaEventEnvelope[]) => void;
|
|
45
86
|
type TerminalListener = (terminalId: string, data: string, exitCode?: number) => void;
|
|
@@ -56,8 +97,11 @@ type ReconnectingListener = (delayMs: number, attempt: number) => void;
|
|
|
56
97
|
* over the one WebSocket.
|
|
57
98
|
*
|
|
58
99
|
* A call made while the connection is down waits a little for it to come back (`waitForOpenMs`): it was
|
|
59
|
-
* not sent. Calls that were sent when the connection was lost fail
|
|
60
|
-
*
|
|
100
|
+
* not sent. Calls that were sent when the connection was lost fail, unless they are safe to send again
|
|
101
|
+
* (`resendable`: reads, and messages ta serve takes once by their clientMessageId), which wait for the
|
|
102
|
+
* next connection and go again for up to `retryForMs`: on a network that drops now and then, a read or a
|
|
103
|
+
* message is late rather than failed. A call that stalls while nothing comes makes it check the
|
|
104
|
+
* connection (`stallMs`), so that one gone without a word is not waited on for long.
|
|
61
105
|
*/
|
|
62
106
|
export declare class TaConnection {
|
|
63
107
|
protected readonly options: TaConnectionOptions;
|
|
@@ -91,6 +135,11 @@ export declare class TaConnection {
|
|
|
91
135
|
go(): void;
|
|
92
136
|
fail(): void;
|
|
93
137
|
}>;
|
|
138
|
+
/** When the last message came, on the clock of Date.now(). */
|
|
139
|
+
protected lastReceivedAt: number;
|
|
140
|
+
/** Checks the calls for a stall while some wait for answers. */
|
|
141
|
+
protected stallTimer?: ReturnType<typeof setInterval>;
|
|
142
|
+
protected probing: boolean;
|
|
94
143
|
constructor(options: TaConnectionOptions);
|
|
95
144
|
/** Resolves when the first connection is open, or rejects if it cannot be made; later losses reconnect. */
|
|
96
145
|
connect(): Promise<void>;
|
|
@@ -123,11 +172,20 @@ export declare class TaConnection {
|
|
|
123
172
|
protected lost(socket: TaSocket, opened: boolean, atOnce?: boolean): void;
|
|
124
173
|
protected createWebSocket(): TaSocket;
|
|
125
174
|
protected scheduleReconnect(): void;
|
|
126
|
-
/** Resolves once the connection is open, or rejects after `waitForOpenMs
|
|
127
|
-
protected opened(): Promise<void>;
|
|
175
|
+
/** Resolves once the connection is open, or rejects after `waitForOpenMs` (or `waitMs`), or at once when it is closed. */
|
|
176
|
+
protected opened(waitMs?: number): Promise<void>;
|
|
128
177
|
protected failPending(): void;
|
|
129
178
|
protected service<T extends object>(name: string): T;
|
|
179
|
+
/**
|
|
180
|
+
* Whether a call may go again after a lost connection, as doing it twice does what doing it once does:
|
|
181
|
+
* a read, or a message with its clientMessageId (TaPromptInput), which ta serve takes once.
|
|
182
|
+
*/
|
|
183
|
+
static resendable(service: string, method: string, params: readonly unknown[]): boolean;
|
|
130
184
|
protected call(service: string, method: string, params: unknown[]): Promise<unknown>;
|
|
185
|
+
/** Sends a call on the open connection; its answer, or its failure when the connection is lost first. */
|
|
186
|
+
protected send(service: string, method: string, params: unknown[]): Promise<unknown>;
|
|
187
|
+
/** While calls wait for answers: one that waits past `stallMs` with nothing come since makes it check the connection. */
|
|
188
|
+
protected watchStalls(): void;
|
|
131
189
|
protected receive(text: string): void;
|
|
132
190
|
}
|
|
133
191
|
export {};
|