The best way to control Claude Code, Codex and more from any computer or phone

main
ts 55 lines 2.47 KB
Raw
1 import {
2 isCompactionCommandMessage,
3 type ModelSelection,
4 type OrchestrationV2ThreadProjection,
5 type OrchestrationV2TurnItem,
6 } from "@t3tools/contracts";
7 import { modelSelectionsEqual } from "@t3tools/shared/model";
8 import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError";
9
10 /**
11 * Clients hide pending queued messages, fold async answers into their question, and replace
12 * `/compact` with a compaction row.
13 */
14 export const isShownUserMessageItem = (item: OrchestrationV2TurnItem): boolean =>
15 item.type === "user_message" &&
16 !(item.inputIntent === "queued_turn" && item.status === "pending") &&
17 !item.messageId.startsWith("async-answer:") &&
18 !isCompactionCommandMessage({ role: "user", ...item });
19
20 type ModelSwitchRun = OrchestrationV2ThreadProjection["runs"][number];
21
22 /** A run that has not been undone and has started or can start. */
23 export const isModelSwitchCandidate = (run: ModelSwitchRun): boolean =>
24 run.status !== "rolled_back" && run.status !== "queued";
25
26 /** A run `modelSwitchSince` can measure from: its prompt is shown, or its handoff row shows it. */
27 export const anchorsModelSwitch = (run: ModelSwitchRun, shownMessageIds: ReadonlySet<string>) =>
28 isModelSwitchCandidate(run) &&
29 (shownMessageIds.has(run.userMessageId) || run.contextHandoffId !== null);
30
31 /**
32 * The model or effort change a new run brings, measured from the latest run the timeline shows
33 * through its message or its handoff row, so consecutive dividers always chain. `baseline` stands
34 * in when there is none, such as a fork's source run. Callers skip starts with a context handoff;
35 * the handoff item already shows those.
36 */
37 export function modelSwitchSince(
38 projection: Pick<OrchestrationV2ThreadProjection, "runs" | "turnItems">,
39 to: ModelSelection,
40 baseline?: ModelSelection,
41 ): Pick<Extract<OrchestrationV2TurnItem, { type: "user_message" }>, "modelSwitch"> {
42 const shown = new Set(
43 projection.turnItems.flatMap((item) =>
44 item.type === "user_message" && isShownUserMessageItem(item) ? [item.messageId] : [],
45 ),
46 );
47 let previous: ModelSwitchRun | undefined;
48 for (const run of projection.runs) {
49 // A wake shows as a notification, but its context handoff row still shows the swap.
50 if (!anchorsModelSwitch(run, shown)) continue;
51 if (previous === undefined || runRanAfter(run, previous)) previous = run;
52 }
53 const from = previous?.modelSelection ?? baseline;
54 return from === undefined || modelSelectionsEqual(from, to) ? {} : { modelSwitch: { from, to } };
55 }