@celljs/ta-client 4.9.1 → 4.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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 { TaConnection } from './ta-connection.js';
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: TaConnection;
57
+ protected readonly connection: SessionConnection;
34
58
  readonly sessionId: string;
59
+ /** The session as the service told it. */
35
60
  protected current: SessionState;
61
+ /** `current` with the messages sent from here on their way: what UIs get. */
62
+ protected shown: SessionState;
63
+ protected sent: Sent[];
36
64
  protected lastSeq?: number;
37
65
  protected readonly listeners: Set<Listener>;
38
66
  protected readonly eventListeners: Set<(event: TaEvent) => void>;
@@ -48,24 +76,74 @@ export declare class SessionStore {
48
76
  protected readonly pageBytes?: number;
49
77
  /** The earlier messages on their way. */
50
78
  protected loadingEarlier?: Promise<void>;
51
- constructor(connection: TaConnection, sessionId: string, options?: SessionStoreOptions);
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
- /** Starts following the session. */
54
- attach(): Promise<TaSessionInfo>;
85
+ /** The conversation as the session has it, without the messages sent from here on their way: for another store of it to start from. */
86
+ get snapshot(): SessionSnapshot;
87
+ /**
88
+ * Starts following the session; `attached`: what opening it attached already (TaOpenedSession.attached),
89
+ * taken at once, in the same turn of the event loop as its answer, so that no event after it is missed.
90
+ */
91
+ attach(attached?: TaAttachResult): Promise<TaSessionInfo>;
55
92
  /** Stops following it. The session goes on. */
56
93
  detach(): Promise<void>;
57
94
  subscribe(listener: Listener): () => void;
58
95
  /** Each new event of the session, once the state has taken it in. */
59
96
  onEvent(listener: (event: TaEvent) => void): () => void;
60
- /** Sends a message with a new id; a resend after a lost connection must reuse the id. */
97
+ /**
98
+ * Sends a message with a new id; a resend after a lost connection must reuse the id. Sent while the
99
+ * agent is idle, it shows at once at the end of the conversation, with the agent at work, until the
100
+ * session has it (a command, which may add none, does not).
101
+ */
61
102
  prompt(message: string, input?: Partial<TaPromptInput>): Promise<TaPromptReceipt>;
103
+ /**
104
+ * As `prompt`, for what the user typed: a message that fails to go stays in the conversation, marked
105
+ * failed, to send again (`resend`) or take back (`discard`), and this resolves without a receipt. One
106
+ * the connection could not take is not failed: it stays on its way and goes once the store is attached
107
+ * again, as a chat app sends what was typed without network once it is back; only after `holdMs`
108
+ * without a connection does it show as failed.
109
+ */
110
+ send(message: string, input?: Partial<TaPromptInput>): Promise<TaPromptReceipt | undefined>;
111
+ /** Sends again a message that failed, with its id: one that reached the service after all runs once. */
112
+ resend(id: string): Promise<void>;
113
+ /**
114
+ * Takes on the messages that failed to go from another store of the same conversation (one that showed
115
+ * it before this one attached, without the computer), to send again from here.
116
+ */
117
+ carry(from: SessionStore): void;
118
+ /** Takes back a message that failed. */
119
+ discard(id: string): void;
120
+ protected deliver(message: string, input: Partial<TaPromptInput>, keep: boolean): Promise<TaPromptReceipt>;
121
+ /** Sends a message shown as sent, and settles it by the answer. */
122
+ protected go(sent: Sent, full: TaPromptInput, keep: boolean): Promise<TaPromptReceipt>;
123
+ protected add(input: TaPromptInput): Sent;
124
+ /** Keeps a message the connection could not take on its way, unless it waited `holdMs` already. */
125
+ protected hold(sent: Sent): boolean;
126
+ /** The messages held `holdMs` that are not going now show as failed. */
127
+ protected expireHeld(): void;
128
+ /** Attached again: the messages held go now, with their ids, so that one the service had after all runs once. */
129
+ protected sendHeld(): void;
130
+ protected fail(sent: Sent, error: unknown): void;
131
+ protected unsend(sent: Sent): void;
132
+ /** The message sent, once the session has a message of the user: the one of the same text, else the first. */
133
+ protected arrived(message: SessionMessage): void;
134
+ protected static textOf(message: SessionMessage): string | undefined;
135
+ /**
136
+ * `state` with the messages sent from here after it (`outbox` says which they are), and the agent at
137
+ * work for those on their way.
138
+ */
139
+ static withSent(state: SessionState, sent: readonly OutboxMessage[]): SessionState;
62
140
  /**
63
141
  * The service no longer has the session after a reconnect (it restarted, or closed the session while
64
142
  * idle): its file stays, to open again.
65
143
  */
66
144
  onGone(listener: () => void): () => void;
67
145
  respondUi(response: RpcExtensionUIResponse): Promise<boolean>;
68
- protected attachAgain(): Promise<TaAttachResult>;
146
+ protected attachAgain(attached?: TaAttachResult): Promise<TaAttachResult>;
69
147
  /**
70
148
  * The latest messages, after the earlier ones the store had if they are still the same where the
71
149
  * latest start: a reconnect does not drop what was loaded further up.
@@ -90,6 +168,8 @@ export declare class SessionStore {
90
168
  /** Once the state has the events: their listeners, and the conversation read again if it was replaced. */
91
169
  protected applied({ applied, replaced }: Taken): void;
92
170
  protected update(state: SessionState): void;
171
+ /** UIs get the state with the messages sent, when either changed. */
172
+ protected show(): void;
93
173
  protected runClientTools(state: SessionState): void;
94
174
  /**
95
175
  * Runs a call once, if this client takes it: every page of the user gets it. A result that could not be
@@ -1,17 +1,22 @@
1
1
  import { TaErrorCode, } from '@celljs/ta-protocol';
2
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;
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,16 +27,31 @@ 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.current;
41
+ return this.shown;
30
42
  }
31
- /** Starts following the session. */
32
- async attach() {
43
+ /** The conversation as the session has it, without the messages sent from here on their way: for another store of it to start from. */
44
+ get snapshot() {
45
+ const { messages, start, tools } = this.current;
46
+ return { messages, start, tools };
47
+ }
48
+ /**
49
+ * Starts following the session; `attached`: what opening it attached already (TaOpenedSession.attached),
50
+ * taken at once, in the same turn of the event loop as its answer, so that no event after it is missed.
51
+ */
52
+ async attach(attached) {
33
53
  this.stop.push(this.connection.onEvents(events => this.apply(events)), this.connection.onOpen(() => void this.attachAgain().catch(error => this.lost(error))));
34
- return (await this.attachAgain()).info;
54
+ return (await this.attachAgain(attached)).info;
35
55
  }
36
56
  /** Stops following it. The session goes on. */
37
57
  async detach() {
@@ -49,9 +69,194 @@ export class SessionStore {
49
69
  this.eventListeners.add(listener);
50
70
  return () => this.eventListeners.delete(listener);
51
71
  }
52
- /** Sends a message with a new id; a resend after a lost connection must reuse the id. */
72
+ /**
73
+ * Sends a message with a new id; a resend after a lost connection must reuse the id. Sent while the
74
+ * agent is idle, it shows at once at the end of the conversation, with the agent at work, until the
75
+ * session has it (a command, which may add none, does not).
76
+ */
53
77
  prompt(message, input = {}) {
54
- return this.connection.server.prompt(this.sessionId, { clientMessageId: crypto.randomUUID(), ...input, message });
78
+ return this.deliver(message, input, false);
79
+ }
80
+ /**
81
+ * As `prompt`, for what the user typed: a message that fails to go stays in the conversation, marked
82
+ * failed, to send again (`resend`) or take back (`discard`), and this resolves without a receipt. One
83
+ * the connection could not take is not failed: it stays on its way and goes once the store is attached
84
+ * again, as a chat app sends what was typed without network once it is back; only after `holdMs`
85
+ * without a connection does it show as failed.
86
+ */
87
+ async send(message, input = {}) {
88
+ try {
89
+ return await this.deliver(message, input, true);
90
+ }
91
+ catch (error) {
92
+ if (this.sent.some(sent => (sent.failed || sent.heldAt) && sent.text === message)) {
93
+ return undefined;
94
+ }
95
+ throw error;
96
+ }
97
+ }
98
+ /** Sends again a message that failed, with its id: one that reached the service after all runs once. */
99
+ async resend(id) {
100
+ const sent = this.sent.find(candidate => candidate.id === id && candidate.failed);
101
+ if (!sent) {
102
+ return;
103
+ }
104
+ this.sent = this.sent.filter(other => other !== sent);
105
+ await this.send(sent.text, { ...sent.input, clientMessageId: sent.id }).catch(() => undefined);
106
+ }
107
+ /**
108
+ * Takes on the messages that failed to go from another store of the same conversation (one that showed
109
+ * it before this one attached, without the computer), to send again from here.
110
+ */
111
+ carry(from) {
112
+ const failed = from.sent.filter(sent => (sent.failed || sent.heldAt) && !this.sent.some(other => other.id === sent.id));
113
+ if (failed.length) {
114
+ this.sent = [...this.sent, ...failed];
115
+ this.show();
116
+ if (this.lastSeq !== undefined) {
117
+ this.sendHeld();
118
+ }
119
+ }
120
+ }
121
+ /** Takes back a message that failed. */
122
+ discard(id) {
123
+ const sent = this.sent.find(candidate => candidate.id === id);
124
+ if (sent) {
125
+ this.unsend(sent);
126
+ }
127
+ }
128
+ deliver(message, input, keep) {
129
+ const full = { clientMessageId: crypto.randomUUID(), ...input, message };
130
+ const sent = this.current.working || message.startsWith('/') ? undefined : this.add(full);
131
+ if (!sent) {
132
+ return this.connection.server.prompt(this.sessionId, full);
133
+ }
134
+ return this.go(sent, full, keep);
135
+ }
136
+ /** Sends a message shown as sent, and settles it by the answer. */
137
+ go(sent, full, keep) {
138
+ return this.connection.server.prompt(this.sessionId, full).then(result => {
139
+ sent.heldAt = undefined;
140
+ if (result.status === 'accepted') {
141
+ sent.accepted = true;
142
+ }
143
+ else {
144
+ // Queued after another run, sent before, or taken by an extension: no message of it comes now.
145
+ this.unsend(sent);
146
+ }
147
+ return result;
148
+ }, error => {
149
+ if (keep && TaRemoteError.isConnectionLost(error) && this.hold(sent)) {
150
+ throw error;
151
+ }
152
+ if (keep) {
153
+ this.fail(sent, error);
154
+ }
155
+ else {
156
+ this.unsend(sent);
157
+ }
158
+ throw error;
159
+ });
160
+ }
161
+ add(input) {
162
+ var _a;
163
+ const message = { role: 'user', content: [{ type: 'text', text: input.message }, ...((_a = input.images) !== null && _a !== void 0 ? _a : [])], timestamp: Date.now() };
164
+ const { message: _text, clientMessageId: _id, ...rest } = input;
165
+ const sent = { id: input.clientMessageId, message, text: input.message, input: rest, accepted: false };
166
+ this.sent = [...this.sent, sent];
167
+ this.show();
168
+ return sent;
169
+ }
170
+ /** Keeps a message the connection could not take on its way, unless it waited `holdMs` already. */
171
+ hold(sent) {
172
+ var _a, _b;
173
+ if (!this.sent.includes(sent)) {
174
+ return false;
175
+ }
176
+ (_a = sent.heldAt) !== null && _a !== void 0 ? _a : (sent.heldAt = Date.now());
177
+ if (Date.now() - sent.heldAt >= this.holdMs) {
178
+ return false;
179
+ }
180
+ (_b = this.holdTimer) !== null && _b !== void 0 ? _b : (this.holdTimer = setTimeout(() => this.expireHeld(), sent.heldAt + this.holdMs - Date.now()));
181
+ return true;
182
+ }
183
+ /** The messages held `holdMs` that are not going now show as failed. */
184
+ expireHeld() {
185
+ this.holdTimer = undefined;
186
+ const now = Date.now();
187
+ let next = Number.POSITIVE_INFINITY;
188
+ for (const sent of this.sent) {
189
+ if (sent.heldAt === undefined || sent.failed || this.resending.has(sent)) {
190
+ continue;
191
+ }
192
+ if (now - sent.heldAt >= this.holdMs) {
193
+ this.fail(sent, TaRemoteError.notConnected());
194
+ }
195
+ else {
196
+ next = Math.min(next, sent.heldAt + this.holdMs - now);
197
+ }
198
+ }
199
+ if (next !== Number.POSITIVE_INFINITY) {
200
+ this.holdTimer = setTimeout(() => this.expireHeld(), next);
201
+ }
202
+ }
203
+ /** Attached again: the messages held go now, with their ids, so that one the service had after all runs once. */
204
+ sendHeld() {
205
+ for (const sent of this.sent) {
206
+ if (sent.heldAt === undefined || sent.failed || this.resending.has(sent)) {
207
+ continue;
208
+ }
209
+ this.resending.add(sent);
210
+ void this.go(sent, { ...sent.input, clientMessageId: sent.id, message: sent.text }, true)
211
+ .catch(() => undefined)
212
+ .finally(() => this.resending.delete(sent));
213
+ }
214
+ }
215
+ fail(sent, error) {
216
+ if (this.sent.includes(sent)) {
217
+ const failed = { ...sent, failed: error instanceof Error ? error.message : String(error) };
218
+ this.sent = this.sent.map(other => (other === sent ? failed : other));
219
+ this.show();
220
+ }
221
+ }
222
+ unsend(sent) {
223
+ if (this.sent.includes(sent)) {
224
+ this.sent = this.sent.filter(other => other !== sent);
225
+ this.show();
226
+ }
227
+ }
228
+ /** The message sent, once the session has a message of the user: the one of the same text, else the first. */
229
+ arrived(message) {
230
+ var _a;
231
+ const waiting = this.sent.filter(sent => !sent.failed);
232
+ const text = SessionStore.textOf(message);
233
+ const sent = (_a = waiting.find(candidate => candidate.text === text)) !== null && _a !== void 0 ? _a : waiting[0];
234
+ this.sent = this.sent.filter(other => other !== sent);
235
+ }
236
+ static textOf(message) {
237
+ const { content } = message;
238
+ if (typeof content === 'string') {
239
+ return content;
240
+ }
241
+ const first = Array.isArray(content) ? content[0] : undefined;
242
+ return (first === null || first === void 0 ? void 0 : first.type) === 'text' ? first.text : undefined;
243
+ }
244
+ /**
245
+ * `state` with the messages sent from here after it (`outbox` says which they are), and the agent at
246
+ * work for those on their way.
247
+ */
248
+ static withSent(state, sent) {
249
+ if (!sent.length) {
250
+ return state;
251
+ }
252
+ const going = sent.some(message => !message.failed);
253
+ return {
254
+ ...state,
255
+ messages: [...state.messages, ...sent.map(message => message.message)],
256
+ outbox: sent,
257
+ working: state.working || going,
258
+ runStart: state.working || !going ? state.runStart : state.messages.length,
259
+ };
55
260
  }
56
261
  /**
57
262
  * The service no longer has the session after a reconnect (it restarted, or closed the session while
@@ -64,15 +269,16 @@ export class SessionStore {
64
269
  respondUi(response) {
65
270
  return this.connection.server.respondUi(this.sessionId, response);
66
271
  }
67
- async attachAgain() {
272
+ async attachAgain(attached) {
68
273
  var _a, _b;
69
- const result = await this.connection.server.attach(this.sessionId, this.lastSeq, this.pageBytes ? { recentBytes: this.pageBytes } : undefined);
274
+ const result = attached !== null && attached !== void 0 ? attached : (await this.connection.server.attach(this.sessionId, this.lastSeq, this.pageBytes ? { recentBytes: this.pageBytes } : undefined));
70
275
  let state = this.current;
71
- if (this.lastSeq === undefined || result.gap) {
276
+ // A conversation given (one attached as it opened) is the session's from scratch, whatever this store had.
277
+ if (this.lastSeq === undefined || result.gap || (attached === null || attached === void 0 ? void 0 : attached.conversation)) {
72
278
  // The conversation as of lastSeq, with the message being written and the calls running.
73
279
  const conversation = (_a = result.conversation) !== null && _a !== void 0 ? _a : { ...(await this.connection.server.getMessages(this.sessionId)), tools: {} };
74
280
  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;
281
+ const kept = SessionReducer.keep(this.current.messages, messages, start - this.current.start);
76
282
  state = {
77
283
  ...this.current,
78
284
  messages: kept,
@@ -81,6 +287,8 @@ export class SessionStore {
81
287
  runStart: kept === this.current.messages ? this.current.runStart : undefined,
82
288
  };
83
289
  this.lastSeq = result.lastSeq;
290
+ // The conversation of the service has those it took.
291
+ this.sent = this.sent.filter(sent => !sent.accepted);
84
292
  }
85
293
  const taken = this.take(state, result.events);
86
294
  state = {
@@ -96,6 +304,7 @@ export class SessionStore {
96
304
  // Once, however much changed: what is drawn changes in one frame.
97
305
  this.update(state);
98
306
  this.applied(taken);
307
+ this.sendHeld();
99
308
  return result;
100
309
  }
101
310
  /**
@@ -181,6 +390,15 @@ export class SessionStore {
181
390
  }
182
391
  this.lastSeq = seq;
183
392
  state = SessionReducer.reduce(state, event);
393
+ if (this.sent.length) {
394
+ if (event.type === 'message_start' && event.message.role === 'user') {
395
+ this.arrived(event.message);
396
+ }
397
+ else if (event.type === 'agent_settled') {
398
+ // Its run ended without it as sent (an extension changed it): it no longer waits.
399
+ this.sent = this.sent.filter(sent => !sent.accepted);
400
+ }
401
+ }
184
402
  replaced || (replaced = event.type === 'session_replaced');
185
403
  applied.push(event);
186
404
  }
@@ -200,12 +418,18 @@ export class SessionStore {
200
418
  update(state) {
201
419
  if (state !== this.current) {
202
420
  this.current = state;
203
- for (const listener of this.listeners) {
204
- listener(state);
205
- }
421
+ this.show();
206
422
  this.runClientTools(state);
207
423
  }
208
424
  }
425
+ /** UIs get the state with the messages sent, when either changed. */
426
+ show() {
427
+ const shown = SessionStore.withSent(this.current, this.sent.map(({ id, message, failed }) => (failed ? { id, message, failed } : { id, message })));
428
+ this.shown = shown;
429
+ for (const listener of this.listeners) {
430
+ listener(shown);
431
+ }
432
+ }
209
433
  runClientTools(state) {
210
434
  for (const request of state.pendingClientTools) {
211
435
  const tool = this.clientTools.get(request.toolName);
@@ -252,7 +476,7 @@ export class SessionStore {
252
476
  /** 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
477
  claim(request) {
254
478
  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) {
479
+ if (TaRemoteError.isMethodNotFound(error)) {
256
480
  return true;
257
481
  }
258
482
  throw error;