tandem-kit-chat 0.0.0 → 0.1.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/LICENSE +21 -0
- package/README.md +38 -1
- package/dist/src/chats.d.ts +27 -0
- package/dist/src/chats.js +108 -0
- package/dist/src/commands.d.ts +22 -0
- package/dist/src/commands.js +43 -0
- package/dist/src/controller.d.ts +143 -0
- package/dist/src/controller.js +600 -0
- package/dist/src/fake.d.ts +59 -0
- package/dist/src/fake.js +98 -0
- package/dist/src/focus.d.ts +29 -0
- package/dist/src/focus.js +61 -0
- package/dist/src/format.d.ts +88 -0
- package/dist/src/format.js +174 -0
- package/dist/src/index.d.ts +13 -0
- package/dist/src/index.js +13 -0
- package/dist/src/labels.d.ts +156 -0
- package/dist/src/labels.js +162 -0
- package/dist/src/locales.d.ts +21 -0
- package/dist/src/locales.js +474 -0
- package/dist/src/queue.d.ts +23 -0
- package/dist/src/queue.js +42 -0
- package/dist/src/reduce.d.ts +5 -0
- package/dist/src/reduce.js +318 -0
- package/dist/src/store.d.ts +10 -0
- package/dist/src/store.js +21 -0
- package/dist/src/tools.d.ts +9 -0
- package/dist/src/tools.js +23 -0
- package/dist/src/transport.d.ts +69 -0
- package/dist/src/transport.js +27 -0
- package/dist/src/types.d.ts +191 -0
- package/dist/src/types.js +1 -0
- package/package.json +40 -4
|
@@ -0,0 +1,600 @@
|
|
|
1
|
+
import { SlashRegistry } from "./commands.js";
|
|
2
|
+
import { ChatDirectory } from "./chats.js";
|
|
3
|
+
import { decodeMessage, encodeAttachments, encodeFocus, kindOfType, bytesText } from "./focus.js";
|
|
4
|
+
import { createLabels } from "./labels.js";
|
|
5
|
+
import { MessageQueue } from "./queue.js";
|
|
6
|
+
import { initialChatState, reduce } from "./reduce.js";
|
|
7
|
+
import { Store } from "./store.js";
|
|
8
|
+
export const DEFAULT_ATTACHMENT_POLICY = { maxFiles: 5, maxBytes: 5 * 1024 * 1024, maxInlineBytes: 64 * 1024, deliver: 'auto', images: 'ref' };
|
|
9
|
+
const DATA_URL = /^data:(image\/[A-Za-z0-9][A-Za-z0-9.+-]*);base64,([A-Za-z0-9+/]+={0,2})$/;
|
|
10
|
+
function imagePart(attachment) {
|
|
11
|
+
const match = attachment.kind === 'image' && attachment.dataUrl ? DATA_URL.exec(attachment.dataUrl) : null;
|
|
12
|
+
return match ? { media_type: match[1], data: match[2], name: attachment.name } : null;
|
|
13
|
+
}
|
|
14
|
+
const EPHEMERAL_FLUSH = new Set(['text_delta', 'thinking', 'context', 'usage']);
|
|
15
|
+
const wait = (ms, signal) => new Promise((resolve) => {
|
|
16
|
+
const timer = setTimeout(resolve, ms);
|
|
17
|
+
signal.addEventListener('abort', () => (clearTimeout(timer), resolve()), { once: true });
|
|
18
|
+
});
|
|
19
|
+
const messageOf = (error) => (error instanceof Error ? error.message : String(error));
|
|
20
|
+
const codeOf = (error) => error?.code;
|
|
21
|
+
export function defaultCommands() {
|
|
22
|
+
return [
|
|
23
|
+
{
|
|
24
|
+
name: 'help',
|
|
25
|
+
description: 'list the commands',
|
|
26
|
+
run: (chat) => {
|
|
27
|
+
const lines = chat.commands.list().map((c) => `/${c.name}${c.usage ? ` ${c.usage}` : ''} - ${c.description}`);
|
|
28
|
+
chat.notify('info', `${chat.labels.helpTitle}\n${lines.join('\n')}`);
|
|
29
|
+
},
|
|
30
|
+
},
|
|
31
|
+
{ name: 'stop', description: 'stop the agent', run: (chat) => chat.stop() },
|
|
32
|
+
{ name: 'compact', description: 'summarise the conversation to free context', usage: '[instructions]', run: (chat, args) => chat.compact(args || undefined) },
|
|
33
|
+
{ name: 'clear', description: 'start a fresh chat', run: (chat) => chat.newChat() },
|
|
34
|
+
{
|
|
35
|
+
name: 'model',
|
|
36
|
+
description: 'switch model',
|
|
37
|
+
usage: '<id>',
|
|
38
|
+
run: (chat, args) => (args ? chat.configure({ model: args }) : chat.notify('info', chat.snapshot.chat.session.settings?.model ?? 'default model')),
|
|
39
|
+
},
|
|
40
|
+
{ name: 'effort', description: 'set the effort level', usage: '<level>', run: (chat, args) => chat.configure({ effort: args || null }) },
|
|
41
|
+
{ name: 'mode', description: 'set the permission mode', usage: '<mode>', run: (chat, args) => chat.configure({ permission_mode: args }) },
|
|
42
|
+
{
|
|
43
|
+
name: 'plan',
|
|
44
|
+
description: 'toggle plan mode',
|
|
45
|
+
run: (chat) => chat.configure({ permission_mode: chat.snapshot.chat.session.settings?.permission_mode === 'plan' ? 'ask' : 'plan' }),
|
|
46
|
+
},
|
|
47
|
+
];
|
|
48
|
+
}
|
|
49
|
+
export class ChatController extends Store {
|
|
50
|
+
transport;
|
|
51
|
+
commands;
|
|
52
|
+
queue = new MessageQueue();
|
|
53
|
+
labels;
|
|
54
|
+
options;
|
|
55
|
+
storage;
|
|
56
|
+
storageKey;
|
|
57
|
+
clock;
|
|
58
|
+
directory;
|
|
59
|
+
policy;
|
|
60
|
+
attachmentCount = 0;
|
|
61
|
+
abort = null;
|
|
62
|
+
generation = 0;
|
|
63
|
+
timer = null;
|
|
64
|
+
disposed = false;
|
|
65
|
+
constructor(options) {
|
|
66
|
+
const storage = options.storage ?? null;
|
|
67
|
+
const key = options.storageKey ?? 'tandem-chat';
|
|
68
|
+
super({
|
|
69
|
+
chat: initialChatState(),
|
|
70
|
+
sessionId: null,
|
|
71
|
+
connection: 'idle',
|
|
72
|
+
queue: [],
|
|
73
|
+
steerId: null,
|
|
74
|
+
sending: false,
|
|
75
|
+
busy: false,
|
|
76
|
+
draft: storage?.getItem(`${key}:draft`) ?? '',
|
|
77
|
+
focus: options.focus ?? null,
|
|
78
|
+
references: options.references ?? [],
|
|
79
|
+
attachments: [],
|
|
80
|
+
editing: null,
|
|
81
|
+
hidden: [],
|
|
82
|
+
chats: [],
|
|
83
|
+
error: null,
|
|
84
|
+
info: null,
|
|
85
|
+
sessions: [],
|
|
86
|
+
loaded: false,
|
|
87
|
+
});
|
|
88
|
+
this.options = options;
|
|
89
|
+
this.transport = options.transport;
|
|
90
|
+
this.storage = storage;
|
|
91
|
+
this.storageKey = key;
|
|
92
|
+
this.clock = options.now ?? Date.now;
|
|
93
|
+
this.labels = createLabels(options.labels);
|
|
94
|
+
this.directory = new ChatDirectory(storage, `${key}:chats`);
|
|
95
|
+
this.policy = options.attachments === false || options.attachments === undefined ? null : { ...DEFAULT_ATTACHMENT_POLICY, ...options.attachments };
|
|
96
|
+
this.commands = new SlashRegistry(options.commands === false ? [] : [...defaultCommands(), ...(Array.isArray(options.commands) ? options.commands : [])]);
|
|
97
|
+
}
|
|
98
|
+
setLabels(labels) {
|
|
99
|
+
if (labels === this.labels)
|
|
100
|
+
return;
|
|
101
|
+
this.labels = labels;
|
|
102
|
+
this.update({ chats: this.entries() });
|
|
103
|
+
}
|
|
104
|
+
get snapshot() {
|
|
105
|
+
return this.getState();
|
|
106
|
+
}
|
|
107
|
+
update(patch, urgent = true) {
|
|
108
|
+
const prev = this.getState();
|
|
109
|
+
const next = { ...prev, ...patch };
|
|
110
|
+
next.busy = next.chat.session.status === 'running' || next.sending;
|
|
111
|
+
this.replace(next, false);
|
|
112
|
+
if (urgent || !this.options.flushMs) {
|
|
113
|
+
if (this.timer)
|
|
114
|
+
clearTimeout(this.timer);
|
|
115
|
+
this.timer = null;
|
|
116
|
+
this.emit();
|
|
117
|
+
}
|
|
118
|
+
else if (!this.timer) {
|
|
119
|
+
this.timer = setTimeout(() => {
|
|
120
|
+
this.timer = null;
|
|
121
|
+
this.emit();
|
|
122
|
+
}, this.options.flushMs);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
publishQueue() {
|
|
126
|
+
return { queue: this.queue.items.slice(), steerId: this.queue.steerId };
|
|
127
|
+
}
|
|
128
|
+
remember(key, value) {
|
|
129
|
+
try {
|
|
130
|
+
if (value === null)
|
|
131
|
+
this.storage?.removeItem(`${this.storageKey}:${key}`);
|
|
132
|
+
else
|
|
133
|
+
this.storage?.setItem(`${this.storageKey}:${key}`, value);
|
|
134
|
+
}
|
|
135
|
+
catch {
|
|
136
|
+
/* storage may be full or blocked */
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
notify(level, text) {
|
|
140
|
+
const event = { type: 'notice', ts: new Date(this.clock()).toISOString(), level, text };
|
|
141
|
+
this.update({ chat: reduce(this.snapshot.chat, event) });
|
|
142
|
+
}
|
|
143
|
+
fail(error) {
|
|
144
|
+
this.update({ error: messageOf(error) });
|
|
145
|
+
this.notify('error', messageOf(error));
|
|
146
|
+
}
|
|
147
|
+
async start() {
|
|
148
|
+
if (this.disposed)
|
|
149
|
+
return;
|
|
150
|
+
const generation = ++this.generation;
|
|
151
|
+
this.update({ connection: 'connecting', error: null });
|
|
152
|
+
this.transport.info?.().then((info) => this.alive(generation) && this.update({ info }), () => undefined);
|
|
153
|
+
try {
|
|
154
|
+
let id = this.options.sessionId ?? this.storage?.getItem(`${this.storageKey}:session`) ?? null;
|
|
155
|
+
if (id) {
|
|
156
|
+
try {
|
|
157
|
+
await this.transport.session(id);
|
|
158
|
+
}
|
|
159
|
+
catch {
|
|
160
|
+
id = null;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
if (!id)
|
|
164
|
+
id = (await this.transport.createSession(this.options.session ?? {})).id;
|
|
165
|
+
if (!this.alive(generation))
|
|
166
|
+
return;
|
|
167
|
+
this.remember('session', id);
|
|
168
|
+
await this.attach(id, generation);
|
|
169
|
+
}
|
|
170
|
+
catch (error) {
|
|
171
|
+
if (!this.alive(generation))
|
|
172
|
+
return;
|
|
173
|
+
this.update({ connection: 'closed', loaded: true });
|
|
174
|
+
this.fail(error);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
alive(generation) {
|
|
178
|
+
return !this.disposed && generation === this.generation;
|
|
179
|
+
}
|
|
180
|
+
async attach(id, generation) {
|
|
181
|
+
this.abort?.abort();
|
|
182
|
+
const abort = new AbortController();
|
|
183
|
+
this.abort = abort;
|
|
184
|
+
this.queue.clear();
|
|
185
|
+
let hidden = [];
|
|
186
|
+
try {
|
|
187
|
+
hidden = JSON.parse(this.storage?.getItem(`${this.storageKey}:hidden:${id}`) ?? '[]');
|
|
188
|
+
}
|
|
189
|
+
catch {
|
|
190
|
+
hidden = [];
|
|
191
|
+
}
|
|
192
|
+
this.update({ chat: initialChatState(), sessionId: id, ...this.publishQueue(), sending: false, loaded: false, hidden, editing: null, attachments: [], chats: this.entries(this.snapshot.sessions, id) });
|
|
193
|
+
const replay = await this.transport.events(id, 0);
|
|
194
|
+
if (!this.alive(generation))
|
|
195
|
+
return;
|
|
196
|
+
let chat = initialChatState();
|
|
197
|
+
for (const event of replay.events)
|
|
198
|
+
chat = reduce(chat, event);
|
|
199
|
+
this.titleFrom(id, chat.items);
|
|
200
|
+
this.update({ chat, loaded: true, connection: 'live', chats: this.entries(this.snapshot.sessions, id) });
|
|
201
|
+
void this.follow(id, generation, abort.signal);
|
|
202
|
+
}
|
|
203
|
+
async follow(id, generation, signal) {
|
|
204
|
+
const base = this.options.reconnectMs ?? 500;
|
|
205
|
+
let attempt = 0;
|
|
206
|
+
while (!signal.aborted && this.alive(generation)) {
|
|
207
|
+
try {
|
|
208
|
+
for await (const event of this.transport.sessionEvents(id, this.snapshot.chat.session.last_seq, signal)) {
|
|
209
|
+
attempt = 0;
|
|
210
|
+
if (this.snapshot.connection !== 'live')
|
|
211
|
+
this.update({ connection: 'live' });
|
|
212
|
+
this.receive(event);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
catch (error) {
|
|
216
|
+
if (signal.aborted || !this.alive(generation))
|
|
217
|
+
return;
|
|
218
|
+
const status = error?.status;
|
|
219
|
+
if (status === 404 || status === 401) {
|
|
220
|
+
this.update({ connection: 'closed' });
|
|
221
|
+
this.fail(error);
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
if (signal.aborted || !this.alive(generation))
|
|
226
|
+
return;
|
|
227
|
+
this.update({ connection: 'reconnecting' });
|
|
228
|
+
await wait(Math.min(base * 2 ** attempt, 10_000), signal);
|
|
229
|
+
attempt += 1;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
receive(event) {
|
|
233
|
+
const prev = this.snapshot;
|
|
234
|
+
const chat = reduce(prev.chat, event);
|
|
235
|
+
const sending = prev.sending && event.type !== 'user' && event.type !== 'turn_started';
|
|
236
|
+
const patch = { chat, sending };
|
|
237
|
+
if (event.type === 'user' && prev.sessionId) {
|
|
238
|
+
this.titleFrom(prev.sessionId, chat.items);
|
|
239
|
+
patch.chats = this.entries(prev.sessions, prev.sessionId);
|
|
240
|
+
}
|
|
241
|
+
this.update(patch, !EPHEMERAL_FLUSH.has(event.type));
|
|
242
|
+
if (event.type === 'turn_finished') {
|
|
243
|
+
const held = Boolean(event.interrupted) || Boolean(event.is_error);
|
|
244
|
+
void this.drain(held);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
async drain(held) {
|
|
248
|
+
const next = this.queue.next({ interrupted: held });
|
|
249
|
+
this.update(this.publishQueue());
|
|
250
|
+
if (next)
|
|
251
|
+
await this.post(next.text, next);
|
|
252
|
+
}
|
|
253
|
+
capture() {
|
|
254
|
+
const { references, attachments } = this.snapshot;
|
|
255
|
+
return { references, attachments };
|
|
256
|
+
}
|
|
257
|
+
transportTakesFiles() {
|
|
258
|
+
return Boolean(this.transport.capabilities?.attachments) && this.policy?.deliver !== 'inline';
|
|
259
|
+
}
|
|
260
|
+
async compose(text, meta) {
|
|
261
|
+
const references = meta.references;
|
|
262
|
+
const attachments = meta.attachments;
|
|
263
|
+
const focus = this.snapshot.focus;
|
|
264
|
+
let body = encodeFocus([...(focus ? [focus] : []), ...references], text);
|
|
265
|
+
const extras = {};
|
|
266
|
+
const sent = [];
|
|
267
|
+
for (const attachment of attachments) {
|
|
268
|
+
const part = this.policy?.images === 'parts' && this.transport.capabilities?.images ? imagePart(attachment) : null;
|
|
269
|
+
if (part) {
|
|
270
|
+
extras.images = [...(extras.images ?? []), part];
|
|
271
|
+
sent.push({ attachment, inline: false });
|
|
272
|
+
}
|
|
273
|
+
else if (this.transportTakesFiles()) {
|
|
274
|
+
extras.attachments = [...(extras.attachments ?? []), { name: attachment.name, type: attachment.type, size: attachment.size, dataUrl: attachment.dataUrl, text: attachment.text }];
|
|
275
|
+
sent.push({ attachment, inline: false });
|
|
276
|
+
}
|
|
277
|
+
else if (this.policy?.upload) {
|
|
278
|
+
sent.push({ attachment, ref: (await this.policy.upload(attachment)) ?? null, inline: false });
|
|
279
|
+
}
|
|
280
|
+
else if (attachment.kind === 'text' && typeof attachment.text === 'string' && attachment.size <= (this.policy?.maxInlineBytes ?? 0)) {
|
|
281
|
+
sent.push({ attachment, inline: true });
|
|
282
|
+
}
|
|
283
|
+
else {
|
|
284
|
+
sent.push({ attachment, inline: false });
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
body = encodeAttachments(body, sent);
|
|
288
|
+
return { body, extras };
|
|
289
|
+
}
|
|
290
|
+
async post(text, from, raw = false) {
|
|
291
|
+
const id = this.snapshot.sessionId;
|
|
292
|
+
if (!id)
|
|
293
|
+
return false;
|
|
294
|
+
const meta = from?.meta ?? this.capture();
|
|
295
|
+
this.update({ sending: true, error: null });
|
|
296
|
+
try {
|
|
297
|
+
const { body, extras } = raw ? { body: text, extras: {} } : await this.compose(text, meta);
|
|
298
|
+
await this.transport.send(id, body, extras.attachments?.length || extras.images?.length ? extras : undefined);
|
|
299
|
+
if (!raw)
|
|
300
|
+
this.update({ editing: null, ...(from ? {} : { references: [], attachments: [] }) });
|
|
301
|
+
return true;
|
|
302
|
+
}
|
|
303
|
+
catch (error) {
|
|
304
|
+
this.update({ sending: false });
|
|
305
|
+
if (from) {
|
|
306
|
+
this.queue.putBack(from);
|
|
307
|
+
this.update(this.publishQueue());
|
|
308
|
+
}
|
|
309
|
+
else if (codeOf(error) === 'busy' && this.options.queue !== false) {
|
|
310
|
+
this.queue.add(text, meta);
|
|
311
|
+
this.update({ ...this.publishQueue(), references: [], attachments: [] });
|
|
312
|
+
}
|
|
313
|
+
else {
|
|
314
|
+
if (!this.snapshot.draft)
|
|
315
|
+
this.setDraft(text);
|
|
316
|
+
this.fail(error);
|
|
317
|
+
}
|
|
318
|
+
return false;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
async submit(input) {
|
|
322
|
+
const text = input.trim();
|
|
323
|
+
const hasFiles = this.snapshot.attachments.length > 0;
|
|
324
|
+
if (!text && !hasFiles)
|
|
325
|
+
return false;
|
|
326
|
+
if (text.startsWith('/') && !hasFiles) {
|
|
327
|
+
const outcome = await this.commands.run(this, text);
|
|
328
|
+
if (outcome === 'ran') {
|
|
329
|
+
this.setDraft('');
|
|
330
|
+
return true;
|
|
331
|
+
}
|
|
332
|
+
if (outcome === 'unknown') {
|
|
333
|
+
this.notify('warn', this.labels.unknownCommand(/^\/([\w-]+)/.exec(text)[1]));
|
|
334
|
+
return false;
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
if (this.snapshot.busy) {
|
|
338
|
+
if (this.options.queue === false)
|
|
339
|
+
return false;
|
|
340
|
+
this.queue.add(text, this.capture());
|
|
341
|
+
this.update({ ...this.publishQueue(), draft: '', references: [], attachments: [], editing: null });
|
|
342
|
+
this.remember('draft', null);
|
|
343
|
+
return true;
|
|
344
|
+
}
|
|
345
|
+
this.setDraft('');
|
|
346
|
+
return this.post(text);
|
|
347
|
+
}
|
|
348
|
+
appendDraft(text) {
|
|
349
|
+
const draft = this.snapshot.draft;
|
|
350
|
+
this.setDraft(draft && !/\s$/.test(draft) ? `${draft} ${text}` : `${draft}${text}`);
|
|
351
|
+
}
|
|
352
|
+
addReference(reference) {
|
|
353
|
+
if (this.snapshot.references.some((r) => r.label === reference.label && r.text === reference.text))
|
|
354
|
+
return;
|
|
355
|
+
this.update({ references: [...this.snapshot.references, reference] });
|
|
356
|
+
}
|
|
357
|
+
removeReference(label) {
|
|
358
|
+
this.update({ references: this.snapshot.references.filter((r) => r.label !== label) });
|
|
359
|
+
}
|
|
360
|
+
setReferences(references) {
|
|
361
|
+
this.update({ references });
|
|
362
|
+
}
|
|
363
|
+
canAttach(input) {
|
|
364
|
+
const policy = this.policy;
|
|
365
|
+
if (!policy)
|
|
366
|
+
return false;
|
|
367
|
+
if (input.size > policy.maxBytes)
|
|
368
|
+
return false;
|
|
369
|
+
if (this.transportTakesFiles() || policy.upload)
|
|
370
|
+
return true;
|
|
371
|
+
if (policy.images === 'parts' && this.transport.capabilities?.images && kindOfType(input.type, input.name) === 'image')
|
|
372
|
+
return true;
|
|
373
|
+
return kindOfType(input.type, input.name) === 'text' && input.size <= policy.maxInlineBytes;
|
|
374
|
+
}
|
|
375
|
+
addAttachment(input) {
|
|
376
|
+
const policy = this.policy;
|
|
377
|
+
if (!policy)
|
|
378
|
+
return null;
|
|
379
|
+
if (this.snapshot.attachments.length >= policy.maxFiles) {
|
|
380
|
+
this.notify('warn', this.labels.attachmentLimit(policy.maxFiles));
|
|
381
|
+
return null;
|
|
382
|
+
}
|
|
383
|
+
if (input.size > policy.maxBytes) {
|
|
384
|
+
this.notify('warn', this.labels.attachmentTooLarge(input.name, bytesText(policy.maxBytes)));
|
|
385
|
+
return null;
|
|
386
|
+
}
|
|
387
|
+
if (!this.canAttach(input)) {
|
|
388
|
+
this.notify('warn', this.labels.attachmentUnsupported(input.name));
|
|
389
|
+
return null;
|
|
390
|
+
}
|
|
391
|
+
const attachment = { ...input, id: `a${++this.attachmentCount}`, kind: kindOfType(input.type, input.name) };
|
|
392
|
+
this.update({ attachments: [...this.snapshot.attachments, attachment] });
|
|
393
|
+
return attachment;
|
|
394
|
+
}
|
|
395
|
+
removeAttachment(id) {
|
|
396
|
+
this.update({ attachments: this.snapshot.attachments.filter((a) => a.id !== id) });
|
|
397
|
+
}
|
|
398
|
+
async retry(key) {
|
|
399
|
+
if (this.snapshot.busy)
|
|
400
|
+
return false;
|
|
401
|
+
const items = this.snapshot.chat.items;
|
|
402
|
+
let from = key ? items.findIndex((item) => item.key === key) : items.length - 1;
|
|
403
|
+
if (from < 0)
|
|
404
|
+
return false;
|
|
405
|
+
for (; from >= 0; from -= 1) {
|
|
406
|
+
const item = items[from];
|
|
407
|
+
if (item.kind === 'user')
|
|
408
|
+
return this.post(item.text, undefined, true);
|
|
409
|
+
}
|
|
410
|
+
return false;
|
|
411
|
+
}
|
|
412
|
+
beginEdit(key) {
|
|
413
|
+
const item = this.snapshot.chat.items.find((it) => it.key === key);
|
|
414
|
+
if (!item || item.kind !== 'user')
|
|
415
|
+
return false;
|
|
416
|
+
this.update({ editing: key });
|
|
417
|
+
this.setDraft(decodeMessage(item.text).text);
|
|
418
|
+
return true;
|
|
419
|
+
}
|
|
420
|
+
cancelEdit() {
|
|
421
|
+
if (this.snapshot.editing === null)
|
|
422
|
+
return;
|
|
423
|
+
this.update({ editing: null });
|
|
424
|
+
this.setDraft('');
|
|
425
|
+
}
|
|
426
|
+
deleteMessage(key) {
|
|
427
|
+
const hidden = [...new Set([...this.snapshot.hidden, key])];
|
|
428
|
+
this.update({ hidden });
|
|
429
|
+
this.remember(`hidden:${this.snapshot.sessionId}`, JSON.stringify(hidden));
|
|
430
|
+
}
|
|
431
|
+
entries(sessions = this.snapshot.sessions, activeId = this.snapshot.sessionId) {
|
|
432
|
+
return this.directory.entries(sessions, activeId, this.labels);
|
|
433
|
+
}
|
|
434
|
+
titleFrom(id, items) {
|
|
435
|
+
const first = items.find((item) => item.kind === 'user');
|
|
436
|
+
if (first && first.kind === 'user')
|
|
437
|
+
this.directory.autoTitle(id, decodeMessage(first.text).text);
|
|
438
|
+
}
|
|
439
|
+
async renameChat(id, title) {
|
|
440
|
+
this.directory.rename(id, title);
|
|
441
|
+
this.update({ chats: this.entries() });
|
|
442
|
+
}
|
|
443
|
+
async deleteChat(id) {
|
|
444
|
+
try {
|
|
445
|
+
await this.transport.deleteSession?.(id);
|
|
446
|
+
}
|
|
447
|
+
catch (error) {
|
|
448
|
+
this.fail(error);
|
|
449
|
+
return false;
|
|
450
|
+
}
|
|
451
|
+
this.directory.remove(id);
|
|
452
|
+
this.remember(`hidden:${id}`, null);
|
|
453
|
+
const sessions = this.snapshot.sessions.filter((s) => s.id !== id);
|
|
454
|
+
this.update({ sessions, chats: this.entries(sessions) });
|
|
455
|
+
if (id === this.snapshot.sessionId) {
|
|
456
|
+
const next = this.snapshot.chats.find((chat) => chat.id !== id);
|
|
457
|
+
if (next)
|
|
458
|
+
await this.open(next.id);
|
|
459
|
+
else
|
|
460
|
+
await this.newChat();
|
|
461
|
+
}
|
|
462
|
+
return true;
|
|
463
|
+
}
|
|
464
|
+
async hydrateTitles(limit = 12) {
|
|
465
|
+
const missing = this.snapshot.chats.filter((chat) => !chat.custom && !this.directory.title(chat.id) && !chat.active).slice(0, limit);
|
|
466
|
+
if (!missing.length)
|
|
467
|
+
return;
|
|
468
|
+
await Promise.all(missing.map(async (chat) => {
|
|
469
|
+
try {
|
|
470
|
+
const { events } = await this.transport.events(chat.id, 0);
|
|
471
|
+
const first = events.find((event) => event.type === 'user');
|
|
472
|
+
if (first?.text)
|
|
473
|
+
this.directory.autoTitle(chat.id, decodeMessage(first.text).text);
|
|
474
|
+
}
|
|
475
|
+
catch {
|
|
476
|
+
/* a chat we cannot read keeps its number */
|
|
477
|
+
}
|
|
478
|
+
}));
|
|
479
|
+
this.update({ chats: this.entries() });
|
|
480
|
+
}
|
|
481
|
+
setDraft(draft) {
|
|
482
|
+
this.update({ draft });
|
|
483
|
+
this.remember('draft', draft || null);
|
|
484
|
+
}
|
|
485
|
+
setFocus(focus) {
|
|
486
|
+
this.update({ focus });
|
|
487
|
+
}
|
|
488
|
+
removeQueued(id) {
|
|
489
|
+
this.queue.remove(id);
|
|
490
|
+
this.update(this.publishQueue());
|
|
491
|
+
}
|
|
492
|
+
async sendNow(id) {
|
|
493
|
+
if (!this.queue.steer(id))
|
|
494
|
+
return;
|
|
495
|
+
this.update(this.publishQueue());
|
|
496
|
+
if (this.snapshot.busy)
|
|
497
|
+
await this.stop();
|
|
498
|
+
else
|
|
499
|
+
await this.drain(false);
|
|
500
|
+
}
|
|
501
|
+
async call(fn) {
|
|
502
|
+
const id = this.snapshot.sessionId;
|
|
503
|
+
if (!id)
|
|
504
|
+
return false;
|
|
505
|
+
try {
|
|
506
|
+
await fn(id);
|
|
507
|
+
return true;
|
|
508
|
+
}
|
|
509
|
+
catch (error) {
|
|
510
|
+
this.fail(error);
|
|
511
|
+
return false;
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
stop() {
|
|
515
|
+
return this.call((id) => this.transport.interrupt(id));
|
|
516
|
+
}
|
|
517
|
+
compact(instructions) {
|
|
518
|
+
return this.call((id) => this.transport.compact(id, instructions));
|
|
519
|
+
}
|
|
520
|
+
configure(settings) {
|
|
521
|
+
return this.call((id) => this.transport.settings(id, settings));
|
|
522
|
+
}
|
|
523
|
+
approve(approvalId, reply) {
|
|
524
|
+
return this.call((id) => this.transport.approve(id, approvalId, reply));
|
|
525
|
+
}
|
|
526
|
+
answer(questionId, answers) {
|
|
527
|
+
return this.call((id) => this.transport.answer(id, questionId, answers));
|
|
528
|
+
}
|
|
529
|
+
resolveClash(doc, clashId, choice) {
|
|
530
|
+
return this.call(async () => {
|
|
531
|
+
if (!this.transport.resolveClash)
|
|
532
|
+
throw new Error('this transport cannot resolve clashes');
|
|
533
|
+
await this.transport.resolveClash(doc, clashId, choice);
|
|
534
|
+
});
|
|
535
|
+
}
|
|
536
|
+
applyProposal(id, options) {
|
|
537
|
+
return this.call(async () => {
|
|
538
|
+
if (!this.transport.applyProposal)
|
|
539
|
+
throw new Error('this transport cannot apply proposals');
|
|
540
|
+
await this.transport.applyProposal(id, options);
|
|
541
|
+
});
|
|
542
|
+
}
|
|
543
|
+
discardProposal(id) {
|
|
544
|
+
return this.call(async () => {
|
|
545
|
+
if (!this.transport.discardProposal)
|
|
546
|
+
throw new Error('this transport cannot discard proposals');
|
|
547
|
+
await this.transport.discardProposal(id);
|
|
548
|
+
});
|
|
549
|
+
}
|
|
550
|
+
async listSessions() {
|
|
551
|
+
try {
|
|
552
|
+
const sessions = (await this.transport.sessions?.())?.sessions ?? [];
|
|
553
|
+
this.update({ sessions, chats: this.entries(sessions) });
|
|
554
|
+
return sessions;
|
|
555
|
+
}
|
|
556
|
+
catch {
|
|
557
|
+
return [];
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
async open(id) {
|
|
561
|
+
const generation = ++this.generation;
|
|
562
|
+
this.update({ connection: 'connecting', error: null });
|
|
563
|
+
try {
|
|
564
|
+
this.remember('session', id);
|
|
565
|
+
await this.attach(id, generation);
|
|
566
|
+
}
|
|
567
|
+
catch (error) {
|
|
568
|
+
if (this.alive(generation)) {
|
|
569
|
+
this.update({ connection: 'closed' });
|
|
570
|
+
this.fail(error);
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
async newChat() {
|
|
575
|
+
this.remember('session', null);
|
|
576
|
+
const generation = ++this.generation;
|
|
577
|
+
this.abort?.abort();
|
|
578
|
+
this.update({ connection: 'connecting', error: null });
|
|
579
|
+
try {
|
|
580
|
+
const created = await this.transport.createSession(this.options.session ?? {});
|
|
581
|
+
if (!this.alive(generation))
|
|
582
|
+
return;
|
|
583
|
+
this.remember('session', created.id);
|
|
584
|
+
await this.attach(created.id, generation);
|
|
585
|
+
}
|
|
586
|
+
catch (error) {
|
|
587
|
+
if (this.alive(generation)) {
|
|
588
|
+
this.update({ connection: 'closed' });
|
|
589
|
+
this.fail(error);
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
dispose() {
|
|
594
|
+
this.disposed = true;
|
|
595
|
+
this.abort?.abort();
|
|
596
|
+
if (this.timer)
|
|
597
|
+
clearTimeout(this.timer);
|
|
598
|
+
this.timer = null;
|
|
599
|
+
}
|
|
600
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { TandemError, type SessionSummary, type TandemEvent } from 'tandem-kit-core';
|
|
2
|
+
import type { ChatTransport } from './transport.js';
|
|
3
|
+
export declare class FakeTransport implements ChatTransport {
|
|
4
|
+
log: TandemEvent[];
|
|
5
|
+
sent: string[];
|
|
6
|
+
calls: string[];
|
|
7
|
+
streams: number;
|
|
8
|
+
afters: number[];
|
|
9
|
+
failSend: TandemError | null;
|
|
10
|
+
existing: Set<string>;
|
|
11
|
+
extras: unknown[];
|
|
12
|
+
deleted: string[];
|
|
13
|
+
listed: SessionSummary[];
|
|
14
|
+
capabilities: {
|
|
15
|
+
attachments?: boolean;
|
|
16
|
+
images?: boolean;
|
|
17
|
+
};
|
|
18
|
+
private seq;
|
|
19
|
+
private buffer;
|
|
20
|
+
private wake;
|
|
21
|
+
private dropping;
|
|
22
|
+
private active;
|
|
23
|
+
emit(type: string, fields?: Record<string, unknown>): void;
|
|
24
|
+
dropStream(): void;
|
|
25
|
+
info: () => Promise<{
|
|
26
|
+
models: {
|
|
27
|
+
id: string;
|
|
28
|
+
label: string;
|
|
29
|
+
}[];
|
|
30
|
+
efforts: string[];
|
|
31
|
+
}>;
|
|
32
|
+
sessions: () => Promise<{
|
|
33
|
+
sessions: SessionSummary[];
|
|
34
|
+
}>;
|
|
35
|
+
deleteSession: (id: string) => Promise<undefined>;
|
|
36
|
+
createSession: () => Promise<SessionSummary>;
|
|
37
|
+
session: (id: string) => Promise<SessionSummary>;
|
|
38
|
+
send: (_id: string, text: string, extras?: unknown) => Promise<{
|
|
39
|
+
seq: number;
|
|
40
|
+
}>;
|
|
41
|
+
interrupt: () => Promise<undefined>;
|
|
42
|
+
compact: () => Promise<undefined>;
|
|
43
|
+
settings: (_id: string, s: unknown) => Promise<undefined>;
|
|
44
|
+
approve: (_id: string, a: string, r: {
|
|
45
|
+
allow: boolean;
|
|
46
|
+
}) => Promise<undefined>;
|
|
47
|
+
answer: (_id: string, q: string, a: unknown) => Promise<undefined>;
|
|
48
|
+
applyProposal: (id: string, options?: {
|
|
49
|
+
edit?: unknown;
|
|
50
|
+
}) => Promise<undefined>;
|
|
51
|
+
discardProposal: (id: string) => Promise<undefined>;
|
|
52
|
+
events: (_id: string, after?: number) => Promise<{
|
|
53
|
+
events: TandemEvent[];
|
|
54
|
+
last_seq: number;
|
|
55
|
+
}>;
|
|
56
|
+
sessionEvents(_id: string, after?: number, signal?: AbortSignal): AsyncGenerator<TandemEvent>;
|
|
57
|
+
finish(extra?: Record<string, unknown>): void;
|
|
58
|
+
summary(id: string): SessionSummary;
|
|
59
|
+
}
|