Files
t3code/apps/server/src/orchestration-v2/ProjectionStore.ts
T
Julius MarmingeandClaude Fable 5 353f352c1e feat(orchestration): port thread title regeneration to the v2 runtime
Follow-ups from the main merge:

- Migration numbering: main's 035_ProjectionThreadTitleRegeneration is
  released and keeps its id; this branch's unreleased v2 migrations shift
  to 036-044 instead (a released migration can never be renumbered).
- thread.metadata.update accepts regenerateTitle: true arms an in-flight
  titleRegeneration marker on the thread payload (requestId + startedAt),
  a landing title or explicit false clears it. The marker projects onto
  thread shells and through the client-runtime shell model, so the
  sidebar's Regenerating state works unchanged.
- New ThreadTitleRegenerationService worker reacts to armed markers on
  the live domain-event stream (so ws, MCP, and mobile dispatches all
  behave the same): builds a newest-first conversation digest from the
  v2 projection (8k-char budget, retained attachments — ported from the
  v1 reactor), generates via TextGeneration, and lands the title with a
  follow-up metadata update. Failures clear the marker and log.
- The server advertises threadTitleRegeneration again, and the client
  updateThreadMetadata dispatches regenerateTitle-only updates.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-03 11:45:15 -04:00

2538 lines
94 KiB
TypeScript

