@celljs/ta-client 4.8.0 → 4.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +2 -2
- package/README.md +3 -3
- package/esm/common/session-reducer.d.ts +10 -11
- package/esm/common/session-reducer.js +31 -2
- package/esm/common/session-store.d.ts +50 -3
- package/esm/common/session-store.js +136 -16
- package/esm/common/ta-connection.d.ts +27 -2
- package/esm/common/ta-connection.js +96 -12
- package/lib/common/session-reducer.d.ts +10 -11
- package/lib/common/session-reducer.js +31 -2
- package/lib/common/session-store.d.ts +50 -3
- package/lib/common/session-store.js +136 -16
- package/lib/common/ta-connection.d.ts +27 -2
- package/lib/common/ta-connection.js +95 -11
- package/package.json +4 -3
- package/esm/common/index.js.map +0 -1
- package/esm/common/session-reducer.js.map +0 -1
- package/esm/common/session-store.js.map +0 -1
- package/esm/common/ta-connection.js.map +0 -1
- package/lib/common/index.d.ts.map +0 -1
- package/lib/common/index.js.map +0 -1
- package/lib/common/session-reducer.d.ts.map +0 -1
- package/lib/common/session-reducer.js.map +0 -1
- package/lib/common/session-reducer.spec.d.ts +0 -2
- package/lib/common/session-reducer.spec.d.ts.map +0 -1
- package/lib/common/session-reducer.spec.js +0 -122
- package/lib/common/session-reducer.spec.js.map +0 -1
- package/lib/common/session-store.d.ts.map +0 -1
- package/lib/common/session-store.js.map +0 -1
- package/lib/common/ta-connection.d.ts.map +0 -1
- package/lib/common/ta-connection.js.map +0 -1
- package/src/common/index.ts +0 -3
- package/src/common/session-reducer.spec.ts +0 -136
- package/src/common/session-reducer.ts +0 -217
- package/src/common/session-store.ts +0 -198
- package/src/common/ta-connection.ts +0 -325
package/README.en.md
CHANGED
|
@@ -16,7 +16,7 @@ await store.prompt('Fix the failing tests');
|
|
|
16
16
|
```
|
|
17
17
|
|
|
18
18
|
- `TaConnection`: auto-reconnects after disconnect using exponential backoff. `onReconnecting(delayMs, attempt)` notifies you before each wait, and `reconnect()` skips the wait and retries immediately. `connection.server` (sessions), `workspace`, `terminals`, `settings`, `packages`, `auth` (login to model services, subscribe to events with `onAuthEvent`), and `relay` (paired devices) are typed proxies for ta serve's services, all sharing one connection. The `createSocket` option lets you use a different transport, like `RelaySocket` through Relay ([@celljs/ta-relay](../ta-relay/README.md)). Calls during disconnection fail immediately (`TaRemoteError`, `code` is `CELL_TA_CONNECTION_LOST`) without queuing; whether to retry is up to the caller (reuse `clientMessageId` when retrying). Connections that drop re-establish themselves; operations from before the drop complete with the previous code if the server still has them.
|
|
19
|
-
- `SessionStore`: the client-side state for one session (messages, tool runs, pending dialogs, extension status bars). After reconnect, it resends missed events by `seq`. If it can't catch up (a `gap`), it auto-syncs with `getMessages`.
|
|
19
|
+
- `SessionStore`: the client-side state for one session (messages, tool runs, pending dialogs, extension status bars). After reconnect, it resends missed events by `seq`. If it can't catch up (a `gap`), it auto-syncs with `getMessages`. With `pageBytes` (e.g. `128 * 1024`), attach takes only about that many bytes of the latest messages (`state.start` is where they start in the whole conversation); `loadEarlier()` puts as much of the earlier ones in front each time, and `loadAll()` takes the rest: a long conversation opens without waiting for all of it.
|
|
20
20
|
- Client tools: the model can call tools run by the client (e.g., read clipboard, let the user pick something in the UI). Declare them when opening a session; `SessionStore` runs them and returns the results:
|
|
21
21
|
|
|
22
22
|
```ts
|
|
@@ -28,6 +28,6 @@ const { sessionId } = await connection.server.openSession({ cwd, clientTools: [p
|
|
|
28
28
|
const store = new SessionStore(connection, sessionId, { clientTools: [pickColor] });
|
|
29
29
|
```
|
|
30
30
|
|
|
31
|
-
Call requests broadcast to all connected clients
|
|
31
|
+
Call requests broadcast to all connected clients. The store first takes a call with `claimClientTool`, and only the client that took it runs it, so a call runs once however many pages are open; if that client leaves the session before answering, the request goes out again for another. After a disconnect, it resends the result already made instead of running again. If `run` is aborted or the session closes, the call ends as failed. The same client tools work in codemode scripts using `tools.pick_color()`.
|
|
32
32
|
- `openSession`'s `appendSystemPrompt` appends a system prompt line to the session (like pi's `--append-system-prompt`), allowing clients to give the Agent a role.
|
|
33
33
|
- `SessionReducer`: a pure function `(state, event) => state`, never mutating old state, so UIs can compare by reference.
|
package/README.md
CHANGED
|
@@ -16,7 +16,7 @@ await store.prompt('修复失败的测试');
|
|
|
16
16
|
```
|
|
17
17
|
|
|
18
18
|
- `TaConnection`:断线后自动重连(指数退避);`onReconnecting(delayMs, attempt)` 在每次等待前通知,`reconnect()` 跳过等待立即重试。`connection.server`(会话)、`workspace`、`terminals`、`settings`、`packages`、`auth`(登录模型服务,事件用 `onAuthEvent` 订阅)、`relay`(配对设备)是 ta serve 各服务的带类型代理,共用这一条连接。`createSocket` 选项可以换成别的传输,例如经 Relay 的 `RelaySocket`([@celljs/ta-relay](../ta-relay/README.md))。断线期间的调用直接失败(`TaRemoteError`,`code` 为 `CELL_TA_CONNECTION_LOST`),不排队,是否重发由调用方决定(重发请复用 `clientMessageId`)。
|
|
19
|
-
- `SessionStore`:一个会话在客户端的状态(消息、工具执行、待回答的对话框、扩展状态栏)。重连后按 `seq` 补发错过的事件;补不上时(`gap`)自动用 `getMessages`
|
|
19
|
+
- `SessionStore`:一个会话在客户端的状态(消息、工具执行、待回答的对话框、扩展状态栏)。重连后按 `seq` 补发错过的事件;补不上时(`gap`)自动用 `getMessages` 重新同步。传 `pageBytes`(如 `128 * 1024`)时,attach 只取最近约这么多字节的消息(`state.start` 是它们在整段对话里的起点),更早的用 `loadEarlier()` 一段段往前补(同样大小),`loadAll()` 取全部:长对话打开时不必等全部传完。
|
|
20
20
|
- 客户端工具:模型可以调用由客户端执行的工具(例如读剪贴板、让用户在界面里选择)。打开会话时声明,`SessionStore` 负责执行并回传结果:
|
|
21
21
|
|
|
22
22
|
```ts
|
|
@@ -28,6 +28,6 @@ const { sessionId } = await connection.server.openSession({ cwd, clientTools: [p
|
|
|
28
28
|
const store = new SessionStore(connection, sessionId, { clientTools: [pickColor] });
|
|
29
29
|
```
|
|
30
30
|
|
|
31
|
-
|
|
31
|
+
调用请求广播给所有已连接的客户端,store 先用 `claimClientTool` 认领,只有认领到的客户端执行,所以开着几个页面都只执行一次;认领者没回答就离开会话时,请求重新广播,由其他客户端接手。断线后重发已算好的结果,而不是再执行一次。run 被中止或会话关闭时调用以失败结束。codemode 脚本里同样可以 `tools.pick_color()`。
|
|
32
32
|
- `openSession` 的 `appendSystemPrompt` 给会话追加一段 system prompt(同 pi 的 `--append-system-prompt`),客户端可以借此给 Agent 一个角色。
|
|
33
|
-
- `SessionReducer`:纯函数 `(state, event) => state`,不改动旧状态,UI 可按引用比较。
|
|
33
|
+
- `SessionReducer`:纯函数 `(state, event) => state`,不改动旧状态,UI 可按引用比较。
|
|
@@ -1,14 +1,6 @@
|
|
|
1
|
-
import type { RpcExtensionUIRequest, TaClientToolRequest,
|
|
2
|
-
export type SessionMessage =
|
|
3
|
-
export
|
|
4
|
-
toolName: string;
|
|
5
|
-
args: unknown;
|
|
6
|
-
/** The latest partial result while it runs, then the result. */
|
|
7
|
-
result?: unknown;
|
|
8
|
-
status: 'running' | 'done' | 'error';
|
|
9
|
-
/** Set for a call another tool made, such as a codemode script. */
|
|
10
|
-
parentToolCallId?: string;
|
|
11
|
-
}
|
|
1
|
+
import type { RpcExtensionUIRequest, TaClientToolRequest, TaEvent, TaMessage, TaToolRun } from '@celljs/ta-protocol';
|
|
2
|
+
export type SessionMessage = TaMessage;
|
|
3
|
+
export type ToolRun = TaToolRun;
|
|
12
4
|
/** A message of `notify`. */
|
|
13
5
|
export interface Notice {
|
|
14
6
|
id: string;
|
|
@@ -31,6 +23,8 @@ export interface SessionState {
|
|
|
31
23
|
/** The agent is working, from the start of a run until it has settled. */
|
|
32
24
|
working: boolean;
|
|
33
25
|
messages: SessionMessage[];
|
|
26
|
+
/** Where `messages` start in the whole conversation: those before are loaded with `SessionStore.loadEarlier`. */
|
|
27
|
+
start: number;
|
|
34
28
|
/** By tool call id. */
|
|
35
29
|
tools: Record<string, ToolRun>;
|
|
36
30
|
/** Dialogs waiting for an answer. */
|
|
@@ -60,4 +54,9 @@ export declare namespace SessionReducer {
|
|
|
60
54
|
function initial(): SessionState;
|
|
61
55
|
/** The next state; the previous one stays valid, so that UIs can compare by identity. */
|
|
62
56
|
function reduce(state: SessionState, event: TaEvent): SessionState;
|
|
57
|
+
/**
|
|
58
|
+
* The messages of `next`, with each that is the same as the one of `previous` at its place kept as it
|
|
59
|
+
* was: a conversation read again after a reconnect has new objects, which a UI would all draw again.
|
|
60
|
+
*/
|
|
61
|
+
function keep(previous: readonly SessionMessage[], next: SessionMessage[]): SessionMessage[];
|
|
63
62
|
}
|
|
@@ -3,7 +3,18 @@ export var SessionReducer;
|
|
|
3
3
|
const DIALOGS = new Set(['select', 'confirm', 'input', 'editor']);
|
|
4
4
|
const MAX_NOTICES = 20;
|
|
5
5
|
function initial() {
|
|
6
|
-
return {
|
|
6
|
+
return {
|
|
7
|
+
working: false,
|
|
8
|
+
messages: [],
|
|
9
|
+
start: 0,
|
|
10
|
+
tools: {},
|
|
11
|
+
pendingUi: [],
|
|
12
|
+
pendingClientTools: [],
|
|
13
|
+
notices: [],
|
|
14
|
+
status: {},
|
|
15
|
+
widgets: {},
|
|
16
|
+
closed: false,
|
|
17
|
+
};
|
|
7
18
|
}
|
|
8
19
|
SessionReducer.initial = initial;
|
|
9
20
|
/** The next state; the previous one stays valid, so that UIs can compare by identity. */
|
|
@@ -36,7 +47,8 @@ export var SessionReducer;
|
|
|
36
47
|
case 'ui_request_resolved':
|
|
37
48
|
return { ...state, pendingUi: state.pendingUi.filter(request => request.id !== event.id) };
|
|
38
49
|
case 'client_tool_request':
|
|
39
|
-
|
|
50
|
+
// Asked again (the client that took it left): in place of the request before.
|
|
51
|
+
return { ...state, pendingClientTools: [...state.pendingClientTools.filter(request => request.id !== event.id), event] };
|
|
40
52
|
case 'client_tool_resolved':
|
|
41
53
|
return { ...state, pendingClientTools: state.pendingClientTools.filter(request => request.id !== event.id) };
|
|
42
54
|
case 'compaction_start':
|
|
@@ -140,5 +152,22 @@ export var SessionReducer;
|
|
|
140
152
|
return undefined;
|
|
141
153
|
}
|
|
142
154
|
}
|
|
155
|
+
/**
|
|
156
|
+
* The messages of `next`, with each that is the same as the one of `previous` at its place kept as it
|
|
157
|
+
* was: a conversation read again after a reconnect has new objects, which a UI would all draw again.
|
|
158
|
+
*/
|
|
159
|
+
function keep(previous, next) {
|
|
160
|
+
let same = previous.length === next.length;
|
|
161
|
+
const kept = next.map((message, index) => {
|
|
162
|
+
const before = previous[index];
|
|
163
|
+
if (before && before.role === message.role && before.timestamp === message.timestamp && JSON.stringify(before) === JSON.stringify(message)) {
|
|
164
|
+
return before;
|
|
165
|
+
}
|
|
166
|
+
same = false;
|
|
167
|
+
return message;
|
|
168
|
+
});
|
|
169
|
+
return same ? previous : kept;
|
|
170
|
+
}
|
|
171
|
+
SessionReducer.keep = keep;
|
|
143
172
|
})(SessionReducer || (SessionReducer = {}));
|
|
144
173
|
//# sourceMappingURL=session-reducer.js.map
|
|
@@ -1,7 +1,12 @@
|
|
|
1
|
-
import type
|
|
2
|
-
import { type SessionState } from './session-reducer.js';
|
|
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
3
|
import type { TaConnection } from './ta-connection.js';
|
|
4
4
|
type Listener = (state: SessionState) => void;
|
|
5
|
+
interface Taken {
|
|
6
|
+
state: SessionState;
|
|
7
|
+
applied: TaEvent[];
|
|
8
|
+
replaced: boolean;
|
|
9
|
+
}
|
|
5
10
|
/**
|
|
6
11
|
* A tool this client runs. Open the session with its `definition` in `clientTools`, and give the tool
|
|
7
12
|
* to the store, which runs each call and sends the result. Its output is what the model reads; a
|
|
@@ -14,6 +19,11 @@ export interface ClientTool {
|
|
|
14
19
|
export interface SessionStoreOptions {
|
|
15
20
|
/** The tools of the session this client runs. Other clients may run them too: the first result counts. */
|
|
16
21
|
clientTools?: ClientTool[];
|
|
22
|
+
/**
|
|
23
|
+
* Only about this many bytes of the latest messages come when it attaches, and as many more each time
|
|
24
|
+
* `loadEarlier` is called: a long conversation shows at once. None: all of it.
|
|
25
|
+
*/
|
|
26
|
+
pageBytes?: number;
|
|
17
27
|
}
|
|
18
28
|
/**
|
|
19
29
|
* The state of one open session on a client: for any UI to render and subscribe to. It catches up by
|
|
@@ -26,12 +36,18 @@ export declare class SessionStore {
|
|
|
26
36
|
protected lastSeq?: number;
|
|
27
37
|
protected readonly listeners: Set<Listener>;
|
|
28
38
|
protected readonly eventListeners: Set<(event: TaEvent) => void>;
|
|
39
|
+
protected readonly goneListeners: Set<() => void>;
|
|
29
40
|
protected readonly stop: (() => void)[];
|
|
30
41
|
protected readonly clientTools: Map<string, ClientTool>;
|
|
31
42
|
/** Calls of client tools this store is running or answering now, by id. */
|
|
32
43
|
protected readonly running: Set<string>;
|
|
33
44
|
/** Results not yet taken by the server, by call id. */
|
|
34
45
|
protected readonly results: Map<string, TaClientToolResult>;
|
|
46
|
+
/** Calls another client took, by id: tried again only when the request comes again (that client left). */
|
|
47
|
+
protected readonly declined: Map<string, TaClientToolRequest>;
|
|
48
|
+
protected readonly pageBytes?: number;
|
|
49
|
+
/** The earlier messages on their way. */
|
|
50
|
+
protected loadingEarlier?: Promise<void>;
|
|
35
51
|
constructor(connection: TaConnection, sessionId: string, options?: SessionStoreOptions);
|
|
36
52
|
get state(): SessionState;
|
|
37
53
|
/** Starts following the session. */
|
|
@@ -43,14 +59,45 @@ export declare class SessionStore {
|
|
|
43
59
|
onEvent(listener: (event: TaEvent) => void): () => void;
|
|
44
60
|
/** Sends a message with a new id; a resend after a lost connection must reuse the id. */
|
|
45
61
|
prompt(message: string, input?: Partial<TaPromptInput>): Promise<TaPromptReceipt>;
|
|
62
|
+
/**
|
|
63
|
+
* The service no longer has the session after a reconnect (it restarted, or closed the session while
|
|
64
|
+
* idle): its file stays, to open again.
|
|
65
|
+
*/
|
|
66
|
+
onGone(listener: () => void): () => void;
|
|
46
67
|
respondUi(response: RpcExtensionUIResponse): Promise<boolean>;
|
|
47
68
|
protected attachAgain(): Promise<TaAttachResult>;
|
|
69
|
+
/**
|
|
70
|
+
* The latest messages, after the earlier ones the store had if they are still the same where the
|
|
71
|
+
* latest start: a reconnect does not drop what was loaded further up.
|
|
72
|
+
*/
|
|
73
|
+
static withEarlier(current: SessionState, messages: SessionMessage[], start: number): {
|
|
74
|
+
messages: SessionMessage[];
|
|
75
|
+
start: number;
|
|
76
|
+
};
|
|
77
|
+
protected lost(error: unknown): void;
|
|
78
|
+
/**
|
|
79
|
+
* The messages before those it has, about `pageBytes` of them, put in front: once they are there, or
|
|
80
|
+
* at once when it has them all. Called again while they come, it waits for the same.
|
|
81
|
+
*/
|
|
82
|
+
loadEarlier(): Promise<void>;
|
|
83
|
+
/** All the messages of the conversation, for what needs the whole of it (an export). */
|
|
84
|
+
loadAll(): Promise<void>;
|
|
85
|
+
protected fetchEarlier(): Promise<void>;
|
|
48
86
|
protected reload(): Promise<void>;
|
|
49
87
|
protected apply(events: TaEventEnvelope[]): void;
|
|
88
|
+
/** `state` with the events of this session not taken yet. */
|
|
89
|
+
protected take(state: SessionState, events: TaEventEnvelope[]): Taken;
|
|
90
|
+
/** Once the state has the events: their listeners, and the conversation read again if it was replaced. */
|
|
91
|
+
protected applied({ applied, replaced }: Taken): void;
|
|
50
92
|
protected update(state: SessionState): void;
|
|
51
93
|
protected runClientTools(state: SessionState): void;
|
|
52
|
-
/**
|
|
94
|
+
/**
|
|
95
|
+
* Runs a call once, if this client takes it: every page of the user gets it. A result that could not be
|
|
96
|
+
* sent is sent again after a reconnect, not made again.
|
|
97
|
+
*/
|
|
53
98
|
protected answer(tool: ClientTool, request: TaClientToolRequest): Promise<void>;
|
|
99
|
+
/** Whether this client runs the call; a Ta service from before claims (a computer not updated yet, reached from a phone) lets every client run it, as it did. */
|
|
100
|
+
protected claim(request: TaClientToolRequest): Promise<boolean>;
|
|
54
101
|
protected run(tool: ClientTool, request: TaClientToolRequest): Promise<TaClientToolResult>;
|
|
55
102
|
}
|
|
56
103
|
export {};
|
|
@@ -1,4 +1,7 @@
|
|
|
1
|
+
import { TaErrorCode, } from '@celljs/ta-protocol';
|
|
1
2
|
import { SessionReducer } from './session-reducer.js';
|
|
3
|
+
/** JSON-RPC's code for a method the server does not have. */
|
|
4
|
+
const METHOD_NOT_FOUND = -32601;
|
|
2
5
|
/**
|
|
3
6
|
* The state of one open session on a client: for any UI to render and subscribe to. It catches up by
|
|
4
7
|
* itself after a reconnect, from the events it missed or, if those are gone, from the session.
|
|
@@ -11,19 +14,23 @@ export class SessionStore {
|
|
|
11
14
|
this.current = SessionReducer.initial();
|
|
12
15
|
this.listeners = new Set();
|
|
13
16
|
this.eventListeners = new Set();
|
|
17
|
+
this.goneListeners = new Set();
|
|
14
18
|
this.stop = [];
|
|
15
19
|
/** Calls of client tools this store is running or answering now, by id. */
|
|
16
20
|
this.running = new Set();
|
|
17
21
|
/** Results not yet taken by the server, by call id. */
|
|
18
22
|
this.results = new Map();
|
|
23
|
+
/** Calls another client took, by id: tried again only when the request comes again (that client left). */
|
|
24
|
+
this.declined = new Map();
|
|
19
25
|
this.clientTools = new Map(((_a = options.clientTools) !== null && _a !== void 0 ? _a : []).map(tool => [tool.definition.name, tool]));
|
|
26
|
+
this.pageBytes = options.pageBytes;
|
|
20
27
|
}
|
|
21
28
|
get state() {
|
|
22
29
|
return this.current;
|
|
23
30
|
}
|
|
24
31
|
/** Starts following the session. */
|
|
25
32
|
async attach() {
|
|
26
|
-
this.stop.push(this.connection.onEvents(events => this.apply(events)), this.connection.onOpen(() => void this.attachAgain()));
|
|
33
|
+
this.stop.push(this.connection.onEvents(events => this.apply(events)), this.connection.onOpen(() => void this.attachAgain().catch(error => this.lost(error))));
|
|
27
34
|
return (await this.attachAgain()).info;
|
|
28
35
|
}
|
|
29
36
|
/** Stops following it. The session goes on. */
|
|
@@ -46,18 +53,38 @@ export class SessionStore {
|
|
|
46
53
|
prompt(message, input = {}) {
|
|
47
54
|
return this.connection.server.prompt(this.sessionId, { clientMessageId: crypto.randomUUID(), ...input, message });
|
|
48
55
|
}
|
|
56
|
+
/**
|
|
57
|
+
* The service no longer has the session after a reconnect (it restarted, or closed the session while
|
|
58
|
+
* idle): its file stays, to open again.
|
|
59
|
+
*/
|
|
60
|
+
onGone(listener) {
|
|
61
|
+
this.goneListeners.add(listener);
|
|
62
|
+
return () => this.goneListeners.delete(listener);
|
|
63
|
+
}
|
|
49
64
|
respondUi(response) {
|
|
50
65
|
return this.connection.server.respondUi(this.sessionId, response);
|
|
51
66
|
}
|
|
52
67
|
async attachAgain() {
|
|
53
|
-
|
|
68
|
+
var _a, _b;
|
|
69
|
+
const result = await this.connection.server.attach(this.sessionId, this.lastSeq, this.pageBytes ? { recentBytes: this.pageBytes } : undefined);
|
|
70
|
+
let state = this.current;
|
|
54
71
|
if (this.lastSeq === undefined || result.gap) {
|
|
55
|
-
|
|
72
|
+
// The conversation as of lastSeq, with the message being written and the calls running.
|
|
73
|
+
const conversation = (_a = result.conversation) !== null && _a !== void 0 ? _a : { ...(await this.connection.server.getMessages(this.sessionId)), tools: {} };
|
|
74
|
+
const { messages, start } = SessionStore.withEarlier(this.current, conversation.messages, (_b = conversation.start) !== null && _b !== void 0 ? _b : 0);
|
|
75
|
+
const kept = start === this.current.start ? SessionReducer.keep(this.current.messages, messages) : messages;
|
|
76
|
+
state = {
|
|
77
|
+
...this.current,
|
|
78
|
+
messages: kept,
|
|
79
|
+
tools: conversation.tools,
|
|
80
|
+
start,
|
|
81
|
+
runStart: kept === this.current.messages ? this.current.runStart : undefined,
|
|
82
|
+
};
|
|
56
83
|
this.lastSeq = result.lastSeq;
|
|
57
84
|
}
|
|
58
|
-
this.
|
|
59
|
-
|
|
60
|
-
...
|
|
85
|
+
const taken = this.take(state, result.events);
|
|
86
|
+
state = {
|
|
87
|
+
...taken.state,
|
|
61
88
|
pendingUi: result.pendingUi,
|
|
62
89
|
pendingClientTools: result.pendingClientTools,
|
|
63
90
|
working: result.info.isStreaming,
|
|
@@ -66,15 +93,86 @@ export class SessionStore {
|
|
|
66
93
|
// What the extensions show now, whatever events were missed.
|
|
67
94
|
state = result.shownUi.reduce(SessionReducer.reduce, { ...state, status: {}, widgets: {} });
|
|
68
95
|
}
|
|
96
|
+
// Once, however much changed: what is drawn changes in one frame.
|
|
69
97
|
this.update(state);
|
|
98
|
+
this.applied(taken);
|
|
70
99
|
return result;
|
|
71
100
|
}
|
|
101
|
+
/**
|
|
102
|
+
* The latest messages, after the earlier ones the store had if they are still the same where the
|
|
103
|
+
* latest start: a reconnect does not drop what was loaded further up.
|
|
104
|
+
*/
|
|
105
|
+
static withEarlier(current, messages, start) {
|
|
106
|
+
const at = start - current.start;
|
|
107
|
+
const had = current.messages[at];
|
|
108
|
+
const first = messages[0];
|
|
109
|
+
if (at > 0 && had && first && had.role === first.role && had.timestamp === first.timestamp) {
|
|
110
|
+
return { messages: [...current.messages.slice(0, at), ...messages], start: current.start };
|
|
111
|
+
}
|
|
112
|
+
return { messages, start };
|
|
113
|
+
}
|
|
114
|
+
lost(error) {
|
|
115
|
+
if ((error === null || error === void 0 ? void 0 : error.code) === TaErrorCode.SESSION_NOT_FOUND) {
|
|
116
|
+
for (const listener of [...this.goneListeners]) {
|
|
117
|
+
listener();
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* The messages before those it has, about `pageBytes` of them, put in front: once they are there, or
|
|
123
|
+
* at once when it has them all. Called again while they come, it waits for the same.
|
|
124
|
+
*/
|
|
125
|
+
loadEarlier() {
|
|
126
|
+
var _a;
|
|
127
|
+
if (this.current.start === 0) {
|
|
128
|
+
return Promise.resolve();
|
|
129
|
+
}
|
|
130
|
+
(_a = this.loadingEarlier) !== null && _a !== void 0 ? _a : (this.loadingEarlier = this.fetchEarlier().finally(() => {
|
|
131
|
+
this.loadingEarlier = undefined;
|
|
132
|
+
}));
|
|
133
|
+
return this.loadingEarlier;
|
|
134
|
+
}
|
|
135
|
+
/** All the messages of the conversation, for what needs the whole of it (an export). */
|
|
136
|
+
async loadAll() {
|
|
137
|
+
while (this.current.start > 0) {
|
|
138
|
+
await this.loadEarlier();
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
async fetchEarlier() {
|
|
142
|
+
var _a;
|
|
143
|
+
const { start, messages } = this.current;
|
|
144
|
+
const first = messages[0];
|
|
145
|
+
const page = await this.connection.server.getEarlierMessages(this.sessionId, start, first === null || first === void 0 ? void 0 : first.timestamp, (_a = this.pageBytes) !== null && _a !== void 0 ? _a : 0);
|
|
146
|
+
// Loaded again meanwhile: this part may not be the one before.
|
|
147
|
+
if (this.current.messages[0] !== first) {
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
if (!page.found) {
|
|
151
|
+
await this.reload();
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
const { runStart } = this.current;
|
|
155
|
+
this.update({
|
|
156
|
+
...this.current,
|
|
157
|
+
messages: [...page.messages, ...this.current.messages],
|
|
158
|
+
start: page.start,
|
|
159
|
+
runStart: runStart === undefined ? undefined : runStart + page.messages.length,
|
|
160
|
+
});
|
|
161
|
+
}
|
|
72
162
|
async reload() {
|
|
73
|
-
const { messages } =
|
|
74
|
-
|
|
163
|
+
const { messages, start } = this.pageBytes
|
|
164
|
+
? await this.connection.server.getEarlierMessages(this.sessionId, undefined, undefined, this.pageBytes)
|
|
165
|
+
: { ...(await this.connection.server.getMessages(this.sessionId)), start: 0 };
|
|
166
|
+
this.update({ ...this.current, messages, start, tools: {}, runStart: undefined });
|
|
75
167
|
}
|
|
76
168
|
apply(events) {
|
|
77
|
-
|
|
169
|
+
const taken = this.take(this.current, events);
|
|
170
|
+
// One notification per batch: a UI renders once however many deltas arrived.
|
|
171
|
+
this.update(taken.state);
|
|
172
|
+
this.applied(taken);
|
|
173
|
+
}
|
|
174
|
+
/** `state` with the events of this session not taken yet. */
|
|
175
|
+
take(state, events) {
|
|
78
176
|
let replaced = false;
|
|
79
177
|
const applied = [];
|
|
80
178
|
for (const { sessionId, seq, event } of events) {
|
|
@@ -86,8 +184,10 @@ export class SessionStore {
|
|
|
86
184
|
replaced || (replaced = event.type === 'session_replaced');
|
|
87
185
|
applied.push(event);
|
|
88
186
|
}
|
|
89
|
-
|
|
90
|
-
|
|
187
|
+
return { state, applied, replaced };
|
|
188
|
+
}
|
|
189
|
+
/** Once the state has the events: their listeners, and the conversation read again if it was replaced. */
|
|
190
|
+
applied({ applied, replaced }) {
|
|
91
191
|
for (const event of applied) {
|
|
92
192
|
for (const listener of this.eventListeners) {
|
|
93
193
|
listener(event);
|
|
@@ -109,22 +209,33 @@ export class SessionStore {
|
|
|
109
209
|
runClientTools(state) {
|
|
110
210
|
for (const request of state.pendingClientTools) {
|
|
111
211
|
const tool = this.clientTools.get(request.toolName);
|
|
112
|
-
if (tool && !this.running.has(request.id)) {
|
|
212
|
+
if (tool && !this.running.has(request.id) && this.declined.get(request.id) !== request) {
|
|
113
213
|
this.running.add(request.id);
|
|
114
214
|
void this.answer(tool, request);
|
|
115
215
|
}
|
|
116
216
|
}
|
|
117
|
-
for (const
|
|
118
|
-
|
|
119
|
-
|
|
217
|
+
for (const calls of [this.results, this.declined]) {
|
|
218
|
+
for (const id of calls.keys()) {
|
|
219
|
+
if (!state.pendingClientTools.some(request => request.id === id)) {
|
|
220
|
+
calls.delete(id);
|
|
221
|
+
}
|
|
120
222
|
}
|
|
121
223
|
}
|
|
122
224
|
}
|
|
123
|
-
/**
|
|
225
|
+
/**
|
|
226
|
+
* Runs a call once, if this client takes it: every page of the user gets it. A result that could not be
|
|
227
|
+
* sent is sent again after a reconnect, not made again.
|
|
228
|
+
*/
|
|
124
229
|
async answer(tool, request) {
|
|
125
230
|
try {
|
|
126
231
|
let result = this.results.get(request.id);
|
|
127
232
|
if (!result) {
|
|
233
|
+
// Not asked again before the request comes again, also when the connection was lost: the reconnect brings it.
|
|
234
|
+
this.declined.set(request.id, request);
|
|
235
|
+
if (!(await this.claim(request))) {
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
this.declined.delete(request.id);
|
|
128
239
|
result = await this.run(tool, request);
|
|
129
240
|
this.results.set(request.id, result);
|
|
130
241
|
}
|
|
@@ -138,6 +249,15 @@ export class SessionStore {
|
|
|
138
249
|
this.running.delete(request.id);
|
|
139
250
|
}
|
|
140
251
|
}
|
|
252
|
+
/** 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
|
+
claim(request) {
|
|
254
|
+
return this.connection.server.claimClientTool(this.sessionId, request.id).catch(error => {
|
|
255
|
+
if ((error === null || error === void 0 ? void 0 : error.code) === METHOD_NOT_FOUND) {
|
|
256
|
+
return true;
|
|
257
|
+
}
|
|
258
|
+
throw error;
|
|
259
|
+
});
|
|
260
|
+
}
|
|
141
261
|
async run(tool, request) {
|
|
142
262
|
try {
|
|
143
263
|
return { id: request.id, output: await tool.run(request.input, request) };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type TaAuthEvent, type TaAuthServer, TaErrorCode, type TaEventEnvelope, type TaPackageServer, type TaRelayServer, type TaRemoteEvent, type TaRemoteServer, type TaServer, type TaSettingsServer, type TaTerminalServer, type TaWorkspaceServer } from '@celljs/ta-protocol';
|
|
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
2
|
/** A failed call. `code` is set for failures the server names. */
|
|
3
3
|
export declare class TaRemoteError extends Error {
|
|
4
4
|
readonly code?: TaErrorCode | undefined;
|
|
@@ -14,6 +14,11 @@ export interface TaConnectionOptions {
|
|
|
14
14
|
reconnectDelayMs?: number;
|
|
15
15
|
/** Default 10000. */
|
|
16
16
|
maxReconnectDelayMs?: number;
|
|
17
|
+
/**
|
|
18
|
+
* How long a call made while the connection is down waits for it to come back before it fails, so
|
|
19
|
+
* that a short drop goes unnoticed. Default 5000; 0 fails at once.
|
|
20
|
+
*/
|
|
21
|
+
waitForOpenMs?: number;
|
|
17
22
|
/**
|
|
18
23
|
* Another way to ta serve than a WebSocket to `url`, such as a relay (RelaySocket of @celljs/ta-relay):
|
|
19
24
|
* a new socket for each connection, which takes care of access itself.
|
|
@@ -50,7 +55,9 @@ type ReconnectingListener = (delayMs: number, attempt: number) => void;
|
|
|
50
55
|
* attaching again ({@link SessionStore} does). Each service of ta serve is a property; all of them go
|
|
51
56
|
* over the one WebSocket.
|
|
52
57
|
*
|
|
53
|
-
*
|
|
58
|
+
* 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 and are not sent again, because only
|
|
60
|
+
* the caller knows whether to resend.
|
|
54
61
|
*/
|
|
55
62
|
export declare class TaConnection {
|
|
56
63
|
protected readonly options: TaConnectionOptions;
|
|
@@ -60,6 +67,9 @@ export declare class TaConnection {
|
|
|
60
67
|
readonly settings: TaSettingsServer;
|
|
61
68
|
readonly packages: TaPackageServer;
|
|
62
69
|
readonly auth: TaAuthServer;
|
|
70
|
+
readonly access: TaAccessServer;
|
|
71
|
+
/** Behind `ta gateway` only: a Ta service alone does not have it. */
|
|
72
|
+
readonly gateway: TaGatewayServer;
|
|
63
73
|
readonly relay: TaRelayServer;
|
|
64
74
|
readonly remote: TaRemoteServer;
|
|
65
75
|
protected socket?: TaSocket;
|
|
@@ -76,6 +86,11 @@ export declare class TaConnection {
|
|
|
76
86
|
protected readonly openListeners: Set<OpenListener>;
|
|
77
87
|
protected readonly closeListeners: Set<CloseListener>;
|
|
78
88
|
protected readonly reconnectingListeners: Set<ReconnectingListener>;
|
|
89
|
+
/** The calls waiting for the connection to open: `go` once it is, `fail` when it is closed. */
|
|
90
|
+
protected readonly waiting: Set<{
|
|
91
|
+
go(): void;
|
|
92
|
+
fail(): void;
|
|
93
|
+
}>;
|
|
79
94
|
constructor(options: TaConnectionOptions);
|
|
80
95
|
/** Resolves when the first connection is open, or rejects if it cannot be made; later losses reconnect. */
|
|
81
96
|
connect(): Promise<void>;
|
|
@@ -96,10 +111,20 @@ export declare class TaConnection {
|
|
|
96
111
|
onReconnecting(listener: ReconnectingListener): () => void;
|
|
97
112
|
/** While the connection is down, tries again now rather than at the end of the wait, which starts over; otherwise does nothing. */
|
|
98
113
|
reconnect(): void;
|
|
114
|
+
/**
|
|
115
|
+
* After the device slept or its network changed, when a connection may be gone without a word: one
|
|
116
|
+
* that is down is tried at once, and an open one that does not answer within `timeoutMs` is given up
|
|
117
|
+
* and made again at once, rather than when the system notices.
|
|
118
|
+
*/
|
|
119
|
+
wake(timeoutMs?: number): void;
|
|
99
120
|
/** With `resolve` and `reject`: the first connection, whose failure is the caller's to handle. */
|
|
100
121
|
protected open(resolve?: () => void, reject?: (error: Error) => void): void;
|
|
122
|
+
/** The connection on `socket` is gone: the calls sent on it fail, and another is made, `atOnce` or after the wait. */
|
|
123
|
+
protected lost(socket: TaSocket, opened: boolean, atOnce?: boolean): void;
|
|
101
124
|
protected createWebSocket(): TaSocket;
|
|
102
125
|
protected scheduleReconnect(): void;
|
|
126
|
+
/** Resolves once the connection is open, or rejects after `waitForOpenMs`, or at once when it is closed. */
|
|
127
|
+
protected opened(): Promise<void>;
|
|
103
128
|
protected failPending(): void;
|
|
104
129
|
protected service<T extends object>(name: string): T;
|
|
105
130
|
protected call(service: string, method: string, params: unknown[]): Promise<unknown>;
|