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