@qlairoslabs/acp-client 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +172 -19
- package/package.json +2 -1
- package/src/activity.ts +513 -0
- package/src/agent-session.ts +231 -9
- package/src/cli/index.ts +21 -3
- package/src/client.ts +8 -0
- package/src/controller.ts +4 -0
- package/src/index.ts +24 -1
- package/src/transcript.ts +228 -16
- package/src/transport/acp-transport.ts +59 -5
- package/src/types.ts +29 -3
- package/src/updates.ts +11 -2
- package/src/wire-log.ts +85 -0
package/src/activity.ts
ADDED
|
@@ -0,0 +1,513 @@
|
|
|
1
|
+
// Folds the ACP delta stream into full-state records.
|
|
2
|
+
//
|
|
3
|
+
// The protocol streams tool calls and thinking as deltas: a tool call is announced before
|
|
4
|
+
// its input is known, updates carry only changed fields, and `content` REPLACES rather
|
|
5
|
+
// than accumulates. Every consumer that renders activity has to fold that, and until now
|
|
6
|
+
// each one hand-rolled it from a README snippet. This module is that fold, published —
|
|
7
|
+
// the same relationship `updates.ts` has to the wire format: the library owns what the
|
|
8
|
+
// protocol MEANS, callers own what to draw.
|
|
9
|
+
//
|
|
10
|
+
// INVARIANT: exactly one aggregator per STREAM, for the life of that stream. Call
|
|
11
|
+
// `startTurn()` between turns rather than constructing a new one — `seq` must keep
|
|
12
|
+
// counting across turns, or a subscriber's discard threshold goes stale and silently eats
|
|
13
|
+
// the start of the next turn (see `snapshot`). `recordId`s for kinds the protocol doesn't
|
|
14
|
+
// identify are instance-local counters, so a second instance over the same stream would
|
|
15
|
+
// also mint different ids for the same thing. When using AgentSession, take its output —
|
|
16
|
+
// don't build a second one.
|
|
17
|
+
//
|
|
18
|
+
// SCOPE: ACP guarantees `toolCallId`, `planId` and `messageId` are unique "within a
|
|
19
|
+
// session", so ids derived from them are used verbatim. Everything else here is MINTED
|
|
20
|
+
// from a per-instance counter and is therefore only turn-unique — pass `idPrefix` to
|
|
21
|
+
// scope those, or a transcript spanning several turns will have a `think-1` per turn and
|
|
22
|
+
// last-wins folding will collapse them all into one.
|
|
23
|
+
//
|
|
24
|
+
// Pure by contract: no I/O, no runtime imports, erasable syntax only. A test enforces it,
|
|
25
|
+
// so this file stays safe to compile for a browser if a consumer ever needs to fold
|
|
26
|
+
// locally.
|
|
27
|
+
|
|
28
|
+
import type { ActivityEvent, ToolActivity } from "./types.ts";
|
|
29
|
+
|
|
30
|
+
/** Where a record sits in its lifecycle. Persisted, so readers can filter without folding. */
|
|
31
|
+
export type EmitReason =
|
|
32
|
+
| "announced" // first seen
|
|
33
|
+
| "input" // a tool call first learned its rawInput
|
|
34
|
+
| "settled" // terminal status reached, or a thinking block ended
|
|
35
|
+
| "flushed" // the turn ended with the record still open
|
|
36
|
+
| "snapshot"; // inherently complete on arrival
|
|
37
|
+
|
|
38
|
+
/** Full state of one thing that happened, identified for last-wins folding. */
|
|
39
|
+
export interface AggregatedRecord {
|
|
40
|
+
recordId: string;
|
|
41
|
+
/** Per-turn logical clock. Every frame from one apply() shares a seq. */
|
|
42
|
+
seq: number;
|
|
43
|
+
reason: EmitReason;
|
|
44
|
+
/** Always FULL state, never a delta. */
|
|
45
|
+
event: ActivityEvent;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* The incremental piece, for kinds this module ACCUMULATES rather than replaces.
|
|
50
|
+
*
|
|
51
|
+
* Only thinking qualifies today. Tool calls are already cumulative on the wire — the
|
|
52
|
+
* agent resends the whole `content` each time — so a full record costs no more than the
|
|
53
|
+
* raw event. Thinking arrives as many small chunks, where re-sending the accumulated
|
|
54
|
+
* block per chunk is quadratic: ~4 KB of text becomes ~800 KB over 400 chunks.
|
|
55
|
+
*/
|
|
56
|
+
export interface ActivityDelta {
|
|
57
|
+
recordId: string;
|
|
58
|
+
seq: number;
|
|
59
|
+
kind: "thinking";
|
|
60
|
+
append: string;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** What a live transport carries. Records are self-contained; deltas need a base. */
|
|
64
|
+
export type ActivityFrame = AggregatedRecord | ActivityDelta;
|
|
65
|
+
|
|
66
|
+
export interface ApplyResult {
|
|
67
|
+
/** Full state of whatever this event touched. Null only if it produced no record. */
|
|
68
|
+
current: AggregatedRecord | null;
|
|
69
|
+
/** Set for accumulating kinds. When present, prefer it over `current` on the wire. */
|
|
70
|
+
delta: ActivityDelta | null;
|
|
71
|
+
/** Checkpoints worth persisting. Usually empty. */
|
|
72
|
+
emitted: AggregatedRecord[];
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Everything known about the turn IN FLIGHT — for replaying to a late subscriber. */
|
|
76
|
+
export interface ActivitySnapshot {
|
|
77
|
+
/**
|
|
78
|
+
* Whether a turn is in flight. False between turns, when `records` is empty.
|
|
79
|
+
*
|
|
80
|
+
* Distinguishes "no turn running" from "a turn that has not produced anything yet" —
|
|
81
|
+
* both return no records, but only the second means frames are coming.
|
|
82
|
+
*/
|
|
83
|
+
active: boolean;
|
|
84
|
+
/**
|
|
85
|
+
* Frames with `seq <= this` are already reflected here and must be discarded.
|
|
86
|
+
*
|
|
87
|
+
* Monotonic for the life of the aggregator, ACROSS turns — so a consumer can store this
|
|
88
|
+
* threshold once and filter forever without knowing where turns begin. That is why
|
|
89
|
+
* `startTurn()` exists and why constructing a fresh aggregator per turn is wrong: the
|
|
90
|
+
* clock would restart and a stale threshold would silently drop the next turn's opening
|
|
91
|
+
* frames.
|
|
92
|
+
*/
|
|
93
|
+
seq: number;
|
|
94
|
+
/**
|
|
95
|
+
* Empty between turns. A settled turn's records belong to the transcript, not to a
|
|
96
|
+
* replay: handing them to a client that connects mid-idle would put activity into its
|
|
97
|
+
* log before the surrounding messages have loaded — activity with no turn around it.
|
|
98
|
+
*/
|
|
99
|
+
records: AggregatedRecord[];
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export interface ActivityAggregatorOptions {
|
|
103
|
+
/**
|
|
104
|
+
* Emit an extra checkpoint the first time a tool call learns its `rawInput`. Default
|
|
105
|
+
* true: agents commonly announce a call long before they know its arguments (Kimi
|
|
106
|
+
* sends rawInput on update 13 of 14), so without this a crash mid-call persists a
|
|
107
|
+
* record that names the tool but not what it was doing.
|
|
108
|
+
*/
|
|
109
|
+
checkpointOnInput?: boolean;
|
|
110
|
+
/**
|
|
111
|
+
* Namespace for MINTED record ids (`think-1`, `plan`, `usage`, …), which are otherwise
|
|
112
|
+
* only unique within this instance's turn. Ids the protocol guarantees session-unique
|
|
113
|
+
* are never prefixed.
|
|
114
|
+
*
|
|
115
|
+
* Sets the prefix for the FIRST turn; `startTurn()` sets it thereafter. Required
|
|
116
|
+
* whenever records outlive the turn — the transcript accumulates across turns, so
|
|
117
|
+
* `AgentSession` passes a per-turn value. That value must be stable across process
|
|
118
|
+
* restarts: an in-memory turn counter restarts at 0 when a session is resumed and would
|
|
119
|
+
* collide with ids already on disk. Use a timestamp or a random id.
|
|
120
|
+
*/
|
|
121
|
+
idPrefix?: string;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Statuses ACP defines as terminal. */
|
|
125
|
+
const TERMINAL_STATUS = ["completed", "failed"];
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Whether a tool call actually knows its arguments yet.
|
|
129
|
+
*
|
|
130
|
+
* Agents announce a call with a PLACEHOLDER — `rawInput: {}` is common (both Kimi and the
|
|
131
|
+
* test fixture do it) — and fill the real arguments in later. Treating the placeholder as
|
|
132
|
+
* "input known" would skip the input checkpoint, so a turn that died between learning the
|
|
133
|
+
* command and finishing it would persist a record naming the tool but not what it ran.
|
|
134
|
+
*/
|
|
135
|
+
function hasInput(rawInput: unknown): boolean {
|
|
136
|
+
if (rawInput === undefined || rawInput === null) return false;
|
|
137
|
+
if (typeof rawInput === "string") return rawInput.length > 0;
|
|
138
|
+
if (Array.isArray(rawInput)) return rawInput.length > 0;
|
|
139
|
+
if (typeof rawInput === "object") return Object.keys(rawInput).length > 0;
|
|
140
|
+
return true;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export class ActivityAggregator {
|
|
144
|
+
private checkpointOnInput: boolean;
|
|
145
|
+
private idPrefix: string;
|
|
146
|
+
private turnOpen = true;
|
|
147
|
+
private seq = 0;
|
|
148
|
+
private records = new Map<string, AggregatedRecord>();
|
|
149
|
+
private calls = new Map<string, ToolActivity>();
|
|
150
|
+
private settled = new Set<string>();
|
|
151
|
+
private inputSeen = new Set<string>();
|
|
152
|
+
private thinking: { recordId: string; messageId?: string; text: string } | null = null;
|
|
153
|
+
private counters = new Map<string, number>();
|
|
154
|
+
private pendingUsage: ActivityEvent | null = null;
|
|
155
|
+
|
|
156
|
+
constructor(options: ActivityAggregatorOptions = {}) {
|
|
157
|
+
this.checkpointOnInput = options.checkpointOnInput !== false;
|
|
158
|
+
this.idPrefix = options.idPrefix ? `${options.idPrefix}:` : "";
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Fold one live event. */
|
|
162
|
+
apply(event: ActivityEvent): ApplyResult {
|
|
163
|
+
this.seq++;
|
|
164
|
+
const emitted: AggregatedRecord[] = [];
|
|
165
|
+
|
|
166
|
+
// A thinking block ends when something else happens. Emit its close BEFORE the
|
|
167
|
+
// record that ended it, so append order matches causal order.
|
|
168
|
+
const closed = this.closeThinkingFor(event);
|
|
169
|
+
if (closed) emitted.push(closed);
|
|
170
|
+
|
|
171
|
+
switch (event.kind) {
|
|
172
|
+
case "thinking":
|
|
173
|
+
return this.foldThinking(event, emitted);
|
|
174
|
+
case "tool":
|
|
175
|
+
return this.foldTool(event, emitted);
|
|
176
|
+
case "tool_update":
|
|
177
|
+
return this.foldToolUpdate(event, emitted);
|
|
178
|
+
case "usage": {
|
|
179
|
+
// Coalesced: many per turn, only the last is worth persisting. `current` is still
|
|
180
|
+
// the live record so a caller can render a context meter.
|
|
181
|
+
this.pendingUsage = event;
|
|
182
|
+
return {
|
|
183
|
+
current: this.put(this.minted("usage"), "snapshot", event),
|
|
184
|
+
delta: null,
|
|
185
|
+
emitted,
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
default: {
|
|
189
|
+
const record = this.put(this.recordIdFor(event), "snapshot", event);
|
|
190
|
+
emitted.push(record);
|
|
191
|
+
return { current: record, delta: null, emitted };
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Close everything still open. Call once at turn end, on BOTH the success and error
|
|
198
|
+
* paths — an unsettled call written at its real status is the record of what the turn
|
|
199
|
+
* was doing when it died.
|
|
200
|
+
*/
|
|
201
|
+
flush(): AggregatedRecord[] {
|
|
202
|
+
this.seq++;
|
|
203
|
+
const out: AggregatedRecord[] = [];
|
|
204
|
+
|
|
205
|
+
const closed = this.closeThinking();
|
|
206
|
+
if (closed) out.push(closed);
|
|
207
|
+
|
|
208
|
+
for (const [id, call] of this.calls) {
|
|
209
|
+
if (this.settled.has(id)) continue;
|
|
210
|
+
this.settled.add(id);
|
|
211
|
+
out.push(this.put(id, "flushed", call));
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
if (this.pendingUsage) {
|
|
215
|
+
out.push(this.put(this.minted("usage"), "snapshot", this.pendingUsage));
|
|
216
|
+
this.pendingUsage = null;
|
|
217
|
+
}
|
|
218
|
+
this.turnOpen = false;
|
|
219
|
+
return out;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Full state of the turn so far. A subscriber that joins mid-turn takes this, then
|
|
224
|
+
* discards any frame whose `seq` is not greater than the snapshot's — otherwise a
|
|
225
|
+
* thinking delta already folded into the snapshot would be applied twice.
|
|
226
|
+
*
|
|
227
|
+
* The threshold stays valid indefinitely: `seq` never restarts (see `startTurn`).
|
|
228
|
+
*
|
|
229
|
+
* Records are returned only while a turn is in flight — `flush()` ends it. The folded
|
|
230
|
+
* state of a finished turn is still readable via `tool()`/`tools()`, which are
|
|
231
|
+
* inspection accessors rather than the replay contract.
|
|
232
|
+
*/
|
|
233
|
+
snapshot(): ActivitySnapshot {
|
|
234
|
+
return {
|
|
235
|
+
seq: this.seq,
|
|
236
|
+
active: this.turnOpen,
|
|
237
|
+
records: this.turnOpen ? [...this.records.values()] : [],
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Begin a turn: clear per-turn state and set the prefix for MINTED record ids, while
|
|
243
|
+
* `seq` keeps counting. Use this instead of constructing a new aggregator.
|
|
244
|
+
*
|
|
245
|
+
* Call `flush()` FIRST — those records belong to the turn that is ending. Anything left
|
|
246
|
+
* open is returned here rather than dropped, but it would be persisted after that
|
|
247
|
+
* turn's assistant message, breaking the `msg`-delimits-turn ordering readers rely on.
|
|
248
|
+
* A correct caller always gets an empty array back.
|
|
249
|
+
*/
|
|
250
|
+
startTurn(idPrefix?: string): AggregatedRecord[] {
|
|
251
|
+
const leftover = this.flush();
|
|
252
|
+
this.clearTurn();
|
|
253
|
+
this.idPrefix = idPrefix ? `${idPrefix}:` : "";
|
|
254
|
+
this.turnOpen = true;
|
|
255
|
+
return leftover;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** Folded state of one tool call. */
|
|
259
|
+
tool(toolCallId: string): ToolActivity | undefined {
|
|
260
|
+
return this.calls.get(toolCallId);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** Every tool call seen this turn, in first-seen order. */
|
|
264
|
+
tools(): ToolActivity[] {
|
|
265
|
+
return [...this.calls.values()];
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Full reset, including the `seq` clock — for reusing the object on an unrelated
|
|
270
|
+
* stream. Any threshold a subscriber is holding becomes invalid, so this is NOT the
|
|
271
|
+
* between-turns call: use `startTurn()` for that.
|
|
272
|
+
*/
|
|
273
|
+
reset(): void {
|
|
274
|
+
this.clearTurn();
|
|
275
|
+
this.seq = 0;
|
|
276
|
+
this.turnOpen = true;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
private clearTurn(): void {
|
|
280
|
+
this.records.clear();
|
|
281
|
+
this.calls.clear();
|
|
282
|
+
this.settled.clear();
|
|
283
|
+
this.inputSeen.clear();
|
|
284
|
+
this.counters.clear();
|
|
285
|
+
this.thinking = null;
|
|
286
|
+
this.pendingUsage = null;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
// --- folds ---------------------------------------------------------------------
|
|
290
|
+
|
|
291
|
+
private foldThinking(
|
|
292
|
+
event: Extract<ActivityEvent, { kind: "thinking" }>,
|
|
293
|
+
emitted: AggregatedRecord[],
|
|
294
|
+
): ApplyResult {
|
|
295
|
+
if (!this.thinking) {
|
|
296
|
+
// `messageId` identifies the block when the agent sends one — most don't, so fall
|
|
297
|
+
// back to a per-turn counter. This is the instance-local id the one-aggregator
|
|
298
|
+
// invariant exists to protect.
|
|
299
|
+
// `messageId` is session-unique per ACP, so it needs no prefix; the counter does.
|
|
300
|
+
const recordId = event.messageId
|
|
301
|
+
? `think-${event.messageId}`
|
|
302
|
+
: this.minted(`think-${this.nextCount("think")}`);
|
|
303
|
+
this.thinking = { recordId, messageId: event.messageId, text: "" };
|
|
304
|
+
}
|
|
305
|
+
this.thinking.text += event.text;
|
|
306
|
+
|
|
307
|
+
const full: ActivityEvent = this.thinking.messageId
|
|
308
|
+
? { kind: "thinking", text: this.thinking.text, messageId: this.thinking.messageId }
|
|
309
|
+
: { kind: "thinking", text: this.thinking.text };
|
|
310
|
+
|
|
311
|
+
return {
|
|
312
|
+
current: this.put(this.thinking.recordId, "announced", full),
|
|
313
|
+
delta: {
|
|
314
|
+
recordId: this.thinking.recordId,
|
|
315
|
+
seq: this.seq,
|
|
316
|
+
kind: "thinking",
|
|
317
|
+
append: event.text,
|
|
318
|
+
},
|
|
319
|
+
emitted,
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
private foldTool(
|
|
324
|
+
event: Extract<ActivityEvent, { kind: "tool" }>,
|
|
325
|
+
emitted: AggregatedRecord[],
|
|
326
|
+
): ApplyResult {
|
|
327
|
+
const call: ToolActivity = { ...event };
|
|
328
|
+
this.calls.set(call.toolCallId, call);
|
|
329
|
+
if (hasInput(call.rawInput)) this.inputSeen.add(call.toolCallId);
|
|
330
|
+
|
|
331
|
+
const terminal = TERMINAL_STATUS.indexOf(call.status) >= 0;
|
|
332
|
+
if (terminal) this.settled.add(call.toolCallId);
|
|
333
|
+
|
|
334
|
+
const record = this.put(call.toolCallId, terminal ? "settled" : "announced", call);
|
|
335
|
+
emitted.push(record);
|
|
336
|
+
return { current: record, delta: null, emitted };
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
private foldToolUpdate(
|
|
340
|
+
event: Extract<ActivityEvent, { kind: "tool_update" }>,
|
|
341
|
+
emitted: AggregatedRecord[],
|
|
342
|
+
): ApplyResult {
|
|
343
|
+
const id = event.toolCallId;
|
|
344
|
+
const previous = this.calls.get(id);
|
|
345
|
+
|
|
346
|
+
// Spreading is the whole merge: `updates.ts` omits absent keys, so only the fields
|
|
347
|
+
// the agent actually changed are present. `content`/`locations` replace wholesale,
|
|
348
|
+
// which a spread also gets right.
|
|
349
|
+
const merged: ToolActivity = previous
|
|
350
|
+
? { ...previous, ...event, kind: "tool" }
|
|
351
|
+
: {
|
|
352
|
+
...event,
|
|
353
|
+
kind: "tool",
|
|
354
|
+
toolKind: event.toolKind ?? "other",
|
|
355
|
+
status: event.status ?? "in_progress",
|
|
356
|
+
};
|
|
357
|
+
this.calls.set(id, merged);
|
|
358
|
+
|
|
359
|
+
const terminal = TERMINAL_STATUS.indexOf(merged.status) >= 0;
|
|
360
|
+
let reason: EmitReason | null = null;
|
|
361
|
+
|
|
362
|
+
if (terminal && !this.settled.has(id)) {
|
|
363
|
+
this.settled.add(id);
|
|
364
|
+
this.inputSeen.add(id); // the settled record is a superset — no input checkpoint too
|
|
365
|
+
reason = "settled";
|
|
366
|
+
} else if (!previous) {
|
|
367
|
+
reason = "announced"; // an update for a call we never saw announced
|
|
368
|
+
} else if (this.checkpointOnInput && !this.inputSeen.has(id) && hasInput(merged.rawInput)) {
|
|
369
|
+
this.inputSeen.add(id);
|
|
370
|
+
reason = "input";
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
const record = this.put(id, reason ?? this.reasonOf(id, "announced"), merged);
|
|
374
|
+
if (reason) emitted.push(record);
|
|
375
|
+
return { current: record, delta: null, emitted };
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
// --- thinking boundary -----------------------------------------------------------
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* THE ONE INVENTED RULE. ACP has no block-end event, so a block ends when the next
|
|
382
|
+
* event isn't thinking, or when `messageId` changes ("a change in messageId indicates
|
|
383
|
+
* a new message has started"). `messageId` is optional and commonly absent, so the
|
|
384
|
+
* heuristic is the usual path. Everything else in this module is protocol-derived; if
|
|
385
|
+
* this rule ever changes, the transcript format version changes with it.
|
|
386
|
+
*/
|
|
387
|
+
private closeThinkingFor(event: ActivityEvent): AggregatedRecord | null {
|
|
388
|
+
if (!this.thinking) return null;
|
|
389
|
+
if (event.kind === "thinking") {
|
|
390
|
+
const sameBlock = (event.messageId ?? null) === (this.thinking.messageId ?? null);
|
|
391
|
+
if (sameBlock) return null;
|
|
392
|
+
}
|
|
393
|
+
return this.closeThinking();
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
private closeThinking(): AggregatedRecord | null {
|
|
397
|
+
const block = this.thinking;
|
|
398
|
+
if (!block) return null;
|
|
399
|
+
this.thinking = null;
|
|
400
|
+
const event: ActivityEvent = block.messageId
|
|
401
|
+
? { kind: "thinking", text: block.text, messageId: block.messageId }
|
|
402
|
+
: { kind: "thinking", text: block.text };
|
|
403
|
+
return this.put(block.recordId, "settled", event);
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
// --- identity --------------------------------------------------------------------
|
|
407
|
+
|
|
408
|
+
/**
|
|
409
|
+
* Ids the protocol guarantees session-unique (`planId`, `messageId`) pass through
|
|
410
|
+
* verbatim; ids we mint are scoped by `idPrefix`.
|
|
411
|
+
*/
|
|
412
|
+
private recordIdFor(event: ActivityEvent): string {
|
|
413
|
+
switch (event.kind) {
|
|
414
|
+
case "plan_update":
|
|
415
|
+
case "plan_removed":
|
|
416
|
+
return `plan-${event.planId}`;
|
|
417
|
+
case "user_message":
|
|
418
|
+
return event.messageId
|
|
419
|
+
? `msg-${event.messageId}`
|
|
420
|
+
: this.minted(`msg-${this.nextCount("msg")}`);
|
|
421
|
+
case "plan":
|
|
422
|
+
case "mode":
|
|
423
|
+
case "commands":
|
|
424
|
+
case "config":
|
|
425
|
+
case "session_info":
|
|
426
|
+
return this.minted(event.kind);
|
|
427
|
+
default:
|
|
428
|
+
return this.minted(`${event.kind}-${this.nextCount(event.kind)}`);
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/** Namespace an id we invented. Protocol-given ids never go through here. */
|
|
433
|
+
private minted(id: string): string {
|
|
434
|
+
return `${this.idPrefix}${id}`;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
private nextCount(key: string): number {
|
|
438
|
+
const next = (this.counters.get(key) ?? 0) + 1;
|
|
439
|
+
this.counters.set(key, next);
|
|
440
|
+
return next;
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
private reasonOf(recordId: string, fallback: EmitReason): EmitReason {
|
|
444
|
+
return this.records.get(recordId)?.reason ?? fallback;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
private put(recordId: string, reason: EmitReason, event: ActivityEvent): AggregatedRecord {
|
|
448
|
+
const record: AggregatedRecord = { recordId, seq: this.seq, reason, event };
|
|
449
|
+
this.records.set(recordId, record);
|
|
450
|
+
return record;
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
// --- consumer-side folds -----------------------------------------------------------
|
|
455
|
+
|
|
456
|
+
/** True for the incremental wire shape. */
|
|
457
|
+
export function isActivityDelta(frame: ActivityFrame): frame is ActivityDelta {
|
|
458
|
+
return "append" in frame;
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/**
|
|
462
|
+
* The PERSISTED fold — what a reader does with transcript lines. Genuinely one
|
|
463
|
+
* operation: transcript lines are always full records, never deltas.
|
|
464
|
+
*
|
|
465
|
+
* This is NOT `apply()`. Feeding records back through `apply()` would, for one, merge two
|
|
466
|
+
* separately-settled thinking blocks into a single block.
|
|
467
|
+
*/
|
|
468
|
+
export function foldRecords(
|
|
469
|
+
records: Iterable<AggregatedRecord>,
|
|
470
|
+
into?: Map<string, AggregatedRecord>,
|
|
471
|
+
): Map<string, AggregatedRecord> {
|
|
472
|
+
const map = into ?? new Map<string, AggregatedRecord>();
|
|
473
|
+
for (const record of records) map.set(record.recordId, record);
|
|
474
|
+
return map;
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
/**
|
|
478
|
+
* The LIVE fold — handles both wire shapes, so a consumer writes neither.
|
|
479
|
+
*
|
|
480
|
+
* A delta for a `recordId` with no base is dropped: it means the subscriber joined
|
|
481
|
+
* mid-block without taking a snapshot first (see `ActivityAggregator.snapshot`).
|
|
482
|
+
*/
|
|
483
|
+
export function foldFrame(
|
|
484
|
+
map: Map<string, AggregatedRecord>,
|
|
485
|
+
frame: ActivityFrame,
|
|
486
|
+
): Map<string, AggregatedRecord> {
|
|
487
|
+
if (!isActivityDelta(frame)) {
|
|
488
|
+
map.set(frame.recordId, frame);
|
|
489
|
+
return map;
|
|
490
|
+
}
|
|
491
|
+
const base = map.get(frame.recordId);
|
|
492
|
+
if (!base || base.event.kind !== "thinking") return map;
|
|
493
|
+
map.set(frame.recordId, {
|
|
494
|
+
...base,
|
|
495
|
+
seq: frame.seq,
|
|
496
|
+
event: { ...base.event, text: base.event.text + frame.append },
|
|
497
|
+
});
|
|
498
|
+
return map;
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
/**
|
|
502
|
+
* What a live transport should send for one `apply()`, in order.
|
|
503
|
+
*
|
|
504
|
+
* `delta ?? current` alone is not enough: when a thinking block closes because a tool
|
|
505
|
+
* call arrived, the close is in `emitted` while `current` is the tool — a subscriber
|
|
506
|
+
* would never learn the block ended. Records already in `emitted` are not repeated.
|
|
507
|
+
*/
|
|
508
|
+
export function wireFrames(result: ApplyResult): ActivityFrame[] {
|
|
509
|
+
const frames: ActivityFrame[] = [...result.emitted];
|
|
510
|
+
const live: ActivityFrame | null = result.delta ?? result.current;
|
|
511
|
+
if (live && !frames.some((f) => f.recordId === live.recordId)) frames.push(live);
|
|
512
|
+
return frames;
|
|
513
|
+
}
|