@supersolutions/super-chat-client 0.1.0 → 0.2.1
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.d.ts +51 -1
- package/dist/index.js +315 -16
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Message, RunState, Card, StoredJob, ContentPart, Provider, ContextBuilder, ToolRegistry, ToolResolution, RunMode, RunConfig, JobStore, ThreadStore, ToolCallRequest, DocumentStore, DocumentQuoteRef, CardAction } from '@supersolutions/super-chat-core';
|
|
1
|
+
import { Message, RunState, Card, StoredJob, ContentPart, SurfaceSpec, SurfaceActivity, Provider, ContextBuilder, ToolRegistry, ToolResolution, RunMode, RunConfig, JobStore, ThreadStore, ToolCallRequest, DocumentStore, CardRegistry, SurfaceCatalogue, DocumentQuoteRef, CardAction, SurfaceActivityState, SurfaceCardAnswer } from '@supersolutions/super-chat-core';
|
|
2
2
|
|
|
3
3
|
type Listener = () => void;
|
|
4
4
|
declare class Store<T> {
|
|
@@ -41,6 +41,10 @@ type ThreadState = {
|
|
|
41
41
|
* from "the button did nothing".
|
|
42
42
|
*/
|
|
43
43
|
stopping?: boolean;
|
|
44
|
+
/** Current state of each surface on the active path, the person's edits included. */
|
|
45
|
+
surfaces: Record<string, SurfaceSpec>;
|
|
46
|
+
/** What became of the last action pressed on each surface. */
|
|
47
|
+
surfaceActivity: Record<string, SurfaceActivity>;
|
|
44
48
|
};
|
|
45
49
|
/** What a finished turn cost, attached to the committed message. */
|
|
46
50
|
type TurnMeta = {
|
|
@@ -48,6 +52,8 @@ type TurnMeta = {
|
|
|
48
52
|
ms: number;
|
|
49
53
|
usage?: RunState["usage"];
|
|
50
54
|
steps?: number;
|
|
55
|
+
/** Set when a person's button press produced this turn rather than a model. */
|
|
56
|
+
origin?: "surface-action";
|
|
51
57
|
};
|
|
52
58
|
type AgentClientConfig = {
|
|
53
59
|
provider: Provider;
|
|
@@ -90,6 +96,10 @@ type AgentClientConfig = {
|
|
|
90
96
|
* Unset, quotes are sent as taken.
|
|
91
97
|
*/
|
|
92
98
|
documentStore?: Pick<DocumentStore, "get">;
|
|
99
|
+
/** The card registry in use, so the UI can ask it which kinds are interactive. */
|
|
100
|
+
cards?: CardRegistry;
|
|
101
|
+
/** The surface catalogue in use, so the renderer validates against what the tools accept. */
|
|
102
|
+
surfaceCatalogue?: SurfaceCatalogue;
|
|
93
103
|
};
|
|
94
104
|
declare class AgentClient {
|
|
95
105
|
readonly store: Store<ThreadState>;
|
|
@@ -107,6 +117,12 @@ declare class AgentClient {
|
|
|
107
117
|
private generation;
|
|
108
118
|
/** Wall-clock start of the current turn, for the committed TurnMeta. */
|
|
109
119
|
private turnStartedAt;
|
|
120
|
+
/** The current run's view of the surfaces, kept level with the person's edits. */
|
|
121
|
+
private surfaceLedger;
|
|
122
|
+
private dirtySurfaces;
|
|
123
|
+
private surfaceSaveTimer;
|
|
124
|
+
/** Actions pressed while a run was busy. One run at a time, so they wait their turn. */
|
|
125
|
+
private surfaceQueue;
|
|
110
126
|
constructor(config: AgentClientConfig);
|
|
111
127
|
/**
|
|
112
128
|
* Append under `parent` (default: the current head) and move the head there.
|
|
@@ -167,6 +183,7 @@ declare class AgentClient {
|
|
|
167
183
|
*/
|
|
168
184
|
switchBranch(messageId: string, delta: number): void;
|
|
169
185
|
private run;
|
|
186
|
+
private awaitDecision;
|
|
170
187
|
private apply;
|
|
171
188
|
/**
|
|
172
189
|
* Fold the finished run's parts into the thread as one assistant message.
|
|
@@ -194,6 +211,39 @@ declare class AgentClient {
|
|
|
194
211
|
/** The card currently blocking the run, if any. */
|
|
195
212
|
pendingCard(): Card | undefined;
|
|
196
213
|
stop(): void;
|
|
214
|
+
/**
|
|
215
|
+
* Write one value into a surface's data model. Neighbours bound to it update at
|
|
216
|
+
* once and no model is called. The thread is rewritten shortly after, not per
|
|
217
|
+
* keystroke, so typing does not re-render every message.
|
|
218
|
+
*/
|
|
219
|
+
setSurfaceData(surfaceId: string, path: string, value: unknown): boolean;
|
|
220
|
+
private putSurface;
|
|
221
|
+
private saveSurfacesNow;
|
|
222
|
+
/**
|
|
223
|
+
* Fold pending edits into the newest snapshot of each surface: the live card, or
|
|
224
|
+
* the stored one. A finished run's cards stay in `run` until the next one starts,
|
|
225
|
+
* so they only count as the newest copy while that run has yet to commit.
|
|
226
|
+
*/
|
|
227
|
+
private flushSurfaceWrites;
|
|
228
|
+
private noteSurfaceActivity;
|
|
229
|
+
/**
|
|
230
|
+
* Run the action of a control the person pressed.
|
|
231
|
+
*
|
|
232
|
+
* Takes the component's id rather than an action: what runs is read from the
|
|
233
|
+
* validated spec here, so nothing in the page can substitute a different one.
|
|
234
|
+
*/
|
|
235
|
+
dispatchSurfaceAction(surfaceId: string, componentId: string, scope?: {
|
|
236
|
+
item?: unknown;
|
|
237
|
+
index?: number;
|
|
238
|
+
}): Promise<SurfaceActivityState>;
|
|
239
|
+
/** Record the answer to an interactive card inside a surface, then run its action if it has one. */
|
|
240
|
+
respondToSurfaceCard(surfaceId: string, componentId: string, answer: Omit<SurfaceCardAnswer, "at">): Promise<SurfaceActivityState>;
|
|
241
|
+
private drainSurfaceQueue;
|
|
242
|
+
private startSurfaceAction;
|
|
243
|
+
/** An event becomes a user turn, marked so the transcript shows a press and not a sentence. */
|
|
244
|
+
private sendSurfaceEvent;
|
|
245
|
+
/** A tool the person started. Same executor, approvals and metering as a model's call. */
|
|
246
|
+
private runSurfaceTool;
|
|
197
247
|
clear(): void;
|
|
198
248
|
/**
|
|
199
249
|
* Re-poll background jobs from a previous session. Call on mount.
|
package/dist/index.js
CHANGED
|
@@ -15,7 +15,20 @@ import {
|
|
|
15
15
|
withQuotes,
|
|
16
16
|
formatQuotes,
|
|
17
17
|
checkQuoteDrift,
|
|
18
|
-
QUOTES_METADATA_KEY
|
|
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
|
|
19
32
|
} from "@supersolutions/super-chat-core";
|
|
20
33
|
|
|
21
34
|
// src/store.ts
|
|
@@ -41,6 +54,9 @@ var Store = class {
|
|
|
41
54
|
};
|
|
42
55
|
|
|
43
56
|
// src/client.ts
|
|
57
|
+
var SURFACE_SAVE_DELAY_MS = 300;
|
|
58
|
+
var SURFACE_QUEUE_LIMIT = 8;
|
|
59
|
+
var SURFACE_CONTEXT_CHARS = 4e3;
|
|
44
60
|
var AgentClient = class {
|
|
45
61
|
store;
|
|
46
62
|
config;
|
|
@@ -57,20 +73,29 @@ var AgentClient = class {
|
|
|
57
73
|
generation = 0;
|
|
58
74
|
/** Wall-clock start of the current turn, for the committed TurnMeta. */
|
|
59
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 = [];
|
|
60
82
|
constructor(config) {
|
|
61
83
|
this.config = config;
|
|
62
84
|
const tree = linkLinear(config.initialMessages ?? []);
|
|
63
85
|
const headId = config.initialHeadId ?? tree.at(-1)?.id ?? null;
|
|
86
|
+
const messages = pathTo(tree, headId);
|
|
64
87
|
this.store = new Store({
|
|
65
88
|
id: config.threadId ?? nextId("thread"),
|
|
66
|
-
messages
|
|
89
|
+
messages,
|
|
67
90
|
tree,
|
|
68
91
|
headId,
|
|
69
92
|
run: initialRunState("", config.mode ?? "stream"),
|
|
70
93
|
cards: [],
|
|
71
94
|
jobs: [],
|
|
72
95
|
attachments: [],
|
|
73
|
-
status: "idle"
|
|
96
|
+
status: "idle",
|
|
97
|
+
surfaces: foldSurfaces(messages),
|
|
98
|
+
surfaceActivity: {}
|
|
74
99
|
});
|
|
75
100
|
}
|
|
76
101
|
/**
|
|
@@ -154,7 +179,8 @@ var AgentClient = class {
|
|
|
154
179
|
for (let i = messages.length - 1; i >= 0; i -= 1) {
|
|
155
180
|
const m = messages[i];
|
|
156
181
|
if (m.role === "user") {
|
|
157
|
-
this.
|
|
182
|
+
this.flushSurfaceWrites();
|
|
183
|
+
this.store.set((s) => onPath({ ...s, headId: m.id, messages: pathTo(s.tree, m.id) }));
|
|
158
184
|
await this.run([...this.store.get().messages], opts);
|
|
159
185
|
return;
|
|
160
186
|
}
|
|
@@ -168,7 +194,9 @@ var AgentClient = class {
|
|
|
168
194
|
if (this.isRunning) throw new Error("A run is already in progress.");
|
|
169
195
|
const original = this.store.get().tree.find((m) => m.id === messageId);
|
|
170
196
|
if (!original || original.role !== "user") return;
|
|
197
|
+
this.flushSurfaceWrites();
|
|
171
198
|
this.appendMessage(userMessage(input), original.parentId ?? null);
|
|
199
|
+
this.store.set(onPath);
|
|
172
200
|
this.persist();
|
|
173
201
|
await this.run([...this.store.get().messages], opts);
|
|
174
202
|
}
|
|
@@ -184,11 +212,15 @@ var AgentClient = class {
|
|
|
184
212
|
const index = siblings.findIndex((m) => m.id === messageId);
|
|
185
213
|
const next = siblings[(index + delta + siblings.length) % siblings.length];
|
|
186
214
|
const headId = latestLeaf(s.tree, next.id);
|
|
187
|
-
this.
|
|
215
|
+
this.flushSurfaceWrites();
|
|
216
|
+
this.store.set((prev) => onPath({ ...prev, headId, messages: pathTo(prev.tree, headId) }));
|
|
188
217
|
this.persist();
|
|
189
218
|
}
|
|
190
219
|
async run(messages, opts) {
|
|
191
220
|
const gen = this.generation;
|
|
221
|
+
this.flushSurfaceWrites();
|
|
222
|
+
const surfaces = new SurfaceLedger(this.store.get().surfaces);
|
|
223
|
+
this.surfaceLedger = surfaces;
|
|
192
224
|
this.controller = new AbortController();
|
|
193
225
|
const mode = this.config.mode ?? "stream";
|
|
194
226
|
this.turnStartedAt = Date.now();
|
|
@@ -228,10 +260,9 @@ var AgentClient = class {
|
|
|
228
260
|
signal: this.controller.signal,
|
|
229
261
|
forceSkillIds: opts.forceSkillIds,
|
|
230
262
|
onHostTool: this.config.onHostTool,
|
|
263
|
+
surfaces,
|
|
231
264
|
// Suspend the run on an interactive card; `respond()` resolves it.
|
|
232
|
-
onUserDecision:
|
|
233
|
-
this.pending.set(callId, { card, resolve });
|
|
234
|
-
})
|
|
265
|
+
onUserDecision: this.awaitDecision
|
|
235
266
|
};
|
|
236
267
|
try {
|
|
237
268
|
for await (const event of runAgent(messages, runConfig)) {
|
|
@@ -242,9 +273,16 @@ var AgentClient = class {
|
|
|
242
273
|
if (gen === this.generation) this.store.set((s) => ({ ...s, status: "error", error: e }));
|
|
243
274
|
} finally {
|
|
244
275
|
this.controller = null;
|
|
245
|
-
|
|
276
|
+
this.surfaceLedger = null;
|
|
277
|
+
if (gen === this.generation) {
|
|
278
|
+
this.commitRun();
|
|
279
|
+
this.drainSurfaceQueue();
|
|
280
|
+
}
|
|
246
281
|
}
|
|
247
282
|
}
|
|
283
|
+
awaitDecision = (callId, card) => new Promise((resolve) => {
|
|
284
|
+
this.pending.set(callId, { card, resolve });
|
|
285
|
+
});
|
|
248
286
|
apply(event) {
|
|
249
287
|
this.store.set((s) => {
|
|
250
288
|
const run = reduceRunEvent(s.run, event);
|
|
@@ -264,6 +302,9 @@ var AgentClient = class {
|
|
|
264
302
|
next.jobs = s.jobs.map((j) => j.handle.id === event.handle.id ? { ...j, status: event.status, updatedAt: Date.now() } : j);
|
|
265
303
|
}
|
|
266
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
|
+
}
|
|
267
308
|
return next;
|
|
268
309
|
});
|
|
269
310
|
}
|
|
@@ -274,7 +315,8 @@ var AgentClient = class {
|
|
|
274
315
|
* them — the ContextBuilder strips artifacts before they reach a provider,
|
|
275
316
|
* so this costs nothing at request time.
|
|
276
317
|
*/
|
|
277
|
-
commitRun() {
|
|
318
|
+
commitRun(origin) {
|
|
319
|
+
this.flushSurfaceWrites(true);
|
|
278
320
|
this.store.set((s) => {
|
|
279
321
|
const status = s.status === "error" ? "error" : s.run.status;
|
|
280
322
|
const run = s.run.partialTools && Object.keys(s.run.partialTools).length ? { ...s.run, partialTools: {} } : s.run;
|
|
@@ -285,13 +327,16 @@ var AgentClient = class {
|
|
|
285
327
|
id: c.id,
|
|
286
328
|
kind: `card:${c.spec.kind ?? "unknown"}`,
|
|
287
329
|
data: c.spec,
|
|
288
|
-
...c.action ? { action: c.action } : {}
|
|
330
|
+
...c.action ? { action: c.action } : {},
|
|
331
|
+
// Where the card belongs among the turn's text.
|
|
332
|
+
...c.callId ? { callId: c.callId } : {}
|
|
289
333
|
}));
|
|
290
334
|
const meta = {
|
|
291
335
|
model: this.config.model,
|
|
292
336
|
ms: this.turnStartedAt ? Date.now() - this.turnStartedAt : 0,
|
|
293
337
|
...s.run.usage && Object.keys(s.run.usage).length ? { usage: s.run.usage } : {},
|
|
294
|
-
...s.run.steps ? { steps: s.run.steps } : {}
|
|
338
|
+
...s.run.steps ? { steps: s.run.steps } : {},
|
|
339
|
+
...origin ? { origin } : {}
|
|
295
340
|
};
|
|
296
341
|
const linked = {
|
|
297
342
|
...assistantMessage([...toolResultsInCallOrder(parts), ...cardParts]),
|
|
@@ -338,12 +383,14 @@ var AgentClient = class {
|
|
|
338
383
|
if (!store) return false;
|
|
339
384
|
const stored = await store.load(id);
|
|
340
385
|
if (!stored) return false;
|
|
386
|
+
this.saveSurfacesNow();
|
|
341
387
|
this.generation += 1;
|
|
342
388
|
this.stop();
|
|
389
|
+
this.surfaceQueue = [];
|
|
343
390
|
this.threadMeta = stored.meta;
|
|
344
391
|
const tree = linkLinear(stored.messages);
|
|
345
392
|
const headId = stored.headId ?? tree.at(-1)?.id ?? null;
|
|
346
|
-
this.store.set((s) => ({
|
|
393
|
+
this.store.set((s) => onPath({
|
|
347
394
|
...s,
|
|
348
395
|
id: stored.meta.id,
|
|
349
396
|
tree,
|
|
@@ -353,14 +400,17 @@ var AgentClient = class {
|
|
|
353
400
|
attachments: [],
|
|
354
401
|
run: initialRunState("", this.config.mode ?? "stream"),
|
|
355
402
|
status: "idle",
|
|
356
|
-
error: void 0
|
|
403
|
+
error: void 0,
|
|
404
|
+
surfaceActivity: {}
|
|
357
405
|
}));
|
|
358
406
|
return true;
|
|
359
407
|
}
|
|
360
408
|
/** Start a fresh thread under a new id (`clear()` keeps the id; this doesn't). */
|
|
361
409
|
newThread() {
|
|
410
|
+
this.saveSurfacesNow();
|
|
362
411
|
this.generation += 1;
|
|
363
412
|
this.stop();
|
|
413
|
+
this.surfaceQueue = [];
|
|
364
414
|
this.threadMeta = void 0;
|
|
365
415
|
this.store.set((s) => ({
|
|
366
416
|
...s,
|
|
@@ -372,7 +422,9 @@ var AgentClient = class {
|
|
|
372
422
|
attachments: [],
|
|
373
423
|
run: initialRunState("", this.config.mode ?? "stream"),
|
|
374
424
|
status: "idle",
|
|
375
|
-
error: void 0
|
|
425
|
+
error: void 0,
|
|
426
|
+
surfaces: {},
|
|
427
|
+
surfaceActivity: {}
|
|
376
428
|
}));
|
|
377
429
|
}
|
|
378
430
|
/** Answer an interactive card. Unblocks the suspended tool. */
|
|
@@ -400,10 +452,237 @@ var AgentClient = class {
|
|
|
400
452
|
entry.resolve({ cardId: entry.card.id, callId, kind: "cancel", type: "cancel", at: Date.now() });
|
|
401
453
|
}
|
|
402
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;
|
|
403
680
|
}
|
|
404
681
|
clear() {
|
|
682
|
+
this.dirtySurfaces.clear();
|
|
405
683
|
this.generation += 1;
|
|
406
684
|
this.stop();
|
|
685
|
+
this.surfaceQueue = [];
|
|
407
686
|
this.store.set((s) => ({
|
|
408
687
|
...s,
|
|
409
688
|
messages: [],
|
|
@@ -414,7 +693,9 @@ var AgentClient = class {
|
|
|
414
693
|
run: initialRunState("", this.config.mode ?? "stream"),
|
|
415
694
|
status: "idle",
|
|
416
695
|
error: void 0,
|
|
417
|
-
stopping: false
|
|
696
|
+
stopping: false,
|
|
697
|
+
surfaces: {},
|
|
698
|
+
surfaceActivity: {}
|
|
418
699
|
}));
|
|
419
700
|
this.persist();
|
|
420
701
|
}
|
|
@@ -462,6 +743,24 @@ var AgentClient = class {
|
|
|
462
743
|
);
|
|
463
744
|
}
|
|
464
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
|
+
};
|
|
465
764
|
function toolResultsInCallOrder(parts) {
|
|
466
765
|
const callAt = /* @__PURE__ */ new Map();
|
|
467
766
|
parts.forEach((p, i) => {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client.ts","../src/store.ts"],"sourcesContent":["// AgentClient — the framework-agnostic controller the React hooks wrap.\n//\n// It owns: the thread, the current run, pending user decisions, and background\n// jobs. Kept outside React so the same object can be driven from a test, a CLI,\n// or a non-React host — the hooks are a thin `useSyncExternalStore` over it.\n\nimport {\n initialRunState,\n reduceRunEvent,\n runAgent,\n resumeJobs,\n type Card,\n type CardAction,\n type ContentPart,\n type ContextBuilder,\n type JobStore,\n type Message,\n type Provider,\n type RunConfig,\n type RunEvent,\n type RunMode,\n type RunState,\n type StoredJob,\n type ThreadMeta,\n type ThreadStore,\n type ToolCallRequest,\n type ToolRegistry,\n type ToolResolution,\n assistantMessage,\n latestLeaf,\n linkLinear,\n nextId,\n pathTo,\n siblingsOf,\n threadSnapshot,\n userMessage,\n withQuotes,\n formatQuotes,\n checkQuoteDrift,\n QUOTES_METADATA_KEY,\n type DocumentQuoteRef,\n type DocumentStore,\n} from \"@supersolutions/super-chat-core\";\nimport { Store } from \"./store.js\";\n\nexport type ThreadState = {\n id: string;\n /**\n * The ACTIVE PATH — root to head — which is what the UI renders and a run\n * consumes. Always derived from `tree` + `headId`; treat as read-only.\n */\n messages: Message[];\n /**\n * Every message ever sent in this thread, abandoned branches included.\n * Replaced on every change, never mutated in place — `useBranches` caches\n * its sibling index per array. Treat as read-only.\n */\n tree: Message[];\n /** Leaf of the active branch. */\n headId: string | null;\n run: RunState;\n /** Cards from the CURRENT run; committed to messages when the run finishes. */\n cards: Card[];\n jobs: StoredJob[];\n /** Parts staged for the NEXT send (file/image attachments). Thread-scoped. */\n attachments: ContentPart[];\n status: RunState[\"status\"];\n error?: unknown;\n /**\n * A stop was requested but the run has not unwound yet.\n *\n * Needed because `stop()` only aborts a signal — a tool that ignores its\n * signal keeps running, and without this the UI cannot distinguish \"stopping\"\n * from \"the button did nothing\".\n */\n stopping?: boolean;\n};\n\n/** What a finished turn cost, attached to the committed message. */\nexport type TurnMeta = { model: string; ms: number; usage?: RunState[\"usage\"]; steps?: number };\n\nexport type AgentClientConfig = {\n provider: Provider;\n model: string;\n contextBuilder: ContextBuilder;\n tools: ToolRegistry;\n toolResolution: ToolResolution;\n mode?: RunMode;\n maxSteps?: number;\n vars?: Record<string, unknown>;\n temperature?: number;\n maxOutputTokens?: number;\n reasoning?: RunConfig[\"reasoning\"];\n // Full RunConfig surface — a React host must not get LESS control than a\n // direct runAgent caller.\n stopWhen?: RunConfig[\"stopWhen\"];\n toolTimeoutMs?: number;\n useServerHistory?: boolean;\n toolChoice?: RunConfig[\"toolChoice\"];\n providerTools?: RunConfig[\"providerTools\"];\n responseFormat?: RunConfig[\"responseFormat\"];\n topP?: number;\n stopSequences?: string[];\n store?: boolean;\n metadata?: Record<string, string>;\n providerOptions?: RunConfig[\"providerOptions\"];\n meter?: RunConfig[\"meter\"];\n meteringMetadata?: RunConfig[\"meteringMetadata\"];\n jobStore?: JobStore;\n /** When set, the thread is saved after each user and assistant turn. */\n threadStore?: ThreadStore;\n onHostTool?: (call: ToolCallRequest) => Promise<unknown>;\n /** Persisted thread to hydrate from (linear list or a parentId tree). */\n initialMessages?: Message[];\n /** Active-branch leaf when `initialMessages` is a tree. Default: last message. */\n initialHeadId?: string | null;\n threadId?: string;\n /**\n * Where quoted documents can be looked up at send time, to catch a quote\n * taken from a revision the document has since moved past. Only `get` is\n * used; a host whose store lives on a server can pass a fetch-backed one.\n * Unset, quotes are sent as taken.\n */\n documentStore?: Pick<DocumentStore, \"get\">;\n};\n\n/** A card waiting on the user, with the resolver that unblocks the run. */\ntype PendingDecision = { card: Card; resolve: (action: CardAction) => void };\n\nexport class AgentClient {\n readonly store: Store<ThreadState>;\n private config: AgentClientConfig;\n private controller: AbortController | null = null;\n private pending = new Map<string, PendingDecision>();\n /** Meta of the last snapshot saved, so createdAt/title survive re-saves. */\n private threadMeta: ThreadMeta | undefined;\n /**\n * Bumped by every thread switch. A run captures the value it started under\n * and stops writing to the store the moment they diverge — so a run dying\n * from `openThread()`'s stop() cannot leak its error/status/commit into the\n * thread the user just opened.\n */\n private generation = 0;\n /** Wall-clock start of the current turn, for the committed TurnMeta. */\n private turnStartedAt = 0;\n\n constructor(config: AgentClientConfig) {\n this.config = config;\n // `initialMessages` may be a plain linear list (pre-branching hosts) or a\n // tree with parentIds (a v2 snapshot); linkLinear handles both.\n const tree = linkLinear(config.initialMessages ?? []);\n const headId = config.initialHeadId ?? tree.at(-1)?.id ?? null;\n this.store = new Store<ThreadState>({\n id: config.threadId ?? nextId(\"thread\"),\n messages: pathTo(tree, headId),\n tree,\n headId,\n run: initialRunState(\"\", config.mode ?? \"stream\"),\n cards: [],\n jobs: [],\n attachments: [],\n status: \"idle\",\n });\n }\n\n /**\n * Append under `parent` (default: the current head) and move the head there.\n *\n * `extra` merges into the SAME `store.set()` — e.g. clearing `attachments`\n * alongside the append — so a caller touching both fields does not force two\n * notifications for one logical change.\n */\n private appendMessage(message: Message, parent?: string | null, extra?: Partial<ThreadState>): void {\n this.store.set((s) => {\n const parentId = parent !== undefined ? parent : s.headId;\n const linked: Message = { ...message, parentId };\n const tree = [...s.tree, linked];\n return { ...s, tree, headId: linked.id, messages: pathTo(tree, linked.id), ...extra };\n });\n }\n\n /**\n * Stage a part (a file/image the host uploaded) for the next send. The\n * Composer only carries text; this is how binary content joins the turn.\n */\n attach(part: ContentPart): void {\n this.store.set((s) => ({ ...s, attachments: [...s.attachments, part] }));\n }\n\n removeAttachment(index: number): void {\n this.store.set((s) => ({ ...s, attachments: s.attachments.filter((_, i) => i !== index) }));\n }\n\n clearAttachments(): void {\n this.store.set((s) => (s.attachments.length ? { ...s, attachments: [] } : s));\n }\n\n /** Update config in place (model switch, preset toggle) without losing the thread. */\n configure(patch: Partial<AgentClientConfig>): void {\n this.config = { ...this.config, ...patch };\n }\n\n getConfig(): AgentClientConfig {\n return this.config;\n }\n\n get isRunning(): boolean {\n const { status } = this.store.get();\n return status === \"running\" || status === \"awaiting-user\";\n }\n\n /**\n * Append a user message (plus any staged attachments) and run a turn.\n *\n * `quotes` are spans the user highlighted in a document artifact. They are\n * flattened into the message's own text rather than injected as context, and\n * the reasoning is in content/quotes.ts: a quote is part of what the user\n * SAID, so it must not go stale between turns and must not be droppable\n * under budget pressure. The structured form rides on `metadata`, which never\n * reaches a provider, so the chips can be re-rendered from history.\n *\n * With a `documentStore` configured, each quote is first checked against the\n * document as it is now, and a quote taken from an older revision goes out\n * with its drift — in the text, so the model re-reads, and in the metadata,\n * so the UI can say so.\n */\n async send(\n input: string | ContentPart[],\n opts: { forceSkillIds?: string[]; quotes?: readonly DocumentQuoteRef[] } = {},\n ): Promise<void> {\n if (this.isRunning) throw new Error(\"A run is already in progress. Call stop() first.\");\n const { documentStore } = this.config;\n const gen = this.generation;\n const quotes =\n opts.quotes?.length && documentStore ? await checkQuoteDrift(opts.quotes, documentStore) : (opts.quotes ?? []);\n // The drift lookup is an await, and a second send could have started in it.\n if (this.isRunning) throw new Error(\"A run is already in progress. Call stop() first.\");\n // The user opened or started another thread while the drift lookup was out: the text they\n // typed belongs to the thread they left, and appending it to this one would be worse than\n // dropping it.\n if (gen !== this.generation) return;\n const staged = this.store.get().attachments;\n const quoted: string | ContentPart[] =\n quotes.length === 0\n ? input\n : typeof input === \"string\"\n ? withQuotes(input, quotes)\n : [{ type: \"text\", text: formatQuotes(quotes) } as ContentPart, ...input];\n const parts: ContentPart[] = typeof quoted === \"string\" ? [{ type: \"text\", text: quoted }] : [...quoted];\n const base = userMessage(staged.length ? [...parts, ...staged] : quoted);\n const message: Message = quotes.length\n ? { ...base, metadata: { ...base.metadata, [QUOTES_METADATA_KEY]: quotes } }\n : base;\n this.appendMessage(message, undefined, { attachments: [] });\n // Persist the user turn before running — a reload mid-run keeps it.\n this.persist();\n await this.run([...this.store.get().messages], opts);\n }\n\n /**\n * Re-run from the last user message. A FORK, not a rewrite: the head moves\n * back to that user message and the new answer grows as a sibling of the\n * old one, which stays switchable via `switchBranch`.\n */\n async regenerate(opts: { forceSkillIds?: string[] } = {}): Promise<void> {\n if (this.isRunning) throw new Error(\"A run is already in progress.\");\n const { messages } = this.store.get();\n for (let i = messages.length - 1; i >= 0; i -= 1) {\n const m = messages[i]!;\n if (m.role === \"user\") {\n this.store.set((s) => ({ ...s, headId: m.id, messages: pathTo(s.tree, m.id) }));\n await this.run([...this.store.get().messages], opts);\n return;\n }\n }\n }\n\n /**\n * Edit a user message: a SIBLING fork under the same parent, preserving the\n * original and everything under it. The edited branch runs immediately.\n */\n async editMessage(messageId: string, input: string | ContentPart[], opts: { forceSkillIds?: string[] } = {}): Promise<void> {\n if (this.isRunning) throw new Error(\"A run is already in progress.\");\n const original = this.store.get().tree.find((m) => m.id === messageId);\n if (!original || original.role !== \"user\") return;\n this.appendMessage(userMessage(input), original.parentId ?? null);\n this.persist();\n await this.run([...this.store.get().messages], opts);\n }\n\n /**\n * Move the active branch to a SIBLING of `messageId` (delta −1/+1 in\n * insertion order), resuming at that branch's latest leaf.\n */\n switchBranch(messageId: string, delta: number): void {\n if (this.isRunning) return; // switching under a live run would cross-write threads of the same id\n const s = this.store.get();\n const siblings = siblingsOf(s.tree, messageId);\n if (siblings.length < 2) return;\n const index = siblings.findIndex((m) => m.id === messageId);\n const next = siblings[(index + delta + siblings.length) % siblings.length]!;\n const headId = latestLeaf(s.tree, next.id);\n this.store.set((prev) => ({ ...prev, headId, messages: pathTo(prev.tree, headId) }));\n this.persist();\n }\n\n private async run(messages: Message[], opts: { forceSkillIds?: string[] }): Promise<void> {\n const gen = this.generation;\n this.controller = new AbortController();\n const mode = this.config.mode ?? \"stream\";\n this.turnStartedAt = Date.now();\n this.store.set((s) => ({\n ...s,\n run: initialRunState(nextId(\"run\"), mode),\n cards: [],\n status: \"running\",\n error: undefined,\n stopping: false,\n }));\n\n const runConfig: RunConfig = {\n provider: this.config.provider,\n model: this.config.model,\n contextBuilder: this.config.contextBuilder,\n tools: this.config.tools,\n toolResolution: this.config.toolResolution,\n mode,\n maxSteps: this.config.maxSteps,\n vars: this.config.vars,\n temperature: this.config.temperature,\n maxOutputTokens: this.config.maxOutputTokens,\n reasoning: this.config.reasoning,\n stopWhen: this.config.stopWhen,\n toolTimeoutMs: this.config.toolTimeoutMs,\n useServerHistory: this.config.useServerHistory,\n toolChoice: this.config.toolChoice,\n providerTools: this.config.providerTools,\n responseFormat: this.config.responseFormat,\n topP: this.config.topP,\n stopSequences: this.config.stopSequences,\n store: this.config.store,\n metadata: this.config.metadata,\n providerOptions: this.config.providerOptions,\n meter: this.config.meter,\n meteringMetadata: this.config.meteringMetadata,\n signal: this.controller.signal,\n forceSkillIds: opts.forceSkillIds,\n onHostTool: this.config.onHostTool,\n // Suspend the run on an interactive card; `respond()` resolves it.\n onUserDecision: (callId, card) =>\n new Promise<CardAction>((resolve) => {\n this.pending.set(callId, { card, resolve });\n }),\n };\n\n try {\n for await (const event of runAgent(messages, runConfig)) {\n if (gen !== this.generation) return; // thread switched under us — drop the rest\n this.apply(event);\n }\n } catch (e) {\n if (gen === this.generation) this.store.set((s) => ({ ...s, status: \"error\", error: e }));\n } finally {\n this.controller = null;\n if (gen === this.generation) this.commitRun();\n }\n }\n\n private apply(event: RunEvent): void {\n this.store.set((s) => {\n const run = reduceRunEvent(s.run, event);\n const next: ThreadState = { ...s, run, status: run.status, cards: run.cards };\n if (event.type === \"job-started\" && this.config.jobStore) {\n const job: StoredJob = {\n handle: event.handle,\n status: \"queued\",\n threadId: s.id,\n createdAt: Date.now(),\n updatedAt: Date.now(),\n };\n // Fire and forget: persistence must not stall the run.\n void this.config.jobStore.put(job);\n next.jobs = [job, ...s.jobs];\n }\n if (event.type === \"job-status\") {\n next.jobs = s.jobs.map((j) => (j.handle.id === event.handle.id ? { ...j, status: event.status, updatedAt: Date.now() } : j));\n }\n if (event.type === \"error\") next.error = event.error;\n return next;\n });\n }\n\n /**\n * Fold the finished run's parts into the thread as one assistant message.\n *\n * Cards are attached as artifact parts so a reloaded thread still renders\n * them — the ContextBuilder strips artifacts before they reach a provider,\n * so this costs nothing at request time.\n */\n private commitRun(): void {\n this.store.set((s) => {\n // run.status reflects only what the agent loop itself saw, never a\n // throw caught in run()'s catch block — so a caught error must win\n // over it here, or the catch's \"error\" status gets overwritten back\n // to whatever the loop last reduced to (e.g. \"running\").\n const status = s.status === \"error\" ? \"error\" : s.run.status;\n // Streaming-argument previews are live-only. run-finish already clears\n // them; a run that died by throwing never sent one, so clear them here\n // too rather than leave a half-drawn card on an errored turn.\n const run = s.run.partialTools && Object.keys(s.run.partialTools).length ? { ...s.run, partialTools: {} } : s.run;\n const parts = run.parts;\n if (!parts.length && !run.cards.length) return { ...s, run, status };\n\n // `data` carries the answer alongside the spec: an answered card that\n // re-renders from history has to show what the user actually chose, and\n // the renderer's own state is gone by then.\n const cardParts: ContentPart[] = s.run.cards.map((c) => ({\n type: \"artifact\",\n id: c.id,\n kind: `card:${(c.spec as { kind?: string }).kind ?? \"unknown\"}`,\n data: c.spec,\n ...(c.action ? { action: c.action } : {}),\n }));\n\n // What the turn cost, recorded on the message. The UI has no other way to\n // show it after the fact: run state is reset by the next turn.\n const meta: TurnMeta = {\n model: this.config.model,\n ms: this.turnStartedAt ? Date.now() - this.turnStartedAt : 0,\n ...(s.run.usage && Object.keys(s.run.usage).length ? { usage: s.run.usage } : {}),\n ...(s.run.steps ? { steps: s.run.steps } : {}),\n };\n\n const linked: Message = {\n ...assistantMessage([...toolResultsInCallOrder(parts), ...cardParts]),\n parentId: s.headId,\n metadata: { turn: meta },\n };\n const tree = [...s.tree, linked];\n return {\n ...s,\n run,\n tree,\n headId: linked.id,\n messages: pathTo(tree, linked.id),\n status: s.run.status,\n stopping: false,\n };\n });\n this.persist();\n }\n\n /**\n * Fire-and-forget save, the same posture as the job store put: persistence\n * must not stall the run, and a failed save degrades to \"not saved\", never\n * to a broken thread.\n */\n private persist(): void {\n const store = this.config.threadStore;\n if (!store) return;\n const s = this.store.get();\n if (this.threadMeta && this.threadMeta.id !== s.id) this.threadMeta = undefined;\n void (async () => {\n // A client hydrated via config (threadId/initialMessages) has no meta in\n // hand; read the stored one so createdAt and title survive the reload.\n const prior = this.threadMeta ?? (await store.load(s.id))?.meta;\n // The TREE persists — abandoned branches included — plus the active head.\n const snapshot = threadSnapshot(s.id, s.tree, prior, s.headId);\n this.threadMeta = snapshot.meta;\n await store.save(snapshot);\n })().catch(() => {\n // Fire-and-forget: a failed save degrades to \"not saved\", never a crash.\n });\n }\n\n /**\n * Load a stored thread and replace the current one. Returns false when the\n * id is unknown (the current thread is left untouched).\n */\n async openThread(id: string): Promise<boolean> {\n const store = this.config.threadStore;\n if (!store) return false;\n const stored = await store.load(id);\n if (!stored) return false;\n this.generation += 1; // invalidate any in-flight run before replacing state\n this.stop();\n this.threadMeta = stored.meta;\n const tree = linkLinear(stored.messages);\n const headId = stored.headId ?? tree.at(-1)?.id ?? null;\n this.store.set((s) => ({\n ...s,\n id: stored.meta.id,\n tree,\n headId,\n messages: pathTo(tree, headId),\n cards: [],\n attachments: [],\n run: initialRunState(\"\", this.config.mode ?? \"stream\"),\n status: \"idle\",\n error: undefined,\n }));\n return true;\n }\n\n /** Start a fresh thread under a new id (`clear()` keeps the id; this doesn't). */\n newThread(): void {\n this.generation += 1;\n this.stop();\n this.threadMeta = undefined;\n this.store.set((s) => ({\n ...s,\n id: nextId(\"thread\"),\n messages: [],\n tree: [],\n headId: null,\n cards: [],\n attachments: [],\n run: initialRunState(\"\", this.config.mode ?? \"stream\"),\n status: \"idle\",\n error: undefined,\n }));\n }\n\n /** Answer an interactive card. Unblocks the suspended tool. */\n respond(action: CardAction): void {\n const entry = this.pending.get(action.callId ?? \"\");\n if (!entry) return;\n this.pending.delete(action.callId ?? \"\");\n entry.resolve(action);\n }\n\n /** The card currently blocking the run, if any. */\n pendingCard(): Card | undefined {\n return this.store.get().run.pendingCard;\n }\n\n stop(): void {\n if (!this.isRunning) return;\n // Mark the request immediately. Aborting is not the same as having stopped:\n // a tool that ignores its signal runs to completion, and the UI has to be\n // able to say \"stopping\" instead of looking inert.\n this.store.set((s) => ({ ...s, stopping: true }));\n this.controller?.abort();\n // A background job keeps running (and billing) server-side after a local\n // abort — cancel it there too, best-effort.\n const job = this.store.get().run.job;\n if (job && this.config.provider.cancelJob && ![\"completed\", \"failed\", \"cancelled\"].includes(job.status)) {\n void this.config.provider.cancelJob(job.handle).catch(() => {});\n void this.config.jobStore?.remove(job.handle.id);\n }\n // Release any suspended tool so the run can unwind instead of hanging.\n for (const [callId, entry] of this.pending) {\n entry.resolve({ cardId: entry.card.id, callId, kind: \"cancel\", type: \"cancel\", at: Date.now() });\n }\n this.pending.clear();\n }\n\n clear(): void {\n this.generation += 1;\n this.stop();\n this.store.set((s) => ({\n ...s,\n messages: [],\n tree: [],\n headId: null,\n cards: [],\n attachments: [],\n run: initialRunState(\"\", this.config.mode ?? \"stream\"),\n status: \"idle\",\n error: undefined,\n stopping: false,\n }));\n // Without this, reload restores the conversation the user just cleared.\n this.persist();\n }\n\n /**\n * Re-poll background jobs from a previous session. Call on mount.\n *\n * Results are routed by `StoredJob.threadId`: the current thread gets its\n * results appended live; another thread's results are written into its\n * stored snapshot (when a ThreadStore is configured), so an answer to\n * thread A never gets pasted into thread B.\n */\n async resumeBackgroundJobs(): Promise<void> {\n const store = this.config.jobStore;\n if (!store) return;\n const results = await resumeJobs(store, { [this.config.provider.id]: this.config.provider });\n this.store.set((s) => ({ ...s, jobs: results.map((r) => r.job) }));\n\n const currentId = this.store.get().id;\n // Jobs landing in an AWAY thread are grouped by threadId: two jobs for the\n // SAME away thread read-modify-write that thread's one stored snapshot, so\n // they must land in order or the second save clobbers the first. Jobs for\n // DIFFERENT away threads touch different snapshots and have no ordering\n // dependency on each other, so those groups load/save concurrently.\n const away = new Map<string, ContentPart[][]>();\n\n for (const { job, snapshot } of results) {\n const parts: ContentPart[] | null =\n snapshot.status === \"completed\" && snapshot.result\n ? snapshot.result.parts\n : snapshot.status === \"failed\"\n ? [{ type: \"text\", text: `_${snapshot.error?.message ?? \"A background job failed.\"}_` }]\n : null;\n if (!parts) continue;\n\n if (!job.threadId || job.threadId === currentId) {\n this.appendMessage(assistantMessage(parts));\n if (job.threadId === currentId) this.persist();\n continue;\n }\n\n const bucket = away.get(job.threadId) ?? [];\n bucket.push(parts);\n away.set(job.threadId, bucket);\n }\n\n const threads = this.config.threadStore;\n if (!threads || !away.size) return; // nowhere to put it; the handle was already reaped\n\n await Promise.all(\n [...away].map(async ([threadId, partsList]) => {\n for (const parts of partsList) {\n const stored = await threads.load(threadId);\n if (!stored) continue;\n const awayHead = stored.headId ?? stored.messages.at(-1)?.id ?? null;\n const appended: Message = { ...assistantMessage(parts), parentId: awayHead };\n await threads.save(\n threadSnapshot(threadId, [...stored.messages, appended], stored.meta, appended.id),\n );\n }\n }),\n );\n }\n}\n\n/**\n * Run state appends tool results as they finish; a committed turn keeps them in\n * the order they were called, the same order runAgent writes back to history.\n * Only results that sit next to each other move, and only among themselves.\n */\nfunction toolResultsInCallOrder(parts: readonly ContentPart[]): ContentPart[] {\n const callAt = new Map<string, number>();\n parts.forEach((p, i) => {\n if (p.type === \"tool-call\") callAt.set(p.callId, i);\n });\n const rank = (p: ContentPart) =>\n p.type === \"tool-result\" ? (callAt.get(p.callId) ?? Number.MAX_SAFE_INTEGER) : Number.MAX_SAFE_INTEGER;\n\n const out: ContentPart[] = [];\n let batch: ContentPart[] = [];\n const flush = () => {\n out.push(...batch.sort((a, b) => rank(a) - rank(b)));\n batch = [];\n };\n for (const p of parts) {\n if (p.type === \"tool-result\") batch.push(p);\n else {\n flush();\n out.push(p);\n }\n }\n flush();\n return out;\n}\n","// A tiny external store, consumed via useSyncExternalStore.\n//\n// Hand-rolled rather than pulling in zustand/valtio for two reasons: the state\n// shape is already defined by the core's `RunState` reducer, and a chat thread\n// under a streaming run notifies at token frequency — a store that allocates a\n// new subscriber array per notify shows up in a profile at 60+ notifies/sec.\n\nexport type Listener = () => void;\n\nexport class Store<T> {\n private state: T;\n private listeners = new Set<Listener>();\n\n constructor(initial: T) {\n this.state = initial;\n }\n\n get = (): T => this.state;\n\n set = (next: T | ((prev: T) => T)): void => {\n const value = typeof next === \"function\" ? (next as (prev: T) => T)(this.state) : next;\n // Reference equality guard: a reducer that returns the same object (a\n // no-op event) must not wake every subscriber.\n if (Object.is(value, this.state)) return;\n this.state = value;\n for (const listener of this.listeners) listener();\n };\n\n subscribe = (listener: Listener): (() => void) => {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n };\n}\n"],"mappings":";AAMA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAkBA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;;;ACjCA,IAAM,QAAN,MAAe;AAAA,EACZ;AAAA,EACA,YAAY,oBAAI,IAAc;AAAA,EAEtC,YAAY,SAAY;AACtB,SAAK,QAAQ;AAAA,EACf;AAAA,EAEA,MAAM,MAAS,KAAK;AAAA,EAEpB,MAAM,CAAC,SAAqC;AAC1C,UAAM,QAAQ,OAAO,SAAS,aAAc,KAAwB,KAAK,KAAK,IAAI;AAGlF,QAAI,OAAO,GAAG,OAAO,KAAK,KAAK,EAAG;AAClC,SAAK,QAAQ;AACb,eAAW,YAAY,KAAK,UAAW,UAAS;AAAA,EAClD;AAAA,EAEA,YAAY,CAAC,aAAqC;AAChD,SAAK,UAAU,IAAI,QAAQ;AAC3B,WAAO,MAAM;AACX,WAAK,UAAU,OAAO,QAAQ;AAAA,IAChC;AAAA,EACF;AACF;;;AD+FO,IAAM,cAAN,MAAkB;AAAA,EACd;AAAA,EACD;AAAA,EACA,aAAqC;AAAA,EACrC,UAAU,oB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;AAChE,gBAAM,WAAoB,EAAE,GAAG,iBAAiB,KAAK,GAAG,UAAU,SAAS;AAC3E,gBAAM,QAAQ;AAAA,YACZ,eAAe,UAAU,CAAC,GAAG,OAAO,UAAU,QAAQ,GAAG,OAAO,MAAM,SAAS,EAAE;AAAA,UACnF;AAAA,QACF;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF;AACF;AAOA,SAAS,uBAAuB,OAA8C;AAC5E,QAAM,SAAS,oBAAI,IAAoB;AACvC,QAAM,QAAQ,CAAC,GAAG,MAAM;AACtB,QAAI,EAAE,SAAS,YAAa,QAAO,IAAI,EAAE,QAAQ,CAAC;AAAA,EACpD,CAAC;AACD,QAAM,OAAO,CAAC,MACZ,EAAE,SAAS,gBAAiB,OAAO,IAAI,EAAE,MAAM,KAAK,OAAO,mBAAoB,OAAO;AAExF,QAAM,MAAqB,CAAC;AAC5B,MAAI,QAAuB,CAAC;AAC5B,QAAM,QAAQ,MAAM;AAClB,QAAI,KAAK,GAAG,MAAM,KAAK,CAAC,GAAG,MAAM,KAAK,CAAC,IAAI,KAAK,CAAC,CAAC,CAAC;AACnD,YAAQ,CAAC;AAAA,EACX;AACA,aAAW,KAAK,OAAO;AACrB,QAAI,EAAE,SAAS,cAAe,OAAM,KAAK,CAAC;AAAA,SACrC;AACH,YAAM;AACN,UAAI,KAAK,CAAC;AAAA,IACZ;AAAA,EACF;AACA,QAAM;AACN,SAAO;AACT;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/client.ts","../src/store.ts"],"sourcesContent":["// AgentClient — the framework-agnostic controller the React hooks wrap.\n//\n// It owns: the thread, the current run, pending user decisions, and background\n// jobs. Kept outside React so the same object can be driven from a test, a CLI,\n// or a non-React host — the hooks are a thin `useSyncExternalStore` over it.\n\nimport {\n initialRunState,\n reduceRunEvent,\n runAgent,\n resumeJobs,\n type Card,\n type CardAction,\n type ContentPart,\n type ContextBuilder,\n type JobStore,\n type Message,\n type Provider,\n type RunConfig,\n type RunEvent,\n type RunMode,\n type RunState,\n type StoredJob,\n type ThreadMeta,\n type ThreadStore,\n type ToolCallRequest,\n type ToolRegistry,\n type ToolResolution,\n assistantMessage,\n latestLeaf,\n linkLinear,\n nextId,\n pathTo,\n siblingsOf,\n threadSnapshot,\n userMessage,\n withQuotes,\n formatQuotes,\n checkQuoteDrift,\n QUOTES_METADATA_KEY,\n type DocumentQuoteRef,\n type DocumentStore,\n type CardRegistry,\n type SurfaceAction,\n type SurfaceActivity,\n type SurfaceActivityState,\n type SurfaceCardAnswer,\n type SurfaceCatalogue,\n type SurfaceComponent,\n type SurfaceEventRecord,\n type SurfaceSpec,\n SURFACE_EVENT_METADATA_KEY,\n SURFACE_LIMITS,\n SurfaceLedger,\n authorizeSurfaceTool,\n evaluateSurfaceCondition,\n foldSurfaces,\n getAt,\n isSurfaceSpec,\n resolveSurfaceAction,\n runSurfaceToolAction,\n setAt,\n stripCardPayload,\n surfaceCardId,\n} from \"@supersolutions/super-chat-core\";\nimport { Store } from \"./store.js\";\n\nexport type ThreadState = {\n id: string;\n /**\n * The ACTIVE PATH — root to head — which is what the UI renders and a run\n * consumes. Always derived from `tree` + `headId`; treat as read-only.\n */\n messages: Message[];\n /**\n * Every message ever sent in this thread, abandoned branches included.\n * Replaced on every change, never mutated in place — `useBranches` caches\n * its sibling index per array. Treat as read-only.\n */\n tree: Message[];\n /** Leaf of the active branch. */\n headId: string | null;\n run: RunState;\n /** Cards from the CURRENT run; committed to messages when the run finishes. */\n cards: Card[];\n jobs: StoredJob[];\n /** Parts staged for the NEXT send (file/image attachments). Thread-scoped. */\n attachments: ContentPart[];\n status: RunState[\"status\"];\n error?: unknown;\n /**\n * A stop was requested but the run has not unwound yet.\n *\n * Needed because `stop()` only aborts a signal — a tool that ignores its\n * signal keeps running, and without this the UI cannot distinguish \"stopping\"\n * from \"the button did nothing\".\n */\n stopping?: boolean;\n /** Current state of each surface on the active path, the person's edits included. */\n surfaces: Record<string, SurfaceSpec>;\n /** What became of the last action pressed on each surface. */\n surfaceActivity: Record<string, SurfaceActivity>;\n};\n\n/** What a finished turn cost, attached to the committed message. */\nexport type TurnMeta = {\n model: string;\n ms: number;\n usage?: RunState[\"usage\"];\n steps?: number;\n /** Set when a person's button press produced this turn rather than a model. */\n origin?: \"surface-action\";\n};\n\nexport type AgentClientConfig = {\n provider: Provider;\n model: string;\n contextBuilder: ContextBuilder;\n tools: ToolRegistry;\n toolResolution: ToolResolution;\n mode?: RunMode;\n maxSteps?: number;\n vars?: Record<string, unknown>;\n temperature?: number;\n maxOutputTokens?: number;\n reasoning?: RunConfig[\"reasoning\"];\n // Full RunConfig surface — a React host must not get LESS control than a\n // direct runAgent caller.\n stopWhen?: RunConfig[\"stopWhen\"];\n toolTimeoutMs?: number;\n useServerHistory?: boolean;\n toolChoice?: RunConfig[\"toolChoice\"];\n providerTools?: RunConfig[\"providerTools\"];\n responseFormat?: RunConfig[\"responseFormat\"];\n topP?: number;\n stopSequences?: string[];\n store?: boolean;\n metadata?: Record<string, string>;\n providerOptions?: RunConfig[\"providerOptions\"];\n meter?: RunConfig[\"meter\"];\n meteringMetadata?: RunConfig[\"meteringMetadata\"];\n jobStore?: JobStore;\n /** When set, the thread is saved after each user and assistant turn. */\n threadStore?: ThreadStore;\n onHostTool?: (call: ToolCallRequest) => Promise<unknown>;\n /** Persisted thread to hydrate from (linear list or a parentId tree). */\n initialMessages?: Message[];\n /** Active-branch leaf when `initialMessages` is a tree. Default: last message. */\n initialHeadId?: string | null;\n threadId?: string;\n /**\n * Where quoted documents can be looked up at send time, to catch a quote\n * taken from a revision the document has since moved past. Only `get` is\n * used; a host whose store lives on a server can pass a fetch-backed one.\n * Unset, quotes are sent as taken.\n */\n documentStore?: Pick<DocumentStore, \"get\">;\n /** The card registry in use, so the UI can ask it which kinds are interactive. */\n cards?: CardRegistry;\n /** The surface catalogue in use, so the renderer validates against what the tools accept. */\n surfaceCatalogue?: SurfaceCatalogue;\n};\n\n/** How long local edits gather before they are written into the thread and saved. */\nconst SURFACE_SAVE_DELAY_MS = 300;\nconst SURFACE_QUEUE_LIMIT = 8;\nconst SURFACE_CONTEXT_CHARS = 4_000;\n\ntype QueuedSurfaceAction = { spec: SurfaceSpec; component: SurfaceComponent; action: Exclude<SurfaceAction, { type: \"set\" }> };\n\n/** A card waiting on the user, with the resolver that unblocks the run. */\ntype PendingDecision = { card: Card; resolve: (action: CardAction) => void };\n\nexport class AgentClient {\n readonly store: Store<ThreadState>;\n private config: AgentClientConfig;\n private controller: AbortController | null = null;\n private pending = new Map<string, PendingDecision>();\n /** Meta of the last snapshot saved, so createdAt/title survive re-saves. */\n private threadMeta: ThreadMeta | undefined;\n /**\n * Bumped by every thread switch. A run captures the value it started under\n * and stops writing to the store the moment they diverge — so a run dying\n * from `openThread()`'s stop() cannot leak its error/status/commit into the\n * thread the user just opened.\n */\n private generation = 0;\n /** Wall-clock start of the current turn, for the committed TurnMeta. */\n private turnStartedAt = 0;\n /** The current run's view of the surfaces, kept level with the person's edits. */\n private surfaceLedger: SurfaceLedger | null = null;\n private dirtySurfaces = new Set<string>();\n private surfaceSaveTimer: ReturnType<typeof setTimeout> | null = null;\n /** Actions pressed while a run was busy. One run at a time, so they wait their turn. */\n private surfaceQueue: QueuedSurfaceAction[] = [];\n\n constructor(config: AgentClientConfig) {\n this.config = config;\n // `initialMessages` may be a plain linear list (pre-branching hosts) or a\n // tree with parentIds (a v2 snapshot); linkLinear handles both.\n const tree = linkLinear(config.initialMessages ?? []);\n const headId = config.initialHeadId ?? tree.at(-1)?.id ?? null;\n const messages = pathTo(tree, headId);\n this.store = new Store<ThreadState>({\n id: config.threadId ?? nextId(\"thread\"),\n messages,\n tree,\n headId,\n run: initialRunState(\"\", config.mode ?? \"stream\"),\n cards: [],\n jobs: [],\n attachments: [],\n status: \"idle\",\n surfaces: foldSurfaces(messages),\n surfaceActivity: {},\n });\n }\n\n /**\n * Append under `parent` (default: the current head) and move the head there.\n *\n * `extra` merges into the SAME `store.set()` — e.g. clearing `attachments`\n * alongside the append — so a caller touching both fields does not force two\n * notifications for one logical change.\n */\n private appendMessage(message: Message, parent?: string | null, extra?: Partial<ThreadState>): void {\n this.store.set((s) => {\n const parentId = parent !== undefined ? parent : s.headId;\n const linked: Message = { ...message, parentId };\n const tree = [...s.tree, linked];\n return { ...s, tree, headId: linked.id, messages: pathTo(tree, linked.id), ...extra };\n });\n }\n\n /**\n * Stage a part (a file/image the host uploaded) for the next send. The\n * Composer only carries text; this is how binary content joins the turn.\n */\n attach(part: ContentPart): void {\n this.store.set((s) => ({ ...s, attachments: [...s.attachments, part] }));\n }\n\n removeAttachment(index: number): void {\n this.store.set((s) => ({ ...s, attachments: s.attachments.filter((_, i) => i !== index) }));\n }\n\n clearAttachments(): void {\n this.store.set((s) => (s.attachments.length ? { ...s, attachments: [] } : s));\n }\n\n /** Update config in place (model switch, preset toggle) without losing the thread. */\n configure(patch: Partial<AgentClientConfig>): void {\n this.config = { ...this.config, ...patch };\n }\n\n getConfig(): AgentClientConfig {\n return this.config;\n }\n\n get isRunning(): boolean {\n const { status } = this.store.get();\n return status === \"running\" || status === \"awaiting-user\";\n }\n\n /**\n * Append a user message (plus any staged attachments) and run a turn.\n *\n * `quotes` are spans the user highlighted in a document artifact. They are\n * flattened into the message's own text rather than injected as context, and\n * the reasoning is in content/quotes.ts: a quote is part of what the user\n * SAID, so it must not go stale between turns and must not be droppable\n * under budget pressure. The structured form rides on `metadata`, which never\n * reaches a provider, so the chips can be re-rendered from history.\n *\n * With a `documentStore` configured, each quote is first checked against the\n * document as it is now, and a quote taken from an older revision goes out\n * with its drift — in the text, so the model re-reads, and in the metadata,\n * so the UI can say so.\n */\n async send(\n input: string | ContentPart[],\n opts: { forceSkillIds?: string[]; quotes?: readonly DocumentQuoteRef[] } = {},\n ): Promise<void> {\n if (this.isRunning) throw new Error(\"A run is already in progress. Call stop() first.\");\n const { documentStore } = this.config;\n const gen = this.generation;\n const quotes =\n opts.quotes?.length && documentStore ? await checkQuoteDrift(opts.quotes, documentStore) : (opts.quotes ?? []);\n // The drift lookup is an await, and a second send could have started in it.\n if (this.isRunning) throw new Error(\"A run is already in progress. Call stop() first.\");\n // The user opened or started another thread while the drift lookup was out: the text they\n // typed belongs to the thread they left, and appending it to this one would be worse than\n // dropping it.\n if (gen !== this.generation) return;\n const staged = this.store.get().attachments;\n const quoted: string | ContentPart[] =\n quotes.length === 0\n ? input\n : typeof input === \"string\"\n ? withQuotes(input, quotes)\n : [{ type: \"text\", text: formatQuotes(quotes) } as ContentPart, ...input];\n const parts: ContentPart[] = typeof quoted === \"string\" ? [{ type: \"text\", text: quoted }] : [...quoted];\n const base = userMessage(staged.length ? [...parts, ...staged] : quoted);\n const message: Message = quotes.length\n ? { ...base, metadata: { ...base.metadata, [QUOTES_METADATA_KEY]: quotes } }\n : base;\n this.appendMessage(message, undefined, { attachments: [] });\n // Persist the user turn before running — a reload mid-run keeps it.\n this.persist();\n await this.run([...this.store.get().messages], opts);\n }\n\n /**\n * Re-run from the last user message. A FORK, not a rewrite: the head moves\n * back to that user message and the new answer grows as a sibling of the\n * old one, which stays switchable via `switchBranch`.\n */\n async regenerate(opts: { forceSkillIds?: string[] } = {}): Promise<void> {\n if (this.isRunning) throw new Error(\"A run is already in progress.\");\n const { messages } = this.store.get();\n for (let i = messages.length - 1; i >= 0; i -= 1) {\n const m = messages[i]!;\n if (m.role === \"user\") {\n this.flushSurfaceWrites();\n this.store.set((s) => onPath({ ...s, headId: m.id, messages: pathTo(s.tree, m.id) }));\n await this.run([...this.store.get().messages], opts);\n return;\n }\n }\n }\n\n /**\n * Edit a user message: a SIBLING fork under the same parent, preserving the\n * original and everything under it. The edited branch runs immediately.\n */\n async editMessage(messageId: string, input: string | ContentPart[], opts: { forceSkillIds?: string[] } = {}): Promise<void> {\n if (this.isRunning) throw new Error(\"A run is already in progress.\");\n const original = this.store.get().tree.find((m) => m.id === messageId);\n if (!original || original.role !== \"user\") return;\n this.flushSurfaceWrites();\n this.appendMessage(userMessage(input), original.parentId ?? null);\n this.store.set(onPath);\n this.persist();\n await this.run([...this.store.get().messages], opts);\n }\n\n /**\n * Move the active branch to a SIBLING of `messageId` (delta −1/+1 in\n * insertion order), resuming at that branch's latest leaf.\n */\n switchBranch(messageId: string, delta: number): void {\n if (this.isRunning) return; // switching under a live run would cross-write threads of the same id\n const s = this.store.get();\n const siblings = siblingsOf(s.tree, messageId);\n if (siblings.length < 2) return;\n const index = siblings.findIndex((m) => m.id === messageId);\n const next = siblings[(index + delta + siblings.length) % siblings.length]!;\n const headId = latestLeaf(s.tree, next.id);\n this.flushSurfaceWrites();\n this.store.set((prev) => onPath({ ...prev, headId, messages: pathTo(prev.tree, headId) }));\n this.persist();\n }\n\n private async run(messages: Message[], opts: { forceSkillIds?: string[] }): Promise<void> {\n const gen = this.generation;\n this.flushSurfaceWrites();\n const surfaces = new SurfaceLedger(this.store.get().surfaces);\n this.surfaceLedger = surfaces;\n this.controller = new AbortController();\n const mode = this.config.mode ?? \"stream\";\n this.turnStartedAt = Date.now();\n this.store.set((s) => ({\n ...s,\n run: initialRunState(nextId(\"run\"), mode),\n cards: [],\n status: \"running\",\n error: undefined,\n stopping: false,\n }));\n\n const runConfig: RunConfig = {\n provider: this.config.provider,\n model: this.config.model,\n contextBuilder: this.config.contextBuilder,\n tools: this.config.tools,\n toolResolution: this.config.toolResolution,\n mode,\n maxSteps: this.config.maxSteps,\n vars: this.config.vars,\n temperature: this.config.temperature,\n maxOutputTokens: this.config.maxOutputTokens,\n reasoning: this.config.reasoning,\n stopWhen: this.config.stopWhen,\n toolTimeoutMs: this.config.toolTimeoutMs,\n useServerHistory: this.config.useServerHistory,\n toolChoice: this.config.toolChoice,\n providerTools: this.config.providerTools,\n responseFormat: this.config.responseFormat,\n topP: this.config.topP,\n stopSequences: this.config.stopSequences,\n store: this.config.store,\n metadata: this.config.metadata,\n providerOptions: this.config.providerOptions,\n meter: this.config.meter,\n meteringMetadata: this.config.meteringMetadata,\n signal: this.controller.signal,\n forceSkillIds: opts.forceSkillIds,\n onHostTool: this.config.onHostTool,\n surfaces,\n // Suspend the run on an interactive card; `respond()` resolves it.\n onUserDecision: this.awaitDecision,\n };\n\n try {\n for await (const event of runAgent(messages, runConfig)) {\n if (gen !== this.generation) return; // thread switched under us — drop the rest\n this.apply(event);\n }\n } catch (e) {\n if (gen === this.generation) this.store.set((s) => ({ ...s, status: \"error\", error: e }));\n } finally {\n this.controller = null;\n this.surfaceLedger = null;\n if (gen === this.generation) {\n this.commitRun();\n this.drainSurfaceQueue();\n }\n }\n }\n\n private awaitDecision = (callId: string, card: Card): Promise<CardAction> =>\n new Promise<CardAction>((resolve) => {\n this.pending.set(callId, { card, resolve });\n });\n\n private apply(event: RunEvent): void {\n this.store.set((s) => {\n const run = reduceRunEvent(s.run, event);\n const next: ThreadState = { ...s, run, status: run.status, cards: run.cards };\n if (event.type === \"job-started\" && this.config.jobStore) {\n const job: StoredJob = {\n handle: event.handle,\n status: \"queued\",\n threadId: s.id,\n createdAt: Date.now(),\n updatedAt: Date.now(),\n };\n // Fire and forget: persistence must not stall the run.\n void this.config.jobStore.put(job);\n next.jobs = [job, ...s.jobs];\n }\n if (event.type === \"job-status\") {\n next.jobs = s.jobs.map((j) => (j.handle.id === event.handle.id ? { ...j, status: event.status, updatedAt: Date.now() } : j));\n }\n if (event.type === \"error\") next.error = event.error;\n if (event.type === \"card\" && isSurfaceSpec(event.card.spec)) {\n next.surfaces = { ...s.surfaces, [event.card.spec.surfaceId]: event.card.spec };\n }\n return next;\n });\n }\n\n /**\n * Fold the finished run's parts into the thread as one assistant message.\n *\n * Cards are attached as artifact parts so a reloaded thread still renders\n * them — the ContextBuilder strips artifacts before they reach a provider,\n * so this costs nothing at request time.\n */\n private commitRun(origin?: TurnMeta[\"origin\"]): void {\n // Edits still gathering belong to this turn's snapshot of the surface.\n this.flushSurfaceWrites(true);\n this.store.set((s) => {\n // run.status reflects only what the agent loop itself saw, never a\n // throw caught in run()'s catch block — so a caught error must win\n // over it here, or the catch's \"error\" status gets overwritten back\n // to whatever the loop last reduced to (e.g. \"running\").\n const status = s.status === \"error\" ? \"error\" : s.run.status;\n // Streaming-argument previews are live-only. run-finish already clears\n // them; a run that died by throwing never sent one, so clear them here\n // too rather than leave a half-drawn card on an errored turn.\n const run = s.run.partialTools && Object.keys(s.run.partialTools).length ? { ...s.run, partialTools: {} } : s.run;\n const parts = run.parts;\n if (!parts.length && !run.cards.length) return { ...s, run, status };\n\n // `data` carries the answer alongside the spec: an answered card that\n // re-renders from history has to show what the user actually chose, and\n // the renderer's own state is gone by then.\n const cardParts: ContentPart[] = s.run.cards.map((c) => ({\n type: \"artifact\",\n id: c.id,\n kind: `card:${(c.spec as { kind?: string }).kind ?? \"unknown\"}`,\n data: c.spec,\n ...(c.action ? { action: c.action } : {}),\n // Where the card belongs among the turn's text.\n ...(c.callId ? { callId: c.callId } : {}),\n }));\n\n // What the turn cost, recorded on the message. The UI has no other way to\n // show it after the fact: run state is reset by the next turn.\n const meta: TurnMeta = {\n model: this.config.model,\n ms: this.turnStartedAt ? Date.now() - this.turnStartedAt : 0,\n ...(s.run.usage && Object.keys(s.run.usage).length ? { usage: s.run.usage } : {}),\n ...(s.run.steps ? { steps: s.run.steps } : {}),\n ...(origin ? { origin } : {}),\n };\n\n const linked: Message = {\n ...assistantMessage([...toolResultsInCallOrder(parts), ...cardParts]),\n parentId: s.headId,\n metadata: { turn: meta },\n };\n const tree = [...s.tree, linked];\n return {\n ...s,\n run,\n tree,\n headId: linked.id,\n messages: pathTo(tree, linked.id),\n status: s.run.status,\n stopping: false,\n };\n });\n this.persist();\n }\n\n /**\n * Fire-and-forget save, the same posture as the job store put: persistence\n * must not stall the run, and a failed save degrades to \"not saved\", never\n * to a broken thread.\n */\n private persist(): void {\n const store = this.config.threadStore;\n if (!store) return;\n const s = this.store.get();\n if (this.threadMeta && this.threadMeta.id !== s.id) this.threadMeta = undefined;\n void (async () => {\n // A client hydrated via config (threadId/initialMessages) has no meta in\n // hand; read the stored one so createdAt and title survive the reload.\n const prior = this.threadMeta ?? (await store.load(s.id))?.meta;\n // The TREE persists — abandoned branches included — plus the active head.\n const snapshot = threadSnapshot(s.id, s.tree, prior, s.headId);\n this.threadMeta = snapshot.meta;\n await store.save(snapshot);\n })().catch(() => {\n // Fire-and-forget: a failed save degrades to \"not saved\", never a crash.\n });\n }\n\n /**\n * Load a stored thread and replace the current one. Returns false when the\n * id is unknown (the current thread is left untouched).\n */\n async openThread(id: string): Promise<boolean> {\n const store = this.config.threadStore;\n if (!store) return false;\n const stored = await store.load(id);\n if (!stored) return false;\n this.saveSurfacesNow();\n this.generation += 1; // invalidate any in-flight run before replacing state\n this.stop();\n this.surfaceQueue = [];\n this.threadMeta = stored.meta;\n const tree = linkLinear(stored.messages);\n const headId = stored.headId ?? tree.at(-1)?.id ?? null;\n this.store.set((s) => onPath({\n ...s,\n id: stored.meta.id,\n tree,\n headId,\n messages: pathTo(tree, headId),\n cards: [],\n attachments: [],\n run: initialRunState(\"\", this.config.mode ?? \"stream\"),\n status: \"idle\",\n error: undefined,\n surfaceActivity: {},\n }));\n return true;\n }\n\n /** Start a fresh thread under a new id (`clear()` keeps the id; this doesn't). */\n newThread(): void {\n this.saveSurfacesNow();\n this.generation += 1;\n this.stop();\n this.surfaceQueue = [];\n this.threadMeta = undefined;\n this.store.set((s) => ({\n ...s,\n id: nextId(\"thread\"),\n messages: [],\n tree: [],\n headId: null,\n cards: [],\n attachments: [],\n run: initialRunState(\"\", this.config.mode ?? \"stream\"),\n status: \"idle\",\n error: undefined,\n surfaces: {},\n surfaceActivity: {},\n }));\n }\n\n /** Answer an interactive card. Unblocks the suspended tool. */\n respond(action: CardAction): void {\n const entry = this.pending.get(action.callId ?? \"\");\n if (!entry) return;\n this.pending.delete(action.callId ?? \"\");\n entry.resolve(action);\n }\n\n /** The card currently blocking the run, if any. */\n pendingCard(): Card | undefined {\n return this.store.get().run.pendingCard;\n }\n\n stop(): void {\n if (!this.isRunning) return;\n // Mark the request immediately. Aborting is not the same as having stopped:\n // a tool that ignores its signal runs to completion, and the UI has to be\n // able to say \"stopping\" instead of looking inert.\n this.store.set((s) => ({ ...s, stopping: true }));\n this.controller?.abort();\n // A background job keeps running (and billing) server-side after a local\n // abort — cancel it there too, best-effort.\n const job = this.store.get().run.job;\n if (job && this.config.provider.cancelJob && ![\"completed\", \"failed\", \"cancelled\"].includes(job.status)) {\n void this.config.provider.cancelJob(job.handle).catch(() => {});\n void this.config.jobStore?.remove(job.handle.id);\n }\n // Release any suspended tool so the run can unwind instead of hanging.\n for (const [callId, entry] of this.pending) {\n entry.resolve({ cardId: entry.card.id, callId, kind: \"cancel\", type: \"cancel\", at: Date.now() });\n }\n this.pending.clear();\n // Stop means stop: what was waiting behind this run does not start after it.\n for (const queued of this.surfaceQueue.splice(0)) {\n this.noteSurfaceActivity(queued.spec.surfaceId, queued.component.id, \"cancelled\", \"Cancelled.\");\n }\n }\n\n // ── surfaces ──────────────────────────────────────────────────────────────\n\n /**\n * Write one value into a surface's data model. Neighbours bound to it update at\n * once and no model is called. The thread is rewritten shortly after, not per\n * keystroke, so typing does not re-render every message.\n */\n setSurfaceData(surfaceId: string, path: string, value: unknown): boolean {\n const current = this.store.get().surfaces[surfaceId];\n if (!current || current.deleted || current.expired) return false;\n const data = setAt(current.data, path, value);\n if (!data || JSON.stringify(data).length > SURFACE_LIMITS.dataChars) return false;\n this.putSurface({ ...current, data, revision: current.revision + 1 });\n return true;\n }\n\n private putSurface(spec: SurfaceSpec): void {\n this.surfaceLedger?.put(spec);\n this.store.set((s) => ({ ...s, surfaces: { ...s.surfaces, [spec.surfaceId]: spec } }));\n this.dirtySurfaces.add(spec.surfaceId);\n if (this.surfaceSaveTimer) return;\n this.surfaceSaveTimer = setTimeout(() => this.saveSurfacesNow(), SURFACE_SAVE_DELAY_MS);\n }\n\n private saveSurfacesNow(): void {\n if (this.surfaceSaveTimer) clearTimeout(this.surfaceSaveTimer);\n this.surfaceSaveTimer = null;\n if (!this.dirtySurfaces.size) return;\n this.flushSurfaceWrites();\n this.persist();\n }\n\n /**\n * Fold pending edits into the newest snapshot of each surface: the live card, or\n * the stored one. A finished run's cards stay in `run` until the next one starts,\n * so they only count as the newest copy while that run has yet to commit.\n */\n private flushSurfaceWrites(uncommittedRun = this.isRunning): void {\n if (this.surfaceSaveTimer) clearTimeout(this.surfaceSaveTimer);\n this.surfaceSaveTimer = null;\n if (!this.dirtySurfaces.size) return;\n const ids = [...this.dirtySurfaces];\n this.dirtySurfaces.clear();\n this.store.set((s) => {\n let { run, tree } = s;\n for (const id of ids) {\n const spec = s.surfaces[id];\n if (!spec) continue;\n const cardId = surfaceCardId(id);\n if (uncommittedRun && run.cards.some((c) => c.id === cardId)) {\n run = { ...run, cards: run.cards.map((c) => (c.id === cardId ? { ...c, spec } : c)) };\n continue;\n }\n const holder = [...s.messages].reverse().find((m) => m.parts.some((p) => p.type === \"artifact\" && p.id === cardId));\n if (!holder) continue;\n tree = tree.map((m) =>\n m.id === holder.id\n ? { ...m, parts: m.parts.map((p) => (p.type === \"artifact\" && p.id === cardId ? { ...p, data: spec } : p)) }\n : m,\n );\n }\n if (run === s.run && tree === s.tree) return s;\n return { ...s, run, cards: run.cards, tree, messages: tree === s.tree ? s.messages : pathTo(tree, s.headId) };\n });\n }\n\n private noteSurfaceActivity(surfaceId: string, componentId: string, state: SurfaceActivityState, message?: string): SurfaceActivityState {\n this.store.set((s) => ({\n ...s,\n surfaceActivity: { ...s.surfaceActivity, [surfaceId]: { componentId, state, ...(message ? { message } : {}), at: Date.now() } },\n }));\n return state;\n }\n\n /**\n * Run the action of a control the person pressed.\n *\n * Takes the component's id rather than an action: what runs is read from the\n * validated spec here, so nothing in the page can substitute a different one.\n */\n async dispatchSurfaceAction(\n surfaceId: string,\n componentId: string,\n scope: { item?: unknown; index?: number } = {},\n ): Promise<SurfaceActivityState> {\n const spec = this.store.get().surfaces[surfaceId];\n const component = spec?.components.find((c) => c.id === componentId);\n const action = component?.[\"action\"] as SurfaceAction | undefined;\n if (!spec || spec.deleted || spec.expired || !component || !action) {\n return this.noteSurfaceActivity(surfaceId, componentId, \"refused\", \"This control is no longer available.\");\n }\n const binding = { data: spec.data, ...scope };\n const disabledWhen = component[\"disabledWhen\"] as Parameters<typeof evaluateSurfaceCondition>[0];\n if (disabledWhen && evaluateSurfaceCondition(disabledWhen, binding)) {\n return this.noteSurfaceActivity(surfaceId, componentId, \"refused\", \"This control is unavailable right now.\");\n }\n\n const resolved = resolveSurfaceAction(action, binding);\n if (resolved.type === \"set\") {\n let data: Record<string, unknown> | undefined = spec.data;\n for (const update of resolved.updates) data = data && setAt(data, update.path, update.value);\n if (!data) return this.noteSurfaceActivity(surfaceId, componentId, \"failed\", \"That change could not be applied.\");\n this.putSurface({ ...spec, data, revision: spec.revision + 1 });\n return this.noteSurfaceActivity(surfaceId, componentId, \"done\");\n }\n\n if (resolved.type === \"tool\") {\n const verdict = authorizeSurfaceTool(resolved.tool, resolved.args, this.config.tools, this.config.toolResolution);\n if (!verdict.ok) return this.noteSurfaceActivity(surfaceId, componentId, \"refused\", verdict.reason);\n }\n\n const queued: QueuedSurfaceAction = { spec, component, action: resolved };\n if (this.isRunning) {\n if (this.surfaceQueue.length >= SURFACE_QUEUE_LIMIT) {\n return this.noteSurfaceActivity(surfaceId, componentId, \"refused\", \"Too many actions are waiting. Try again shortly.\");\n }\n this.surfaceQueue.push(queued);\n return this.noteSurfaceActivity(surfaceId, componentId, \"queued\", \"Waiting for the agent to finish.\");\n }\n return this.startSurfaceAction(queued);\n }\n\n /** Record the answer to an interactive card inside a surface, then run its action if it has one. */\n async respondToSurfaceCard(surfaceId: string, componentId: string, answer: Omit<SurfaceCardAnswer, \"at\">): Promise<SurfaceActivityState> {\n const spec = this.store.get().surfaces[surfaceId];\n const component = spec?.components.find((c) => c.id === componentId);\n const bind = component?.[\"bind\"];\n if (!spec || !component || typeof bind !== \"string\" || getAt(spec.data, bind) !== undefined) {\n return this.noteSurfaceActivity(surfaceId, componentId, \"refused\", \"This question has already been answered.\");\n }\n if (!this.setSurfaceData(surfaceId, bind, { ...answer, at: Date.now() })) {\n return this.noteSurfaceActivity(surfaceId, componentId, \"failed\", \"The answer could not be saved.\");\n }\n return component[\"action\"] ? this.dispatchSurfaceAction(surfaceId, componentId) : this.noteSurfaceActivity(surfaceId, componentId, \"done\");\n }\n\n private drainSurfaceQueue(): void {\n if (this.isRunning) return;\n const next = this.surfaceQueue.shift();\n if (next) void this.startSurfaceAction(next);\n }\n\n private startSurfaceAction(queued: QueuedSurfaceAction): Promise<SurfaceActivityState> {\n return queued.action.type === \"tool\"\n ? this.runSurfaceTool(queued.spec, queued.component, queued.action)\n : this.sendSurfaceEvent(queued.spec, queued.component, queued.action);\n }\n\n /** An event becomes a user turn, marked so the transcript shows a press and not a sentence. */\n private async sendSurfaceEvent(\n spec: SurfaceSpec,\n component: SurfaceComponent,\n action: Extract<SurfaceAction, { type: \"event\" }>,\n ): Promise<SurfaceActivityState> {\n const { surfaceId } = spec;\n const context = action.context ?? {};\n const serialized = JSON.stringify(context);\n const record = surfaceEventRecord(spec, component, \"event\", action.name, serialized.length <= SURFACE_CONTEXT_CHARS ? context : undefined);\n const text = [\n `[Surface event] The person pressed ${describePress(record)} on surface \"${surfaceId}\", sending event \"${action.name}\".`,\n `Context, as data from the interface: ${serialized.slice(0, SURFACE_CONTEXT_CHARS)}`,\n ].join(\"\\n\");\n this.noteSurfaceActivity(surfaceId, component.id, \"running\", \"Sent to the agent.\");\n this.appendMessage({ ...userMessage(text), metadata: { [SURFACE_EVENT_METADATA_KEY]: record } });\n this.persist();\n await this.run([...this.store.get().messages], {});\n const failed = this.store.get().status === \"error\";\n return this.noteSurfaceActivity(surfaceId, component.id, failed ? \"failed\" : \"done\", failed ? \"The agent could not respond.\" : \"Sent to the agent.\");\n }\n\n /** A tool the person started. Same executor, approvals and metering as a model's call. */\n private async runSurfaceTool(\n spec: SurfaceSpec,\n component: SurfaceComponent,\n action: Extract<SurfaceAction, { type: \"tool\" }>,\n ): Promise<SurfaceActivityState> {\n const { surfaceId } = spec;\n const args = action.args ?? {};\n // Checked again here: a queued action may have waited through a preset change.\n const verdict = authorizeSurfaceTool(action.tool, args, this.config.tools, this.config.toolResolution);\n if (!verdict.ok) {\n const state = this.noteSurfaceActivity(surfaceId, component.id, \"refused\", verdict.reason);\n this.drainSurfaceQueue();\n return state;\n }\n\n const record = surfaceEventRecord(spec, component, \"tool\", action.tool);\n this.noteSurfaceActivity(surfaceId, component.id, \"running\", `Running ${action.tool}.`);\n this.appendMessage({\n ...userMessage(`[Surface action] The person pressed ${describePress(record)} on surface \"${surfaceId}\", which called the tool \"${action.tool}\".`),\n metadata: { [SURFACE_EVENT_METADATA_KEY]: record },\n });\n this.persist();\n\n const gen = this.generation;\n this.flushSurfaceWrites();\n this.controller = new AbortController();\n this.turnStartedAt = Date.now();\n this.store.set((s) => ({\n ...s,\n run: initialRunState(nextId(\"run\"), \"sync\"),\n cards: [],\n status: \"running\",\n error: undefined,\n stopping: false,\n }));\n\n let result: Extract<RunEvent, { type: \"tool-result\" }> | undefined;\n try {\n const events = runSurfaceToolAction({\n tool: verdict.tool,\n args,\n surfaceId,\n componentId: component.id,\n provider: this.config.provider.id,\n model: this.config.model,\n vars: this.config.vars,\n signal: this.controller.signal,\n toolTimeoutMs: this.config.toolTimeoutMs,\n meter: this.config.meter,\n meteringMetadata: this.config.meteringMetadata,\n onUserDecision: this.awaitDecision,\n onHostTool: this.config.onHostTool,\n });\n for await (const event of events) {\n if (gen !== this.generation) return \"cancelled\";\n if (event.type === \"tool-result\") result = event;\n this.apply(event);\n }\n } catch (e) {\n if (gen === this.generation) this.store.set((s) => ({ ...s, status: \"error\", error: e }));\n } finally {\n this.controller = null;\n }\n if (gen !== this.generation) return \"cancelled\";\n\n let state: SurfaceActivityState;\n let message: string | undefined;\n if (!result || (result.failure && result.failure !== \"denied\")) {\n state = \"failed\";\n message = failureMessage(result?.output) ?? `${action.tool} failed.`;\n } else if (result.failure === \"denied\") {\n state = \"cancelled\";\n message = \"Cancelled.\";\n } else {\n state = \"done\";\n message = \"Done.\";\n if (action.resultPath && !this.setSurfaceData(surfaceId, action.resultPath, stripCardPayload(result.output))) {\n state = \"failed\";\n message = \"The result was too large to show here.\";\n }\n }\n this.commitRun(\"surface-action\");\n this.noteSurfaceActivity(surfaceId, component.id, state, message);\n this.drainSurfaceQueue();\n return state;\n }\n\n clear(): void {\n this.dirtySurfaces.clear();\n this.generation += 1;\n this.stop();\n this.surfaceQueue = [];\n this.store.set((s) => ({\n ...s,\n messages: [],\n tree: [],\n headId: null,\n cards: [],\n attachments: [],\n run: initialRunState(\"\", this.config.mode ?? \"stream\"),\n status: \"idle\",\n error: undefined,\n stopping: false,\n surfaces: {},\n surfaceActivity: {},\n }));\n // Without this, reload restores the conversation the user just cleared.\n this.persist();\n }\n\n /**\n * Re-poll background jobs from a previous session. Call on mount.\n *\n * Results are routed by `StoredJob.threadId`: the current thread gets its\n * results appended live; another thread's results are written into its\n * stored snapshot (when a ThreadStore is configured), so an answer to\n * thread A never gets pasted into thread B.\n */\n async resumeBackgroundJobs(): Promise<void> {\n const store = this.config.jobStore;\n if (!store) return;\n const results = await resumeJobs(store, { [this.config.provider.id]: this.config.provider });\n this.store.set((s) => ({ ...s, jobs: results.map((r) => r.job) }));\n\n const currentId = this.store.get().id;\n // Jobs landing in an AWAY thread are grouped by threadId: two jobs for the\n // SAME away thread read-modify-write that thread's one stored snapshot, so\n // they must land in order or the second save clobbers the first. Jobs for\n // DIFFERENT away threads touch different snapshots and have no ordering\n // dependency on each other, so those groups load/save concurrently.\n const away = new Map<string, ContentPart[][]>();\n\n for (const { job, snapshot } of results) {\n const parts: ContentPart[] | null =\n snapshot.status === \"completed\" && snapshot.result\n ? snapshot.result.parts\n : snapshot.status === \"failed\"\n ? [{ type: \"text\", text: `_${snapshot.error?.message ?? \"A background job failed.\"}_` }]\n : null;\n if (!parts) continue;\n\n if (!job.threadId || job.threadId === currentId) {\n this.appendMessage(assistantMessage(parts));\n if (job.threadId === currentId) this.persist();\n continue;\n }\n\n const bucket = away.get(job.threadId) ?? [];\n bucket.push(parts);\n away.set(job.threadId, bucket);\n }\n\n const threads = this.config.threadStore;\n if (!threads || !away.size) return; // nowhere to put it; the handle was already reaped\n\n await Promise.all(\n [...away].map(async ([threadId, partsList]) => {\n for (const parts of partsList) {\n const stored = await threads.load(threadId);\n if (!stored) continue;\n const awayHead = stored.headId ?? stored.messages.at(-1)?.id ?? null;\n const appended: Message = { ...assistantMessage(parts), parentId: awayHead };\n await threads.save(\n threadSnapshot(threadId, [...stored.messages, appended], stored.meta, appended.id),\n );\n }\n }),\n );\n }\n}\n\n/** Re-derive surfaces after the head moved: each branch shows them as it left them. */\nconst onPath = (s: ThreadState): ThreadState => ({ ...s, surfaces: foldSurfaces(s.messages) });\n\nfunction surfaceEventRecord(\n spec: SurfaceSpec,\n component: SurfaceComponent,\n type: SurfaceEventRecord[\"type\"],\n name: string,\n context?: Record<string, unknown>,\n): SurfaceEventRecord {\n const label = component[\"label\"];\n return {\n surfaceId: spec.surfaceId,\n componentId: component.id,\n ...(spec.title ? { title: spec.title } : {}),\n ...(typeof label === \"string\" ? { label } : {}),\n type,\n name,\n ...(context ? { context } : {}),\n };\n}\n\nconst describePress = (record: SurfaceEventRecord) => (record.label ? JSON.stringify(record.label) : `control \"${record.componentId}\"`);\n\nconst failureMessage = (output: unknown): string | undefined => {\n const error = (output as { error?: unknown } | null)?.error;\n return typeof error === \"string\" ? error.slice(0, 200) : undefined;\n};\n\n/**\n * Run state appends tool results as they finish; a committed turn keeps them in\n * the order they were called, the same order runAgent writes back to history.\n * Only results that sit next to each other move, and only among themselves.\n */\nfunction toolResultsInCallOrder(parts: readonly ContentPart[]): ContentPart[] {\n const callAt = new Map<string, number>();\n parts.forEach((p, i) => {\n if (p.type === \"tool-call\") callAt.set(p.callId, i);\n });\n const rank = (p: ContentPart) =>\n p.type === \"tool-result\" ? (callAt.get(p.callId) ?? Number.MAX_SAFE_INTEGER) : Number.MAX_SAFE_INTEGER;\n\n const out: ContentPart[] = [];\n let batch: ContentPart[] = [];\n const flush = () => {\n out.push(...batch.sort((a, b) => rank(a) - rank(b)));\n batch = [];\n };\n for (const p of parts) {\n if (p.type === \"tool-result\") batch.push(p);\n else {\n flush();\n out.push(p);\n }\n }\n flush();\n return out;\n}\n","// A tiny external store, consumed via useSyncExternalStore.\n//\n// Hand-rolled rather than pulling in zustand/valtio for two reasons: the state\n// shape is already defined by the core's `RunState` reducer, and a chat thread\n// under a streaming run notifies at token frequency — a store that allocates a\n// new subscriber array per notify shows up in a profile at 60+ notifies/sec.\n\nexport type Listener = () => void;\n\nexport class Store<T> {\n private state: T;\n private listeners = new Set<Listener>();\n\n constructor(initial: T) {\n this.state = initial;\n }\n\n get = (): T => this.state;\n\n set = (next: T | ((prev: T) => T)): void => {\n const value = typeof next === \"function\" ? (next as (prev: T) => T)(this.state) : next;\n // Reference equality guard: a reducer that returns the same object (a\n // no-op event) must not wake every subscriber.\n if (Object.is(value, this.state)) return;\n this.state = value;\n for (const listener of this.listeners) listener();\n };\n\n subscribe = (listener: Listener): (() => void) => {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n };\n}\n"],"mappings":";AAMA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAkBA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAYA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACvDA,IAAM,QAAN,MAAe;AAAA,EACZ;AAAA,EACA,YAAY,oBAAI,IAAc;AAAA,EAEtC,YAAY,SAAY;AACtB,SAAK,QAAQ;AAAA,EACf;AAAA,EAEA,MAAM,MAAS,KAAK;A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,CAAC;AACnD,YAAQ,CAAC;AAAA,EACX;AACA,aAAW,KAAK,OAAO;AACrB,QAAI,EAAE,SAAS,cAAe,OAAM,KAAK,CAAC;AAAA,SACrC;AACH,YAAM;AACN,UAAI,KAAK,CAAC;AAAA,IACZ;AAAA,EACF;AACA,QAAM;AACN,SAAO;AACT;","names":["state"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@supersolutions/super-chat-client",
|
|
3
|
-
"version": "0.1
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"description": "Framework-agnostic client for superchat: one AgentClient store per thread that drives the agent runtime. No UI framework dependency.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "SUPER SOLUTION LABS INC",
|
|
@@ -43,7 +43,7 @@
|
|
|
43
43
|
"access": "public"
|
|
44
44
|
},
|
|
45
45
|
"dependencies": {
|
|
46
|
-
"@supersolutions/super-chat-core": "0.1
|
|
46
|
+
"@supersolutions/super-chat-core": "0.2.1"
|
|
47
47
|
},
|
|
48
48
|
"devDependencies": {
|
|
49
49
|
"tsup": "^8.3.5",
|