Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
261 changes: 209 additions & 52 deletions apps/server/src/orchestration-v2/Orchestrator.ts

Large diffs are not rendered by default.

85 changes: 82 additions & 3 deletions apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -707,6 +707,8 @@ it.each([

function makeLocalCommandHarness(input: {
readonly text: string;
readonly mailbox?: boolean;
readonly failMailboxStart?: boolean;
readonly manualContinuation?: boolean;
readonly nativeResumeUnsupported?: boolean;
readonly steeringRestart?: boolean;
Expand Down Expand Up @@ -943,6 +945,33 @@ function makeLocalCommandHarness(input: {
checkpoints: [],
updatedAt: now,
};
if (input.mailbox) {
const folded = {
...run,
id: RunId.make("folded-run"),
userMessageId: MessageId.make("folded-message"),
rootNodeId: null,
status: "queued" as const,
};
projection = {
...projection,
runs: [
{
...run,
mailbox: [
{
messageId: folded.userMessageId,
runId: folded.id,
senderRole: "agent",
requestedAt: now,
text: "Folded instruction must survive.",
},
],
},
folded,
],
};
}
const parentThreadId = ThreadId.make("side-chat-parent");
const parentRunId = RunId.make("side-chat-parent-run");
const parentProviderThread = {
Expand Down Expand Up @@ -1402,7 +1431,26 @@ function makeLocalCommandHarness(input: {
),
ensureThread: fallbackEnsureThread,
};
const startTurn = vi.fn((_turn: ProviderAdapter.ProviderAdapterV2TurnInput) => Effect.void);
const startTurn = vi.fn((_turn: ProviderAdapter.ProviderAdapterV2TurnInput) =>
Effect.suspend(() => {
if (input.mailbox) {
expect(projection.runs.find((candidate) => candidate.id === "folded-run")?.status).toBe(
"queued",
);
}
return input.failMailboxStart
? Effect.fail(
new ProviderAdapter.ProviderAdapterTurnStartError({
driver: providerThread.driver,
threadId,
providerThreadId,
runId,
cause: "Synthetic provider refusal before acceptance",
}),
)
: Effect.void;
}),
);
const sideChatThread = {
...providerThread,
nativeThreadRef: {
Expand Down Expand Up @@ -1497,7 +1545,7 @@ function makeLocalCommandHarness(input: {
),
);
const writeIfRunCurrent = vi.fn<EventSink.EventSinkV2["Service"]["writeIfRunCurrent"]>(
({ events: incoming, activeAttemptId, expectedStatus }) =>
({ events: incoming, runId: targetRunId, activeAttemptId, expectedStatus }) =>
"writeFailure" in input
? Effect.fail(
new EventSink.EventSinkWriteError({
Expand All @@ -1506,7 +1554,7 @@ function makeLocalCommandHarness(input: {
}),
)
: Effect.sync(() => {
const current = projection.runs.find((candidate) => candidate.id === runId);
const current = projection.runs.find((candidate) => candidate.id === targetRunId);
const committed =
current !== undefined &&
current.activeAttemptId === activeAttemptId &&
Expand Down Expand Up @@ -1751,6 +1799,37 @@ function layerStartEffectWorker(
);
}

effectIt.effect("consumes folded mailbox runs only after provider acceptance", () => {
const harness = makeLocalCommandHarness({
text: "Head instruction",
mailbox: true,
sideChat: { contextRun: "current" },
});
return Effect.gen(function* () {
yield* harness.start;
expect(harness.startTurn.mock.calls[0]?.[0].message.text).toContain(
"Folded instruction must survive.",
);
expect(harness.projection().runs.find((run) => run.id === "folded-run")?.status).toBe(
"cancelled",
);
});
});

effectIt.effect("retains folded mailbox runs when the provider refuses the combined turn", () => {
const harness = makeLocalCommandHarness({
text: "Head instruction",
mailbox: true,
failMailboxStart: true,
sideChat: { contextRun: "current" },
});
return Effect.gen(function* () {
yield* harness.start;
expect(harness.startTurn).toHaveBeenCalledOnce();
expect(harness.projection().runs.find((run) => run.id === "folded-run")?.status).toBe("queued");
});
});

const enqueueStart = (
projection: OrchestrationV2ThreadProjection,
request?: EffectOutbox.OrchestrationEffectRequestV2,
Expand Down
77 changes: 66 additions & 11 deletions apps/server/src/orchestration-v2/ProviderTurnStartService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";

import * as ServerConfig from "../config.ts";
import { formatMailboxForProvider } from "./StandingMailbox.ts";
import { queuedRunCancellationEvents } from "./QueuedRunOrder.ts";
import {
CLAUDE_PROVIDER,
CLAUDE_QUERY_ENDED_BEFORE_TURN_DETAIL,
Expand Down Expand Up @@ -1156,19 +1158,22 @@ export const layer: Layer.Layer<
? (providerMessage.sentBy?.founder ?? null)
: null;
const messageText = formatDigestForProvider(
formatSeenMarkerForProvider(
formatSharedSenderForProvider(
withMessageSenderNote(
providerMessage,
projectComposerContextForProvider({
text: providerMessage.text,
records: providerMessage.context?.records ?? [],
}),
formatMailboxForProvider(
formatSeenMarkerForProvider(
formatSharedSenderForProvider(
withMessageSenderNote(
providerMessage,
projectComposerContextForProvider({
text: providerMessage.text,
records: providerMessage.context?.records ?? [],
}),
),
sharedFounder,
),
providerMessage.seenMarker,
sharedFounder,
),
providerMessage.seenMarker,
sharedFounder,
run.mailbox,
),
run.digest,
);
Expand Down Expand Up @@ -2058,6 +2063,7 @@ export const layer: Layer.Layer<
} = handoffContext;
const retryHandoff = resumedRetryHandoff ?? (yield* prepareRetryHandoff(handoffContext));
const carriesPendingContext =
(run.mailbox?.length ?? 0) > 0 ||
effectiveHandoffs.length > 0 ||
retryHandoff.handoffs.length > 0 ||
retryHandoff.attachments.length > 0 ||
Expand Down Expand Up @@ -2308,7 +2314,8 @@ export const layer: Layer.Layer<
!turnInput.message.attachments.some((current) => current.id === missed.id),
);
// Like pending history, pending images need a prompt; native resume carries none.
const prompted = context !== "" || missedAttachments.length > 0;
const prompted =
context !== "" || missedAttachments.length > 0 || (run.mailbox?.length ?? 0) > 0;
// A resume that must be prompted still needs a request, or the agent has nothing to do.
const requestText =
turnInput.resume && prompted && userText === "" ? RESUME_PROMPT : userText;
Expand Down Expand Up @@ -2353,6 +2360,54 @@ export const layer: Layer.Layer<
yield* inlineDeliveryLock.withPermits(1)(
Effect.gen(function* () {
if (promptDroppedOnTerminal) return;
// Keep folded runs queued until the provider accepts the combined prompt.
// Each cancellation compares the stored run so Stop or another delivery wins.
if ((run.mailbox?.length ?? 0) > 0) {
yield* Effect.gen(function* () {
const foldedIds = new Set(run.mailbox?.map((entry) => entry.runId));
const foldedRuns = projection.runs.filter((candidate) =>
foldedIds.has(candidate.id),
);
const current = yield* projectionStore.getThreadRecords(
projection.thread.id,
["runs", "nodes", "attempts"],
{
runIds: [...foldedIds],
nodeIds: foldedRuns.flatMap((folded) =>
folded.rootNodeId === null ? [] : [folded.rootNodeId],
),
attemptIds: foldedRuns.flatMap((folded) =>
folded.activeAttemptId === null ? [] : [folded.activeAttemptId],
),
},
);
const acceptedAt = yield* DateTime.now;
for (const entry of run.mailbox ?? []) {
const folded = current.runs.find((candidate) => candidate.id === entry.runId);
if (folded?.status !== "queued" || folded.activeAttemptId === null) continue;
yield* eventSink.writeIfRunCurrent({
threadId: projection.thread.id,
runId: folded.id,
activeAttemptId: folded.activeAttemptId,
expectedStatus: "queued",
events: yield* Effect.forEach(
queuedRunCancellationEvents(current, folded, acceptedAt),
(event) =>
Effect.map(
idAllocator.allocate.event({ threadId: projection.thread.id }),
(id) => ({ ...event, id }),
),
),
});
}
}).pipe(
Effect.catchCause(() =>
Effect.logWarning("Failed to record accepted mailbox delivery", {
runId: run.id,
}),
),
);
}
// After provider acceptance, failed delivery bookkeeping must not stop live ingestion.
const nativeThreadId = runningProviderThread.nativeThreadRef?.nativeId;
yield* Effect.forEach(
Expand Down
57 changes: 56 additions & 1 deletion apps/server/src/orchestration-v2/QueuedRunOrder.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import type { OrchestrationV2Run, OrchestrationV2ThreadProjection } from "@t3tools/contracts";
import type {
OrchestrationV2DomainEvent,
OrchestrationV2Run,
OrchestrationV2ThreadProjection,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";

export function isAutomaticCompletionRun(
Expand Down Expand Up @@ -49,3 +53,54 @@ export function queuedRunsInDeliveryOrder(
}
}
}

type CancellationEventType = "run.updated" | "run-attempt.updated" | "node.updated";
type CancellationEvent = {
[Type in CancellationEventType]: Omit<
Extract<OrchestrationV2DomainEvent, { readonly type: Type }>,
"id"
>;
}[CancellationEventType];

export function queuedRunCancellationEvents(
projection: Pick<OrchestrationV2ThreadProjection, "nodes" | "attempts">,
run: OrchestrationV2Run,
now: DateTime.Utc,
): ReadonlyArray<CancellationEvent> {
const rootNode = projection.nodes.find((node) => node.id === run.rootNodeId);
const attempt = projection.attempts.find((candidate) => candidate.id === run.activeAttemptId);
const events: Array<CancellationEvent> = [
{
type: "run.updated",
threadId: run.threadId,
runId: run.id,
...(run.rootNodeId === null ? {} : { nodeId: run.rootNodeId }),
providerInstanceId: run.providerInstanceId,
occurredAt: now,
payload: { ...run, status: "cancelled", queuePosition: null, completedAt: now },
},
];
if (attempt !== undefined && rootNode !== undefined) {
events.push({
type: "run-attempt.updated",
threadId: run.threadId,
runId: run.id,
nodeId: rootNode.id,
providerInstanceId: run.providerInstanceId,
occurredAt: now,
payload: { ...attempt, status: "cancelled", completedAt: now },
});
}
if (rootNode !== undefined) {
events.push({
type: "node.updated",
threadId: run.threadId,
runId: run.id,
nodeId: rootNode.id,
providerInstanceId: run.providerInstanceId,
occurredAt: now,
payload: { ...rootNode, status: "cancelled", completedAt: now },
});
}
return events;
}
Loading
Loading