Files
t3code/packages/client-runtime/src/state/threadWorkflows.ts
T
+36 de34391427 feat(orchestrator): introduce new orchestrator (#2829)
Co-authored-by: maria-rcks <[email protected]>
Co-authored-by: Bilal Bakr <[email protected]>
Co-authored-by: shivam <[email protected]>
Co-authored-by: Vitalii Yehorov <[email protected]>
Co-authored-by: Jake Leventhal <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Co-authored-by: Alex Southwell <[email protected]>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Nicholas Wasmiller <[email protected]>
Co-authored-by: PB <[email protected]>
Co-authored-by: Exotic <[email protected]>
Co-authored-by: Yash Singh <[email protected]>
Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Theo Browne <[email protected]>
Co-authored-by: Gabriel De Andrade <[email protected]>
Co-authored-by: Dara Adedeji <[email protected]>
Co-authored-by: scratchyone <[email protected]>
Co-authored-by: Dominic Roy <[email protected]>
Co-authored-by: chukfinley <[email protected]>
Co-authored-by: Primož Ajdišek <[email protected]>
Co-authored-by: benthecarman <[email protected]>
Co-authored-by: NaveDanan <[email protected]>
Co-authored-by: aaditagrawal <[email protected]>
Co-authored-by: Aditya Garud <[email protected]>
Co-authored-by: Nick Anisimov <[email protected]>
Co-authored-by: MacKinley Smith <[email protected]>
Co-authored-by: Yordis Prieto <[email protected]>
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
Co-authored-by: AKolenda <[email protected]>
Co-authored-by: Guillermo Casanova <[email protected]>
Co-authored-by: Otavio Salvador <[email protected]>
Co-authored-by: Shirish Pothi <[email protected]>
Co-authored-by: Ishaan Kothari <[email protected]>
Co-authored-by: Bob Fowler <[email protected]>
Co-authored-by: Anton Bezdenezhnykh <[email protected]>
Co-authored-by: ValeraZSD <[email protected]>
Co-authored-by: Ephraim <[email protected]>
Co-authored-by: Ryan Ilano <[email protected]>
Co-authored-by: Alex <[email protected]>
Co-authored-by: maco <[email protected]>
Co-authored-by: Cursor <[email protected]>
Co-authored-by: Tristan Knight <[email protected]>
Co-authored-by: PR Batch Tester <[email protected]>
Co-authored-by: oliver <[email protected]>
Co-authored-by: kamkm <[email protected]>
Signed-off-by: Yordis Prieto <[email protected]>
2026-10-02 12:22:22 -07:00

191 lines
7.3 KiB
TypeScript

import type {
ChatAttachment,
OrchestrationV2ProjectedTurnItem,
OrchestrationV2ProviderCapabilities,
OrchestrationV2ThreadProjection,
} from "@t3tools/contracts";
import { copySorted } from "@t3tools/shared/Array";
type Projection = OrchestrationV2ThreadProjection;
type Run = Projection["runs"][number];
type Message = Projection["messages"][number];
type ProviderSession = Projection["providerSessions"][number];
const ACTIVE_RUN_STATUSES = new Set<Run["status"]>(["preparing", "starting", "running", "waiting"]);
const MERGE_BACK_RUN_STATUSES = new Set<Run["status"]>(["waiting", "completed"]);
const MERGE_BACK_BLOCKING_RUN_STATUSES = new Set<Run["status"]>([
"preparing",
"starting",
"running",
]);
export interface QueuedThreadRun {
readonly run: Run;
readonly text: string;
readonly attachments: ReadonlyArray<ChatAttachment>;
/** Editing replaces this message's content, so its id and context travel with the row. */
readonly messageId: Message["id"];
readonly context?: Message["context"];
}
export interface ThreadQueueWorkflowState {
readonly activeRun: Run | null;
readonly queuedRuns: ReadonlyArray<QueuedThreadRun>;
readonly isHeld: boolean;
readonly canReorder: boolean;
readonly canPromoteToSteer: boolean;
}
export function resolveActiveThreadRun(projection: Pick<Projection, "runs">): Run | null {
return projection.runs.findLast((run) => ACTIVE_RUN_STATUSES.has(run.status)) ?? null;
}
/**
* A successfully finished provider turn remains in `waiting` while its
* checkpoint is captured. Keep that newest turn available for merge-back
* instead of falling through to an older fully checkpointed run.
*/
export function resolveLatestMergeBackRun(projection: Projection): Run | null {
const latestProviderFinishedRun = projection.runs.reduce<Run | null>(
(latest, run) =>
MERGE_BACK_RUN_STATUSES.has(run.status) && (latest === null || run.ordinal > latest.ordinal)
? run
: latest,
null,
);
if (latestProviderFinishedRun === null) return null;
const hasNewerActiveRun = projection.runs.some(
(run) =>
run.ordinal > latestProviderFinishedRun.ordinal &&
MERGE_BACK_BLOCKING_RUN_STATUSES.has(run.status),
);
return hasNewerActiveRun ? null : latestProviderFinishedRun;
}
function resolveThreadProviderSession(projection: Projection): ProviderSession | null {
const activeRun = resolveActiveThreadRun(projection);
const providerThreadId = activeRun?.providerThreadId ?? projection.thread.activeProviderThreadId;
const activeProviderThread =
providerThreadId === null
? null
: (projection.providerThreads.find((thread) => thread.id === providerThreadId) ?? null);
const attachedProviderThread =
activeProviderThread ??
projection.providerThreads.find(
(thread) => thread.appThreadId === projection.thread.id && thread.providerSessionId !== null,
) ??
null;
const sessionId = attachedProviderThread?.providerSessionId ?? null;
if (sessionId !== null) {
return projection.providerSessions.find((session) => session.id === sessionId) ?? null;
}
return (
projection.providerSessions.findLast(
(session) => session.status !== "stopped" && session.status !== "error",
) ?? null
);
}
export function threadSupportsProviderHandoff(projection: Projection | null | undefined): boolean {
if (projection == null) return false;
const session = resolveThreadProviderSession(projection);
if (session !== null) {
return session.capabilities.sessions.supportsProviderSwitchingViaHandoff;
}
if (resolveActiveThreadRun(projection) !== null) return false;
if (projection.thread.historyOrigin === "v1_import" || projection.runs.length === 0) return true;
// Detaching a stopped session removes it from the projection, but its native
// provider thread remains available for the next turn's portable handoff.
return projection.providerThreads.some(
(thread) =>
thread.id === projection.thread.activeProviderThreadId &&
thread.appThreadId === projection.thread.id &&
thread.providerInstanceId === projection.thread.modelSelection.instanceId &&
thread.nativeThreadRef !== null,
);
}
/** Automatic completion/notification runs are not messages in the user's queue. */
export function getUserQueuedThreadRuns(
projection: Pick<Projection, "runs" | "messages">,
): ReadonlyArray<Run> {
const automaticCompletionMessageIds = new Set(
projection.messages
.filter(
(message) =>
message.delegatedCompletion !== undefined || message.notification !== undefined,
)
.map((message) => message.id),
);
return projection.runs.filter(
(run) => run.status === "queued" && !automaticCompletionMessageIds.has(run.userMessageId),
);
}
export function deriveThreadQueueWorkflowState(projection: Projection): ThreadQueueWorkflowState {
const activeRun = resolveActiveThreadRun(projection);
const session = resolveThreadProviderSession(projection);
const capabilities = session?.capabilities.turns;
const hasSteerableProviderTurn =
activeRun?.status === "running" &&
activeRun.activeAttemptId !== null &&
projection.providerTurns.some(
(turn) => turn.runAttemptId === activeRun.activeAttemptId && turn.status === "running",
);
const queuedRuns = copySorted(
getUserQueuedThreadRuns(projection),
(left, right) =>
(left.queuePosition ?? left.ordinal) - (right.queuePosition ?? right.ordinal) ||
left.ordinal - right.ordinal,
).map((run) => {
const message = projection.messages.find((candidate) => candidate.id === run.userMessageId);
return {
run,
text: message?.text ?? "Queued message",
attachments: message?.attachments ?? [],
messageId: run.userMessageId,
...(message?.context ? { context: message.context } : {}),
};
});
return {
activeRun,
queuedRuns,
isHeld: projection.runs.some((run) => run.status === "queued" && run.queueHeld === true),
canReorder: capabilities?.supportsQueuedMessages === true,
canPromoteToSteer:
hasSteerableProviderTurn &&
(capabilities?.supportsActiveSteering === true ||
capabilities?.supportsSteeringByInterruptRestart === true),
};
}
export function canForkProjectedAssistantItem(input: {
readonly projectedItem: OrchestrationV2ProjectedTurnItem;
readonly capabilities?: OrchestrationV2ProviderCapabilities | undefined;
}): boolean {
const item = input.projectedItem.item;
if (item.type !== "assistant_message" || item.runId === null || item.status !== "completed") {
return false;
}
if (input.capabilities === undefined) {
// Historical and inherited rows may outlive their provider-session record.
// Keep the portable server-side fallback available when capability evidence
// is absent; a known incapable provider is rejected below.
return true;
}
const capabilities = input.capabilities;
const canForkNatively =
capabilities.threads.canForkThread &&
capabilities.threads.canForkFromTurn &&
capabilities.identity.nativeThreadIds === "strong";
return canForkNatively || capabilities.context.supportsFullThreadHandoff;
}
export function canDetachThreadProviderSession(projection: Projection): boolean {
const session = resolveThreadProviderSession(projection);
return session !== null && session.status !== "stopped" && session.status !== "error";
}