Skip to content
Merged
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
35 changes: 24 additions & 11 deletions apps/server/src/mcp/OrchestratorMcpService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,9 @@ import * as Stream from "effect/Stream";

import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts";
import {
SUBAGENT_RESULT_TURN_ITEM_TYPES,
subagentResultForRun,
subagentStopNotice,
delegatedTaskProgress,
delegatedTaskReportRuns,
} from "@t3tools/provider-core/server/subagentProjection";
Expand Down Expand Up @@ -732,15 +734,26 @@ function pageIncludesTerminalTaskResult(input: {
const result = subagentResultForRun(input.target, run);
if (result.messageId === null && result.turnItemId === null) return false;

return input.items.some((item) => {
if (item.sourceThreadId !== input.target.thread.id) return false;
const matchesResult =
(result.turnItemId !== null && item.itemId === result.turnItemId) ||
(result.messageId !== null &&
item.type === "assistant_message" &&
item.messageId === result.messageId);
return matchesResult && item.text !== null && !item.textTruncated;
});
const onPage = (matches: (item: OrchestratorMcpThreadTimelineItem) => boolean) =>
input.items.some(
(item) =>
item.sourceThreadId === input.target.thread.id &&
matches(item) &&
item.text !== null &&
!item.textTruncated,
);
// The result ends with the stop reason, so the page shows it only when it has both.
const notice = subagentStopNotice(input.target, run);
return (
onPage(
(item) =>
(result.turnItemId !== null && item.itemId === result.turnItemId) ||
(result.messageId !== null &&
item.type === "assistant_message" &&
item.messageId === result.messageId),
) &&
(notice === undefined || onPage((item) => item.itemId === notice.id))
);
}

function latestTerminalResultRun(
Expand Down Expand Up @@ -1874,7 +1887,7 @@ const make = Effect.gen(function* () {
messageRoles: ["assistant"],
messageRunIds: resultRunIds,
turnItemRunIds: resultRunIds,
turnItemTypes: ["assistant_message", "error", "system_notice"],
turnItemTypes: SUBAGENT_RESULT_TURN_ITEM_TYPES,
})
.pipe(Effect.mapError(threadManagementFailure));
const childProjection = {
Expand Down Expand Up @@ -3597,7 +3610,7 @@ const make = Effect.gen(function* () {
messageRoles: ["assistant"],
messageRunIds: resultRunIds,
turnItemRunIds: resultRunIds,
turnItemTypes: ["assistant_message", "error"],
turnItemTypes: SUBAGENT_RESULT_TURN_ITEM_TYPES,
})
.pipe(Effect.mapError(threadManagementFailure));
if (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1414,7 +1414,7 @@ const seedRestartCancelledChild = (input: {
readonly name: string;
readonly completionWake: "always" | "settled_only";
readonly continuationPending: boolean;
readonly runStatus?: "cancelled" | "completed";
readonly runStatus?: "cancelled" | "completed" | "interrupted";
readonly lostWork?: OrchestrationV2Run["restartCancelledBackgroundWork"];
readonly now: DateTime.Utc;
}) =>
Expand Down Expand Up @@ -5150,6 +5150,72 @@ it.layer(layerTest)("delegated tasks across a server restart", (it) => {
`Child task completed without an assistant result.\n\n${stopReason}`,
);
assert.isUndefined(task?.cancelledRunId);

// Codex 0.169 reports a hook-stopped turn as interrupted; its reason is the interrupt result.
const interrupted = yield* seedRestartCancelledChild({
parentThreadId: threadId,
projectId,
parentRunId: runId,
rootNodeId,
name: "cancel-finished-interrupted-child",
completionWake: "always",
continuationPending: false,
runStatus: "interrupted",
now,
});
yield* eventSink.write({
commandId: CommandId.make("command:cancel-finished-interrupted-child:result"),
events: [
{
id: EventId.make("event:cancel-finished-interrupted-child:result"),
type: "turn-item.updated",
threadId: interrupted.childThreadId,
runId: interrupted.childRunId,
nodeId: rootNodeId,
providerInstanceId: modelSelection.instanceId,
occurredAt: now,
payload: {
id: IdAllocator.derive.runSignalTurnItem({
runId: interrupted.childRunId,
signal: "interrupt-result",
}),
type: "run_interrupt_result",
threadId: interrupted.childThreadId,
runId: interrupted.childRunId,
nodeId: rootNodeId,
providerThreadId: null,
providerTurnId: null,
nativeItemRef: null,
parentItemId: null,
ordinal: 98,
status: "interrupted",
title: "Interrupted",
startedAt: now,
completedAt: now,
updatedAt: now,
message: stopReason,
},
},
],
});
yield* orchestrator.cancelDelegatedTask({
parentThreadId: threadId,
taskId: interrupted.taskId,
command: {
type: "thread.stop",
commandId: CommandId.make("cancel-finished-interrupted-child"),
threadId: interrupted.childThreadId,
stopDelegatedTasks: false,
},
stopDescendants: () => Effect.void,
});
const interruptedTask = (yield* orchestrator.getThreadProjection(threadId)).subagents.find(
(row) => row.id === interrupted.taskId,
);
assert.equal(
interruptedTask?.result,
`Child task ended with status interrupted.\n\n${stopReason}`,
);
}),
);

Expand Down
3 changes: 2 additions & 1 deletion apps/server/src/orchestration-v2/Orchestrator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,7 @@ import {
endOrphanedNativeSubagent,
endRunlessRootTurns,
makeSubagentChildThread,
SUBAGENT_RESULT_TURN_ITEM_TYPES,
subagentResultForRun,
delegatedTaskProgress,
delegatedTaskReportRuns,
Expand Down Expand Up @@ -14998,7 +14999,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
messageRoles: ["assistant"],
messageRunIds: resultRunIds,
turnItemRunIds: resultRunIds,
turnItemTypes: ["assistant_message", "error", "system_notice"],
turnItemTypes: SUBAGENT_RESULT_TURN_ITEM_TYPES,
providerTurnAttemptIds: [childRun, ...reportRuns].flatMap(
(run) => run.activeAttemptId ?? [],
),
Expand Down
44 changes: 43 additions & 1 deletion apps/server/src/orchestration-v2/SubagentProjection.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -492,7 +492,7 @@ it("exposes the provider failure rather than a progress message from the failed
assert.isNull(result.messageId);
});

it("reports a provider's stop reason for a completed run without an assistant result", () => {
it("reports a provider's stop reason with and without assistant progress", () => {
const { projection, run } = taskFixture();
const notice = {
id: IdAllocator.derive.runSignalTurnItem({
Expand Down Expand Up @@ -520,6 +520,48 @@ it("reports a provider's stop reason for a completed run without an assistant re
subagentResultForRun({ ...projection, turnItems: [notice] }, run).text,
`Child task completed without an assistant result.\n\n${notice.message}`,
);
const progress = makeSubagentConversationArtifacts({
messageId: MessageId.make("before-hook-stop"),
turnItemId: TurnItemId.make("before-hook-stop"),
threadId: parentThreadId,
rootNodeId: NodeId.make("root"),
providerThreadId: null,
providerTurnId: null,
nativeItemRef: null,
role: "assistant",
text: "I am checking the remaining files.",
ordinal: 1,
now: childCreatedAt,
});
assert.equal(
subagentResultForRun(
{
...projection,
messages: [{ ...progress.message, runId: run.id }],
turnItems: [{ ...progress.turnItem, runId: run.id }, notice],
},
run,
).text,
`${progress.message.text}\n\n${notice.message}`,
);
const interruptResult = {
...notice,
id: IdAllocator.derive.runSignalTurnItem({ runId: run.id, signal: "interrupt-result" }),
status: "interrupted",
title: "Interrupted",
type: "run_interrupt_result",
} satisfies OrchestrationV2TurnItem;
assert.equal(
subagentResultForRun(
{
...projection,
messages: [{ ...progress.message, runId: run.id }],
turnItems: [{ ...progress.turnItem, runId: run.id }, interruptResult],
},
{ ...run, status: "interrupted" },
).text,
`${progress.message.text}\n\n${notice.message}`,
);
});

it("keeps the final report of a run that failed after its turn ended", () => {
Expand Down
58 changes: 45 additions & 13 deletions packages/provider-core/src/server/subagentProjection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,13 +194,43 @@ export function withExecutedModelNote(
/** Run signal of the notice that carries a provider's stop reason on a completed run. */
export const PROVIDER_STOP_REASON_SIGNAL = "provider-stop-reason";

function stopNotice(
/** Turn item types `subagentResultForRun` reads; load at least these for its projection. */
export const SUBAGENT_RESULT_TURN_ITEM_TYPES = [
"assistant_message",
"error",
"system_notice",
"run_interrupt_result",
] as const satisfies ReadonlyArray<OrchestrationV2TurnItem["type"]>;

/** The item carrying a provider's stop reason for a run, which its delegated result ends with. */
export function subagentStopNotice(
projection: Pick<OrchestrationV2ThreadProjection, "turnItems">,
run: OrchestrationV2Run,
): string | undefined {
const id = derive.runSignalTurnItem({ runId: run.id, signal: PROVIDER_STOP_REASON_SIGNAL });
const notice = projection.turnItems.find((item) => item.id === id);
return notice?.type === "system_notice" ? notice.message : undefined;
) {
// Codex ends a hook-stopped turn as completed or interrupted, depending on its version.
const ids = [
derive.runSignalTurnItem({ runId: run.id, signal: PROVIDER_STOP_REASON_SIGNAL }),
derive.runSignalTurnItem({ runId: run.id, signal: "interrupt-result" }),
];
return projection.turnItems.find(
(
item,
): item is Extract<
OrchestrationV2TurnItem,
{ readonly type: "system_notice" | "run_interrupt_result" }
> =>
ids.includes(item.id) &&
(item.type === "system_notice" || item.type === "run_interrupt_result"),
);
}

function withStopNotice(
projection: Pick<OrchestrationV2ThreadProjection, "turnItems">,
run: OrchestrationV2Run,
text: string,
): string {
const notice = subagentStopNotice(projection, run);
return notice === undefined ? text : `${text}\n\n${notice.message}`;
}

type MonitorNotice = Pick<OrchestrationV2ConversationMessage, "runId" | "notification">;
Expand Down Expand Up @@ -263,7 +293,7 @@ export function subagentResultForRun(
run.status !== "completed" ||
result.messageId !== null ||
result.turnItemId !== null ||
stopNotice(projection, run) !== undefined
subagentStopNotice(projection, run) !== undefined
)
return result;
for (const earlier of delegatedTaskReportRuns(
Expand Down Expand Up @@ -320,19 +350,21 @@ function resultOfRun(
failure !== undefined && turnItem !== null && turnItem.ordinal < failure.ordinal
? (message?.text ?? turnItem.text)
: undefined;
const report = message?.text ?? turnItem?.text;
const text =
(failure?.type === "error"
? reportBeforeFailure === undefined
? failure.failure.message
: `${failure.failure.message}\n\nLast assistant message before the run failed:\n\n${reportBeforeFailure}`
: undefined) ??
message?.text ??
turnItem?.text ??
(run.status === "completed"
? ["Child task completed without an assistant result.", stopNotice(projection, run)]
.filter((part) => part !== undefined)
.join("\n\n")
: `Child task ended with status ${run.status}.`);
withStopNotice(
projection,
run,
report ??
(run.status === "completed"
? "Child task completed without an assistant result."
: `Child task ended with status ${run.status}.`),
);
const executedModel = latestProviderTurnForAttempt(
projection.providerTurns,
run.activeAttemptId,
Expand Down
Loading