import type {
OrchestrationV2ConversationMessage,
OrchestrationV2DomainEvent,
OrchestrationV2ProjectedTurnItem,
OrchestrationV2ThreadShellSnapshot,
OrchestrationV2ShellThreadStatus,
OrchestrationV2ThreadShell,
OrchestrationV2ThreadProjection,
OrchestrationV2TurnItem,
ProviderSessionId,
} from "@t3tools/contracts";
import {
OrchestrationV2AppThreadJson as OrchestrationV2AppThreadJsonSchema,
OrchestrationV2CheckpointJson as OrchestrationV2CheckpointJsonSchema,
OrchestrationV2CheckpointScopeJson as OrchestrationV2CheckpointScopeJsonSchema,
OrchestrationV2ContextHandoffJson as OrchestrationV2ContextHandoffJsonSchema,
OrchestrationV2ContextTransferJson as OrchestrationV2ContextTransferJsonSchema,
OrchestrationV2ConversationMessageJson as OrchestrationV2ConversationMessageJsonSchema,
OrchestrationV2ExecutionNodeJson as OrchestrationV2ExecutionNodeJsonSchema,
OrchestrationV2PlanArtifact as OrchestrationV2PlanArtifactSchema,
OrchestrationV2ProviderSessionJson as OrchestrationV2ProviderSessionJsonSchema,
OrchestrationV2ProviderThreadJson as OrchestrationV2ProviderThreadJsonSchema,
OrchestrationV2ProviderTurnJson as OrchestrationV2ProviderTurnJsonSchema,
OrchestrationV2RunAttemptJson as OrchestrationV2RunAttemptJsonSchema,
OrchestrationV2RunJson as OrchestrationV2RunJsonSchema,
OrchestrationV2RuntimeRequestJson as OrchestrationV2RuntimeRequestJsonSchema,
OrchestrationV2SubagentJson as OrchestrationV2SubagentJsonSchema,
OrchestrationV2TurnItemJson as OrchestrationV2TurnItemJsonSchema,
RunId,
ThreadId,
TurnItemId,
} from "@t3tools/contracts";
import {
isOrchestrationV2SupersededInterrupt,
isOrchestrationV2TurnItemVisible,
} from "@t3tools/shared/orchestrationV2Timeline";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export class ProjectionStoreApplyEventError extends Schema.TaggedErrorClass<ProjectionStoreApplyEventError>()(
"ProjectionStoreApplyEventError",
{
eventType: Schema.String,
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `Failed to apply orchestration projection event ${this.eventType}.`;
}
}
export class ProjectionStoreSetupError extends Schema.TaggedErrorClass<ProjectionStoreSetupError>()(
"ProjectionStoreSetupError",
{
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return "Failed to initialize orchestration projection store.";
}
}
export class ProjectionStoreThreadNotFoundError extends Schema.TaggedErrorClass<ProjectionStoreThreadNotFoundError>()(
"ProjectionStoreThreadNotFoundError",
{
threadId: ThreadId,
},
) {
override get message(): string {
return `No orchestration projection exists for thread ${this.threadId}.`;
}
}
export class ProjectionStoreReadError extends Schema.TaggedErrorClass<ProjectionStoreReadError>()(
"ProjectionStoreReadError",
{
threadId: ThreadId,
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `Failed to read orchestration projection for thread ${this.threadId}.`;
}
}
export const ProjectionStoreV2Error = Schema.Union([
ProjectionStoreSetupError,
ProjectionStoreApplyEventError,
ProjectionStoreThreadNotFoundError,
ProjectionStoreReadError,
]);
export type ProjectionStoreV2Error = typeof ProjectionStoreV2Error.Type;
export interface ProjectionStoreV2Shape {
readonly apply: (
event: OrchestrationV2DomainEvent,
) => Effect.Effect<void, ProjectionStoreV2Error>;
readonly getShellSnapshot: () => Effect.Effect<
OrchestrationV2ThreadShellSnapshot,
ProjectionStoreV2Error
>;
readonly getThreadShell: (
threadId: ThreadId,
) => Effect.Effect<OrchestrationV2ThreadShell | null, ProjectionStoreV2Error>;
readonly getThreadProjection: (
threadId: ThreadId,
) => Effect.Effect<OrchestrationV2ThreadProjection, ProjectionStoreV2Error>;
readonly getThreadSnapshot: (threadId: ThreadId) => Effect.Effect<
{
readonly schemaVersion: number;
readonly snapshotSequence: number;
readonly projection: OrchestrationV2ThreadProjection;
},
ProjectionStoreV2Error
>;
}
export class ProjectionStoreV2 extends Context.Service<ProjectionStoreV2, ProjectionStoreV2Shape>()(
"t3/orchestration-v2/ProjectionStore/ProjectionStoreV2",
) {}
export const ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION = 2;
function upsertById<T extends { readonly id: string }>(items: ReadonlyArray<T>, next: T): Array<T> {
const index = items.findIndex((item) => item.id === next.id);
if (index === -1) {
return [...items, next];
}
const updated = [...items];
updated[index] = next;
return updated;
}
export function emptyProjection(
event: Extract<OrchestrationV2DomainEvent, { readonly type: "thread.created" }>,
): OrchestrationV2ThreadProjection {
return {
thread: event.payload,
runs: [],
attempts: [],
nodes: [],
subagents: [],
providerSessions: [],
providerThreads: [],
providerTurns: [],
runtimeRequests: [],
messages: [],
plans: [],
turnItems: [],
checkpointScopes: [],
checkpoints: [],
contextHandoffs: [],
contextTransfers: [],
visibleTurnItems: [],
updatedAt: event.occurredAt,
};
}
export function applyToProjection(
projection: OrchestrationV2ThreadProjection,
event: OrchestrationV2DomainEvent,
): OrchestrationV2ThreadProjection {
const base = {
...projection,
thread: {
...projection.thread,
updatedAt: event.occurredAt,
},
updatedAt: event.occurredAt,
};
switch (event.type) {
case "thread.created":
case "thread.archived":
case "thread.unarchived":
case "thread.deleted":
case "thread.metadata-updated":
case "thread.runtime-mode-updated":
case "thread.interaction-mode-updated":
case "thread.model-selection-updated":
case "thread.provider-switched":
return {
...base,
thread: event.payload,
};
// Visited tracking is read state, not activity: skip the updatedAt bump so
// viewing a thread does not surface it as recently active.
case "thread.visited":
case "thread.marked-unread":
return {
...projection,
thread: event.payload,
};
case "run.created":
case "run.updated":
return withLocalVisibleTurnItems({
...base,
runs: upsertById(base.runs, event.payload),
});
case "run-attempt.created":
case "run-attempt.updated":
return withLocalVisibleTurnItems({
...base,
attempts: upsertById(base.attempts, event.payload),
});
case "node.updated":
return {
...base,
nodes: upsertById(base.nodes, event.payload),
};
case "subagent.updated":
return {
...base,
subagents: upsertById(base.subagents, event.payload),
};
case "provider-session.attached":
case "provider-session.updated":
return {
...base,
providerSessions: upsertById(base.providerSessions, event.payload),
};
case "provider-session.detached":
return {
...base,
providerSessions: base.providerSessions.filter(
(session) => session.id !== event.payload.providerSessionId,
),
};
case "provider-thread.updated":
return {
...base,
thread:
event.payload.appThreadId === base.thread.id
? {
...base.thread,
activeProviderThreadId: event.payload.id,
}
: base.thread,
providerThreads: upsertById(base.providerThreads, event.payload),
};
case "provider-turn.updated":
return {
...base,
providerTurns: upsertById(base.providerTurns, event.payload),
};
case "runtime-request.updated":
return {
...base,
runtimeRequests: upsertById(base.runtimeRequests, event.payload),
};
case "message.updated":
return {
...base,
messages: upsertById(base.messages, event.payload),
};
case "turn-item.updated":
return withLocalVisibleTurnItems({
...base,
turnItems: upsertById(base.turnItems, event.payload),
});
case "plan.updated":
return {
...base,
plans: upsertById(base.plans, event.payload),
};
case "checkpoint-scope.created":
return {
...base,
checkpointScopes: upsertById(base.checkpointScopes, event.payload),
};
case "checkpoint.captured":
return {
...base,
checkpoints: upsertById(base.checkpoints, event.payload),
};
case "checkpoint.rollback-requested":
return base;
case "context-handoff.updated":
return {
...base,
contextHandoffs: upsertById(base.contextHandoffs, event.payload),
};
case "context-transfer.created":
case "context-transfer.updated":
return {
...base,
contextTransfers: upsertById(base.contextTransfers, event.payload),
};
}
}
/**
* Replay state for entities whose persisted projection is shared across thread bindings.
*
* Provider sessions are process-scoped: one session row can be bound to several app
* threads. Updating that row changes what every bound thread reads, even though the
* application event itself belongs to one thread stream. Keeping the binding index here
* makes in-memory replay match the normalized SQL projection without scanning every
* thread for every session event.
*/
export interface ProjectionReplayState {
readonly projections: Map<ThreadId, OrchestrationV2ThreadProjection>;
readonly providerSessionThreadIds: Map<ProviderSessionId, ReadonlySet<ThreadId>>;
}
export function makeProjectionReplayState(): ProjectionReplayState {
return {
projections: new Map(),
providerSessionThreadIds: new Map(),
};
}
export function applyToProjectionReplayState(
state: ProjectionReplayState,
event: OrchestrationV2DomainEvent,
): boolean {
if (event.type === "thread.created" && !state.projections.has(event.threadId)) {
state.projections.set(event.threadId, emptyProjection(event));
return true;
}
const current = state.projections.get(event.threadId);
if (current === undefined) {
return false;
}
let next = applyToProjection(current, event);
if (event.type === "provider-session.updated") {
const boundThreadIds = state.providerSessionThreadIds.get(event.payload.id);
if (boundThreadIds?.has(event.threadId) !== true) {
// The SQL projection updates the global session row but does not implicitly
// create a thread binding for an update event.
next = { ...next, providerSessions: current.providerSessions };
}
}
state.projections.set(event.threadId, next);
switch (event.type) {
case "provider-session.attached": {
const boundThreadIds = new Set(state.providerSessionThreadIds.get(event.payload.id) ?? []);
boundThreadIds.add(event.threadId);
state.providerSessionThreadIds.set(event.payload.id, boundThreadIds);
for (const threadId of boundThreadIds) {
if (threadId === event.threadId) continue;
const projection = state.projections.get(threadId);
if (projection === undefined) continue;
state.projections.set(threadId, {
...projection,
providerSessions: upsertById(projection.providerSessions, event.payload),
});
}
break;
}
case "provider-session.updated": {
const boundThreadIds = state.providerSessionThreadIds.get(event.payload.id) ?? [];
for (const threadId of boundThreadIds) {
if (threadId === event.threadId) continue;
const projection = state.projections.get(threadId);
if (projection === undefined) continue;
state.projections.set(threadId, {
...projection,
providerSessions: upsertById(projection.providerSessions, event.payload),
});
}
break;
}
case "provider-session.detached": {
const boundThreadIds = new Set(
state.providerSessionThreadIds.get(event.payload.providerSessionId) ?? [],
);
boundThreadIds.delete(event.threadId);
if (boundThreadIds.size === 0) {
state.providerSessionThreadIds.delete(event.payload.providerSessionId);
} else {
state.providerSessionThreadIds.set(event.payload.providerSessionId, boundThreadIds);
}
break;
}
}
return true;
}
type PayloadRow = {
readonly payload_json: string;
};
type ShellThreadRow = {
readonly thread_id: string;
readonly payload_json: string;
readonly forked_from_run_source_thread_id: string | null;
readonly latest_run_id: string | null;
readonly latest_run_status: string | null;
readonly latest_run_requested_at: string | null;
readonly latest_run_started_at: string | null;
readonly latest_run_completed_at: string | null;
readonly active_run_id: string | null;
readonly last_error: string | null;
readonly pending_request_payload_json: string | null;
readonly latest_message_payload_json: string | null;
readonly latest_user_message_at: string | null;
readonly has_actionable_proposed_plan: number;
readonly item_count: number;
readonly runless_item_count: number;
};
type ShellRunRow = {
readonly thread_id: string;
readonly run_id: string;
readonly ordinal: number;
};
type ShellRunItemCountRow = {
readonly thread_id: string;
readonly run_id: string;
readonly item_count: number;
};
const encodeThreadPayload = Schema.encodeEffect(
Schema.fromJsonString(OrchestrationV2AppThreadJsonSchema),
);
const encodeRunPayload = Schema.encodeEffect(Schema.fromJsonString(OrchestrationV2RunJsonSchema));
const encodeRunAttemptPayload = Schema.encodeEffect(
Schema.fromJsonString(OrchestrationV2RunAttemptJsonSchema),
);
const encodeNodePayload = Schema.encodeEffect(
Schema.fromJsonString(OrchestrationV2ExecutionNodeJsonSchema),
);
const encodeSubagentPayload = Schema.encodeEffect(
Schema.fromJsonString(OrchestrationV2SubagentJsonSchema),
);
const encodeProviderSessionPayload = Schema.encodeEffect(
Schema.fromJsonString(OrchestrationV2ProviderSessionJsonSchema),
);
const encodeProviderThreadPayload = Schema.encodeEffect(
Schema.fromJsonString(OrchestrationV2ProviderThreadJsonSchema),
);
const encodeProviderTurnPayload = Schema.encodeEffect(
Schema.fromJsonString(OrchestrationV2ProviderTurnJsonSchema),
);
const encodeRuntimeRequestPayload = Schema.encodeEffect(
Schema.fromJsonString(OrchestrationV2RuntimeRequestJsonSchema),
);
const encodeMessagePayload = Schema.encodeEffect(
Schema.fromJsonString(OrchestrationV2ConversationMessageJsonSchema),
);
const encodePlanPayload = Schema.encodeEffect(
Schema.fromJsonString(OrchestrationV2PlanArtifactSchema),
);
const encodeTurnItemPayload = Schema.encodeEffect(
Schema.fromJsonString(OrchestrationV2TurnItemJsonSchema),
);
const encodeCheckpointScopePayload = Schema.encodeEffect(
Schema.fromJsonString(OrchestrationV2CheckpointScopeJsonSchema),
);
const encodeCheckpointPayload = Schema.encodeEffect(
Schema.fromJsonString(OrchestrationV2CheckpointJsonSchema),
);
const encodeContextHandoffPayload = Schema.encodeEffect(
Schema.fromJsonString(OrchestrationV2ContextHandoffJsonSchema),
);
const encodeContextTransferPayload = Schema.encodeEffect(
Schema.fromJsonString(OrchestrationV2ContextTransferJsonSchema),
);
const decodeThreadPayload = (json: string) =>
Schema.decodeUnknownEffect(Schema.fromJsonString(OrchestrationV2AppThreadJsonSchema))(json);
const decodeRunPayload = (json: string) =>
Schema.decodeUnknownEffect(Schema.fromJsonString(OrchestrationV2RunJsonSchema))(json);
const decodeRunAttemptPayload = (json: string) =>
Schema.decodeUnknownEffect(Schema.fromJsonString(OrchestrationV2RunAttemptJsonSchema))(json);
const decodeNodePayload = (json: string) =>
Schema.decodeUnknownEffect(Schema.fromJsonString(OrchestrationV2ExecutionNodeJsonSchema))(json);
const decodeSubagentPayload = (json: string) =>
Schema.decodeUnknownEffect(Schema.fromJsonString(OrchestrationV2SubagentJsonSchema))(json);
const decodeProviderSessionPayload = (json: string) =>
Schema.decodeUnknownEffect(Schema.fromJsonString(OrchestrationV2ProviderSessionJsonSchema))(json);
const decodeProviderThreadPayload = (json: string) =>
Schema.decodeUnknownEffect(Schema.fromJsonString(OrchestrationV2ProviderThreadJsonSchema))(json);
const decodeProviderTurnPayload = (json: string) =>
Schema.decodeUnknownEffect(Schema.fromJsonString(OrchestrationV2ProviderTurnJsonSchema))(json);
const decodeRuntimeRequestPayload = (json: string) =>
Schema.decodeUnknownEffect(Schema.fromJsonString(OrchestrationV2RuntimeRequestJsonSchema))(json);
const decodeMessagePayload = (json: string) =>
Schema.decodeUnknownEffect(Schema.fromJsonString(OrchestrationV2ConversationMessageJsonSchema))(
json,
);
const decodePlanPayload = (json: string) =>
Schema.decodeUnknownEffect(OrchestrationV2PlanArtifactSchema)(parseEncodedPayload(json));
const decodeTurnItemPayload = (json: string) =>
Schema.decodeUnknownEffect(Schema.fromJsonString(OrchestrationV2TurnItemJsonSchema))(json);
const decodeCheckpointScopePayload = (json: string) =>
Schema.decodeUnknownEffect(Schema.fromJsonString(OrchestrationV2CheckpointScopeJsonSchema))(json);
const decodeCheckpointPayload = (json: string) =>
Schema.decodeUnknownEffect(Schema.fromJsonString(OrchestrationV2CheckpointJsonSchema))(json);
const decodeContextHandoffPayload = (json: string) =>
Schema.decodeUnknownEffect(Schema.fromJsonString(OrchestrationV2ContextHandoffJsonSchema))(json);
const decodeContextTransferPayload = (json: string) =>
Schema.decodeUnknownEffect(Schema.fromJsonString(OrchestrationV2ContextTransferJsonSchema))(json);
function parseEncodedPayload(json: string): Record<string, unknown> {
return JSON.parse(json) as Record<string, unknown>;
}
function stringField(payload: Record<string, unknown>, field: string): string {
const value = payload[field];
return typeof value === "string" ? value : String(value);
}
function nullableStringField(payload: Record<string, unknown>, field: string): string | null {
const value = payload[field];
if (value === null || value === undefined) {
return null;
}
return typeof value === "string" ? value : String(value);
}
function booleanInt(value: boolean): 0 | 1 {
return value ? 1 : 0;
}
const decodeRows =
<A, E>(decode: (json: string) => Effect.Effect<A, E>, threadId: ThreadId) =>
(rows: ReadonlyArray<PayloadRow>): Effect.Effect<Array<A>, ProjectionStoreReadError> =>
Effect.forEach(rows, (row) => decode(row.payload_json)).pipe(
Effect.mapError(
(cause) =>
new ProjectionStoreReadError({
threadId,
cause,
}),
),
);
function messageIdForTurnItem(item: OrchestrationV2TurnItem): string | null {
switch (item.type) {
case "user_message":
case "assistant_message":
return item.messageId;
default:
return null;
}
}
function sortMessagesByTurnItemOrder(
messages: ReadonlyArray<OrchestrationV2ConversationMessage>,
turnItems: ReadonlyArray<OrchestrationV2TurnItem>,
): Array<OrchestrationV2ConversationMessage> {
const messageOrdinals = new Map<string, number>();
for (const turnItem of turnItems) {
const messageId = messageIdForTurnItem(turnItem);
if (messageId === null) {
continue;
}
const existing = messageOrdinals.get(messageId);
if (existing === undefined || turnItem.ordinal < existing) {
messageOrdinals.set(messageId, turnItem.ordinal);
}
}
return messages.toSorted((left, right) => {
const leftOrdinal = messageOrdinals.get(left.id) ?? Number.MAX_SAFE_INTEGER;
const rightOrdinal = messageOrdinals.get(right.id) ?? Number.MAX_SAFE_INTEGER;
if (leftOrdinal !== rightOrdinal) {
return leftOrdinal - rightOrdinal;
}
const leftCreatedAt = DateTime.toEpochMillis(left.createdAt);
const rightCreatedAt = DateTime.toEpochMillis(right.createdAt);
if (leftCreatedAt !== rightCreatedAt) {
return leftCreatedAt - rightCreatedAt;
}
return left.id.localeCompare(right.id);
});
}
function activeLocalTurnItems(
projection: OrchestrationV2ThreadProjection,
): Array<OrchestrationV2ProjectedTurnItem> {
return projection.turnItems
.filter((item) =>
isOrchestrationV2TurnItemVisible({
item,
runs: projection.runs,
attempts: projection.attempts,
items: projection.turnItems,
}),
)
.map((item, position) => ({
position,
visibility: "local" as const,
sourceThreadId: item.threadId,
sourceItemId: item.id,
item,
}));
}
function localVisibleTurnItems(
projection: OrchestrationV2ThreadProjection,
): Array<OrchestrationV2ProjectedTurnItem> {
return activeLocalTurnItems(projection);
}
function inheritedVisibleTurnItemsFromLocalItems(
items: ReadonlyArray<OrchestrationV2TurnItem>,
): Array<Omit<OrchestrationV2ProjectedTurnItem, "position">> {
return items.map((item) => ({
visibility: "inherited" as const,
sourceThreadId: item.threadId,
sourceItemId: item.id,
item,
}));
}
function withLocalVisibleTurnItems(
projection: OrchestrationV2ThreadProjection,
): OrchestrationV2ThreadProjection {
return {
...projection,
visibleTurnItems: localVisibleTurnItems(projection),
};
}
function renumberVisibleTurnItems(
rows: ReadonlyArray<Omit<OrchestrationV2ProjectedTurnItem, "position">>,
): Array<OrchestrationV2ProjectedTurnItem> {
return rows.map((row, position) => ({ ...row, position }));
}
function makeForkMarkerTurnItem(input: {
readonly targetProjection: OrchestrationV2ThreadProjection;
readonly sourceThreadId: ThreadId;
readonly sourceRunId: NonNullable<OrchestrationV2TurnItem["runId"]>;
}): OrchestrationV2TurnItem {
const createdAt = input.targetProjection.thread.createdAt;
return {
id: TurnItemId.make(`turn-item:fork:${input.targetProjection.thread.id}`),
threadId: input.targetProjection.thread.id,
runId: null,
nodeId: null,
providerTurnId: null,
nativeItemRef: null,
parentItemId: null,
ordinal: 0,
status: "completed",
title: "Forked from conversation",
startedAt: null,
completedAt: createdAt,
updatedAt: createdAt,
type: "fork",
source: { type: "run", threadId: input.sourceThreadId, runId: input.sourceRunId },
targetThreadId: input.targetProjection.thread.id,
};
}
export function isTurnItemAtOrBeforeRun(input: {
readonly historyOrigin: OrchestrationV2ThreadProjection["thread"]["historyOrigin"];
readonly itemRunId: OrchestrationV2TurnItem["runId"];
readonly runOrdinalById: ReadonlyMap<NonNullable<OrchestrationV2TurnItem["runId"]>, number>;
readonly sourceRunOrdinal: number;
}): boolean {
if (input.itemRunId === null) {
return input.historyOrigin === "v1_import";
}
const ordinal = input.runOrdinalById.get(input.itemRunId);
return ordinal !== undefined && ordinal <= input.sourceRunOrdinal;
}
function visibleTurnItemsThroughRun(input: {
readonly sourceProjection: OrchestrationV2ThreadProjection;
readonly sourceRunId: NonNullable<OrchestrationV2TurnItem["runId"]>;
}): Array<Omit<OrchestrationV2ProjectedTurnItem, "position">> {
const sourceRun = input.sourceProjection.runs.find((run) => run.id === input.sourceRunId);
if (sourceRun === undefined) {
return [];
}
const runOrdinalById = new Map(input.sourceProjection.runs.map((run) => [run.id, run.ordinal]));
const inheritedPrefix = input.sourceProjection.visibleTurnItems
.filter(
(row) => row.item.threadId !== input.sourceProjection.thread.id || row.item.type === "fork",
)
.map((row) => ({
visibility: "inherited" as const,
sourceThreadId: row.sourceThreadId,
sourceItemId: row.sourceItemId,
item: row.item,
}));
const localPrefix = inheritedVisibleTurnItemsFromLocalItems(
input.sourceProjection.turnItems.filter((item) => {
if (
isOrchestrationV2SupersededInterrupt({
item,
attempts: input.sourceProjection.attempts,
items: input.sourceProjection.turnItems,
})
) {
return false;
}
return isTurnItemAtOrBeforeRun({
historyOrigin: input.sourceProjection.thread.historyOrigin,
itemRunId: item.runId,
runOrdinalById,
sourceRunOrdinal: sourceRun.ordinal,
});
}),
);
return [...inheritedPrefix, ...localPrefix];
}
function buildVisibleTurnItems(input: {
readonly projection: OrchestrationV2ThreadProjection;
readonly sourceProjection: OrchestrationV2ThreadProjection | null;
}): Array<OrchestrationV2ProjectedTurnItem> {
const forkedFrom = input.projection.thread.forkedFrom;
if (forkedFrom?.type !== "run" || input.sourceProjection === null) {
return localVisibleTurnItems(input.projection);
}
const inherited = visibleTurnItemsThroughRun({
sourceProjection: input.sourceProjection,
sourceRunId: forkedFrom.runId,
});
const markerItem = makeForkMarkerTurnItem({
targetProjection: input.projection,
sourceThreadId: forkedFrom.threadId,
sourceRunId: forkedFrom.runId,
});
const local = activeLocalTurnItems(input.projection).map((row) => ({
visibility: "local" as const,
sourceThreadId: row.sourceThreadId,
sourceItemId: row.sourceItemId,
item: row.item,
}));
return renumberVisibleTurnItems([
...inherited,
{
visibility: "synthetic",
sourceThreadId: forkedFrom.threadId,
sourceItemId: markerItem.id,
item: markerItem,
},
...local,
]);
}
export function threadShellFromProjection(
projection: OrchestrationV2ThreadProjection,
): OrchestrationV2ThreadShell {
const latestRun = projection.runs.at(-1) ?? null;
const activeRun =
projection.runs
.filter(isInterruptibleRunForShell)
.toSorted((left, right) => right.ordinal - left.ordinal)[0] ?? null;
const pendingRuntimeRequest =
projection.runtimeRequests
.filter((request) => request.status === "pending")
.toSorted(
(left, right) =>
DateTime.toEpochMillis(right.createdAt) - DateTime.toEpochMillis(left.createdAt),
)[0] ?? null;
const latestVisibleMessage =
projection.messages.toSorted(
(left, right) =>
DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt),
)[0] ?? null;
const latestUserMessage =
projection.messages
.filter((message) => message.role === "user")
.toSorted(
(left, right) =>
DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt),
)[0] ?? null;
const providerSession =
projection.providerSessions
.filter((session) => session.providerInstanceId === projection.thread.providerInstanceId)
.toSorted(
(left, right) =>
DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt),
)[0] ?? null;
return {
createdBy: projection.thread.createdBy,
creationSource: projection.thread.creationSource,
id: projection.thread.id,
projectId: projection.thread.projectId,
title: projection.thread.title,
providerInstanceId: projection.thread.providerInstanceId,
modelSelection: projection.thread.modelSelection,
runtimeMode: projection.thread.runtimeMode,
interactionMode: projection.thread.interactionMode,
branch: projection.thread.branch,
worktreePath: projection.thread.worktreePath,
lineage: projection.thread.lineage,
forkedFrom: projection.thread.forkedFrom,
activeProviderThreadId: projection.thread.activeProviderThreadId,
...(projection.thread.historyOrigin === undefined
? {}
: { historyOrigin: projection.thread.historyOrigin }),
latestRunId: latestRun?.id ?? null,
latestRunRequestedAt: latestRun?.requestedAt ?? null,
latestRunStartedAt: latestRun?.startedAt ?? null,
latestRunCompletedAt: latestRun?.completedAt ?? null,
activeRunId: activeRun?.id ?? null,
status: latestRun?.status ?? "idle",
lastError: providerSession?.lastError ?? null,
pendingRuntimeRequest:
pendingRuntimeRequest === null
? null
: {
id: pendingRuntimeRequest.id,
kind: pendingRuntimeRequest.kind,
createdAt: pendingRuntimeRequest.createdAt,
},
latestVisibleMessage:
latestVisibleMessage === null
? null
: {
id: latestVisibleMessage.id,
role: latestVisibleMessage.role,
text: latestVisibleMessage.text,
updatedAt: latestVisibleMessage.updatedAt,
},
latestUserMessageAt: latestUserMessage?.updatedAt ?? null,
hasActionableProposedPlan: projection.plans.some(
(plan) => plan.kind === "proposed_plan" && plan.status === "active",
),
itemCount: activeLocalTurnItems(projection).length,
visibleItemCount: projection.visibleTurnItems.length,
createdAt: projection.thread.createdAt,
updatedAt: projection.updatedAt,
archivedAt: projection.thread.archivedAt,
settledOverride: projection.thread.settledOverride,
settledAt: projection.thread.settledAt,
snoozedUntil: projection.thread.snoozedUntil ?? null,
snoozedAt: projection.thread.snoozedAt ?? null,
lastVisitedAt: projection.thread.lastVisitedAt,
titleRegeneration: projection.thread.titleRegeneration ?? null,
deletedAt: projection.thread.deletedAt,
};
}
function isInterruptibleRunForShell(run: OrchestrationV2ThreadProjection["runs"][number]): boolean {
return run.status === "preparing" || run.status === "starting" || run.status === "running";
}
type ShellThreadState = {
readonly thread: OrchestrationV2ThreadProjection["thread"];
readonly latestRunId: RunId | null;
readonly latestRunStatus: OrchestrationV2ShellThreadStatus;
readonly latestRunRequestedAt: DateTime.Utc | null;
readonly latestRunStartedAt: DateTime.Utc | null;
readonly latestRunCompletedAt: DateTime.Utc | null;
readonly activeRunId: RunId | null;
readonly lastError: string | null;
readonly pendingRuntimeRequest: OrchestrationV2ThreadProjection["runtimeRequests"][number] | null;
readonly latestVisibleMessage: OrchestrationV2ConversationMessage | null;
readonly latestUserMessageAt: DateTime.Utc | null;
readonly hasActionableProposedPlan: boolean;
readonly itemCount: number;
readonly runlessItemCount: number;
readonly updatedAt: OrchestrationV2ThreadProjection["updatedAt"];
readonly runOrdinalById: ReadonlyMap<RunId, number>;
readonly itemCountByRunId: ReadonlyMap<RunId, number>;
};
function shellStatusFromStoredRunStatus(status: string | null): OrchestrationV2ShellThreadStatus {
switch (status) {
case null:
return "idle";
case "preparing":
case "queued":
case "starting":
case "running":
case "waiting":
case "completed":
case "interrupted":
case "failed":
case "cancelled":
case "rolled_back":
return status;
default:
return "failed";
}
}
function itemCountThroughRun(input: {
readonly state: ShellThreadState;
readonly runId: RunId;
}): number {
const runOrdinal = input.state.runOrdinalById.get(input.runId);
if (runOrdinal === undefined) {
return 0;
}
let count = input.state.thread.historyOrigin === "v1_import" ? input.state.runlessItemCount : 0;
for (const [runId, itemCount] of input.state.itemCountByRunId) {
const itemRunOrdinal = input.state.runOrdinalById.get(runId);
if (itemRunOrdinal !== undefined && itemRunOrdinal <= runOrdinal) {
count += itemCount;
}
}
return count;
}
function visibleItemCountForShell(input: {
readonly threadId: ThreadId;
readonly statesByThreadId: ReadonlyMap<ThreadId, ShellThreadState>;
readonly seenThreadIds?: ReadonlySet<ThreadId>;
}): number {
const state = input.statesByThreadId.get(input.threadId);
if (state === undefined) {
return 0;
}
const forkedFrom = state.thread.forkedFrom;
if (forkedFrom?.type !== "run") {
return state.itemCount;
}
const seenThreadIds = input.seenThreadIds ?? new Set<ThreadId>();
if (seenThreadIds.has(state.thread.id)) {
return state.itemCount;
}
const sourceState = input.statesByThreadId.get(forkedFrom.threadId);
if (sourceState === undefined) {
return state.itemCount;
}
const sourceForkedFrom = sourceState.thread.forkedFrom;
const inheritedPrefixCount =
sourceForkedFrom?.type === "run"
? visibleItemCountForShell({
threadId: sourceState.thread.id,
statesByThreadId: input.statesByThreadId,
seenThreadIds: new Set([...seenThreadIds, state.thread.id]),
}) - sourceState.itemCount
: 0;
return (
inheritedPrefixCount +
itemCountThroughRun({ state: sourceState, runId: forkedFrom.runId }) +
1 +
state.itemCount
);
}
function shellFromState(input: {
readonly state: ShellThreadState;
readonly visibleItemCount: number;
}): OrchestrationV2ThreadShell {
return {
createdBy: input.state.thread.createdBy,
creationSource: input.state.thread.creationSource,
id: input.state.thread.id,
projectId: input.state.thread.projectId,
title: input.state.thread.title,
providerInstanceId: input.state.thread.providerInstanceId,
modelSelection: input.state.thread.modelSelection,
runtimeMode: input.state.thread.runtimeMode,
interactionMode: input.state.thread.interactionMode,
branch: input.state.thread.branch,
worktreePath: input.state.thread.worktreePath,
lineage: input.state.thread.lineage,
forkedFrom: input.state.thread.forkedFrom,
activeProviderThreadId: input.state.thread.activeProviderThreadId,
...(input.state.thread.historyOrigin === undefined
? {}
: { historyOrigin: input.state.thread.historyOrigin }),
latestRunId: input.state.latestRunId,
latestRunRequestedAt: input.state.latestRunRequestedAt,
latestRunStartedAt: input.state.latestRunStartedAt,
latestRunCompletedAt: input.state.latestRunCompletedAt,
activeRunId: input.state.activeRunId,
status: input.state.latestRunStatus,
lastError: input.state.lastError,
pendingRuntimeRequest:
input.state.pendingRuntimeRequest === null
? null
: {
id: input.state.pendingRuntimeRequest.id,
kind: input.state.pendingRuntimeRequest.kind,
createdAt: input.state.pendingRuntimeRequest.createdAt,
},
latestVisibleMessage:
input.state.latestVisibleMessage === null
? null
: {
id: input.state.latestVisibleMessage.id,
role: input.state.latestVisibleMessage.role,
text: input.state.latestVisibleMessage.text,
updatedAt: input.state.latestVisibleMessage.updatedAt,
},
latestUserMessageAt: input.state.latestUserMessageAt,
hasActionableProposedPlan: input.state.hasActionableProposedPlan,
itemCount: input.state.itemCount,
visibleItemCount: input.visibleItemCount,
createdAt: input.state.thread.createdAt,
updatedAt: input.state.updatedAt,
archivedAt: input.state.thread.archivedAt,
settledOverride: input.state.thread.settledOverride,
settledAt: input.state.thread.settledAt,
snoozedUntil: input.state.thread.snoozedUntil ?? null,
snoozedAt: input.state.thread.snoozedAt ?? null,
lastVisitedAt: input.state.thread.lastVisitedAt,
titleRegeneration: input.state.thread.titleRegeneration ?? null,
deletedAt: input.state.thread.deletedAt,
};
}
export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> = Layer.effect(
ProjectionStoreV2,
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const apply: ProjectionStoreV2Shape["apply"] = (event) =>
Effect.gen(function* () {
switch (event.type) {
case "thread.created":
case "thread.archived":
case "thread.unarchived":
case "thread.deleted":
case "thread.settled":
case "thread.unsettled":
case "thread.snoozed":
case "thread.unsnoozed":
case "thread.visited":
case "thread.marked-unread":
case "thread.metadata-updated":
case "thread.runtime-mode-updated":
case "thread.interaction-mode-updated":
case "thread.model-selection-updated":
case "thread.provider-switched": {
const payloadJson = yield* encodeThreadPayload(event.payload);
const payload = parseEncodedPayload(payloadJson);
yield* sql`
INSERT INTO orchestration_v2_projection_threads (
thread_id,
project_id,
title,
default_provider,
provider_instance_id,
runtime_mode,
interaction_mode,
active_provider_thread_id,
created_at,
updated_at,
archived_at,
deleted_at,
payload_json
)
VALUES (
${event.payload.id},
${event.payload.projectId},
${event.payload.title},
${event.payload.providerInstanceId},
${event.payload.providerInstanceId},
${event.payload.runtimeMode},
${event.payload.interactionMode},
${event.payload.activeProviderThreadId},
${stringField(payload, "createdAt")},
${stringField(payload, "updatedAt")},
${nullableStringField(payload, "archivedAt")},
${nullableStringField(payload, "deletedAt")},
${payloadJson}
)
ON CONFLICT(thread_id)
DO UPDATE SET
project_id = excluded.project_id,
title = excluded.title,
default_provider = excluded.default_provider,
provider_instance_id = excluded.provider_instance_id,
runtime_mode = excluded.runtime_mode,
interaction_mode = excluded.interaction_mode,
active_provider_thread_id = excluded.active_provider_thread_id,
created_at = excluded.created_at,
updated_at = excluded.updated_at,
archived_at = excluded.archived_at,
deleted_at = excluded.deleted_at,
payload_json = excluded.payload_json
`;
break;
}
case "run.created":
case "run.updated": {
const payloadJson = yield* encodeRunPayload(event.payload);
const payload = parseEncodedPayload(payloadJson);
yield* sql`
INSERT INTO orchestration_v2_projection_runs (
run_id,
thread_id,
ordinal,
provider,
provider_instance_id,
provider_thread_id,
status,
requested_at,
completed_at,
payload_json
)
VALUES (
${event.payload.id},
${event.payload.threadId},
${event.payload.ordinal},
${event.payload.providerInstanceId},
${event.payload.providerInstanceId},
${event.payload.providerThreadId},
${event.payload.status},
${stringField(payload, "requestedAt")},
${nullableStringField(payload, "completedAt")},
${payloadJson}
)
ON CONFLICT(run_id)
DO UPDATE SET
thread_id = excluded.thread_id,
ordinal = excluded.ordinal,
provider = excluded.provider,
provider_instance_id = excluded.provider_instance_id,
provider_thread_id = excluded.provider_thread_id,
status = excluded.status,
requested_at = excluded.requested_at,
completed_at = excluded.completed_at,
payload_json = excluded.payload_json
`;
break;
}
case "run-attempt.created":
case "run-attempt.updated": {
const payloadJson = yield* encodeRunAttemptPayload(event.payload);
yield* sql`
INSERT INTO orchestration_v2_projection_run_attempts (
attempt_id,
thread_id,
run_id,
attempt_ordinal,
root_node_id,
provider,
provider_instance_id,
provider_thread_id,
provider_turn_id,
status,
payload_json
)
VALUES (
${event.payload.id},
${event.threadId},
${event.payload.runId},
${event.payload.attemptOrdinal},
${event.payload.rootNodeId},
${event.payload.providerInstanceId},
${event.payload.providerInstanceId},
${event.payload.providerThreadId},
${event.payload.providerTurnId},
${event.payload.status},
${payloadJson}
)
ON CONFLICT(attempt_id)
DO UPDATE SET
thread_id = excluded.thread_id,
run_id = excluded.run_id,
attempt_ordinal = excluded.attempt_ordinal,
root_node_id = excluded.root_node_id,
provider = excluded.provider,
provider_instance_id = excluded.provider_instance_id,
provider_thread_id = excluded.provider_thread_id,
provider_turn_id = excluded.provider_turn_id,
status = excluded.status,
payload_json = excluded.payload_json
`;
break;
}
case "node.updated": {
const payloadJson = yield* encodeNodePayload(event.payload);
const payload = parseEncodedPayload(payloadJson);
yield* sql`
INSERT INTO orchestration_v2_projection_nodes (
node_id,
thread_id,
run_id,
parent_node_id,
root_node_id,
kind,
status,
provider_thread_id,
provider_turn_id,
runtime_request_id,
checkpoint_scope_id,
started_at,
completed_at,
payload_json
)
VALUES (
${event.payload.id},
${event.payload.threadId},
${event.payload.runId},
${event.payload.parentNodeId},
${event.payload.rootNodeId},
${event.payload.kind},
${event.payload.status},
${event.payload.providerThreadId},
${event.payload.providerTurnId},
${event.payload.runtimeRequestId},
${event.payload.checkpointScopeId},
${nullableStringField(payload, "startedAt")},
${nullableStringField(payload, "completedAt")},
${payloadJson}
)
ON CONFLICT(node_id)
DO UPDATE SET
thread_id = excluded.thread_id,
run_id = excluded.run_id,
parent_node_id = excluded.parent_node_id,
root_node_id = excluded.root_node_id,
kind = excluded.kind,
status = excluded.status,
provider_thread_id = excluded.provider_thread_id,
provider_turn_id = excluded.provider_turn_id,
runtime_request_id = excluded.runtime_request_id,
checkpoint_scope_id = excluded.checkpoint_scope_id,
started_at = excluded.started_at,
completed_at = excluded.completed_at,
payload_json = excluded.payload_json
`;
break;
}
case "subagent.updated": {
const payloadJson = yield* encodeSubagentPayload(event.payload);
const payload = parseEncodedPayload(payloadJson);
yield* sql`
INSERT INTO orchestration_v2_projection_subagents (
subagent_id,
thread_id,
run_id,
parent_node_id,
provider,
driver,
provider_instance_id,
provider_thread_id,
child_thread_id,
origin,
status,
started_at,
completed_at,
updated_at,
payload_json
)
VALUES (
${event.payload.id},
${event.payload.threadId},
${event.payload.runId},
${event.payload.parentNodeId},
${event.payload.providerInstanceId},
${event.payload.driver},
${event.payload.providerInstanceId},
${event.payload.providerThreadId},
${event.payload.childThreadId},
${event.payload.origin},
${event.payload.status},
${nullableStringField(payload, "startedAt")},
${nullableStringField(payload, "completedAt")},
${stringField(payload, "updatedAt")},
${payloadJson}
)
ON CONFLICT(subagent_id)
DO UPDATE SET
thread_id = excluded.thread_id,
run_id = excluded.run_id,
parent_node_id = excluded.parent_node_id,
provider = excluded.provider,
driver = excluded.driver,
provider_instance_id = excluded.provider_instance_id,
provider_thread_id = excluded.provider_thread_id,
child_thread_id = excluded.child_thread_id,
origin = excluded.origin,
status = excluded.status,
started_at = excluded.started_at,
completed_at = excluded.completed_at,
updated_at = excluded.updated_at,
payload_json = excluded.payload_json
`;
break;
}
case "provider-session.attached":
case "provider-session.updated": {
const payloadJson = yield* encodeProviderSessionPayload(event.payload);
const payload = parseEncodedPayload(payloadJson);
yield* sql`
INSERT INTO orchestration_v2_projection_provider_sessions (
provider_session_id,
thread_id,
provider,
driver,
provider_instance_id,
status,
model,
updated_at,
payload_json
)
VALUES (
${event.payload.id},
${event.threadId},
${event.payload.providerInstanceId},
${event.payload.driver},
${event.payload.providerInstanceId},
${event.payload.status},
${event.payload.model},
${stringField(payload, "updatedAt")},
${payloadJson}
)
ON CONFLICT(provider_session_id)
DO UPDATE SET
thread_id = excluded.thread_id,
provider = excluded.provider,
driver = excluded.driver,
provider_instance_id = excluded.provider_instance_id,
status = excluded.status,
model = excluded.model,
updated_at = excluded.updated_at,
payload_json = excluded.payload_json
`;
if (event.type === "provider-session.attached") {
yield* sql`
INSERT OR IGNORE INTO orchestration_v2_projection_provider_session_bindings (
provider_session_id,
thread_id
)
VALUES (${event.payload.id}, ${event.threadId})
`;
}
break;
}
case "provider-session.detached": {
yield* sql`
DELETE FROM orchestration_v2_projection_provider_session_bindings
WHERE provider_session_id = ${event.payload.providerSessionId}
AND thread_id = ${event.threadId}
`;
break;
}
case "provider-thread.updated": {
const payloadJson = yield* encodeProviderThreadPayload(event.payload);
const payload = parseEncodedPayload(payloadJson);
yield* sql`
INSERT INTO orchestration_v2_projection_provider_threads (
provider_thread_id,
thread_id,
owner_node_id,
provider,
driver,
provider_instance_id,
provider_session_id,
status,
first_run_ordinal,
last_run_ordinal,
updated_at,
payload_json
)
VALUES (
${event.payload.id},
${event.payload.appThreadId},
${event.payload.ownerNodeId},
${event.payload.providerInstanceId},
${event.payload.driver},
${event.payload.providerInstanceId},
${event.payload.providerSessionId},
${event.payload.status},
${event.payload.firstRunOrdinal},
${event.payload.lastRunOrdinal},
${stringField(payload, "updatedAt")},
${payloadJson}
)
ON CONFLICT(provider_thread_id)
DO UPDATE SET
thread_id = excluded.thread_id,
owner_node_id = excluded.owner_node_id,
provider = excluded.provider,
driver = excluded.driver,
provider_instance_id = excluded.provider_instance_id,
provider_session_id = excluded.provider_session_id,
status = excluded.status,
first_run_ordinal = excluded.first_run_ordinal,
last_run_ordinal = excluded.last_run_ordinal,
updated_at = excluded.updated_at,
payload_json = excluded.payload_json
`;
if (event.payload.appThreadId !== null) {
const threadRows = yield* sql<PayloadRow>`
SELECT payload_json
FROM orchestration_v2_projection_threads
WHERE thread_id = ${event.payload.appThreadId}
LIMIT 1
`;
const threadRow = threadRows[0];
if (threadRow !== undefined) {
const thread = yield* decodeThreadPayload(threadRow.payload_json);
const updatedThread = {
...thread,
activeProviderThreadId: event.payload.id,
updatedAt: event.payload.updatedAt,
};
const updatedThreadPayloadJson = yield* encodeThreadPayload(updatedThread);
yield* sql`
UPDATE orchestration_v2_projection_threads
SET
active_provider_thread_id = ${event.payload.id},
updated_at = ${stringField(parseEncodedPayload(updatedThreadPayloadJson), "updatedAt")},
payload_json = ${updatedThreadPayloadJson}
WHERE thread_id = ${event.payload.appThreadId}
`;
}
}
break;
}
case "provider-turn.updated": {
const payloadJson = yield* encodeProviderTurnPayload(event.payload);
const payload = parseEncodedPayload(payloadJson);
yield* sql`
INSERT INTO orchestration_v2_projection_provider_turns (
provider_turn_id,
thread_id,
provider_thread_id,
node_id,
run_attempt_id,
ordinal,
status,
started_at,
completed_at,
payload_json
)
VALUES (
${event.payload.id},
${event.threadId},
${event.payload.providerThreadId},
${event.payload.nodeId},
${event.payload.runAttemptId},
${event.payload.ordinal},
${event.payload.status},
${nullableStringField(payload, "startedAt")},
${nullableStringField(payload, "completedAt")},
${payloadJson}
)
ON CONFLICT(provider_turn_id)
DO UPDATE SET
thread_id = excluded.thread_id,
provider_thread_id = excluded.provider_thread_id,
node_id = excluded.node_id,
run_attempt_id = excluded.run_attempt_id,
ordinal = excluded.ordinal,
status = excluded.status,
started_at = excluded.started_at,
completed_at = excluded.completed_at,
payload_json = excluded.payload_json
`;
break;
}
case "runtime-request.updated": {
const payloadJson = yield* encodeRuntimeRequestPayload(event.payload);
const payload = parseEncodedPayload(payloadJson);
yield* sql`
INSERT INTO orchestration_v2_projection_runtime_requests (
runtime_request_id,
thread_id,
node_id,
provider_turn_id,
kind,
status,
created_at,
resolved_at,
payload_json
)
VALUES (
${event.payload.id},
${event.threadId},
${event.payload.nodeId},
${event.payload.providerTurnId},
${event.payload.kind},
${event.payload.status},
${stringField(payload, "createdAt")},
${nullableStringField(payload, "resolvedAt")},
${payloadJson}
)
ON CONFLICT(runtime_request_id)
DO UPDATE SET
thread_id = excluded.thread_id,
node_id = excluded.node_id,
provider_turn_id = excluded.provider_turn_id,
kind = excluded.kind,
status = excluded.status,
created_at = excluded.created_at,
resolved_at = excluded.resolved_at,
payload_json = excluded.payload_json
`;
break;
}
case "message.updated": {
const payloadJson = yield* encodeMessagePayload(event.payload);
const payload = parseEncodedPayload(payloadJson);
yield* sql`
INSERT INTO orchestration_v2_projection_messages (
message_id,
thread_id,
run_id,
node_id,
role,
streaming,
created_at,
updated_at,
payload_json
)
VALUES (
${event.payload.id},
${event.payload.threadId},
${event.payload.runId},
${event.payload.nodeId},
${event.payload.role},
${booleanInt(event.payload.streaming)},
${stringField(payload, "createdAt")},
${stringField(payload, "updatedAt")},
${payloadJson}
)
ON CONFLICT(message_id)
DO UPDATE SET
thread_id = excluded.thread_id,
run_id = excluded.run_id,
node_id = excluded.node_id,
role = excluded.role,
streaming = excluded.streaming,
created_at = excluded.created_at,
updated_at = excluded.updated_at,
payload_json = excluded.payload_json
`;
break;
}
case "plan.updated": {
const payloadJson = yield* encodePlanPayload(event.payload);
yield* sql`
INSERT INTO orchestration_v2_projection_plans (
plan_id,
thread_id,
run_id,
node_id,
kind,
status,
payload_json
)
VALUES (
${event.payload.id},
${event.payload.threadId},
${event.payload.runId},
${event.payload.nodeId},
${event.payload.kind},
${event.payload.status},
${payloadJson}
)
ON CONFLICT(plan_id)
DO UPDATE SET
thread_id = excluded.thread_id,
run_id = excluded.run_id,
node_id = excluded.node_id,
kind = excluded.kind,
status = excluded.status,
payload_json = excluded.payload_json
`;
break;
}
case "turn-item.updated": {
const payloadJson = yield* encodeTurnItemPayload(event.payload);
const payload = parseEncodedPayload(payloadJson);
yield* sql`
INSERT INTO orchestration_v2_projection_turn_items (
turn_item_id,
thread_id,
run_id,
node_id,
provider_thread_id,
provider_turn_id,
parent_item_id,
ordinal,
type,
status,
updated_at,
payload_json
)
VALUES (
${event.payload.id},
${event.payload.threadId},
${event.payload.runId},
${event.payload.nodeId},
${event.payload.providerThreadId},
${event.payload.providerTurnId},
${event.payload.parentItemId},
${event.payload.ordinal},
${event.payload.type},
${event.payload.status},
${stringField(payload, "updatedAt")},
${payloadJson}
)
ON CONFLICT(turn_item_id)
DO UPDATE SET
thread_id = excluded.thread_id,
run_id = excluded.run_id,
node_id = excluded.node_id,
provider_thread_id = excluded.provider_thread_id,
provider_turn_id = excluded.provider_turn_id,
parent_item_id = excluded.parent_item_id,
ordinal = excluded.ordinal,
type = excluded.type,
status = excluded.status,
updated_at = excluded.updated_at,
payload_json = excluded.payload_json
`;
break;
}
case "checkpoint-scope.created": {
const payloadJson = yield* encodeCheckpointScopePayload(event.payload);
const payload = parseEncodedPayload(payloadJson);
yield* sql`
INSERT INTO orchestration_v2_projection_checkpoint_scopes (
scope_id,
thread_id,
run_id,
node_id,
parent_scope_id,
provider_thread_id,
kind,
ordinal_within_parent,
advances_app_run_count,
created_at,
payload_json
)
VALUES (
${event.payload.id},
${event.payload.threadId},
${event.payload.runId},
${event.payload.nodeId},
${event.payload.parentScopeId},
${event.payload.providerThreadId},
${event.payload.kind},
${event.payload.ordinalWithinParent},
${booleanInt(event.payload.advancesAppRunCount)},
${stringField(payload, "createdAt")},
${payloadJson}
)
ON CONFLICT(scope_id)
DO UPDATE SET
thread_id = excluded.thread_id,
run_id = excluded.run_id,
node_id = excluded.node_id,
parent_scope_id = excluded.parent_scope_id,
provider_thread_id = excluded.provider_thread_id,
kind = excluded.kind,
ordinal_within_parent = excluded.ordinal_within_parent,
advances_app_run_count = excluded.advances_app_run_count,
created_at = excluded.created_at,
payload_json = excluded.payload_json
`;
break;
}
case "checkpoint.captured": {
const payloadJson = yield* encodeCheckpointPayload(event.payload);
const payload = parseEncodedPayload(payloadJson);
yield* sql`
INSERT INTO orchestration_v2_projection_checkpoints (
checkpoint_id,
thread_id,
scope_id,
run_id,
node_id,
parent_checkpoint_id,
ordinal_within_scope,
app_run_ordinal,
status,
captured_at,
payload_json
)
VALUES (
${event.payload.id},
${event.payload.threadId},
${event.payload.scopeId},
${event.payload.runId},
${event.payload.nodeId},
${event.payload.parentCheckpointId},
${event.payload.ordinalWithinScope},
${event.payload.appRunOrdinal},
${event.payload.status},
${stringField(payload, "capturedAt")},
${payloadJson}
)
ON CONFLICT(checkpoint_id)
DO UPDATE SET
thread_id = excluded.thread_id,
scope_id = excluded.scope_id,
run_id = excluded.run_id,
node_id = excluded.node_id,
parent_checkpoint_id = excluded.parent_checkpoint_id,
ordinal_within_scope = excluded.ordinal_within_scope,
app_run_ordinal = excluded.app_run_ordinal,
status = excluded.status,
captured_at = excluded.captured_at,
payload_json = excluded.payload_json
`;
break;
}
case "checkpoint.rollback-requested":
break;
case "context-handoff.updated": {
const payloadJson = yield* encodeContextHandoffPayload(event.payload);
const payload = parseEncodedPayload(payloadJson);
yield* sql`
INSERT INTO orchestration_v2_projection_context_handoffs (
context_handoff_id,
thread_id,
target_run_id,
to_provider_thread_id,
strategy,
status,
updated_at,
payload_json
)
VALUES (
${event.payload.id},
${event.payload.threadId},
${event.payload.targetRunId},
${event.payload.toProviderThreadId},
${event.payload.strategy},
${event.payload.status},
${stringField(payload, "updatedAt")},
${payloadJson}
)
ON CONFLICT(context_handoff_id)
DO UPDATE SET
thread_id = excluded.thread_id,
target_run_id = excluded.target_run_id,
to_provider_thread_id = excluded.to_provider_thread_id,
strategy = excluded.strategy,
status = excluded.status,
updated_at = excluded.updated_at,
payload_json = excluded.payload_json
`;
break;
}
case "context-transfer.created":
case "context-transfer.updated": {
const payloadJson = yield* encodeContextTransferPayload(event.payload);
const payload = parseEncodedPayload(payloadJson);
yield* sql`
INSERT INTO orchestration_v2_projection_context_transfers (
context_transfer_id,
source_thread_id,
target_thread_id,
target_run_id,
type,
status,
source_provider,
target_provider,
source_provider_instance_id,
target_provider_instance_id,
updated_at,
payload_json
)
VALUES (
${event.payload.id},
${event.payload.sourceThreadId},
${event.payload.targetThreadId},
${event.payload.targetRunId},
${event.payload.type},
${event.payload.status},
${event.payload.sourceProviderInstanceId},
${event.payload.targetProviderInstanceId},
${event.payload.sourceProviderInstanceId},
${event.payload.targetProviderInstanceId},
${stringField(payload, "updatedAt")},
${payloadJson}
)
ON CONFLICT(context_transfer_id)
DO UPDATE SET
source_thread_id = excluded.source_thread_id,
target_thread_id = excluded.target_thread_id,
target_run_id = excluded.target_run_id,
type = excluded.type,
status = excluded.status,
source_provider = excluded.source_provider,
target_provider = excluded.target_provider,
source_provider_instance_id = excluded.source_provider_instance_id,
target_provider_instance_id = excluded.target_provider_instance_id,
updated_at = excluded.updated_at,
payload_json = excluded.payload_json
`;
break;
}
}
if (
event.type !== "thread.created" &&
event.type !== "thread.archived" &&
event.type !== "thread.unarchived" &&
event.type !== "thread.deleted" &&
event.type !== "thread.metadata-updated" &&
event.type !== "thread.runtime-mode-updated" &&
event.type !== "thread.interaction-mode-updated" &&
event.type !== "thread.model-selection-updated" &&
event.type !== "thread.provider-switched"
) {
const rows = yield* sql<PayloadRow>`
SELECT payload_json
FROM orchestration_v2_projection_threads
WHERE thread_id = ${event.threadId}
LIMIT 1
`;
const row = rows[0];
if (row !== undefined) {
const thread = yield* decodeThreadPayload(row.payload_json);
const updatedThread = { ...thread, updatedAt: event.occurredAt };
const payloadJson = yield* encodeThreadPayload(updatedThread);
yield* sql`
UPDATE orchestration_v2_projection_threads
SET
updated_at = ${stringField(parseEncodedPayload(payloadJson), "updatedAt")},
payload_json = ${payloadJson}
WHERE thread_id = ${event.threadId}
`;
}
}
}).pipe(
Effect.mapError(
(cause) =>
new ProjectionStoreApplyEventError({
eventType: event.type,
cause,
}),
),
);
const readCanonicalProjection: ProjectionStoreV2Shape["getThreadProjection"] = (threadId) =>
Effect.gen(function* () {
const threadRows = yield* sql<PayloadRow>`
SELECT payload_json
FROM orchestration_v2_projection_threads
WHERE thread_id = ${threadId}
LIMIT 1
`;
const threadRow = threadRows[0];
if (!threadRow) {
return yield* new ProjectionStoreThreadNotFoundError({ threadId });
}
const [
thread,
runRows,
attemptRows,
nodeRows,
subagentRows,
providerSessionRows,
providerThreadRows,
providerTurnRows,
runtimeRequestRows,
messageRows,
planRows,
turnItemRows,
checkpointScopeRows,
checkpointRows,
contextHandoffRows,
contextTransferRows,
] = yield* Effect.all([
decodeThreadPayload(threadRow.payload_json),
sql<PayloadRow>`
SELECT payload_json
FROM orchestration_v2_projection_runs
WHERE thread_id = ${threadId}
ORDER BY ordinal ASC
`,
sql<PayloadRow>`
SELECT payload_json
FROM orchestration_v2_projection_run_attempts
WHERE thread_id = ${threadId}
ORDER BY run_id ASC, attempt_ordinal ASC
`,
sql<PayloadRow>`
SELECT payload_json
FROM orchestration_v2_projection_nodes
WHERE thread_id = ${threadId}
ORDER BY COALESCE(started_at, ''), node_id ASC
`,
sql<PayloadRow>`
SELECT payload_json
FROM orchestration_v2_projection_subagents
WHERE thread_id = ${threadId}
ORDER BY COALESCE(started_at, ''), subagent_id ASC
`,
sql<PayloadRow>`
SELECT sessions.payload_json
FROM orchestration_v2_projection_provider_sessions AS sessions
INNER JOIN orchestration_v2_projection_provider_session_bindings AS bindings
ON bindings.provider_session_id = sessions.provider_session_id
WHERE bindings.thread_id = ${threadId}
ORDER BY sessions.updated_at ASC, sessions.provider_session_id ASC
`,
sql<PayloadRow>`
SELECT payload_json
FROM orchestration_v2_projection_provider_threads
WHERE thread_id = ${threadId}
OR owner_node_id IN (
SELECT node_id
FROM orchestration_v2_projection_nodes
WHERE thread_id = ${threadId}
)
OR provider_thread_id IN (
SELECT provider_thread_id
FROM orchestration_v2_projection_subagents
WHERE thread_id = ${threadId}
AND provider_thread_id IS NOT NULL
)
ORDER BY COALESCE(first_run_ordinal, 0), provider_thread_id ASC
`,
sql<PayloadRow>`
SELECT payload_json
FROM orchestration_v2_projection_provider_turns
WHERE thread_id = ${threadId}
ORDER BY provider_thread_id ASC, ordinal ASC
`,
sql<PayloadRow>`
SELECT payload_json
FROM orchestration_v2_projection_runtime_requests
WHERE thread_id = ${threadId}
ORDER BY created_at ASC, runtime_request_id ASC
`,
sql<PayloadRow>`
SELECT payload_json
FROM orchestration_v2_projection_messages
WHERE thread_id = ${threadId}
ORDER BY created_at ASC, message_id ASC
`,
sql<PayloadRow>`
SELECT payload_json
FROM orchestration_v2_projection_plans
WHERE thread_id = ${threadId}
ORDER BY plan_id ASC
`,
sql<PayloadRow>`
SELECT payload_json
FROM orchestration_v2_projection_turn_items
WHERE thread_id = ${threadId}
ORDER BY ordinal ASC, turn_item_id ASC
`,
sql<PayloadRow>`
SELECT payload_json
FROM orchestration_v2_projection_checkpoint_scopes
WHERE thread_id = ${threadId}
ORDER BY ordinal_within_parent ASC, scope_id ASC
`,
sql<PayloadRow>`
SELECT payload_json
FROM orchestration_v2_projection_checkpoints
WHERE thread_id = ${threadId}
ORDER BY scope_id ASC, ordinal_within_scope ASC
`,
sql<PayloadRow>`
SELECT payload_json
FROM orchestration_v2_projection_context_handoffs
WHERE thread_id = ${threadId}
ORDER BY rowid ASC
`,
sql<PayloadRow>`
SELECT payload_json
FROM orchestration_v2_projection_context_transfers
WHERE source_thread_id = ${threadId} OR target_thread_id = ${threadId}
ORDER BY rowid ASC
`,
]);
const [
runs,
attempts,
nodes,
subagents,
providerSessions,
providerThreads,
providerTurns,
runtimeRequests,
messages,
plans,
turnItems,
checkpointScopes,
checkpoints,
contextHandoffs,
contextTransfers,
] = yield* Effect.all([
decodeRows(decodeRunPayload, threadId)(runRows),
decodeRows(decodeRunAttemptPayload, threadId)(attemptRows),
decodeRows(decodeNodePayload, threadId)(nodeRows),
decodeRows(decodeSubagentPayload, threadId)(subagentRows),
decodeRows(decodeProviderSessionPayload, threadId)(providerSessionRows),
decodeRows(decodeProviderThreadPayload, threadId)(providerThreadRows),
decodeRows(decodeProviderTurnPayload, threadId)(providerTurnRows),
decodeRows(decodeRuntimeRequestPayload, threadId)(runtimeRequestRows),
decodeRows(decodeMessagePayload, threadId)(messageRows),
decodeRows(decodePlanPayload, threadId)(planRows),
decodeRows(decodeTurnItemPayload, threadId)(turnItemRows),
decodeRows(decodeCheckpointScopePayload, threadId)(checkpointScopeRows),
decodeRows(decodeCheckpointPayload, threadId)(checkpointRows),
decodeRows(decodeContextHandoffPayload, threadId)(contextHandoffRows),
decodeRows(decodeContextTransferPayload, threadId)(contextTransferRows),
]);
const orderedMessages = sortMessagesByTurnItemOrder(messages, turnItems);
const projection = {
thread,
runs,
attempts,
nodes,
subagents,
providerSessions,
providerThreads,
providerTurns,
runtimeRequests,
messages: orderedMessages,
plans,
turnItems,
checkpointScopes,
checkpoints,
contextHandoffs,
contextTransfers,
visibleTurnItems: [],
updatedAt: thread.updatedAt,
} satisfies OrchestrationV2ThreadProjection;
return withLocalVisibleTurnItems(projection);
}).pipe(
Effect.mapError((cause) =>
Schema.is(ProjectionStoreThreadNotFoundError)(cause)
? cause
: new ProjectionStoreReadError({
threadId,
cause,
}),
),
);
const readProjection = (
threadId: ThreadId,
seenThreadIds: ReadonlySet<ThreadId>,
): Effect.Effect<OrchestrationV2ThreadProjection, ProjectionStoreV2Error> =>
Effect.gen(function* () {
const projection = yield* readCanonicalProjection(threadId);
const forkedFrom = projection.thread.forkedFrom;
if (forkedFrom?.type !== "run" || seenThreadIds.has(forkedFrom.threadId)) {
return withLocalVisibleTurnItems(projection);
}
const sourceProjection = yield* readProjection(
forkedFrom.threadId,
new Set([...seenThreadIds, threadId]),
);
return {
...projection,
visibleTurnItems: buildVisibleTurnItems({
projection,
sourceProjection,
}),
};
});
const getThreadProjection: ProjectionStoreV2Shape["getThreadProjection"] = (threadId) =>
readProjection(threadId, new Set());
const getThreadSnapshot: ProjectionStoreV2Shape["getThreadSnapshot"] = (threadId) =>
sql
.withTransaction(
Effect.gen(function* () {
const projection = yield* getThreadProjection(threadId);
const rows = yield* sql<{ readonly snapshot_sequence: number | null }>`
SELECT MAX(sequence) AS snapshot_sequence
FROM orchestration_events
WHERE application_event_version = 2
AND aggregate_kind = 'thread'
AND stream_id = ${threadId}
`;
return {
schemaVersion: ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION,
snapshotSequence: rows[0]?.snapshot_sequence ?? 0,
projection,
};
}),
)
.pipe(
Effect.mapError((cause) =>
Schema.is(ProjectionStoreThreadNotFoundError)(cause) ||
Schema.is(ProjectionStoreReadError)(cause)
? cause
: new ProjectionStoreReadError({ threadId, cause }),
),
);
const selectShellThreadRows = (threadId?: ThreadId) =>
sql<ShellThreadRow>`
SELECT
t.thread_id,
t.payload_json,
CASE
WHEN json_extract(t.payload_json, '$.forkedFrom.type') = 'run'
THEN json_extract(t.payload_json, '$.forkedFrom.threadId')
ELSE NULL
END AS forked_from_run_source_thread_id,
(
SELECT r.run_id
FROM orchestration_v2_projection_runs r
WHERE r.thread_id = t.thread_id
ORDER BY r.ordinal DESC, r.run_id DESC
LIMIT 1
) AS latest_run_id,
(
SELECT r.status
FROM orchestration_v2_projection_runs r
WHERE r.thread_id = t.thread_id
ORDER BY r.ordinal DESC, r.run_id DESC
LIMIT 1
) AS latest_run_status,
(
SELECT r.requested_at
FROM orchestration_v2_projection_runs r
WHERE r.thread_id = t.thread_id
ORDER BY r.ordinal DESC, r.run_id DESC
LIMIT 1
) AS latest_run_requested_at,
(
SELECT json_extract(r.payload_json, '$.startedAt')
FROM orchestration_v2_projection_runs r
WHERE r.thread_id = t.thread_id
ORDER BY r.ordinal DESC, r.run_id DESC
LIMIT 1
) AS latest_run_started_at,
(
SELECT r.completed_at
FROM orchestration_v2_projection_runs r
WHERE r.thread_id = t.thread_id
ORDER BY r.ordinal DESC, r.run_id DESC
LIMIT 1
) AS latest_run_completed_at,
(
SELECT r.run_id
FROM orchestration_v2_projection_runs r
WHERE r.thread_id = t.thread_id
AND r.status IN ('preparing', 'starting', 'running')
ORDER BY r.ordinal DESC, r.run_id DESC
LIMIT 1
) AS active_run_id,
(
SELECT json_extract(session.payload_json, '$.lastError')
FROM orchestration_v2_projection_provider_sessions session
INNER JOIN orchestration_v2_projection_provider_session_bindings binding
ON binding.provider_session_id = session.provider_session_id
WHERE binding.thread_id = t.thread_id
AND session.provider_instance_id = t.provider_instance_id
ORDER BY session.updated_at DESC, session.provider_session_id DESC
LIMIT 1
) AS last_error,
(
SELECT request.payload_json
FROM orchestration_v2_projection_runtime_requests request
WHERE request.thread_id = t.thread_id
AND request.status = 'pending'
ORDER BY request.created_at DESC, request.runtime_request_id DESC
LIMIT 1
) AS pending_request_payload_json,
(
SELECT message.payload_json
FROM orchestration_v2_projection_messages message
WHERE message.thread_id = t.thread_id
ORDER BY message.updated_at DESC, message.message_id DESC
LIMIT 1
) AS latest_message_payload_json,
(
SELECT message.updated_at
FROM orchestration_v2_projection_messages message
WHERE message.thread_id = t.thread_id
AND message.role = 'user'
ORDER BY message.updated_at DESC, message.message_id DESC
LIMIT 1
) AS latest_user_message_at,
EXISTS (
SELECT 1
FROM orchestration_v2_projection_plans plan
WHERE plan.thread_id = t.thread_id
AND plan.kind = 'proposed_plan'
AND plan.status = 'active'
) AS has_actionable_proposed_plan,
(
SELECT COUNT(*)
FROM orchestration_v2_projection_turn_items i
LEFT JOIN orchestration_v2_projection_runs r
ON r.run_id = i.run_id
WHERE i.thread_id = t.thread_id
AND (i.run_id IS NULL OR r.status <> 'rolled_back')
) AS item_count,
(
SELECT COUNT(*)
FROM orchestration_v2_projection_turn_items i
WHERE i.thread_id = t.thread_id
AND i.run_id IS NULL
) AS runless_item_count
FROM orchestration_v2_projection_threads t
WHERE t.deleted_at IS NULL${threadId === undefined ? sql`` : sql` AND t.thread_id = ${threadId}`}
ORDER BY t.updated_at ASC, t.thread_id ASC
`;
const selectShellRunRows = (threadIds?: ReadonlyArray<ThreadId>) =>
threadIds === undefined
? sql<ShellRunRow>`
SELECT thread_id, run_id, ordinal
FROM orchestration_v2_projection_runs
`
: sql<ShellRunRow>`
SELECT thread_id, run_id, ordinal
FROM orchestration_v2_projection_runs
WHERE thread_id IN ${sql.in(threadIds)}
`;
const selectShellRunItemCounts = (threadIds?: ReadonlyArray<ThreadId>) =>
threadIds === undefined
? sql<ShellRunItemCountRow>`
SELECT thread_id, run_id, COUNT(*) AS item_count
FROM orchestration_v2_projection_turn_items
WHERE run_id IS NOT NULL
GROUP BY thread_id, run_id
`
: sql<ShellRunItemCountRow>`
SELECT thread_id, run_id, COUNT(*) AS item_count
FROM orchestration_v2_projection_turn_items
WHERE run_id IS NOT NULL
AND thread_id IN ${sql.in(threadIds)}
GROUP BY thread_id, run_id
`;
const runMapsByThreadId = (input: {
readonly runRows: ReadonlyArray<ShellRunRow>;
readonly itemCountRows: ReadonlyArray<ShellRunItemCountRow>;
}) => {
const runOrdinalsByThreadId = new Map<ThreadId, Map<RunId, number>>();
for (const row of input.runRows) {
const threadId = ThreadId.make(row.thread_id);
const runId = RunId.make(row.run_id);
const existing = runOrdinalsByThreadId.get(threadId) ?? new Map<RunId, number>();
existing.set(runId, row.ordinal);
runOrdinalsByThreadId.set(threadId, existing);
}
const itemCountsByThreadId = new Map<ThreadId, Map<RunId, number>>();
for (const row of input.itemCountRows) {
const threadId = ThreadId.make(row.thread_id);
const runId = RunId.make(row.run_id);
const existing = itemCountsByThreadId.get(threadId) ?? new Map<RunId, number>();
existing.set(runId, row.item_count);
itemCountsByThreadId.set(threadId, existing);
}
return { runOrdinalsByThreadId, itemCountsByThreadId };
};
const shellThreadStateFromRow = (input: {
readonly row: ShellThreadRow;
readonly runOrdinalsByThreadId: ReadonlyMap<ThreadId, Map<RunId, number>>;
readonly itemCountsByThreadId: ReadonlyMap<ThreadId, Map<RunId, number>>;
}) =>
Effect.gen(function* () {
const { row, runOrdinalsByThreadId, itemCountsByThreadId } = input;
const thread = yield* decodeThreadPayload(row.payload_json);
const pendingRuntimeRequest =
row.pending_request_payload_json === null
? null
: yield* decodeRuntimeRequestPayload(row.pending_request_payload_json);
const latestVisibleMessage =
row.latest_message_payload_json === null
? null
: yield* decodeMessagePayload(row.latest_message_payload_json);
return {
thread,
latestRunId: row.latest_run_id === null ? null : RunId.make(row.latest_run_id),
latestRunStatus: shellStatusFromStoredRunStatus(row.latest_run_status),
latestRunRequestedAt:
row.latest_run_requested_at === null
? null
: DateTime.makeUnsafe(row.latest_run_requested_at),
latestRunStartedAt:
row.latest_run_started_at === null
? null
: DateTime.makeUnsafe(row.latest_run_started_at),
latestRunCompletedAt:
row.latest_run_completed_at === null
? null
: DateTime.makeUnsafe(row.latest_run_completed_at),
activeRunId: row.active_run_id === null ? null : RunId.make(row.active_run_id),
lastError: row.last_error,
pendingRuntimeRequest,
latestVisibleMessage,
latestUserMessageAt:
row.latest_user_message_at === null
? null
: DateTime.makeUnsafe(row.latest_user_message_at),
hasActionableProposedPlan: row.has_actionable_proposed_plan === 1,
itemCount: row.item_count,
runlessItemCount: row.runless_item_count,
updatedAt: thread.updatedAt,
runOrdinalById: runOrdinalsByThreadId.get(ThreadId.make(row.thread_id)) ?? new Map(),
itemCountByRunId: itemCountsByThreadId.get(ThreadId.make(row.thread_id)) ?? new Map(),
} satisfies ShellThreadState;
});
const getShellSnapshot: ProjectionStoreV2Shape["getShellSnapshot"] = () =>
sql
.withTransaction(
Effect.gen(function* () {
const [threadRows, runRows, itemCountRows, sequenceRows] = yield* Effect.all([
selectShellThreadRows(),
selectShellRunRows(),
selectShellRunItemCounts(),
sql<{ readonly snapshot_sequence: number | null }>`
SELECT MAX(sequence) AS snapshot_sequence
FROM orchestration_events
WHERE application_event_version = 2
AND aggregate_kind = 'thread'
`,
]);
const { runOrdinalsByThreadId, itemCountsByThreadId } = runMapsByThreadId({
runRows,
itemCountRows,
});
const states = yield* Effect.forEach(threadRows, (row) =>
shellThreadStateFromRow({ row, runOrdinalsByThreadId, itemCountsByThreadId }),
);
const statesByThreadId = new Map(states.map((state) => [state.thread.id, state]));
const shells = states.map((state) =>
shellFromState({
state,
visibleItemCount: visibleItemCountForShell({
threadId: state.thread.id,
statesByThreadId,
}),
}),
);
return {
schemaVersion: ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION,
snapshotSequence: sequenceRows[0]?.snapshot_sequence ?? 0,
threads: shells.filter((thread) => thread.archivedAt === null),
archivedThreads: shells.filter((thread) => thread.archivedAt !== null),
};
}),
)
.pipe(
Effect.mapError(
(cause) =>
new ProjectionStoreReadError({
threadId: ThreadId.make("thread:shell"),
cause,
}),
),
);
// Per-thread shell for the live shell streams: reads only the target thread
// plus its fork-source chain instead of materializing every thread. Returns
// null when the thread is deleted or unknown.
const getThreadShell: ProjectionStoreV2Shape["getThreadShell"] = (threadId) =>
sql
.withTransaction(
Effect.gen(function* () {
const rowsByThreadId = new Map<ThreadId, ShellThreadRow>();
const pending: Array<ThreadId> = [threadId];
while (pending.length > 0) {
const nextId = pending.pop();
if (nextId === undefined || rowsByThreadId.has(nextId)) {
continue;
}
const rows = yield* selectShellThreadRows(nextId);
const row = rows[0];
if (row === undefined) {
continue;
}
rowsByThreadId.set(nextId, row);
if (row.forked_from_run_source_thread_id !== null) {
pending.push(ThreadId.make(row.forked_from_run_source_thread_id));
}
}
if (!rowsByThreadId.has(threadId)) {
return null;
}
const threadIds = [...rowsByThreadId.keys()];
const [runRows, itemCountRows] = yield* Effect.all([
selectShellRunRows(threadIds),
selectShellRunItemCounts(threadIds),
]);
const { runOrdinalsByThreadId, itemCountsByThreadId } = runMapsByThreadId({
runRows,
itemCountRows,
});
const states = yield* Effect.forEach([...rowsByThreadId.values()], (row) =>
shellThreadStateFromRow({ row, runOrdinalsByThreadId, itemCountsByThreadId }),
);
const statesByThreadId = new Map(states.map((state) => [state.thread.id, state]));
const state = statesByThreadId.get(threadId);
if (state === undefined) {
return null;
}
return shellFromState({
state,
visibleItemCount: visibleItemCountForShell({ threadId, statesByThreadId }),
});
}),
)
.pipe(Effect.mapError((cause) => new ProjectionStoreReadError({ threadId, cause })));
return {
apply,
getShellSnapshot,
getThreadShell,
getThreadProjection,
getThreadSnapshot,
} satisfies ProjectionStoreV2Shape;
}),
);
export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(
ProjectionStoreV2,
Effect.gen(function* () {
const replayState = yield* Ref.make(makeProjectionReplayState());
const sequence = yield* Ref.make(0);
const service: ProjectionStoreV2Shape = {
apply: (event) =>
Effect.gen(function* () {
const result = yield* Ref.modify(replayState, (existing) => {
const next: ProjectionReplayState = {
projections: new Map(existing.projections),
providerSessionThreadIds: new Map(existing.providerSessionThreadIds),
};
if (!applyToProjectionReplayState(next, event)) {
return [
new ProjectionStoreThreadNotFoundError({ threadId: event.threadId }),
existing,
] as const;
}
return [undefined, next] as const;
});
if (result) {
return yield* result;
}
yield* Ref.update(sequence, (current) => current + 1);
}),
getShellSnapshot: () =>
Effect.gen(function* () {
const existing = (yield* Ref.get(replayState)).projections;
const shells = yield* Effect.forEach(
[...existing.keys()].toSorted((left, right) =>
String(left).localeCompare(String(right)),
),
(threadId) =>
service.getThreadProjection(threadId).pipe(Effect.map(threadShellFromProjection)),
);
const visible = shells.filter((thread) => thread.deletedAt === null);
return {
schemaVersion: ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION,
snapshotSequence: yield* Ref.get(sequence),
threads: visible.filter((thread) => thread.archivedAt === null),
archivedThreads: visible.filter((thread) => thread.archivedAt !== null),
};
}),
getThreadShell: (threadId) =>
Effect.gen(function* () {
const existing = (yield* Ref.get(replayState)).projections;
if (!existing.has(threadId)) {
return null;
}
const shell = yield* service
.getThreadProjection(threadId)
.pipe(Effect.map(threadShellFromProjection));
return shell.deletedAt === null ? shell : null;
}),
getThreadProjection: (threadId) =>
Effect.gen(function* () {
const existing = (yield* Ref.get(replayState)).projections;
const readProjection = (
targetThreadId: ThreadId,
seenThreadIds: ReadonlySet<ThreadId>,
): OrchestrationV2ThreadProjection | null => {
const projection = existing.get(targetThreadId);
if (!projection) {
return null;
}
const forkedFrom = projection.thread.forkedFrom;
if (forkedFrom?.type !== "run" || seenThreadIds.has(forkedFrom.threadId)) {
return withLocalVisibleTurnItems(projection);
}
const sourceProjection = readProjection(
forkedFrom.threadId,
new Set([...seenThreadIds, targetThreadId]),
);
return {
...projection,
visibleTurnItems: buildVisibleTurnItems({
projection,
sourceProjection,
}),
};
};
const projection = readProjection(threadId, new Set());
if (!projection) {
return yield* new ProjectionStoreThreadNotFoundError({ threadId });
}
return projection;
}),
getThreadSnapshot: (threadId) =>
service.getThreadProjection(threadId).pipe(
Effect.flatMap((projection) =>
Ref.get(sequence).pipe(
Effect.map((snapshotSequence) => ({
schemaVersion: ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION,
snapshotSequence,
projection,
})),
),
),
),
};
return service;
}),
);