@supersolutions/super-chat-client 0.0.0 → 0.2.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/dist/index.js ADDED
@@ -0,0 +1,790 @@
1
+ // src/client.ts
2
+ import {
3
+ initialRunState,
4
+ reduceRunEvent,
5
+ runAgent,
6
+ resumeJobs,
7
+ assistantMessage,
8
+ latestLeaf,
9
+ linkLinear,
10
+ nextId,
11
+ pathTo,
12
+ siblingsOf,
13
+ threadSnapshot,
14
+ userMessage,
15
+ withQuotes,
16
+ formatQuotes,
17
+ checkQuoteDrift,
18
+ QUOTES_METADATA_KEY,
19
+ SURFACE_EVENT_METADATA_KEY,
20
+ SURFACE_LIMITS,
21
+ SurfaceLedger,
22
+ authorizeSurfaceTool,
23
+ evaluateSurfaceCondition,
24
+ foldSurfaces,
25
+ getAt,
26
+ isSurfaceSpec,
27
+ resolveSurfaceAction,
28
+ runSurfaceToolAction,
29
+ setAt,
30
+ stripCardPayload,
31
+ surfaceCardId
32
+ } from "@supersolutions/super-chat-core";
33
+
34
+ // src/store.ts
35
+ var Store = class {
36
+ state;
37
+ listeners = /* @__PURE__ */ new Set();
38
+ constructor(initial) {
39
+ this.state = initial;
40
+ }
41
+ get = () => this.state;
42
+ set = (next) => {
43
+ const value = typeof next === "function" ? next(this.state) : next;
44
+ if (Object.is(value, this.state)) return;
45
+ this.state = value;
46
+ for (const listener of this.listeners) listener();
47
+ };
48
+ subscribe = (listener) => {
49
+ this.listeners.add(listener);
50
+ return () => {
51
+ this.listeners.delete(listener);
52
+ };
53
+ };
54
+ };
55
+
56
+ // src/client.ts
57
+ var SURFACE_SAVE_DELAY_MS = 300;
58
+ var SURFACE_QUEUE_LIMIT = 8;
59
+ var SURFACE_CONTEXT_CHARS = 4e3;
60
+ var AgentClient = class {
61
+ store;
62
+ config;
63
+ controller = null;
64
+ pending = /* @__PURE__ */ new Map();
65
+ /** Meta of the last snapshot saved, so createdAt/title survive re-saves. */
66
+ threadMeta;
67
+ /**
68
+ * Bumped by every thread switch. A run captures the value it started under
69
+ * and stops writing to the store the moment they diverge — so a run dying
70
+ * from `openThread()`'s stop() cannot leak its error/status/commit into the
71
+ * thread the user just opened.
72
+ */
73
+ generation = 0;
74
+ /** Wall-clock start of the current turn, for the committed TurnMeta. */
75
+ turnStartedAt = 0;
76
+ /** The current run's view of the surfaces, kept level with the person's edits. */
77
+ surfaceLedger = null;
78
+ dirtySurfaces = /* @__PURE__ */ new Set();
79
+ surfaceSaveTimer = null;
80
+ /** Actions pressed while a run was busy. One run at a time, so they wait their turn. */
81
+ surfaceQueue = [];
82
+ constructor(config) {
83
+ this.config = config;
84
+ const tree = linkLinear(config.initialMessages ?? []);
85
+ const headId = config.initialHeadId ?? tree.at(-1)?.id ?? null;
86
+ const messages = pathTo(tree, headId);
87
+ this.store = new Store({
88
+ id: config.threadId ?? nextId("thread"),
89
+ messages,
90
+ tree,
91
+ headId,
92
+ run: initialRunState("", config.mode ?? "stream"),
93
+ cards: [],
94
+ jobs: [],
95
+ attachments: [],
96
+ status: "idle",
97
+ surfaces: foldSurfaces(messages),
98
+ surfaceActivity: {}
99
+ });
100
+ }
101
+ /**
102
+ * Append under `parent` (default: the current head) and move the head there.
103
+ *
104
+ * `extra` merges into the SAME `store.set()` — e.g. clearing `attachments`
105
+ * alongside the append — so a caller touching both fields does not force two
106
+ * notifications for one logical change.
107
+ */
108
+ appendMessage(message, parent, extra) {
109
+ this.store.set((s) => {
110
+ const parentId = parent !== void 0 ? parent : s.headId;
111
+ const linked = { ...message, parentId };
112
+ const tree = [...s.tree, linked];
113
+ return { ...s, tree, headId: linked.id, messages: pathTo(tree, linked.id), ...extra };
114
+ });
115
+ }
116
+ /**
117
+ * Stage a part (a file/image the host uploaded) for the next send. The
118
+ * Composer only carries text; this is how binary content joins the turn.
119
+ */
120
+ attach(part) {
121
+ this.store.set((s) => ({ ...s, attachments: [...s.attachments, part] }));
122
+ }
123
+ removeAttachment(index) {
124
+ this.store.set((s) => ({ ...s, attachments: s.attachments.filter((_, i) => i !== index) }));
125
+ }
126
+ clearAttachments() {
127
+ this.store.set((s) => s.attachments.length ? { ...s, attachments: [] } : s);
128
+ }
129
+ /** Update config in place (model switch, preset toggle) without losing the thread. */
130
+ configure(patch) {
131
+ this.config = { ...this.config, ...patch };
132
+ }
133
+ getConfig() {
134
+ return this.config;
135
+ }
136
+ get isRunning() {
137
+ const { status } = this.store.get();
138
+ return status === "running" || status === "awaiting-user";
139
+ }
140
+ /**
141
+ * Append a user message (plus any staged attachments) and run a turn.
142
+ *
143
+ * `quotes` are spans the user highlighted in a document artifact. They are
144
+ * flattened into the message's own text rather than injected as context, and
145
+ * the reasoning is in content/quotes.ts: a quote is part of what the user
146
+ * SAID, so it must not go stale between turns and must not be droppable
147
+ * under budget pressure. The structured form rides on `metadata`, which never
148
+ * reaches a provider, so the chips can be re-rendered from history.
149
+ *
150
+ * With a `documentStore` configured, each quote is first checked against the
151
+ * document as it is now, and a quote taken from an older revision goes out
152
+ * with its drift — in the text, so the model re-reads, and in the metadata,
153
+ * so the UI can say so.
154
+ */
155
+ async send(input, opts = {}) {
156
+ if (this.isRunning) throw new Error("A run is already in progress. Call stop() first.");
157
+ const { documentStore } = this.config;
158
+ const gen = this.generation;
159
+ const quotes = opts.quotes?.length && documentStore ? await checkQuoteDrift(opts.quotes, documentStore) : opts.quotes ?? [];
160
+ if (this.isRunning) throw new Error("A run is already in progress. Call stop() first.");
161
+ if (gen !== this.generation) return;
162
+ const staged = this.store.get().attachments;
163
+ const quoted = quotes.length === 0 ? input : typeof input === "string" ? withQuotes(input, quotes) : [{ type: "text", text: formatQuotes(quotes) }, ...input];
164
+ const parts = typeof quoted === "string" ? [{ type: "text", text: quoted }] : [...quoted];
165
+ const base = userMessage(staged.length ? [...parts, ...staged] : quoted);
166
+ const message = quotes.length ? { ...base, metadata: { ...base.metadata, [QUOTES_METADATA_KEY]: quotes } } : base;
167
+ this.appendMessage(message, void 0, { attachments: [] });
168
+ this.persist();
169
+ await this.run([...this.store.get().messages], opts);
170
+ }
171
+ /**
172
+ * Re-run from the last user message. A FORK, not a rewrite: the head moves
173
+ * back to that user message and the new answer grows as a sibling of the
174
+ * old one, which stays switchable via `switchBranch`.
175
+ */
176
+ async regenerate(opts = {}) {
177
+ if (this.isRunning) throw new Error("A run is already in progress.");
178
+ const { messages } = this.store.get();
179
+ for (let i = messages.length - 1; i >= 0; i -= 1) {
180
+ const m = messages[i];
181
+ if (m.role === "user") {
182
+ this.flushSurfaceWrites();
183
+ this.store.set((s) => onPath({ ...s, headId: m.id, messages: pathTo(s.tree, m.id) }));
184
+ await this.run([...this.store.get().messages], opts);
185
+ return;
186
+ }
187
+ }
188
+ }
189
+ /**
190
+ * Edit a user message: a SIBLING fork under the same parent, preserving the
191
+ * original and everything under it. The edited branch runs immediately.
192
+ */
193
+ async editMessage(messageId, input, opts = {}) {
194
+ if (this.isRunning) throw new Error("A run is already in progress.");
195
+ const original = this.store.get().tree.find((m) => m.id === messageId);
196
+ if (!original || original.role !== "user") return;
197
+ this.flushSurfaceWrites();
198
+ this.appendMessage(userMessage(input), original.parentId ?? null);
199
+ this.store.set(onPath);
200
+ this.persist();
201
+ await this.run([...this.store.get().messages], opts);
202
+ }
203
+ /**
204
+ * Move the active branch to a SIBLING of `messageId` (delta −1/+1 in
205
+ * insertion order), resuming at that branch's latest leaf.
206
+ */
207
+ switchBranch(messageId, delta) {
208
+ if (this.isRunning) return;
209
+ const s = this.store.get();
210
+ const siblings = siblingsOf(s.tree, messageId);
211
+ if (siblings.length < 2) return;
212
+ const index = siblings.findIndex((m) => m.id === messageId);
213
+ const next = siblings[(index + delta + siblings.length) % siblings.length];
214
+ const headId = latestLeaf(s.tree, next.id);
215
+ this.flushSurfaceWrites();
216
+ this.store.set((prev) => onPath({ ...prev, headId, messages: pathTo(prev.tree, headId) }));
217
+ this.persist();
218
+ }
219
+ async run(messages, opts) {
220
+ const gen = this.generation;
221
+ this.flushSurfaceWrites();
222
+ const surfaces = new SurfaceLedger(this.store.get().surfaces);
223
+ this.surfaceLedger = surfaces;
224
+ this.controller = new AbortController();
225
+ const mode = this.config.mode ?? "stream";
226
+ this.turnStartedAt = Date.now();
227
+ this.store.set((s) => ({
228
+ ...s,
229
+ run: initialRunState(nextId("run"), mode),
230
+ cards: [],
231
+ status: "running",
232
+ error: void 0,
233
+ stopping: false
234
+ }));
235
+ const runConfig = {
236
+ provider: this.config.provider,
237
+ model: this.config.model,
238
+ contextBuilder: this.config.contextBuilder,
239
+ tools: this.config.tools,
240
+ toolResolution: this.config.toolResolution,
241
+ mode,
242
+ maxSteps: this.config.maxSteps,
243
+ vars: this.config.vars,
244
+ temperature: this.config.temperature,
245
+ maxOutputTokens: this.config.maxOutputTokens,
246
+ reasoning: this.config.reasoning,
247
+ stopWhen: this.config.stopWhen,
248
+ toolTimeoutMs: this.config.toolTimeoutMs,
249
+ useServerHistory: this.config.useServerHistory,
250
+ toolChoice: this.config.toolChoice,
251
+ providerTools: this.config.providerTools,
252
+ responseFormat: this.config.responseFormat,
253
+ topP: this.config.topP,
254
+ stopSequences: this.config.stopSequences,
255
+ store: this.config.store,
256
+ metadata: this.config.metadata,
257
+ providerOptions: this.config.providerOptions,
258
+ meter: this.config.meter,
259
+ meteringMetadata: this.config.meteringMetadata,
260
+ signal: this.controller.signal,
261
+ forceSkillIds: opts.forceSkillIds,
262
+ onHostTool: this.config.onHostTool,
263
+ surfaces,
264
+ // Suspend the run on an interactive card; `respond()` resolves it.
265
+ onUserDecision: this.awaitDecision
266
+ };
267
+ try {
268
+ for await (const event of runAgent(messages, runConfig)) {
269
+ if (gen !== this.generation) return;
270
+ this.apply(event);
271
+ }
272
+ } catch (e) {
273
+ if (gen === this.generation) this.store.set((s) => ({ ...s, status: "error", error: e }));
274
+ } finally {
275
+ this.controller = null;
276
+ this.surfaceLedger = null;
277
+ if (gen === this.generation) {
278
+ this.commitRun();
279
+ this.drainSurfaceQueue();
280
+ }
281
+ }
282
+ }
283
+ awaitDecision = (callId, card) => new Promise((resolve) => {
284
+ this.pending.set(callId, { card, resolve });
285
+ });
286
+ apply(event) {
287
+ this.store.set((s) => {
288
+ const run = reduceRunEvent(s.run, event);
289
+ const next = { ...s, run, status: run.status, cards: run.cards };
290
+ if (event.type === "job-started" && this.config.jobStore) {
291
+ const job = {
292
+ handle: event.handle,
293
+ status: "queued",
294
+ threadId: s.id,
295
+ createdAt: Date.now(),
296
+ updatedAt: Date.now()
297
+ };
298
+ void this.config.jobStore.put(job);
299
+ next.jobs = [job, ...s.jobs];
300
+ }
301
+ if (event.type === "job-status") {
302
+ next.jobs = s.jobs.map((j) => j.handle.id === event.handle.id ? { ...j, status: event.status, updatedAt: Date.now() } : j);
303
+ }
304
+ if (event.type === "error") next.error = event.error;
305
+ if (event.type === "card" && isSurfaceSpec(event.card.spec)) {
306
+ next.surfaces = { ...s.surfaces, [event.card.spec.surfaceId]: event.card.spec };
307
+ }
308
+ return next;
309
+ });
310
+ }
311
+ /**
312
+ * Fold the finished run's parts into the thread as one assistant message.
313
+ *
314
+ * Cards are attached as artifact parts so a reloaded thread still renders
315
+ * them — the ContextBuilder strips artifacts before they reach a provider,
316
+ * so this costs nothing at request time.
317
+ */
318
+ commitRun(origin) {
319
+ this.flushSurfaceWrites(true);
320
+ this.store.set((s) => {
321
+ const status = s.status === "error" ? "error" : s.run.status;
322
+ const run = s.run.partialTools && Object.keys(s.run.partialTools).length ? { ...s.run, partialTools: {} } : s.run;
323
+ const parts = run.parts;
324
+ if (!parts.length && !run.cards.length) return { ...s, run, status };
325
+ const cardParts = s.run.cards.map((c) => ({
326
+ type: "artifact",
327
+ id: c.id,
328
+ kind: `card:${c.spec.kind ?? "unknown"}`,
329
+ data: c.spec,
330
+ ...c.action ? { action: c.action } : {},
331
+ // Where the card belongs among the turn's text.
332
+ ...c.callId ? { callId: c.callId } : {}
333
+ }));
334
+ const meta = {
335
+ model: this.config.model,
336
+ ms: this.turnStartedAt ? Date.now() - this.turnStartedAt : 0,
337
+ ...s.run.usage && Object.keys(s.run.usage).length ? { usage: s.run.usage } : {},
338
+ ...s.run.steps ? { steps: s.run.steps } : {},
339
+ ...origin ? { origin } : {}
340
+ };
341
+ const linked = {
342
+ ...assistantMessage([...toolResultsInCallOrder(parts), ...cardParts]),
343
+ parentId: s.headId,
344
+ metadata: { turn: meta }
345
+ };
346
+ const tree = [...s.tree, linked];
347
+ return {
348
+ ...s,
349
+ run,
350
+ tree,
351
+ headId: linked.id,
352
+ messages: pathTo(tree, linked.id),
353
+ status: s.run.status,
354
+ stopping: false
355
+ };
356
+ });
357
+ this.persist();
358
+ }
359
+ /**
360
+ * Fire-and-forget save, the same posture as the job store put: persistence
361
+ * must not stall the run, and a failed save degrades to "not saved", never
362
+ * to a broken thread.
363
+ */
364
+ persist() {
365
+ const store = this.config.threadStore;
366
+ if (!store) return;
367
+ const s = this.store.get();
368
+ if (this.threadMeta && this.threadMeta.id !== s.id) this.threadMeta = void 0;
369
+ void (async () => {
370
+ const prior = this.threadMeta ?? (await store.load(s.id))?.meta;
371
+ const snapshot = threadSnapshot(s.id, s.tree, prior, s.headId);
372
+ this.threadMeta = snapshot.meta;
373
+ await store.save(snapshot);
374
+ })().catch(() => {
375
+ });
376
+ }
377
+ /**
378
+ * Load a stored thread and replace the current one. Returns false when the
379
+ * id is unknown (the current thread is left untouched).
380
+ */
381
+ async openThread(id) {
382
+ const store = this.config.threadStore;
383
+ if (!store) return false;
384
+ const stored = await store.load(id);
385
+ if (!stored) return false;
386
+ this.saveSurfacesNow();
387
+ this.generation += 1;
388
+ this.stop();
389
+ this.surfaceQueue = [];
390
+ this.threadMeta = stored.meta;
391
+ const tree = linkLinear(stored.messages);
392
+ const headId = stored.headId ?? tree.at(-1)?.id ?? null;
393
+ this.store.set((s) => onPath({
394
+ ...s,
395
+ id: stored.meta.id,
396
+ tree,
397
+ headId,
398
+ messages: pathTo(tree, headId),
399
+ cards: [],
400
+ attachments: [],
401
+ run: initialRunState("", this.config.mode ?? "stream"),
402
+ status: "idle",
403
+ error: void 0,
404
+ surfaceActivity: {}
405
+ }));
406
+ return true;
407
+ }
408
+ /** Start a fresh thread under a new id (`clear()` keeps the id; this doesn't). */
409
+ newThread() {
410
+ this.saveSurfacesNow();
411
+ this.generation += 1;
412
+ this.stop();
413
+ this.surfaceQueue = [];
414
+ this.threadMeta = void 0;
415
+ this.store.set((s) => ({
416
+ ...s,
417
+ id: nextId("thread"),
418
+ messages: [],
419
+ tree: [],
420
+ headId: null,
421
+ cards: [],
422
+ attachments: [],
423
+ run: initialRunState("", this.config.mode ?? "stream"),
424
+ status: "idle",
425
+ error: void 0,
426
+ surfaces: {},
427
+ surfaceActivity: {}
428
+ }));
429
+ }
430
+ /** Answer an interactive card. Unblocks the suspended tool. */
431
+ respond(action) {
432
+ const entry = this.pending.get(action.callId ?? "");
433
+ if (!entry) return;
434
+ this.pending.delete(action.callId ?? "");
435
+ entry.resolve(action);
436
+ }
437
+ /** The card currently blocking the run, if any. */
438
+ pendingCard() {
439
+ return this.store.get().run.pendingCard;
440
+ }
441
+ stop() {
442
+ if (!this.isRunning) return;
443
+ this.store.set((s) => ({ ...s, stopping: true }));
444
+ this.controller?.abort();
445
+ const job = this.store.get().run.job;
446
+ if (job && this.config.provider.cancelJob && !["completed", "failed", "cancelled"].includes(job.status)) {
447
+ void this.config.provider.cancelJob(job.handle).catch(() => {
448
+ });
449
+ void this.config.jobStore?.remove(job.handle.id);
450
+ }
451
+ for (const [callId, entry] of this.pending) {
452
+ entry.resolve({ cardId: entry.card.id, callId, kind: "cancel", type: "cancel", at: Date.now() });
453
+ }
454
+ this.pending.clear();
455
+ for (const queued of this.surfaceQueue.splice(0)) {
456
+ this.noteSurfaceActivity(queued.spec.surfaceId, queued.component.id, "cancelled", "Cancelled.");
457
+ }
458
+ }
459
+ // ── surfaces ──────────────────────────────────────────────────────────────
460
+ /**
461
+ * Write one value into a surface's data model. Neighbours bound to it update at
462
+ * once and no model is called. The thread is rewritten shortly after, not per
463
+ * keystroke, so typing does not re-render every message.
464
+ */
465
+ setSurfaceData(surfaceId, path, value) {
466
+ const current = this.store.get().surfaces[surfaceId];
467
+ if (!current || current.deleted || current.expired) return false;
468
+ const data = setAt(current.data, path, value);
469
+ if (!data || JSON.stringify(data).length > SURFACE_LIMITS.dataChars) return false;
470
+ this.putSurface({ ...current, data, revision: current.revision + 1 });
471
+ return true;
472
+ }
473
+ putSurface(spec) {
474
+ this.surfaceLedger?.put(spec);
475
+ this.store.set((s) => ({ ...s, surfaces: { ...s.surfaces, [spec.surfaceId]: spec } }));
476
+ this.dirtySurfaces.add(spec.surfaceId);
477
+ if (this.surfaceSaveTimer) return;
478
+ this.surfaceSaveTimer = setTimeout(() => this.saveSurfacesNow(), SURFACE_SAVE_DELAY_MS);
479
+ }
480
+ saveSurfacesNow() {
481
+ if (this.surfaceSaveTimer) clearTimeout(this.surfaceSaveTimer);
482
+ this.surfaceSaveTimer = null;
483
+ if (!this.dirtySurfaces.size) return;
484
+ this.flushSurfaceWrites();
485
+ this.persist();
486
+ }
487
+ /**
488
+ * Fold pending edits into the newest snapshot of each surface: the live card, or
489
+ * the stored one. A finished run's cards stay in `run` until the next one starts,
490
+ * so they only count as the newest copy while that run has yet to commit.
491
+ */
492
+ flushSurfaceWrites(uncommittedRun = this.isRunning) {
493
+ if (this.surfaceSaveTimer) clearTimeout(this.surfaceSaveTimer);
494
+ this.surfaceSaveTimer = null;
495
+ if (!this.dirtySurfaces.size) return;
496
+ const ids = [...this.dirtySurfaces];
497
+ this.dirtySurfaces.clear();
498
+ this.store.set((s) => {
499
+ let { run, tree } = s;
500
+ for (const id of ids) {
501
+ const spec = s.surfaces[id];
502
+ if (!spec) continue;
503
+ const cardId = surfaceCardId(id);
504
+ if (uncommittedRun && run.cards.some((c) => c.id === cardId)) {
505
+ run = { ...run, cards: run.cards.map((c) => c.id === cardId ? { ...c, spec } : c) };
506
+ continue;
507
+ }
508
+ const holder = [...s.messages].reverse().find((m) => m.parts.some((p) => p.type === "artifact" && p.id === cardId));
509
+ if (!holder) continue;
510
+ tree = tree.map(
511
+ (m) => m.id === holder.id ? { ...m, parts: m.parts.map((p) => p.type === "artifact" && p.id === cardId ? { ...p, data: spec } : p) } : m
512
+ );
513
+ }
514
+ if (run === s.run && tree === s.tree) return s;
515
+ return { ...s, run, cards: run.cards, tree, messages: tree === s.tree ? s.messages : pathTo(tree, s.headId) };
516
+ });
517
+ }
518
+ noteSurfaceActivity(surfaceId, componentId, state, message) {
519
+ this.store.set((s) => ({
520
+ ...s,
521
+ surfaceActivity: { ...s.surfaceActivity, [surfaceId]: { componentId, state, ...message ? { message } : {}, at: Date.now() } }
522
+ }));
523
+ return state;
524
+ }
525
+ /**
526
+ * Run the action of a control the person pressed.
527
+ *
528
+ * Takes the component's id rather than an action: what runs is read from the
529
+ * validated spec here, so nothing in the page can substitute a different one.
530
+ */
531
+ async dispatchSurfaceAction(surfaceId, componentId, scope = {}) {
532
+ const spec = this.store.get().surfaces[surfaceId];
533
+ const component = spec?.components.find((c) => c.id === componentId);
534
+ const action = component?.["action"];
535
+ if (!spec || spec.deleted || spec.expired || !component || !action) {
536
+ return this.noteSurfaceActivity(surfaceId, componentId, "refused", "This control is no longer available.");
537
+ }
538
+ const binding = { data: spec.data, ...scope };
539
+ const disabledWhen = component["disabledWhen"];
540
+ if (disabledWhen && evaluateSurfaceCondition(disabledWhen, binding)) {
541
+ return this.noteSurfaceActivity(surfaceId, componentId, "refused", "This control is unavailable right now.");
542
+ }
543
+ const resolved = resolveSurfaceAction(action, binding);
544
+ if (resolved.type === "set") {
545
+ let data = spec.data;
546
+ for (const update of resolved.updates) data = data && setAt(data, update.path, update.value);
547
+ if (!data) return this.noteSurfaceActivity(surfaceId, componentId, "failed", "That change could not be applied.");
548
+ this.putSurface({ ...spec, data, revision: spec.revision + 1 });
549
+ return this.noteSurfaceActivity(surfaceId, componentId, "done");
550
+ }
551
+ if (resolved.type === "tool") {
552
+ const verdict = authorizeSurfaceTool(resolved.tool, resolved.args, this.config.tools, this.config.toolResolution);
553
+ if (!verdict.ok) return this.noteSurfaceActivity(surfaceId, componentId, "refused", verdict.reason);
554
+ }
555
+ const queued = { spec, component, action: resolved };
556
+ if (this.isRunning) {
557
+ if (this.surfaceQueue.length >= SURFACE_QUEUE_LIMIT) {
558
+ return this.noteSurfaceActivity(surfaceId, componentId, "refused", "Too many actions are waiting. Try again shortly.");
559
+ }
560
+ this.surfaceQueue.push(queued);
561
+ return this.noteSurfaceActivity(surfaceId, componentId, "queued", "Waiting for the agent to finish.");
562
+ }
563
+ return this.startSurfaceAction(queued);
564
+ }
565
+ /** Record the answer to an interactive card inside a surface, then run its action if it has one. */
566
+ async respondToSurfaceCard(surfaceId, componentId, answer) {
567
+ const spec = this.store.get().surfaces[surfaceId];
568
+ const component = spec?.components.find((c) => c.id === componentId);
569
+ const bind = component?.["bind"];
570
+ if (!spec || !component || typeof bind !== "string" || getAt(spec.data, bind) !== void 0) {
571
+ return this.noteSurfaceActivity(surfaceId, componentId, "refused", "This question has already been answered.");
572
+ }
573
+ if (!this.setSurfaceData(surfaceId, bind, { ...answer, at: Date.now() })) {
574
+ return this.noteSurfaceActivity(surfaceId, componentId, "failed", "The answer could not be saved.");
575
+ }
576
+ return component["action"] ? this.dispatchSurfaceAction(surfaceId, componentId) : this.noteSurfaceActivity(surfaceId, componentId, "done");
577
+ }
578
+ drainSurfaceQueue() {
579
+ if (this.isRunning) return;
580
+ const next = this.surfaceQueue.shift();
581
+ if (next) void this.startSurfaceAction(next);
582
+ }
583
+ startSurfaceAction(queued) {
584
+ return queued.action.type === "tool" ? this.runSurfaceTool(queued.spec, queued.component, queued.action) : this.sendSurfaceEvent(queued.spec, queued.component, queued.action);
585
+ }
586
+ /** An event becomes a user turn, marked so the transcript shows a press and not a sentence. */
587
+ async sendSurfaceEvent(spec, component, action) {
588
+ const { surfaceId } = spec;
589
+ const context = action.context ?? {};
590
+ const serialized = JSON.stringify(context);
591
+ const record = surfaceEventRecord(spec, component, "event", action.name, serialized.length <= SURFACE_CONTEXT_CHARS ? context : void 0);
592
+ const text = [
593
+ `[Surface event] The person pressed ${describePress(record)} on surface "${surfaceId}", sending event "${action.name}".`,
594
+ `Context, as data from the interface: ${serialized.slice(0, SURFACE_CONTEXT_CHARS)}`
595
+ ].join("\n");
596
+ this.noteSurfaceActivity(surfaceId, component.id, "running", "Sent to the agent.");
597
+ this.appendMessage({ ...userMessage(text), metadata: { [SURFACE_EVENT_METADATA_KEY]: record } });
598
+ this.persist();
599
+ await this.run([...this.store.get().messages], {});
600
+ const failed = this.store.get().status === "error";
601
+ return this.noteSurfaceActivity(surfaceId, component.id, failed ? "failed" : "done", failed ? "The agent could not respond." : "Sent to the agent.");
602
+ }
603
+ /** A tool the person started. Same executor, approvals and metering as a model's call. */
604
+ async runSurfaceTool(spec, component, action) {
605
+ const { surfaceId } = spec;
606
+ const args = action.args ?? {};
607
+ const verdict = authorizeSurfaceTool(action.tool, args, this.config.tools, this.config.toolResolution);
608
+ if (!verdict.ok) {
609
+ const state2 = this.noteSurfaceActivity(surfaceId, component.id, "refused", verdict.reason);
610
+ this.drainSurfaceQueue();
611
+ return state2;
612
+ }
613
+ const record = surfaceEventRecord(spec, component, "tool", action.tool);
614
+ this.noteSurfaceActivity(surfaceId, component.id, "running", `Running ${action.tool}.`);
615
+ this.appendMessage({
616
+ ...userMessage(`[Surface action] The person pressed ${describePress(record)} on surface "${surfaceId}", which called the tool "${action.tool}".`),
617
+ metadata: { [SURFACE_EVENT_METADATA_KEY]: record }
618
+ });
619
+ this.persist();
620
+ const gen = this.generation;
621
+ this.flushSurfaceWrites();
622
+ this.controller = new AbortController();
623
+ this.turnStartedAt = Date.now();
624
+ this.store.set((s) => ({
625
+ ...s,
626
+ run: initialRunState(nextId("run"), "sync"),
627
+ cards: [],
628
+ status: "running",
629
+ error: void 0,
630
+ stopping: false
631
+ }));
632
+ let result;
633
+ try {
634
+ const events = runSurfaceToolAction({
635
+ tool: verdict.tool,
636
+ args,
637
+ surfaceId,
638
+ componentId: component.id,
639
+ provider: this.config.provider.id,
640
+ model: this.config.model,
641
+ vars: this.config.vars,
642
+ signal: this.controller.signal,
643
+ toolTimeoutMs: this.config.toolTimeoutMs,
644
+ meter: this.config.meter,
645
+ meteringMetadata: this.config.meteringMetadata,
646
+ onUserDecision: this.awaitDecision,
647
+ onHostTool: this.config.onHostTool
648
+ });
649
+ for await (const event of events) {
650
+ if (gen !== this.generation) return "cancelled";
651
+ if (event.type === "tool-result") result = event;
652
+ this.apply(event);
653
+ }
654
+ } catch (e) {
655
+ if (gen === this.generation) this.store.set((s) => ({ ...s, status: "error", error: e }));
656
+ } finally {
657
+ this.controller = null;
658
+ }
659
+ if (gen !== this.generation) return "cancelled";
660
+ let state;
661
+ let message;
662
+ if (!result || result.failure && result.failure !== "denied") {
663
+ state = "failed";
664
+ message = failureMessage(result?.output) ?? `${action.tool} failed.`;
665
+ } else if (result.failure === "denied") {
666
+ state = "cancelled";
667
+ message = "Cancelled.";
668
+ } else {
669
+ state = "done";
670
+ message = "Done.";
671
+ if (action.resultPath && !this.setSurfaceData(surfaceId, action.resultPath, stripCardPayload(result.output))) {
672
+ state = "failed";
673
+ message = "The result was too large to show here.";
674
+ }
675
+ }
676
+ this.commitRun("surface-action");
677
+ this.noteSurfaceActivity(surfaceId, component.id, state, message);
678
+ this.drainSurfaceQueue();
679
+ return state;
680
+ }
681
+ clear() {
682
+ this.dirtySurfaces.clear();
683
+ this.generation += 1;
684
+ this.stop();
685
+ this.surfaceQueue = [];
686
+ this.store.set((s) => ({
687
+ ...s,
688
+ messages: [],
689
+ tree: [],
690
+ headId: null,
691
+ cards: [],
692
+ attachments: [],
693
+ run: initialRunState("", this.config.mode ?? "stream"),
694
+ status: "idle",
695
+ error: void 0,
696
+ stopping: false,
697
+ surfaces: {},
698
+ surfaceActivity: {}
699
+ }));
700
+ this.persist();
701
+ }
702
+ /**
703
+ * Re-poll background jobs from a previous session. Call on mount.
704
+ *
705
+ * Results are routed by `StoredJob.threadId`: the current thread gets its
706
+ * results appended live; another thread's results are written into its
707
+ * stored snapshot (when a ThreadStore is configured), so an answer to
708
+ * thread A never gets pasted into thread B.
709
+ */
710
+ async resumeBackgroundJobs() {
711
+ const store = this.config.jobStore;
712
+ if (!store) return;
713
+ const results = await resumeJobs(store, { [this.config.provider.id]: this.config.provider });
714
+ this.store.set((s) => ({ ...s, jobs: results.map((r) => r.job) }));
715
+ const currentId = this.store.get().id;
716
+ const away = /* @__PURE__ */ new Map();
717
+ for (const { job, snapshot } of results) {
718
+ const parts = snapshot.status === "completed" && snapshot.result ? snapshot.result.parts : snapshot.status === "failed" ? [{ type: "text", text: `_${snapshot.error?.message ?? "A background job failed."}_` }] : null;
719
+ if (!parts) continue;
720
+ if (!job.threadId || job.threadId === currentId) {
721
+ this.appendMessage(assistantMessage(parts));
722
+ if (job.threadId === currentId) this.persist();
723
+ continue;
724
+ }
725
+ const bucket = away.get(job.threadId) ?? [];
726
+ bucket.push(parts);
727
+ away.set(job.threadId, bucket);
728
+ }
729
+ const threads = this.config.threadStore;
730
+ if (!threads || !away.size) return;
731
+ await Promise.all(
732
+ [...away].map(async ([threadId, partsList]) => {
733
+ for (const parts of partsList) {
734
+ const stored = await threads.load(threadId);
735
+ if (!stored) continue;
736
+ const awayHead = stored.headId ?? stored.messages.at(-1)?.id ?? null;
737
+ const appended = { ...assistantMessage(parts), parentId: awayHead };
738
+ await threads.save(
739
+ threadSnapshot(threadId, [...stored.messages, appended], stored.meta, appended.id)
740
+ );
741
+ }
742
+ })
743
+ );
744
+ }
745
+ };
746
+ var onPath = (s) => ({ ...s, surfaces: foldSurfaces(s.messages) });
747
+ function surfaceEventRecord(spec, component, type, name, context) {
748
+ const label = component["label"];
749
+ return {
750
+ surfaceId: spec.surfaceId,
751
+ componentId: component.id,
752
+ ...spec.title ? { title: spec.title } : {},
753
+ ...typeof label === "string" ? { label } : {},
754
+ type,
755
+ name,
756
+ ...context ? { context } : {}
757
+ };
758
+ }
759
+ var describePress = (record) => record.label ? JSON.stringify(record.label) : `control "${record.componentId}"`;
760
+ var failureMessage = (output) => {
761
+ const error = output?.error;
762
+ return typeof error === "string" ? error.slice(0, 200) : void 0;
763
+ };
764
+ function toolResultsInCallOrder(parts) {
765
+ const callAt = /* @__PURE__ */ new Map();
766
+ parts.forEach((p, i) => {
767
+ if (p.type === "tool-call") callAt.set(p.callId, i);
768
+ });
769
+ const rank = (p) => p.type === "tool-result" ? callAt.get(p.callId) ?? Number.MAX_SAFE_INTEGER : Number.MAX_SAFE_INTEGER;
770
+ const out = [];
771
+ let batch = [];
772
+ const flush = () => {
773
+ out.push(...batch.sort((a, b) => rank(a) - rank(b)));
774
+ batch = [];
775
+ };
776
+ for (const p of parts) {
777
+ if (p.type === "tool-result") batch.push(p);
778
+ else {
779
+ flush();
780
+ out.push(p);
781
+ }
782
+ }
783
+ flush();
784
+ return out;
785
+ }
786
+ export {
787
+ AgentClient,
788
+ Store
789
+ };
790
+ //# sourceMappingURL=index.js.map