Repository navigation
Expand file tree
/
Copy pathThreadStream.ts
More file actions
619 lines (585 loc) · 20.3 KB
/
Copy pathThreadStream.ts
File metadata and controls
619 lines (585 loc) · 20.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
import {
OrchestrationV2ConversationMessage,
OrchestrationV2PlanArtifact,
OrchestrationV2TurnItem,
type MessageId,
type OrchestrationV2ThreadProjection,
type OrchestrationV2ThreadStreamItem,
type OrchestrationV2ThreadTextDelta,
type PlanId,
type TurnItemId,
} from "@t3tools/contracts";
import type * as Arr from "effect/Array";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { omitLocalVisibleTurnItems } from "@t3tools/shared/orchestrationV2BoundedSnapshot";
import { dedupeSnapshotBodies } from "@t3tools/shared/orchestrationV2DedupedBodies";
import {
buildBoundedThreadProjection,
type BoundedProjectionResult,
} from "./threadHistoryPaging.ts";
import {
capProjectionCheckpointFilesForWire,
compactThreadProjectionForWire,
projectThreadProjectionForWire,
} from "./WireProjection.ts";
export const THREAD_RESUME_MAX_REPLAY_EVENTS = 128;
export const THREAD_RESUME_MAX_REPLAY_ENCODED_BYTES = 1_048_576;
/** Decoded objects and temporary strings exceed stored JSON size, even before wire slimming. */
export const THREAD_RESUME_MAX_RAW_PAYLOAD_BYTES = 1_048_576;
export function isThreadReplayRawPayloadSafe(rawPayloadBytes: number): boolean {
return rawPayloadBytes <= THREAD_RESUME_MAX_RAW_PAYLOAD_BYTES;
}
export function threadReplayEncodedBytes(
items: ReadonlyArray<unknown>,
limit: number = THREAD_RESUME_MAX_REPLAY_ENCODED_BYTES,
): number {
let total = 0;
for (const item of items) {
const encoded = JSON.stringify(item);
total += Buffer.byteLength(encoded ?? "", "utf8");
if (total > limit) break;
}
return total;
}
type ThreadSnapshotStreamItem = Extract<
OrchestrationV2ThreadStreamItem,
{ readonly kind: "snapshot" }
>;
export function boundedSnapshotResponseFields(input: {
readonly bounded: BoundedProjectionResult;
readonly compactTurnItems: boolean;
readonly dedupeBodies: boolean;
readonly compactIds: boolean;
readonly compactWire?: boolean;
}) {
const { bounded } = input;
const compactWire = input.compactWire === true;
const capped = capProjectionCheckpointFilesForWire(bounded.projection);
const slimmed = compactWire ? compactThreadProjectionForWire(capped) : capped;
// Dedupe keeps shared items one object, which the compaction's identity check needs.
const projection = input.dedupeBodies ? dedupeSnapshotBodies(slimmed) : slimmed;
const compactProjection = input.compactTurnItems ? omitLocalVisibleTurnItems(projection) : null;
return {
projection: compactProjection ?? projection,
historyCursor: bounded.historyCursor,
hasMoreHistory: bounded.hasMoreHistory,
latestLocalTurnOrdinal: bounded.latestLocalTurnOrdinal,
...(compactProjection === null ? {} : { turnItemsOmitLocalVisible: true as const }),
...(input.compactIds ? { idTable: true as const } : {}),
...(compactWire ? { compactWire: true as const } : {}),
};
}
export function buildBoundedThreadStreamSnapshot(input: {
readonly snapshotSequence: number;
readonly projection: OrchestrationV2ThreadProjection;
readonly compactTurnItems?: boolean;
readonly dedupeBodies?: boolean;
readonly compactIds?: boolean;
readonly compactWire?: boolean;
}): ThreadSnapshotStreamItem {
const compactWire = input.compactWire === true;
const bounded = buildBoundedThreadProjection({
snapshotSequence: input.snapshotSequence,
projection: projectThreadProjectionForWire(input.projection),
pruneOffWindowMessages: compactWire,
});
return {
kind: "snapshot",
snapshotSequence: input.snapshotSequence,
...boundedSnapshotResponseFields({
bounded,
compactTurnItems: input.compactTurnItems === true,
dedupeBodies: input.dedupeBodies === true,
compactIds: input.compactIds === true,
compactWire,
}),
};
}
export type ThreadResumePlan =
| {
readonly mode: "replay";
readonly afterSequence: number;
readonly throughSequence: number;
}
| { readonly mode: "snapshot" };
/** Bound event count and encoded bytes; replace excessive replay with one current snapshot. */
export function decideThreadResume(input: {
readonly afterSequence: number;
readonly highWater: number;
readonly replayEventCount: number;
readonly replayEncodedBytes: number;
}): ThreadResumePlan {
if (
input.afterSequence > input.highWater ||
input.replayEventCount > THREAD_RESUME_MAX_REPLAY_EVENTS ||
input.replayEncodedBytes > THREAD_RESUME_MAX_REPLAY_ENCODED_BYTES
) {
return { mode: "snapshot" };
}
return {
mode: "replay",
afterSequence: input.afterSequence,
throughSequence: input.highWater,
};
}
const LIVE_TEXT_DELTA_MEMORY = 32;
const sameConversationMessage = Schema.toEquivalence(OrchestrationV2ConversationMessage);
const sameTurnItem = Schema.toEquivalence(OrchestrationV2TurnItem);
const samePlanArtifact = Schema.toEquivalence(OrchestrationV2PlanArtifact);
type StreamableTextTurnItem = Extract<
OrchestrationV2TurnItem,
{ readonly type: "assistant_message" | "reasoning" | "proposed_plan" }
>;
type StreamableProposedPlan = Extract<
OrchestrationV2PlanArtifact,
{ readonly kind: "proposed_plan" }
>;
type ThreadEventStreamItem = Extract<OrchestrationV2ThreadStreamItem, { readonly kind: "event" }>;
function rememberBounded<K, V>(memory: Map<K, V>, key: K, value: V): void {
memory.delete(key);
memory.set(key, value);
if (memory.size > LIVE_TEXT_DELTA_MEMORY) {
memory.delete(memory.keys().next().value as K);
}
}
function sameInstant(left: DateTime.Utc, right: DateTime.Utc): boolean {
return DateTime.toEpochMillis(left) === DateTime.toEpochMillis(right);
}
function sameNullableInstant(left: DateTime.Utc | null, right: DateTime.Utc | null): boolean {
return left === right || (left !== null && right !== null && sameInstant(left, right));
}
function isStreamableTextTurnItem(item: OrchestrationV2TurnItem): item is StreamableTextTurnItem {
return (
item.type === "assistant_message" || item.type === "reasoning" || item.type === "proposed_plan"
);
}
function isStreamableProposedPlan(
plan: OrchestrationV2PlanArtifact,
): plan is StreamableProposedPlan {
return plan.kind === "proposed_plan" && (plan.status === "draft" || plan.status === "active");
}
function turnItemText(item: StreamableTextTurnItem): string {
return item.type === "proposed_plan" ? item.markdown : item.text;
}
function sameTurnItemExceptStreamingFields(
previous: StreamableTextTurnItem,
next: StreamableTextTurnItem,
): boolean {
if (previous.type !== next.type || Object.keys(previous).length !== Object.keys(next).length) {
return false;
}
if (previous.type === "proposed_plan" && next.type === "proposed_plan") {
return sameTurnItem(
{
...previous,
markdown: "",
updatedAt: previous.updatedAt,
streaming: next.streaming,
status: next.status,
completedAt: next.completedAt,
},
{ ...next, markdown: "", updatedAt: previous.updatedAt },
);
}
if (previous.type === "assistant_message" && next.type === "assistant_message") {
return sameTurnItem(
{
...previous,
text: "",
updatedAt: previous.updatedAt,
streaming: next.streaming,
status: next.status,
completedAt: next.completedAt,
},
{ ...next, text: "", updatedAt: previous.updatedAt },
);
}
if (previous.type === "reasoning" && next.type === "reasoning") {
return sameTurnItem(
{
...previous,
text: "",
updatedAt: previous.updatedAt,
streaming: next.streaming,
status: next.status,
completedAt: next.completedAt,
},
{ ...next, text: "", updatedAt: previous.updatedAt },
);
}
return false;
}
function matchMessageDelta(
previous: OrchestrationV2ConversationMessage | undefined,
item: ThreadEventStreamItem & {
readonly event: Extract<ThreadEventStreamItem["event"], { readonly type: "message.updated" }>;
},
) {
const next = item.event.payload;
if (
previous === undefined ||
!previous.streaming ||
previous.id !== next.id ||
previous.role !== next.role ||
next.text.length < previous.text.length ||
!next.text.startsWith(previous.text) ||
Object.keys(previous).length !== Object.keys(next).length ||
!sameConversationMessage(
{ ...previous, text: "", updatedAt: previous.updatedAt, streaming: next.streaming },
{ ...next, text: "", updatedAt: previous.updatedAt },
)
) {
return null;
}
return {
offset: previous.text.length,
chunk: next.text.slice(previous.text.length),
done: !next.streaming,
occurredAt: item.event.occurredAt,
updatedAt: next.updatedAt,
next,
} as const;
}
function matchTurnItemDelta(
previous: StreamableTextTurnItem | undefined,
item: ThreadEventStreamItem & {
readonly event: Extract<ThreadEventStreamItem["event"], { readonly type: "turn-item.updated" }>;
},
) {
const next = item.event.payload;
if (
previous === undefined ||
!isStreamableTextTurnItem(next) ||
previous.type !== next.type ||
!previous.streaming ||
previous.status !== "running" ||
(next.type === "assistant_message" && next.textOmitted === true)
) {
return null;
}
let done = false;
if (next.streaming) {
if (next.status !== "running" || !sameNullableInstant(next.completedAt, previous.completedAt)) {
return null;
}
} else {
if (
next.status !== "completed" ||
next.completedAt === null ||
!sameInstant(next.completedAt, next.updatedAt)
) {
return null;
}
done = true;
}
const previousText = turnItemText(previous);
const nextText = turnItemText(next);
if (
nextText.length < previousText.length ||
!nextText.startsWith(previousText) ||
!sameTurnItemExceptStreamingFields(previous, next)
) {
return null;
}
return {
offset: previousText.length,
chunk: nextText.slice(previousText.length),
done,
occurredAt: item.event.occurredAt,
updatedAt: next.updatedAt,
next,
} as const;
}
function matchPlanDelta(
previous: StreamableProposedPlan | undefined,
item: ThreadEventStreamItem & {
readonly event: Extract<ThreadEventStreamItem["event"], { readonly type: "plan.updated" }>;
},
) {
const next = item.event.payload;
if (
previous === undefined ||
!isStreamableProposedPlan(next) ||
previous.status !== next.status ||
next.markdown.length < previous.markdown.length ||
!next.markdown.startsWith(previous.markdown) ||
Object.keys(previous).length !== Object.keys(next).length ||
!samePlanArtifact({ ...previous, markdown: "" }, { ...next, markdown: "" })
) {
return null;
}
return {
offset: previous.markdown.length,
chunk: next.markdown.slice(previous.markdown.length),
occurredAt: item.event.occurredAt,
next,
} as const;
}
function makeLiveTextDeltaBatchEncoder(): (
items: Arr.NonEmptyReadonlyArray<OrchestrationV2ThreadStreamItem>,
) => Arr.NonEmptyReadonlyArray<OrchestrationV2ThreadStreamItem> {
const messages = new Map<MessageId, OrchestrationV2ConversationMessage>();
const turnItems = new Map<TurnItemId, StreamableTextTurnItem>();
const plans = new Map<PlanId, StreamableProposedPlan>();
const clear = () => {
messages.clear();
turnItems.clear();
plans.clear();
};
const recordMessage = (message: OrchestrationV2ConversationMessage) => {
if (message.streaming) rememberBounded(messages, message.id, message);
else messages.delete(message.id);
};
const recordTurnItem = (turnItem: OrchestrationV2TurnItem) => {
if (
isStreamableTextTurnItem(turnItem) &&
turnItem.streaming &&
turnItem.status === "running" &&
!(turnItem.type === "assistant_message" && turnItem.textOmitted === true)
) {
rememberBounded(turnItems, turnItem.id, turnItem);
return;
}
turnItems.delete(turnItem.id);
};
const recordPlan = (plan: OrchestrationV2PlanArtifact) => {
if (isStreamableProposedPlan(plan)) rememberBounded(plans, plan.id, plan);
else plans.delete(plan.id);
};
const seedFromSnapshot = (snapshot: ThreadSnapshotStreamItem) => {
clear();
const messageTextById = new Map(
snapshot.projection.messages.map((message) => [message.id, message.text] as const),
);
for (const message of snapshot.projection.messages) {
if (message.streaming) rememberBounded(messages, message.id, message);
}
for (const plan of snapshot.projection.plans) {
if (isStreamableProposedPlan(plan)) rememberBounded(plans, plan.id, plan);
}
// Snapshots can omit local visible turnItems and blank mirrored message text; mirror what the client restores.
const seedTurnItem = (turnItem: OrchestrationV2TurnItem) => {
if (
!isStreamableTextTurnItem(turnItem) ||
!turnItem.streaming ||
turnItem.status !== "running"
) {
return;
}
if (turnItem.type === "assistant_message" && turnItem.textOmitted === true) {
const restoredText = messageTextById.get(turnItem.messageId);
if (restoredText === undefined) return;
const { textOmitted: _textOmitted, ...rest } = turnItem;
rememberBounded(turnItems, turnItem.id, { ...rest, text: restoredText });
return;
}
rememberBounded(turnItems, turnItem.id, turnItem);
};
for (const turnItem of snapshot.projection.turnItems) seedTurnItem(turnItem);
if (snapshot.turnItemsOmitLocalVisible === true) {
for (const row of snapshot.projection.visibleTurnItems) {
if (row.visibility === "local" || row.sourceThreadId === snapshot.projection.thread.id) {
seedTurnItem(row.item);
}
}
}
};
return (items) => {
const out: Array<OrchestrationV2ThreadStreamItem> = [];
for (let index = 0; index < items.length; index += 1) {
const item = items[index]!;
if (item.kind === "snapshot") {
seedFromSnapshot(item);
out.push(item);
continue;
}
if (item.kind !== "event") {
out.push(item);
continue;
}
const { event } = item;
if (event.type === "thread.deleted") {
clear();
out.push(item);
continue;
}
if (event.type === "message.updated") {
const matched = matchMessageDelta(messages.get(event.payload.id), { ...item, event });
if (matched === null) {
recordMessage(event.payload);
out.push(item);
continue;
}
const nextItem = items[index + 1];
if (
nextItem !== undefined &&
nextItem.kind === "event" &&
nextItem.event.type === "turn-item.updated" &&
nextItem.event.threadId === event.threadId &&
nextItem.sequence >= item.sequence &&
nextItem.event.payload.type === "assistant_message" &&
nextItem.event.payload.messageId === event.payload.id
) {
const mirror = matchTurnItemDelta(turnItems.get(nextItem.event.payload.id), {
...nextItem,
event: nextItem.event,
});
if (
mirror !== null &&
mirror.offset === matched.offset &&
mirror.chunk === matched.chunk &&
mirror.done === matched.done
) {
recordMessage(matched.next);
recordTurnItem(mirror.next);
const occurredAt = mirror.occurredAt;
const delta: OrchestrationV2ThreadTextDelta = {
kind: "text-delta",
sequence: nextItem.sequence,
target: "message",
id: matched.next.id,
mirrorItemId: mirror.next.id,
offset: matched.offset,
chunk: matched.chunk,
occurredAt,
...(sameInstant(matched.updatedAt, occurredAt)
? {}
: { updatedAt: matched.updatedAt }),
...(sameInstant(mirror.updatedAt, matched.updatedAt)
? {}
: { mirrorUpdatedAt: mirror.updatedAt }),
...(matched.done ? { done: true as const } : {}),
};
out.push(delta);
index += 1;
continue;
}
}
recordMessage(matched.next);
const delta: OrchestrationV2ThreadTextDelta = {
kind: "text-delta",
sequence: item.sequence,
target: "message",
id: matched.next.id,
offset: matched.offset,
chunk: matched.chunk,
occurredAt: matched.occurredAt,
...(sameInstant(matched.updatedAt, matched.occurredAt)
? {}
: { updatedAt: matched.updatedAt }),
...(matched.done ? { done: true as const } : {}),
};
out.push(delta);
continue;
}
if (event.type === "plan.updated") {
const matched = matchPlanDelta(plans.get(event.payload.id), { ...item, event });
if (matched === null) {
recordPlan(event.payload);
out.push(item);
continue;
}
const nextItem = items[index + 1];
if (
nextItem !== undefined &&
nextItem.kind === "event" &&
nextItem.event.type === "turn-item.updated" &&
nextItem.event.threadId === event.threadId &&
nextItem.sequence >= item.sequence &&
nextItem.event.payload.type === "proposed_plan" &&
nextItem.event.payload.planId === event.payload.id
) {
const mirror = matchTurnItemDelta(turnItems.get(nextItem.event.payload.id), {
...nextItem,
event: nextItem.event,
});
if (
mirror !== null &&
!mirror.done &&
mirror.offset === matched.offset &&
mirror.chunk === matched.chunk
) {
recordPlan(matched.next);
recordTurnItem(mirror.next);
const occurredAt = mirror.occurredAt;
const delta: OrchestrationV2ThreadTextDelta = {
kind: "text-delta",
sequence: nextItem.sequence,
target: "plan",
id: matched.next.id,
mirrorItemId: mirror.next.id,
offset: matched.offset,
chunk: matched.chunk,
occurredAt,
...(sameInstant(mirror.updatedAt, occurredAt)
? {}
: { mirrorUpdatedAt: mirror.updatedAt }),
};
out.push(delta);
index += 1;
continue;
}
}
recordPlan(matched.next);
const delta: OrchestrationV2ThreadTextDelta = {
kind: "text-delta",
sequence: item.sequence,
target: "plan",
id: matched.next.id,
offset: matched.offset,
chunk: matched.chunk,
occurredAt: matched.occurredAt,
};
out.push(delta);
continue;
}
if (event.type === "turn-item.updated") {
const matched = matchTurnItemDelta(turnItems.get(event.payload.id), { ...item, event });
if (matched === null) {
recordTurnItem(event.payload);
out.push(item);
continue;
}
recordTurnItem(matched.next);
const delta: OrchestrationV2ThreadTextDelta = {
kind: "text-delta",
sequence: item.sequence,
target: "turn-item",
id: matched.next.id,
offset: matched.offset,
chunk: matched.chunk,
occurredAt: matched.occurredAt,
...(sameInstant(matched.updatedAt, matched.occurredAt)
? {}
: { updatedAt: matched.updatedAt }),
...(matched.done ? { done: true as const } : {}),
};
out.push(delta);
continue;
}
out.push(item);
}
return isNonEmpty(out) ? out : items;
};
}
function isNonEmpty<A>(items: ReadonlyArray<A>): items is Arr.NonEmptyReadonlyArray<A> {
return items.length > 0;
}
/**
* Per-subscriber wire encoder: replaces append-only streaming text/reasoning/plan updates with
* compact `text-delta` items and fuses adjacent mirrored record+turn-item updates into one frame.
*/
export function withLiveTextDeltas<E, R>(
stream: Stream.Stream<OrchestrationV2ThreadStreamItem, E, R>,
): Stream.Stream<OrchestrationV2ThreadStreamItem, E, R> {
return Stream.fromPull(
Effect.gen(function* () {
const pull = yield* Stream.toPull(stream);
const encodeBatch = makeLiveTextDeltaBatchEncoder();
return Effect.map(pull, encodeBatch);
}),
).pipe(Stream.scoped);
}