Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

contextBoundary.ts

57 lines2.3 KB

1import type { OrchestrationV2Run, OrchestrationV2ThreadProjection } from "@t3tools/contracts";
2​
3import { cancelledBeforeStart } from "./RestartBackgroundNote.ts";
4​
5/** A fresh-session schedule run starts a side conversation; the thread's own one continues past it. */
6export function isScheduledFreshRun(
7 run: Pick<OrchestrationV2Run, "id" | "freshContext" | "userMessageId">,
8 turnItems: OrchestrationV2ThreadProjection["turnItems"],
9): boolean {
10 if (run.freshContext !== true) return false;
11 // A steering restart replaces userMessageId; the run's first prompt still records its origin.
12 // A compacted thread's command read loads these prompts for every fresh-context run.
13 let prompt: OrchestrationV2ThreadProjection["turnItems"][number] | undefined;
14 for (const item of turnItems) {
15 if (item.type !== "user_message") continue;
16 if (item.runId === run.id) {
17 if (prompt?.runId !== run.id || item.ordinal < prompt.ordinal) prompt = item;
18 } else if (prompt === undefined && item.messageId === run.userMessageId) {
19 prompt = item;
20 }
21 }
22 return prompt?.type === "user_message" && prompt.scheduledTaskId !== undefined;
24​
25/** Ordinal of the latest started fresh-context run. Runs before it never reach a provider again. */
26export function contextBoundaryOrdinal(
27 projection: Pick<OrchestrationV2ThreadProjection, "runs" | "turnItems">,
28): number {
29 let boundary = 0;
30 for (const run of projection.runs) {
31 if (
32 run.freshContext === true &&
33 run.status !== "queued" &&
34 !cancelledBeforeStart(run) &&
35 run.ordinal > boundary &&
36 !isScheduledFreshRun(run, projection.turnItems)
37 ) {
38 boundary = run.ordinal;
39 }
40 }
41 return boundary;
43​
44/** Rows of runs from the latest context boundary on; all rows when nothing was cleared. */
45export function turnItemsSinceContextBoundary(
46 projection: Pick<OrchestrationV2ThreadProjection, "runs" | "turnItems">,
47): { readonly boundary: number; readonly turnItems: OrchestrationV2ThreadProjection["turnItems"] } {
48 const boundary = contextBoundaryOrdinal(projection);
49 if (boundary === 0) return { boundary, turnItems: projection.turnItems };
50 const kept = new Set(
51 projection.runs.filter((run) => run.ordinal >= boundary).map((run) => run.id),
52 );
53 return {
54 boundary,
55 turnItems: projection.turnItems.filter((item) => item.runId !== null && kept.has(item.runId)),
56 };