Add MCP thread management and Codex turn mapping
- Add scoped thread list, read, send, wait, and interrupt tools - Track creation provenance and map provider turns across adapters - Centralize thread lifecycle operations in a management service
This commit is contained in:
1 parent
bd23813e34
commit
96b3a4e578
38 files changed
+2085
-48
No files matched your search
@@ -6,6 +6,8 @@ import {
|
||||
NodeId,
|
||||
type OrchestrationV2Run,
|
||||
type OrchestrationV2ThreadProjection,
|
||||
type OrchestrationV2ThreadShell,
|
||||
type OrchestrationV2TurnItem,
|
||||
OrchestratorMcpFailure,
|
||||
type OrchestratorMcpCapabilitiesResult,
|
||||
type OrchestratorMcpCreateThreadsInput,
|
||||
@@ -18,6 +20,20 @@ import {
|
||||
type OrchestratorMcpTarget,
|
||||
type OrchestratorMcpTaskCancelInput,
|
||||
type OrchestratorMcpTaskCancelResult,
|
||||
type OrchestratorMcpThreadDetail,
|
||||
type OrchestratorMcpThreadInterruptInput,
|
||||
type OrchestratorMcpThreadInterruptResult,
|
||||
type OrchestratorMcpThreadListInput,
|
||||
type OrchestratorMcpThreadListItem,
|
||||
type OrchestratorMcpThreadListResult,
|
||||
type OrchestratorMcpThreadReadInput,
|
||||
type OrchestratorMcpThreadReadResult,
|
||||
type OrchestratorMcpThreadRun,
|
||||
type OrchestratorMcpThreadSendInput,
|
||||
type OrchestratorMcpThreadSendResult,
|
||||
type OrchestratorMcpThreadTimelineItem,
|
||||
type OrchestratorMcpThreadWaitInput,
|
||||
type OrchestratorMcpThreadWaitResult,
|
||||
type ProviderInteractionMode,
|
||||
ProviderInstanceId,
|
||||
type RuntimeMode,
|
||||
@@ -26,20 +42,32 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { isBuiltInProviderAdapterDriverV2 } from "../orchestration-v2/builtInProviderAdapterDrivers.ts";
|
||||
import { OrchestratorV2 } from "../orchestration-v2/Orchestrator.ts";
|
||||
import { subagentResultForRun } from "../orchestration-v2/SubagentProjection.ts";
|
||||
import {
|
||||
isActiveRun,
|
||||
latestActiveRun,
|
||||
latestRun,
|
||||
ThreadManagementError,
|
||||
ThreadManagementService,
|
||||
} from "../orchestration-v2/ThreadManagementService.ts";
|
||||
import { ProviderRegistry } from "../provider/Services/ProviderRegistry.ts";
|
||||
import type { McpInvocationScope } from "./McpInvocationContext.ts";
|
||||
|
||||
const DEFAULT_WAIT_TIMEOUT_MS = 10 * 60 * 1_000;
|
||||
const MAX_WAIT_TIMEOUT_MS = 60 * 60 * 1_000;
|
||||
const TASK_POLL_INTERVAL_MS = 50;
|
||||
const DEFAULT_THREAD_LIST_LIMIT = 50;
|
||||
const DEFAULT_THREAD_READ_LIMIT = 50;
|
||||
const DEFAULT_THREAD_RUN_LIMIT = 10;
|
||||
const DEFAULT_THREAD_ITEM_MAX_CHARS = 20_000;
|
||||
|
||||
interface ResolvedTarget {
|
||||
readonly modelSelection: ModelSelection;
|
||||
@@ -70,6 +98,26 @@ export interface OrchestratorMcpServiceShape {
|
||||
scope: McpInvocationScope,
|
||||
input: OrchestratorMcpCreateThreadsInput,
|
||||
) => Effect.Effect<OrchestratorMcpCreateThreadsResult, OrchestratorMcpFailure>;
|
||||
readonly listThreads: (
|
||||
scope: McpInvocationScope,
|
||||
input: OrchestratorMcpThreadListInput,
|
||||
) => Effect.Effect<OrchestratorMcpThreadListResult, OrchestratorMcpFailure>;
|
||||
readonly readThread: (
|
||||
scope: McpInvocationScope,
|
||||
input: OrchestratorMcpThreadReadInput,
|
||||
) => Effect.Effect<OrchestratorMcpThreadReadResult, OrchestratorMcpFailure>;
|
||||
readonly sendToThread: (
|
||||
scope: McpInvocationScope,
|
||||
input: OrchestratorMcpThreadSendInput,
|
||||
) => Effect.Effect<OrchestratorMcpThreadSendResult, OrchestratorMcpFailure>;
|
||||
readonly waitForThread: (
|
||||
scope: McpInvocationScope,
|
||||
input: OrchestratorMcpThreadWaitInput,
|
||||
) => Effect.Effect<OrchestratorMcpThreadWaitResult, OrchestratorMcpFailure>;
|
||||
readonly interruptThread: (
|
||||
scope: McpInvocationScope,
|
||||
input: OrchestratorMcpThreadInterruptInput,
|
||||
) => Effect.Effect<OrchestratorMcpThreadInterruptResult, OrchestratorMcpFailure>;
|
||||
}
|
||||
|
||||
export class OrchestratorMcpService extends Context.Service<
|
||||
@@ -77,6 +125,8 @@ export class OrchestratorMcpService extends Context.Service<
|
||||
OrchestratorMcpServiceShape
|
||||
>()("t3/mcp/OrchestratorMcpService") {}
|
||||
|
||||
const isThreadManagementError = Schema.is(ThreadManagementError);
|
||||
|
||||
function failure(code: OrchestratorMcpFailure["code"], message: string): OrchestratorMcpFailure {
|
||||
return new OrchestratorMcpFailure({ code, message });
|
||||
}
|
||||
@@ -108,10 +158,6 @@ function providerConstraints(
|
||||
return constraints;
|
||||
}
|
||||
|
||||
function isActiveRun(run: OrchestrationV2Run): boolean {
|
||||
return run.status === "starting" || run.status === "running" || run.status === "waiting";
|
||||
}
|
||||
|
||||
function taskStatusForRun(
|
||||
run: OrchestrationV2Run | undefined,
|
||||
): OrchestratorMcpDelegateTaskResult["status"] {
|
||||
@@ -246,6 +292,22 @@ function stableMessageId(input: {
|
||||
);
|
||||
}
|
||||
|
||||
function stableOperationMessageId(input: {
|
||||
readonly scope: McpInvocationScope;
|
||||
readonly requestKey: string;
|
||||
readonly operation: string;
|
||||
}): MessageId {
|
||||
return MessageId.make(
|
||||
[
|
||||
"message",
|
||||
"mcp",
|
||||
stablePart(input.scope.providerSessionId),
|
||||
stablePart(input.operation),
|
||||
stablePart(input.requestKey),
|
||||
].join(":"),
|
||||
);
|
||||
}
|
||||
|
||||
function threadTitle(input: {
|
||||
readonly parentTitle: string;
|
||||
readonly prompt: string | undefined;
|
||||
@@ -263,9 +325,166 @@ function taskPrompt(input: OrchestratorMcpDelegateTaskInput): string {
|
||||
: `Act as the ${input.role} sub-agent for this task.\n\n${input.task}`;
|
||||
}
|
||||
|
||||
function listItemFromShell(shell: OrchestrationV2ThreadShell): OrchestratorMcpThreadListItem {
|
||||
return {
|
||||
threadId: shell.id,
|
||||
title: shell.title,
|
||||
createdBy: shell.createdBy,
|
||||
creationSource: shell.creationSource,
|
||||
status: shell.status,
|
||||
latestRunId: shell.latestRunId,
|
||||
providerInstanceId: shell.modelSelection.instanceId,
|
||||
model: shell.modelSelection.model,
|
||||
runtimeMode: shell.runtimeMode,
|
||||
interactionMode: shell.interactionMode,
|
||||
parentThreadId: shell.lineage.parentThreadId,
|
||||
relationshipToParent: shell.lineage.relationshipToParent,
|
||||
itemCount: shell.visibleItemCount,
|
||||
createdAt: DateTime.formatIso(shell.createdAt),
|
||||
updatedAt: DateTime.formatIso(shell.updatedAt),
|
||||
};
|
||||
}
|
||||
|
||||
function threadDetail(projection: OrchestrationV2ThreadProjection): OrchestratorMcpThreadDetail {
|
||||
const latest = latestRun(projection);
|
||||
const active = latestActiveRun(projection);
|
||||
return {
|
||||
threadId: projection.thread.id,
|
||||
projectId: projection.thread.projectId,
|
||||
title: projection.thread.title,
|
||||
createdBy: projection.thread.createdBy,
|
||||
creationSource: projection.thread.creationSource,
|
||||
status: latest?.status ?? "idle",
|
||||
latestRunId: latest?.id ?? null,
|
||||
activeRunId: active?.id ?? null,
|
||||
providerInstanceId: projection.thread.modelSelection.instanceId,
|
||||
model: projection.thread.modelSelection.model,
|
||||
runtimeMode: projection.thread.runtimeMode,
|
||||
interactionMode: projection.thread.interactionMode,
|
||||
branch: projection.thread.branch,
|
||||
worktreePath: projection.thread.worktreePath,
|
||||
parentThreadId: projection.thread.lineage.parentThreadId,
|
||||
relationshipToParent: projection.thread.lineage.relationshipToParent,
|
||||
runCount: projection.runs.length,
|
||||
itemCount: projection.visibleTurnItems.length,
|
||||
pendingRequestCount: projection.runtimeRequests.filter(
|
||||
(request) => request.status === "pending",
|
||||
).length,
|
||||
archived: projection.thread.archivedAt !== null,
|
||||
createdAt: DateTime.formatIso(projection.thread.createdAt),
|
||||
updatedAt: DateTime.formatIso(projection.updatedAt),
|
||||
};
|
||||
}
|
||||
|
||||
function threadRun(run: OrchestrationV2Run): OrchestratorMcpThreadRun {
|
||||
return {
|
||||
runId: run.id,
|
||||
ordinal: run.ordinal,
|
||||
status: run.status,
|
||||
providerInstanceId: run.modelSelection.instanceId,
|
||||
model: run.modelSelection.model,
|
||||
requestedAt: DateTime.formatIso(run.requestedAt),
|
||||
startedAt: run.startedAt === null ? null : DateTime.formatIso(run.startedAt),
|
||||
completedAt: run.completedAt === null ? null : DateTime.formatIso(run.completedAt),
|
||||
};
|
||||
}
|
||||
|
||||
function jsonText(value: unknown): string {
|
||||
try {
|
||||
return JSON.stringify(value, null, 2);
|
||||
} catch {
|
||||
return String(value);
|
||||
}
|
||||
}
|
||||
|
||||
function turnItemText(item: OrchestrationV2TurnItem): string | null {
|
||||
switch (item.type) {
|
||||
case "user_message":
|
||||
case "assistant_message":
|
||||
case "reasoning":
|
||||
return item.text;
|
||||
case "proposed_plan":
|
||||
return item.markdown;
|
||||
case "todo_list":
|
||||
return [item.explanation, ...item.steps.map((step) => `[${step.status}] ${step.text}`)]
|
||||
.filter((line): line is string => line !== undefined)
|
||||
.join("\n");
|
||||
case "user_input_request":
|
||||
return jsonText(item.questions);
|
||||
case "file_change":
|
||||
return [
|
||||
item.fileName,
|
||||
item.additions === undefined && item.deletions === undefined
|
||||
? undefined
|
||||
: `+${item.additions ?? 0} -${item.deletions ?? 0}`,
|
||||
item.diffStr ?? item.newStr,
|
||||
]
|
||||
.filter((line): line is string => line !== undefined)
|
||||
.join("\n");
|
||||
case "command_execution":
|
||||
return [`$ ${item.input}`, item.output]
|
||||
.filter((line): line is string => line !== undefined)
|
||||
.join("\n");
|
||||
case "file_search":
|
||||
return jsonText({ pattern: item.pattern, results: item.results });
|
||||
case "web_search":
|
||||
return jsonText({ patterns: item.patterns, results: item.results });
|
||||
case "approval_request":
|
||||
return item.prompt ?? item.requestKind;
|
||||
case "checkpoint":
|
||||
return jsonText(item.files);
|
||||
case "run_interrupt_request":
|
||||
case "run_interrupt_result":
|
||||
return item.message;
|
||||
case "compaction":
|
||||
return item.summary ?? null;
|
||||
case "handoff":
|
||||
return item.summary ?? `${item.strategy} handoff to ${item.toProvider}`;
|
||||
case "fork":
|
||||
return `Forked to thread ${item.targetThreadId}.`;
|
||||
case "subagent":
|
||||
return item.result ?? item.prompt;
|
||||
case "dynamic_tool":
|
||||
return jsonText({ toolName: item.toolName, input: item.input, output: item.output });
|
||||
}
|
||||
}
|
||||
|
||||
function timelineItem(input: {
|
||||
readonly row: OrchestrationV2ThreadProjection["visibleTurnItems"][number];
|
||||
readonly maxChars: number;
|
||||
readonly projection: OrchestrationV2ThreadProjection;
|
||||
}): OrchestratorMcpThreadTimelineItem {
|
||||
const text = turnItemText(input.row.item);
|
||||
const textTruncated = text !== null && text.length > input.maxChars;
|
||||
const messageId =
|
||||
input.row.item.type === "user_message" || input.row.item.type === "assistant_message"
|
||||
? input.row.item.messageId
|
||||
: null;
|
||||
const message =
|
||||
messageId === null
|
||||
? undefined
|
||||
: input.projection.messages.find((candidate) => candidate.id === messageId);
|
||||
return {
|
||||
position: input.row.position,
|
||||
visibility: input.row.visibility,
|
||||
sourceThreadId: input.row.sourceThreadId,
|
||||
itemId: input.row.sourceItemId,
|
||||
runId: input.row.item.runId,
|
||||
messageId,
|
||||
createdBy: message?.createdBy ?? null,
|
||||
creationSource: message?.creationSource ?? null,
|
||||
type: input.row.item.type,
|
||||
status: input.row.item.status,
|
||||
title: input.row.item.title,
|
||||
text: textTruncated ? `${text.slice(0, input.maxChars)}\n…[truncated]` : text,
|
||||
textTruncated,
|
||||
updatedAt: DateTime.formatIso(input.row.item.updatedAt),
|
||||
};
|
||||
}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const orchestrator = yield* OrchestratorV2;
|
||||
const threadManagement = yield* ThreadManagementService;
|
||||
const providerRegistry = yield* ProviderRegistry;
|
||||
|
||||
const requireCapability = (scope: McpInvocationScope) =>
|
||||
@@ -279,7 +498,7 @@ const make = Effect.gen(function* () {
|
||||
);
|
||||
|
||||
const loadProjection = (threadId: ThreadId) =>
|
||||
orchestrator
|
||||
threadManagement
|
||||
.getThreadProjection(threadId)
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
@@ -290,6 +509,29 @@ const make = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
const loadProjectThread = (
|
||||
projectId: OrchestrationV2ThreadProjection["thread"]["projectId"],
|
||||
threadId: ThreadId,
|
||||
): Effect.Effect<OrchestrationV2ThreadProjection, OrchestratorMcpFailure> =>
|
||||
threadManagement
|
||||
.getProjectThread({ projectId, threadId })
|
||||
.pipe(
|
||||
Effect.mapError(() =>
|
||||
failure("thread_not_found", `Thread ${threadId} was not found in the calling project.`),
|
||||
),
|
||||
);
|
||||
|
||||
const loadScopedThread = (scope: McpInvocationScope, threadId: ThreadId) =>
|
||||
Effect.gen(function* () {
|
||||
yield* requireCapability(scope);
|
||||
const parent = yield* loadProjection(scope.threadId);
|
||||
const target =
|
||||
threadId === scope.threadId
|
||||
? parent
|
||||
: yield* loadProjectThread(parent.thread.projectId, threadId);
|
||||
return { parent, target } as const;
|
||||
});
|
||||
|
||||
const loadProviders = providerRegistry.getProviders;
|
||||
|
||||
const resolveTarget = (input: {
|
||||
@@ -484,6 +726,8 @@ const make = Effect.gen(function* () {
|
||||
asyncPolling: true,
|
||||
cancellation: true,
|
||||
batchThreadCreation: true,
|
||||
threadManagement: true,
|
||||
incrementalThreadRead: true,
|
||||
maxBatchThreads: 20,
|
||||
},
|
||||
};
|
||||
@@ -522,9 +766,11 @@ const make = Effect.gen(function* () {
|
||||
requestKey: key,
|
||||
operation: "delegate-task",
|
||||
});
|
||||
const result = yield* orchestrator
|
||||
const result = yield* threadManagement
|
||||
.dispatch({
|
||||
type: "delegated_task.request",
|
||||
createdBy: "agent",
|
||||
creationSource: "mcp",
|
||||
commandId,
|
||||
parentThreadId: scope.threadId,
|
||||
parentRunId: parentRun.id,
|
||||
@@ -585,7 +831,7 @@ const make = Effect.gen(function* () {
|
||||
);
|
||||
}
|
||||
const key = yield* requestKey(input.clientRequestId);
|
||||
yield* orchestrator
|
||||
yield* threadManagement
|
||||
.dispatch({
|
||||
type: "run.interrupt",
|
||||
commandId: stableCommandId({
|
||||
@@ -644,9 +890,11 @@ const make = Effect.gen(function* () {
|
||||
title: request.title,
|
||||
index,
|
||||
});
|
||||
yield* orchestrator
|
||||
yield* threadManagement
|
||||
.dispatch({
|
||||
type: "thread.create",
|
||||
createdBy: "agent",
|
||||
creationSource: "mcp",
|
||||
commandId: stableCommandId({
|
||||
scope,
|
||||
requestKey: key,
|
||||
@@ -671,9 +919,11 @@ const make = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
if (request.prompt !== undefined) {
|
||||
yield* orchestrator
|
||||
yield* threadManagement
|
||||
.dispatch({
|
||||
type: "message.dispatch",
|
||||
createdBy: "agent",
|
||||
creationSource: "mcp",
|
||||
commandId: stableCommandId({
|
||||
scope,
|
||||
requestKey: key,
|
||||
@@ -707,6 +957,8 @@ const make = Effect.gen(function* () {
|
||||
runId: run?.id ?? null,
|
||||
status: run?.status ?? "idle",
|
||||
title: projection.thread.title,
|
||||
createdBy: projection.thread.createdBy,
|
||||
creationSource: projection.thread.creationSource,
|
||||
providerInstanceId: target.modelSelection.instanceId,
|
||||
model: target.modelSelection.model,
|
||||
} satisfies OrchestratorMcpCreatedThread;
|
||||
@@ -715,11 +967,188 @@ const make = Effect.gen(function* () {
|
||||
);
|
||||
return { threads: created };
|
||||
}),
|
||||
listThreads: (scope, input) =>
|
||||
Effect.gen(function* () {
|
||||
yield* requireCapability(scope);
|
||||
const parent = yield* loadProjection(scope.threadId);
|
||||
const projectThreads = yield* threadManagement
|
||||
.listProjectThreads({
|
||||
projectId: parent.thread.projectId,
|
||||
includeSubagents: input.includeSubagents !== false,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
failure("orchestration_error", `Unable to list threads: ${errorMessage(error)}`),
|
||||
),
|
||||
);
|
||||
const statuses = input.statuses === undefined ? null : new Set(input.statuses);
|
||||
const titleContains = input.titleContains?.toLocaleLowerCase();
|
||||
const filtered = projectThreads
|
||||
.filter((thread) => statuses === null || statuses.has(thread.status))
|
||||
.filter(
|
||||
(thread) =>
|
||||
titleContains === undefined ||
|
||||
thread.title.toLocaleLowerCase().includes(titleContains),
|
||||
);
|
||||
const cursor = input.cursor ?? 0;
|
||||
const limit = input.limit ?? DEFAULT_THREAD_LIST_LIMIT;
|
||||
const page = filtered.slice(cursor, cursor + limit);
|
||||
const nextCursor = cursor + page.length < filtered.length ? cursor + page.length : null;
|
||||
return {
|
||||
projectId: parent.thread.projectId,
|
||||
currentThreadId: scope.threadId,
|
||||
threads: page.map(listItemFromShell),
|
||||
nextCursor,
|
||||
total: filtered.length,
|
||||
} satisfies OrchestratorMcpThreadListResult;
|
||||
}),
|
||||
readThread: (scope, input) =>
|
||||
Effect.gen(function* () {
|
||||
const { target } = yield* loadScopedThread(scope, input.threadId);
|
||||
const view = input.view ?? "messages";
|
||||
const afterPosition = input.afterPosition ?? -1;
|
||||
const limit = input.limit ?? DEFAULT_THREAD_READ_LIMIT;
|
||||
const maxChars = input.maxCharsPerItem ?? DEFAULT_THREAD_ITEM_MAX_CHARS;
|
||||
const matching = target.visibleTurnItems
|
||||
.filter((row) => row.position > afterPosition)
|
||||
.filter(
|
||||
(row) =>
|
||||
view === "activity" ||
|
||||
row.item.type === "user_message" ||
|
||||
row.item.type === "assistant_message" ||
|
||||
row.item.type === "proposed_plan",
|
||||
);
|
||||
const page = matching.slice(0, limit);
|
||||
return {
|
||||
thread: threadDetail(target),
|
||||
recentRuns: target.runs
|
||||
.toSorted((left, right) => right.ordinal - left.ordinal)
|
||||
.slice(0, input.runLimit ?? DEFAULT_THREAD_RUN_LIMIT)
|
||||
.map(threadRun),
|
||||
items: page.map((row) => timelineItem({ row, maxChars, projection: target })),
|
||||
nextPosition: page.at(-1)?.position ?? null,
|
||||
hasMore: page.length < matching.length,
|
||||
} satisfies OrchestratorMcpThreadReadResult;
|
||||
}),
|
||||
sendToThread: (scope, input) =>
|
||||
Effect.gen(function* () {
|
||||
const { parent, target } = yield* loadScopedThread(scope, input.threadId);
|
||||
yield* resolveRuntimeMode(parent.thread.runtimeMode, target.thread.runtimeMode);
|
||||
yield* resolveInteractionMode(parent.thread.interactionMode, target.thread.interactionMode);
|
||||
|
||||
const mode = input.mode ?? "auto";
|
||||
const key = yield* requestKey(input.clientRequestId);
|
||||
const messageId = stableOperationMessageId({
|
||||
scope,
|
||||
requestKey: key,
|
||||
operation: "thread-send",
|
||||
});
|
||||
const result = yield* threadManagement
|
||||
.sendToThread({
|
||||
projectId: parent.thread.projectId,
|
||||
commandId: stableCommandId({
|
||||
scope,
|
||||
requestKey: key,
|
||||
operation: "thread-send",
|
||||
}),
|
||||
threadId: input.threadId,
|
||||
messageId,
|
||||
text: input.message,
|
||||
attachments: [],
|
||||
mode,
|
||||
createdBy: "agent",
|
||||
creationSource: "mcp",
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
failure(
|
||||
"thread_not_sendable",
|
||||
`Unable to send to thread ${input.threadId}: ${errorMessage(error)}`,
|
||||
),
|
||||
),
|
||||
);
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
messageId,
|
||||
runId: result.run.id,
|
||||
status: result.run.status,
|
||||
delivery: result.delivery,
|
||||
} satisfies OrchestratorMcpThreadSendResult;
|
||||
}),
|
||||
waitForThread: (scope, input) =>
|
||||
Effect.gen(function* () {
|
||||
const { parent } = yield* loadScopedThread(scope, input.threadId);
|
||||
const result = yield* threadManagement
|
||||
.waitForThread({
|
||||
projectId: parent.thread.projectId,
|
||||
threadId: input.threadId,
|
||||
...(input.runId === undefined ? {} : { runId: input.runId }),
|
||||
timeoutMs: Math.min(
|
||||
MAX_WAIT_TIMEOUT_MS,
|
||||
Math.max(1, input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS),
|
||||
),
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
failure(
|
||||
error.code === "run_not_found" ? "run_not_found" : "orchestration_error",
|
||||
error.message,
|
||||
),
|
||||
),
|
||||
);
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
runId: result.run?.id ?? null,
|
||||
status: result.run?.status ?? "idle",
|
||||
timedOut: result.timedOut,
|
||||
} satisfies OrchestratorMcpThreadWaitResult;
|
||||
}),
|
||||
interruptThread: (scope, input) =>
|
||||
Effect.gen(function* () {
|
||||
const { parent } = yield* loadScopedThread(scope, input.threadId);
|
||||
const key = yield* requestKey(input.clientRequestId);
|
||||
const result = yield* threadManagement
|
||||
.interruptThread({
|
||||
projectId: parent.thread.projectId,
|
||||
commandId: stableCommandId({
|
||||
scope,
|
||||
requestKey: key,
|
||||
operation: "thread-interrupt",
|
||||
}),
|
||||
threadId: input.threadId,
|
||||
...(input.runId === undefined ? {} : { runId: input.runId }),
|
||||
...(input.reason === undefined ? {} : { reason: input.reason }),
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
failure(
|
||||
isThreadManagementError(error) && error.code === "run_not_found"
|
||||
? "run_not_found"
|
||||
: "thread_not_interruptible",
|
||||
isThreadManagementError(error)
|
||||
? error.message
|
||||
: `Unable to interrupt thread ${input.threadId}: ${errorMessage(error)}`,
|
||||
),
|
||||
),
|
||||
);
|
||||
if (result.type === "no_active_run") {
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
runId: null,
|
||||
status: "no_active_run",
|
||||
} satisfies OrchestratorMcpThreadInterruptResult;
|
||||
}
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
runId: result.run.id,
|
||||
status: result.type === "already_terminal" ? result.run.status : "interrupt_requested",
|
||||
} satisfies OrchestratorMcpThreadInterruptResult;
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer: Layer.Layer<
|
||||
OrchestratorMcpService,
|
||||
never,
|
||||
Crypto.Crypto | OrchestratorV2 | ProviderRegistry
|
||||
Crypto.Crypto | ThreadManagementService | ProviderRegistry
|
||||
> = Layer.effect(OrchestratorMcpService, make);
|
||||
@@ -10,8 +10,14 @@ import {
|
||||
type OrchestrationV2ProviderThread,
|
||||
type OrchestrationV2ThreadProjection,
|
||||
OrchestratorMcpCreateThreadsResult,
|
||||
OrchestratorMcpCreatedThread,
|
||||
OrchestratorMcpDelegateTaskResult,
|
||||
OrchestratorMcpTaskCancelResult,
|
||||
OrchestratorMcpThreadInterruptResult,
|
||||
OrchestratorMcpThreadListResult,
|
||||
OrchestratorMcpThreadReadResult,
|
||||
OrchestratorMcpThreadSendResult,
|
||||
OrchestratorMcpThreadWaitResult,
|
||||
ProjectId,
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
@@ -34,6 +40,7 @@ import { McpSchema, McpServer } from "effect/unstable/ai";
|
||||
import { ClaudeProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/ClaudeAdapterV2.ts";
|
||||
import { CodexProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/CodexAdapterV2.ts";
|
||||
import { OrchestratorV2, type OrchestratorV2Shape } from "../orchestration-v2/Orchestrator.ts";
|
||||
import { layer as threadManagementServiceLayer } from "../orchestration-v2/ThreadManagementService.ts";
|
||||
import {
|
||||
type ProviderAdapterV2Event,
|
||||
ProviderAdapterProtocolError,
|
||||
@@ -60,8 +67,16 @@ const cancellationPrompt = "Remain active until the parent cancels this delegate
|
||||
const createdThreadPrompt = "Complete the newly created ordinary thread.";
|
||||
|
||||
const decodeCreateThreadsResult = Schema.decodeUnknownEffect(OrchestratorMcpCreateThreadsResult);
|
||||
const decodeCreatedThread = Schema.decodeUnknownEffect(OrchestratorMcpCreatedThread);
|
||||
const decodeDelegateTaskResult = Schema.decodeUnknownEffect(OrchestratorMcpDelegateTaskResult);
|
||||
const decodeTaskCancelResult = Schema.decodeUnknownEffect(OrchestratorMcpTaskCancelResult);
|
||||
const decodeThreadInterruptResult = Schema.decodeUnknownEffect(
|
||||
OrchestratorMcpThreadInterruptResult,
|
||||
);
|
||||
const decodeThreadListResult = Schema.decodeUnknownEffect(OrchestratorMcpThreadListResult);
|
||||
const decodeThreadReadResult = Schema.decodeUnknownEffect(OrchestratorMcpThreadReadResult);
|
||||
const decodeThreadSendResult = Schema.decodeUnknownEffect(OrchestratorMcpThreadSendResult);
|
||||
const decodeThreadWaitResult = Schema.decodeUnknownEffect(OrchestratorMcpThreadWaitResult);
|
||||
|
||||
const codexSelection = {
|
||||
instanceId: codexInstanceId,
|
||||
@@ -364,6 +379,10 @@ describe("orchestrator MCP toolkit", () => {
|
||||
},
|
||||
registryLayer,
|
||||
);
|
||||
const orchestrationLayer = Layer.merge(
|
||||
orchestratorLayer,
|
||||
threadManagementServiceLayer.pipe(Layer.provide(orchestratorLayer)),
|
||||
);
|
||||
const providerRegistryLayer = makeProviderRegistryLayer([
|
||||
makeProviderSnapshot({
|
||||
instanceId: codexInstanceId,
|
||||
@@ -383,7 +402,7 @@ describe("orchestrator MCP toolkit", () => {
|
||||
]);
|
||||
const testLayer = McpHttpServer.OrchestratorToolkitRegistrationLive.pipe(
|
||||
Layer.provideMerge(McpServer.McpServer.layer),
|
||||
Layer.provideMerge(orchestratorLayer),
|
||||
Layer.provideMerge(orchestrationLayer),
|
||||
Layer.provide(providerRegistryLayer),
|
||||
Layer.provide(NodeServices.layer),
|
||||
);
|
||||
@@ -393,6 +412,8 @@ describe("orchestrator MCP toolkit", () => {
|
||||
const server = yield* McpServer.McpServer;
|
||||
yield* orchestrator.dispatch({
|
||||
type: "thread.create",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command:mcp-parent:create"),
|
||||
threadId: parentThreadId,
|
||||
projectId,
|
||||
@@ -405,6 +426,8 @@ describe("orchestrator MCP toolkit", () => {
|
||||
});
|
||||
yield* orchestrator.dispatch({
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command:mcp-parent:start"),
|
||||
threadId: parentThreadId,
|
||||
messageId: MessageId.make("message:mcp-parent:start"),
|
||||
@@ -453,6 +476,19 @@ describe("orchestrator MCP toolkit", () => {
|
||||
({ tool }) => tool.name === "create_threads",
|
||||
);
|
||||
expect(createThreadsTool?.tool.annotations?.destructiveHint).toBe(true);
|
||||
const threadListTool = server.tools.find(({ tool }) => tool.name === "t3_thread_list");
|
||||
expect(threadListTool?.tool.annotations?.readOnlyHint).toBe(true);
|
||||
expect(threadListTool?.tool.annotations?.idempotentHint).toBe(true);
|
||||
const threadReadTool = server.tools.find(({ tool }) => tool.name === "t3_thread_read");
|
||||
expect(threadReadTool?.tool.annotations?.readOnlyHint).toBe(true);
|
||||
const threadSendTool = server.tools.find(({ tool }) => tool.name === "t3_thread_send");
|
||||
expect(threadSendTool?.tool.annotations?.destructiveHint).toBe(true);
|
||||
const threadWaitTool = server.tools.find(({ tool }) => tool.name === "t3_thread_wait");
|
||||
expect(threadWaitTool?.tool.annotations?.readOnlyHint).toBe(true);
|
||||
const threadInterruptTool = server.tools.find(
|
||||
({ tool }) => tool.name === "t3_thread_interrupt",
|
||||
);
|
||||
expect(threadInterruptTool?.tool.annotations?.destructiveHint).toBe(true);
|
||||
|
||||
const capabilities = yield* invoke("orchestrator_capabilities", {});
|
||||
expect(capabilities.isError).toBe(false);
|
||||
@@ -464,6 +500,8 @@ describe("orchestrator MCP toolkit", () => {
|
||||
asyncPolling: true,
|
||||
cancellation: true,
|
||||
batchThreadCreation: true,
|
||||
threadManagement: true,
|
||||
incrementalThreadRead: true,
|
||||
},
|
||||
providers: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
@@ -472,7 +510,7 @@ describe("orchestrator MCP toolkit", () => {
|
||||
}),
|
||||
expect.objectContaining({
|
||||
providerInstanceId: "opencode",
|
||||
canRunChildTask: false,
|
||||
canRunChildTask: true,
|
||||
}),
|
||||
]),
|
||||
});
|
||||
@@ -527,6 +565,10 @@ describe("orchestrator MCP toolkit", () => {
|
||||
relationshipToParent: "subagent",
|
||||
rootThreadId: parentThreadId,
|
||||
});
|
||||
expect(child.thread).toMatchObject({
|
||||
createdBy: "agent",
|
||||
creationSource: "mcp",
|
||||
});
|
||||
expect(child.thread.modelSelection).toEqual(claudeSelection);
|
||||
expect(
|
||||
child.messages
|
||||
@@ -645,10 +687,14 @@ describe("orchestrator MCP toolkit", () => {
|
||||
const promptedThread = created.threads[1]!;
|
||||
expect(emptyThread).toMatchObject({
|
||||
status: "idle",
|
||||
createdBy: "agent",
|
||||
creationSource: "mcp",
|
||||
providerInstanceId: codexInstanceId,
|
||||
model: codexModel,
|
||||
});
|
||||
expect(promptedThread).toMatchObject({
|
||||
createdBy: "agent",
|
||||
creationSource: "mcp",
|
||||
providerInstanceId: claudeInstanceId,
|
||||
model: claudeModel,
|
||||
});
|
||||
@@ -658,6 +704,10 @@ describe("orchestrator MCP toolkit", () => {
|
||||
relationshipToParent: null,
|
||||
rootThreadId: emptyThread.threadId,
|
||||
});
|
||||
expect(emptyProjection.thread).toMatchObject({
|
||||
createdBy: "agent",
|
||||
creationSource: "mcp",
|
||||
});
|
||||
expect(emptyProjection.thread.forkedFrom).toBeNull();
|
||||
expect(emptyProjection.runs).toEqual([]);
|
||||
const promptedProjection = yield* waitForProjection(
|
||||
@@ -679,6 +729,196 @@ describe("orchestrator MCP toolkit", () => {
|
||||
expect(repeatedCreated.threads.map((thread) => thread.threadId)).toEqual(
|
||||
created.threads.map((thread) => thread.threadId),
|
||||
);
|
||||
|
||||
const promptedReadCall = yield* invoke("t3_thread_read", {
|
||||
threadId: promptedThread.threadId,
|
||||
limit: 1,
|
||||
});
|
||||
const promptedRead = yield* decodeThreadReadResult(
|
||||
promptedReadCall.structuredContent,
|
||||
).pipe(Effect.orDie);
|
||||
expect(promptedRead.thread.status).toBe("completed");
|
||||
expect(promptedRead.thread).toMatchObject({
|
||||
createdBy: "agent",
|
||||
creationSource: "mcp",
|
||||
});
|
||||
expect(promptedRead.items.map((item) => item.type)).toEqual(["user_message"]);
|
||||
expect(promptedRead.items[0]).toMatchObject({
|
||||
createdBy: "agent",
|
||||
creationSource: "mcp",
|
||||
});
|
||||
expect(promptedRead.hasMore).toBe(true);
|
||||
const promptedReadNextCall = yield* invoke("t3_thread_read", {
|
||||
threadId: promptedThread.threadId,
|
||||
afterPosition: promptedRead.nextPosition,
|
||||
limit: 1,
|
||||
});
|
||||
const promptedReadNext = yield* decodeThreadReadResult(
|
||||
promptedReadNextCall.structuredContent,
|
||||
).pipe(Effect.orDie);
|
||||
expect(promptedReadNext.items.map((item) => item.type)).toEqual(["assistant_message"]);
|
||||
expect(promptedReadNext.items[0]?.text).toBe(
|
||||
`Claude completed: ${createdThreadPrompt}`,
|
||||
);
|
||||
|
||||
const ordinaryLoopPrompt = "Run an ordinary thread loop iteration.";
|
||||
const sendCall = yield* invoke("t3_thread_send", {
|
||||
threadId: emptyThread.threadId,
|
||||
message: ordinaryLoopPrompt,
|
||||
clientRequestId: "ordinary-loop-send-1",
|
||||
});
|
||||
const sent = yield* decodeThreadSendResult(sendCall.structuredContent).pipe(
|
||||
Effect.orDie,
|
||||
);
|
||||
expect(sent.delivery).toBe("started");
|
||||
const waitCall = yield* invoke("t3_thread_wait", {
|
||||
threadId: emptyThread.threadId,
|
||||
runId: sent.runId,
|
||||
timeoutMs: 10_000,
|
||||
});
|
||||
const waited = yield* decodeThreadWaitResult(waitCall.structuredContent).pipe(
|
||||
Effect.orDie,
|
||||
);
|
||||
expect(waited).toMatchObject({
|
||||
runId: sent.runId,
|
||||
status: "completed",
|
||||
timedOut: false,
|
||||
});
|
||||
const repeatedSendCall = yield* invoke("t3_thread_send", {
|
||||
threadId: emptyThread.threadId,
|
||||
message: ordinaryLoopPrompt,
|
||||
clientRequestId: "ordinary-loop-send-1",
|
||||
});
|
||||
const repeatedSend = yield* decodeThreadSendResult(
|
||||
repeatedSendCall.structuredContent,
|
||||
).pipe(Effect.orDie);
|
||||
expect(repeatedSend.runId).toBe(sent.runId);
|
||||
expect(
|
||||
(yield* orchestrator.getThreadProjection(emptyThread.threadId)).runs,
|
||||
).toHaveLength(1);
|
||||
|
||||
const activeThreadCall = yield* invoke("t3_thread_start", {
|
||||
prompt: cancellationPrompt,
|
||||
title: "Managed active thread",
|
||||
clientRequestId: "managed-active-thread-1",
|
||||
});
|
||||
const activeThread = yield* decodeCreatedThread(
|
||||
activeThreadCall.structuredContent,
|
||||
).pipe(Effect.orDie);
|
||||
const activeProjection = yield* waitForProjection(
|
||||
orchestrator,
|
||||
activeThread.threadId,
|
||||
(projection) =>
|
||||
projection.runs.some((run) => run.status === "running") &&
|
||||
projection.providerTurns.some((turn) => turn.status === "running"),
|
||||
);
|
||||
const activeRun = activeProjection.runs[0]!;
|
||||
const activeTimeoutCall = yield* invoke("t3_thread_wait", {
|
||||
threadId: activeThread.threadId,
|
||||
runId: activeRun.id,
|
||||
timeoutMs: 1,
|
||||
});
|
||||
const activeTimeout = yield* decodeThreadWaitResult(
|
||||
activeTimeoutCall.structuredContent,
|
||||
).pipe(Effect.orDie);
|
||||
expect(activeTimeout).toMatchObject({
|
||||
runId: activeRun.id,
|
||||
status: "running",
|
||||
timedOut: true,
|
||||
});
|
||||
const steerCall = yield* invoke("t3_thread_send", {
|
||||
threadId: activeThread.threadId,
|
||||
message: "Include the latest parent guidance before finishing.",
|
||||
mode: "steer",
|
||||
clientRequestId: "managed-active-steer-1",
|
||||
});
|
||||
const steered = yield* decodeThreadSendResult(steerCall.structuredContent).pipe(
|
||||
Effect.orDie,
|
||||
);
|
||||
expect(steered).toMatchObject({
|
||||
runId: activeRun.id,
|
||||
delivery: "steered",
|
||||
});
|
||||
const interruptCall = yield* invoke("t3_thread_interrupt", {
|
||||
threadId: activeThread.threadId,
|
||||
reason: "The orchestration loop has enough evidence.",
|
||||
clientRequestId: "managed-active-interrupt-1",
|
||||
});
|
||||
const interrupted = yield* decodeThreadInterruptResult(
|
||||
interruptCall.structuredContent,
|
||||
).pipe(Effect.orDie);
|
||||
expect(interrupted).toMatchObject({
|
||||
runId: activeRun.id,
|
||||
status: "interrupt_requested",
|
||||
});
|
||||
const interruptedWaitCall = yield* invoke("t3_thread_wait", {
|
||||
threadId: activeThread.threadId,
|
||||
runId: activeRun.id,
|
||||
timeoutMs: 10_000,
|
||||
});
|
||||
const interruptedWait = yield* decodeThreadWaitResult(
|
||||
interruptedWaitCall.structuredContent,
|
||||
).pipe(Effect.orDie);
|
||||
expect(interruptedWait.status).toBe("interrupted");
|
||||
const repeatedInterruptCall = yield* invoke("t3_thread_interrupt", {
|
||||
threadId: activeThread.threadId,
|
||||
runId: activeRun.id,
|
||||
});
|
||||
const repeatedInterrupt = yield* decodeThreadInterruptResult(
|
||||
repeatedInterruptCall.structuredContent,
|
||||
).pipe(Effect.orDie);
|
||||
expect(repeatedInterrupt.status).toBe("interrupted");
|
||||
|
||||
const foreignThreadId = ThreadId.make("thread:mcp-foreign-project");
|
||||
yield* orchestrator.dispatch({
|
||||
type: "thread.create",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command:mcp-foreign-project:create"),
|
||||
threadId: foreignThreadId,
|
||||
projectId: ProjectId.make("project:mcp-foreign"),
|
||||
title: "Foreign project thread",
|
||||
modelSelection: codexSelection,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: cwd,
|
||||
});
|
||||
const foreignReadCall = yield* invoke("t3_thread_read", {
|
||||
threadId: foreignThreadId,
|
||||
});
|
||||
expect(foreignReadCall.structuredContent).toMatchObject({
|
||||
_tag: "OrchestratorMcpFailure",
|
||||
code: "thread_not_found",
|
||||
});
|
||||
const listCall = yield* invoke("t3_thread_list", {
|
||||
includeSubagents: false,
|
||||
limit: 100,
|
||||
});
|
||||
const listed = yield* decodeThreadListResult(listCall.structuredContent).pipe(
|
||||
Effect.orDie,
|
||||
);
|
||||
expect(listed.projectId).toBe(projectId);
|
||||
expect(listed.threads.map((thread) => thread.threadId)).toEqual(
|
||||
expect.arrayContaining([
|
||||
parentThreadId,
|
||||
emptyThread.threadId,
|
||||
promptedThread.threadId,
|
||||
activeThread.threadId,
|
||||
]),
|
||||
);
|
||||
expect(
|
||||
listed.threads.find((thread) => thread.threadId === emptyThread.threadId),
|
||||
).toMatchObject({
|
||||
createdBy: "agent",
|
||||
creationSource: "mcp",
|
||||
});
|
||||
expect(listed.threads.some((thread) => thread.threadId === foreignThreadId)).toBe(
|
||||
false,
|
||||
);
|
||||
expect(
|
||||
listed.threads.some((thread) => thread.relationshipToParent === "subagent"),
|
||||
).toBe(false);
|
||||
}).pipe(Effect.provide(testLayer));
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -35,6 +35,56 @@ const handlers = {
|
||||
const service = yield* OrchestratorMcpService;
|
||||
return yield* service.createThreads(scope, input);
|
||||
}),
|
||||
t3_thread_start: (input) =>
|
||||
Effect.gen(function* () {
|
||||
const scope = yield* McpInvocationContext;
|
||||
const service = yield* OrchestratorMcpService;
|
||||
const result = yield* service.createThreads(scope, {
|
||||
...(input.clientRequestId === undefined ? {} : { clientRequestId: input.clientRequestId }),
|
||||
threads: [
|
||||
{
|
||||
prompt: input.prompt,
|
||||
...(input.title === undefined ? {} : { title: input.title }),
|
||||
...(input.target === undefined ? {} : { target: input.target }),
|
||||
...(input.runtimeMode === undefined ? {} : { runtimeMode: input.runtimeMode }),
|
||||
...(input.interactionMode === undefined
|
||||
? {}
|
||||
: { interactionMode: input.interactionMode }),
|
||||
},
|
||||
],
|
||||
});
|
||||
return result.threads[0]!;
|
||||
}),
|
||||
t3_thread_list: (input) =>
|
||||
Effect.gen(function* () {
|
||||
const scope = yield* McpInvocationContext;
|
||||
const service = yield* OrchestratorMcpService;
|
||||
return yield* service.listThreads(scope, input);
|
||||
}),
|
||||
t3_thread_read: (input) =>
|
||||
Effect.gen(function* () {
|
||||
const scope = yield* McpInvocationContext;
|
||||
const service = yield* OrchestratorMcpService;
|
||||
return yield* service.readThread(scope, input);
|
||||
}),
|
||||
t3_thread_send: (input) =>
|
||||
Effect.gen(function* () {
|
||||
const scope = yield* McpInvocationContext;
|
||||
const service = yield* OrchestratorMcpService;
|
||||
return yield* service.sendToThread(scope, input);
|
||||
}),
|
||||
t3_thread_wait: (input) =>
|
||||
Effect.gen(function* () {
|
||||
const scope = yield* McpInvocationContext;
|
||||
const service = yield* OrchestratorMcpService;
|
||||
return yield* service.waitForThread(scope, input);
|
||||
}),
|
||||
t3_thread_interrupt: (input) =>
|
||||
Effect.gen(function* () {
|
||||
const scope = yield* McpInvocationContext;
|
||||
const service = yield* OrchestratorMcpService;
|
||||
return yield* service.interruptThread(scope, input);
|
||||
}),
|
||||
} satisfies Parameters<typeof OrchestratorToolkit.toLayer>[0];
|
||||
|
||||
export const OrchestratorToolkitHandlersLive = OrchestratorToolkit.toLayer(handlers);
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
OrchestratorMcpCapabilitiesResult,
|
||||
OrchestratorMcpCreatedThread,
|
||||
OrchestratorMcpCreateThreadsInput,
|
||||
OrchestratorMcpCreateThreadsResult,
|
||||
OrchestratorMcpDelegateTaskInput,
|
||||
@@ -8,6 +9,17 @@ import {
|
||||
OrchestratorMcpTaskCancelInput,
|
||||
OrchestratorMcpTaskCancelResult,
|
||||
OrchestratorMcpTaskStatusInput,
|
||||
OrchestratorMcpThreadInterruptInput,
|
||||
OrchestratorMcpThreadInterruptResult,
|
||||
OrchestratorMcpThreadListInput,
|
||||
OrchestratorMcpThreadListResult,
|
||||
OrchestratorMcpThreadReadInput,
|
||||
OrchestratorMcpThreadReadResult,
|
||||
OrchestratorMcpThreadSendInput,
|
||||
OrchestratorMcpThreadSendResult,
|
||||
OrchestratorMcpThreadStartInput,
|
||||
OrchestratorMcpThreadWaitInput,
|
||||
OrchestratorMcpThreadWaitResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { Tool, Toolkit } from "effect/unstable/ai";
|
||||
|
||||
@@ -81,10 +93,96 @@ export const CreateThreadsTool = Tool.make("create_threads", {
|
||||
.annotate(Tool.Destructive, true)
|
||||
.annotate(Tool.OpenWorld, true);
|
||||
|
||||
export const ThreadStartTool = Tool.make("t3_thread_start", {
|
||||
description:
|
||||
"Create an ordinary top-level T3 thread and immediately start its first turn. The new thread inherits this thread's project, checkout, provider, model, and runtime settings unless overridden. Use t3_thread_wait and t3_thread_read to collect its result.",
|
||||
parameters: OrchestratorMcpThreadStartInput,
|
||||
success: OrchestratorMcpCreatedThread,
|
||||
failure: OrchestratorMcpFailure,
|
||||
failureMode: "return",
|
||||
dependencies,
|
||||
})
|
||||
.annotate(Tool.Title, "Start a T3 thread")
|
||||
.annotate(Tool.Destructive, true)
|
||||
.annotate(Tool.OpenWorld, true);
|
||||
|
||||
export const ThreadListTool = Tool.make("t3_thread_list", {
|
||||
description:
|
||||
"List T3 threads in the calling thread's project, newest first. Filter by durable run status or title and paginate with the returned cursor. Threads from other projects are never exposed.",
|
||||
parameters: OrchestratorMcpThreadListInput,
|
||||
success: OrchestratorMcpThreadListResult,
|
||||
failure: OrchestratorMcpFailure,
|
||||
failureMode: "return",
|
||||
dependencies,
|
||||
})
|
||||
.annotate(Tool.Title, "List T3 threads")
|
||||
.annotate(Tool.Readonly, true)
|
||||
.annotate(Tool.Destructive, false)
|
||||
.annotate(Tool.Idempotent, true);
|
||||
|
||||
export const ThreadReadTool = Tool.make("t3_thread_read", {
|
||||
description:
|
||||
"Read durable state and a paginated timeline from a T3 thread in the calling project. The default messages view returns user messages, assistant messages, and proposed plans; activity returns all summarized timeline items. Continue with afterPosition=nextPosition.",
|
||||
parameters: OrchestratorMcpThreadReadInput,
|
||||
success: OrchestratorMcpThreadReadResult,
|
||||
failure: OrchestratorMcpFailure,
|
||||
failureMode: "return",
|
||||
dependencies,
|
||||
})
|
||||
.annotate(Tool.Title, "Read a T3 thread")
|
||||
.annotate(Tool.Readonly, true)
|
||||
.annotate(Tool.Destructive, false)
|
||||
.annotate(Tool.Idempotent, true);
|
||||
|
||||
export const ThreadSendTool = Tool.make("t3_thread_send", {
|
||||
description:
|
||||
"Send a message to a T3 thread in the calling project. mode='auto' starts an idle thread, steers a fully active turn, or queues behind a turn that is not yet steerable. Use queue for a separate follow-up turn, steer for an in-flight update, or restart to interrupt-and-restart the active turn. clientRequestId makes retries idempotent.",
|
||||
parameters: OrchestratorMcpThreadSendInput,
|
||||
success: OrchestratorMcpThreadSendResult,
|
||||
failure: OrchestratorMcpFailure,
|
||||
failureMode: "return",
|
||||
dependencies,
|
||||
})
|
||||
.annotate(Tool.Title, "Send to a T3 thread")
|
||||
.annotate(Tool.Destructive, true)
|
||||
.annotate(Tool.OpenWorld, true);
|
||||
|
||||
export const ThreadWaitTool = Tool.make("t3_thread_wait", {
|
||||
description:
|
||||
"Wait for a T3 thread run to reach a terminal durable state. Without runId, the latest run at call time is selected; an idle thread returns immediately. Timeout does not interrupt work, so call again or use t3_thread_read/list after timedOut=true.",
|
||||
parameters: OrchestratorMcpThreadWaitInput,
|
||||
success: OrchestratorMcpThreadWaitResult,
|
||||
failure: OrchestratorMcpFailure,
|
||||
failureMode: "return",
|
||||
dependencies,
|
||||
})
|
||||
.annotate(Tool.Title, "Wait for a T3 thread")
|
||||
.annotate(Tool.Readonly, true)
|
||||
.annotate(Tool.Destructive, false)
|
||||
.annotate(Tool.Idempotent, true);
|
||||
|
||||
export const ThreadInterruptTool = Tool.make("t3_thread_interrupt", {
|
||||
description:
|
||||
"Request interruption of a running turn in a T3 thread in the calling project. Without runId, the newest interruptible run is selected. Terminal runs and threads without an active turn return without another side effect. clientRequestId makes retries idempotent.",
|
||||
parameters: OrchestratorMcpThreadInterruptInput,
|
||||
success: OrchestratorMcpThreadInterruptResult,
|
||||
failure: OrchestratorMcpFailure,
|
||||
failureMode: "return",
|
||||
dependencies,
|
||||
})
|
||||
.annotate(Tool.Title, "Interrupt a T3 thread")
|
||||
.annotate(Tool.Destructive, true);
|
||||
|
||||
export const OrchestratorToolkit = Toolkit.make(
|
||||
OrchestratorCapabilitiesTool,
|
||||
DelegateTaskTool,
|
||||
TaskStatusTool,
|
||||
TaskCancelTool,
|
||||
CreateThreadsTool,
|
||||
ThreadStartTool,
|
||||
ThreadListTool,
|
||||
ThreadReadTool,
|
||||
ThreadSendTool,
|
||||
ThreadWaitTool,
|
||||
ThreadInterruptTool,
|
||||
);
|
||||
@@ -99,6 +99,8 @@ describe.runIf(process.env.T3_ACP_REGISTRY_LIVE_ORCHESTRATOR === "1")(
|
||||
|
||||
yield* orchestrator.dispatch({
|
||||
type: "thread.create",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command:acp-registry-live:create"),
|
||||
threadId,
|
||||
projectId,
|
||||
@@ -114,6 +116,8 @@ describe.runIf(process.env.T3_ACP_REGISTRY_LIVE_ORCHESTRATOR === "1")(
|
||||
);
|
||||
yield* orchestrator.dispatch({
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command:acp-registry-live:first"),
|
||||
threadId,
|
||||
messageId: MessageId.make("message:acp-registry-live:first"),
|
||||
@@ -136,6 +140,8 @@ describe.runIf(process.env.T3_ACP_REGISTRY_LIVE_ORCHESTRATOR === "1")(
|
||||
yield* Console.log("First ACP turn completed; dispatching continuation prompt.");
|
||||
yield* orchestrator.dispatch({
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command:acp-registry-live:second"),
|
||||
threadId,
|
||||
messageId: MessageId.make("message:acp-registry-live:second"),
|
||||
|
||||
@@ -81,6 +81,8 @@ function makeTurnInput(input: {
|
||||
const modelSelection = { instanceId: input.instanceId, model: "default" } as const;
|
||||
return {
|
||||
appThread: {
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
id: input.threadId,
|
||||
projectId: ProjectId.make(`project:${input.threadId}`),
|
||||
title: "ACP adapter test",
|
||||
@@ -110,6 +112,8 @@ function makeTurnInput(input: {
|
||||
rootNodeId: NodeId.make(`node:${suffix}`),
|
||||
providerThread: input.providerThread,
|
||||
message: {
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
messageId: MessageId.make(`message:${suffix}`),
|
||||
text: "test prompt",
|
||||
attachments: [],
|
||||
|
||||
@@ -783,6 +783,8 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
|
||||
nativeItemId: segment.nativeItemId,
|
||||
});
|
||||
const message: OrchestrationV2ConversationMessage = {
|
||||
createdBy: "agent",
|
||||
creationSource: "provider",
|
||||
id: messageId,
|
||||
threadId: context.input.threadId,
|
||||
runId: context.input.runId,
|
||||
@@ -1143,6 +1145,8 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
|
||||
const previous = current.messages.get(key);
|
||||
const messages = new Map(current.messages);
|
||||
messages.set(key, {
|
||||
createdBy: previous?.createdBy ?? (role === "user" ? "user" : "agent"),
|
||||
creationSource: previous?.creationSource ?? "provider",
|
||||
id: messageId,
|
||||
threadId: input.threadId,
|
||||
runId: null,
|
||||
@@ -1855,6 +1859,8 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
|
||||
},
|
||||
});
|
||||
yield* rememberSnapshotMessage({
|
||||
createdBy: turnInput.message.createdBy,
|
||||
creationSource: turnInput.message.creationSource,
|
||||
id: turnInput.message.messageId,
|
||||
threadId: turnInput.threadId,
|
||||
runId: turnInput.runId,
|
||||
|
||||
@@ -388,6 +388,8 @@ describe("ClaudeAdapterV2 native fork", () => {
|
||||
|
||||
yield* runtime.startTurn({
|
||||
appThread: {
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
id: targetThreadId,
|
||||
projectId: ProjectId.make("project-claude-fork-target"),
|
||||
title: "Claude fork target",
|
||||
@@ -420,6 +422,8 @@ describe("ClaudeAdapterV2 native fork", () => {
|
||||
rootNodeId: NodeId.make("node-claude-fork-target-root"),
|
||||
providerThread: forkedProviderThread,
|
||||
message: {
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
messageId: MessageId.make("message-claude-fork-target"),
|
||||
text: "Respond with fork ok",
|
||||
attachments: [],
|
||||
|
||||
@@ -1589,6 +1589,8 @@ function buildAssistantArtifacts(input: {
|
||||
completedAt: input.completedAt,
|
||||
},
|
||||
message: {
|
||||
createdBy: "agent",
|
||||
creationSource: "provider",
|
||||
id: messageId,
|
||||
threadId: input.turnInput.threadId,
|
||||
runId: input.turnInput.runId,
|
||||
@@ -2016,6 +2018,8 @@ export function makeClaudeAdapterV2(
|
||||
ordinal: input.context.subagentsByTaskId.size,
|
||||
}),
|
||||
now,
|
||||
createdBy: "agent",
|
||||
creationSource: "provider",
|
||||
});
|
||||
yield* emitProviderEvent({
|
||||
type: "app_thread.created",
|
||||
|
||||
@@ -1451,6 +1451,8 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
|
||||
ordinal: index + 1,
|
||||
}),
|
||||
now,
|
||||
createdBy: "agent",
|
||||
creationSource: "provider",
|
||||
});
|
||||
const promptNativeItemId = `${nativeItemId}:prompt`;
|
||||
const promptArtifacts = makeSubagentConversationArtifacts({
|
||||
@@ -2303,6 +2305,8 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
|
||||
completedAt,
|
||||
};
|
||||
const message: OrchestrationV2ConversationMessage = {
|
||||
createdBy: "agent",
|
||||
creationSource: "provider",
|
||||
id: messageId,
|
||||
threadId: context.projectionThreadId,
|
||||
runId: context.projectionRunId,
|
||||
|
||||
@@ -953,6 +953,8 @@ export function makeCursorAdapterV2(
|
||||
type: "message.updated",
|
||||
provider: CURSOR_PROVIDER,
|
||||
message: {
|
||||
createdBy: "agent",
|
||||
creationSource: "provider",
|
||||
id: messageId,
|
||||
threadId: context.input.threadId,
|
||||
runId: context.input.runId,
|
||||
@@ -1548,6 +1550,8 @@ export function makeCursorAdapterV2(
|
||||
ordinal: input.context.subagents.size,
|
||||
}),
|
||||
now,
|
||||
createdBy: "agent",
|
||||
creationSource: "provider",
|
||||
}),
|
||||
});
|
||||
const promptNativeId = `${nativeItemId}:prompt`;
|
||||
@@ -2334,6 +2338,8 @@ export function makeCursorAdapterV2(
|
||||
}
|
||||
return [
|
||||
{
|
||||
createdBy: message.type === "user" ? "user" : "agent",
|
||||
creationSource: "provider",
|
||||
id: idAllocator.derive.messageFromProviderItem({
|
||||
provider: CURSOR_PROVIDER,
|
||||
nativeItemId: message.uuid,
|
||||
|
||||
@@ -926,6 +926,8 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
|
||||
nativeItemId: part.id,
|
||||
});
|
||||
const message: OrchestrationV2ConversationMessage = {
|
||||
createdBy: "agent",
|
||||
creationSource: "provider",
|
||||
id: messageId,
|
||||
threadId: turn.threadId,
|
||||
runId: turn.runId,
|
||||
@@ -1060,6 +1062,8 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
|
||||
ordinal: itemOrdinal(turn, part.id),
|
||||
}),
|
||||
now,
|
||||
createdBy: "agent",
|
||||
creationSource: "provider",
|
||||
});
|
||||
const childProviderThread: OrchestrationV2ProviderThread = {
|
||||
id: context.childProviderThreadId,
|
||||
@@ -1829,6 +1833,8 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
|
||||
nativeItemId: part.messageID,
|
||||
});
|
||||
const projected: OrchestrationV2ConversationMessage = {
|
||||
createdBy: "agent",
|
||||
creationSource: "provider",
|
||||
id: messageId,
|
||||
threadId: turn.threadId,
|
||||
runId: null,
|
||||
@@ -1850,6 +1856,8 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
|
||||
type: "turn_item.updated",
|
||||
provider: OPENCODE_PROVIDER,
|
||||
turnItem: {
|
||||
createdBy: "agent",
|
||||
creationSource: "provider",
|
||||
id: turnItemId,
|
||||
threadId: turn.threadId,
|
||||
runId: null,
|
||||
@@ -2187,6 +2195,8 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
|
||||
const createdAt = dateTimeFromEpoch(info.time.created, snapshotNow);
|
||||
return [
|
||||
{
|
||||
createdBy: info.role === "user" ? "user" : "agent",
|
||||
creationSource: "provider",
|
||||
id: idAllocator.derive.messageFromProviderItem({
|
||||
provider: OPENCODE_PROVIDER,
|
||||
nativeItemId: info.id,
|
||||
|
||||
@@ -82,6 +82,8 @@ describe.runIf(process.env.T3_CURSOR_LIVE_ORCHESTRATOR === "1")(
|
||||
|
||||
yield* orchestrator.dispatch({
|
||||
type: "thread.create",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command:cursor-live-portable-fork:create"),
|
||||
threadId: sourceThreadId,
|
||||
projectId,
|
||||
@@ -94,6 +96,8 @@ describe.runIf(process.env.T3_CURSOR_LIVE_ORCHESTRATOR === "1")(
|
||||
});
|
||||
yield* orchestrator.dispatch({
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command:cursor-live-portable-fork:source"),
|
||||
threadId: sourceThreadId,
|
||||
messageId: MessageId.make("message:cursor-live-portable-fork:source"),
|
||||
@@ -107,6 +111,8 @@ describe.runIf(process.env.T3_CURSOR_LIVE_ORCHESTRATOR === "1")(
|
||||
|
||||
yield* orchestrator.dispatch({
|
||||
type: "thread.fork",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command:cursor-live-portable-fork:fork"),
|
||||
sourceThreadId,
|
||||
targetThreadId,
|
||||
@@ -115,6 +121,8 @@ describe.runIf(process.env.T3_CURSOR_LIVE_ORCHESTRATOR === "1")(
|
||||
});
|
||||
yield* orchestrator.dispatch({
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command:cursor-live-portable-fork:target"),
|
||||
threadId: targetThreadId,
|
||||
messageId: MessageId.make("message:cursor-live-portable-fork:target"),
|
||||
|
||||
@@ -78,6 +78,8 @@ describe.runIf(process.env.T3_GROK_LIVE_ORCHESTRATOR === "1")("Grok V2 live orch
|
||||
|
||||
yield* orchestrator.dispatch({
|
||||
type: "thread.create",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command:grok-live-portable-fork:create"),
|
||||
threadId: sourceThreadId,
|
||||
projectId,
|
||||
@@ -91,6 +93,8 @@ describe.runIf(process.env.T3_GROK_LIVE_ORCHESTRATOR === "1")("Grok V2 live orch
|
||||
yield* Console.log("Grok live source thread created; dispatching source prompt.");
|
||||
yield* orchestrator.dispatch({
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command:grok-live-portable-fork:source"),
|
||||
threadId: sourceThreadId,
|
||||
messageId: MessageId.make("message:grok-live-portable-fork:source"),
|
||||
@@ -105,6 +109,8 @@ describe.runIf(process.env.T3_GROK_LIVE_ORCHESTRATOR === "1")("Grok V2 live orch
|
||||
|
||||
yield* orchestrator.dispatch({
|
||||
type: "thread.fork",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command:grok-live-portable-fork:fork"),
|
||||
sourceThreadId,
|
||||
targetThreadId,
|
||||
@@ -113,6 +119,8 @@ describe.runIf(process.env.T3_GROK_LIVE_ORCHESTRATOR === "1")("Grok V2 live orch
|
||||
});
|
||||
yield* orchestrator.dispatch({
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command:grok-live-portable-fork:target"),
|
||||
threadId: targetThreadId,
|
||||
messageId: MessageId.make("message:grok-live-portable-fork:target"),
|
||||
|
||||
@@ -689,6 +689,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
messageId: message.id,
|
||||
text: message.text,
|
||||
attachments: message.attachments,
|
||||
createdBy: message.createdBy,
|
||||
creationSource: message.creationSource,
|
||||
},
|
||||
modelSelection,
|
||||
runtimePolicy: resolvedRuntimePolicy,
|
||||
@@ -709,6 +711,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
const now = yield* DateTime.now;
|
||||
const emitEvent = emit(events, command);
|
||||
const thread: OrchestrationV2AppThread = {
|
||||
createdBy: command.createdBy,
|
||||
creationSource: command.creationSource,
|
||||
id: command.threadId,
|
||||
projectId: command.projectId,
|
||||
title: command.title,
|
||||
@@ -785,6 +789,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
const emitEvent = emit(events, command);
|
||||
const targetThread: OrchestrationV2AppThread = {
|
||||
...sourceProjection.thread,
|
||||
createdBy: command.createdBy,
|
||||
creationSource: command.creationSource,
|
||||
id: command.targetThreadId,
|
||||
title: command.title ?? `${sourceProjection.thread.title} fork`,
|
||||
activeProviderThreadId: null,
|
||||
@@ -822,7 +828,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
targetRunId: null,
|
||||
status: "pending",
|
||||
resolution: null,
|
||||
createdBy: "user",
|
||||
createdBy: command.createdBy,
|
||||
error:
|
||||
sourceProviderThread?.nativeThreadRef?.strength === "strong"
|
||||
? null
|
||||
@@ -953,7 +959,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
targetRunId: null,
|
||||
status: "pending",
|
||||
resolution: null,
|
||||
createdBy: "user",
|
||||
createdBy: command.createdBy,
|
||||
error:
|
||||
sourceProviderThread === undefined ? "Source merge-back run has no provider thread." : null,
|
||||
createdAt: now,
|
||||
@@ -996,6 +1002,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
readonly messageId: OrchestrationV2ConversationMessage["id"];
|
||||
readonly text: string;
|
||||
readonly attachments: ReadonlyArray<ChatAttachment>;
|
||||
readonly createdBy: OrchestrationV2ConversationMessage["createdBy"];
|
||||
readonly creationSource: OrchestrationV2ConversationMessage["creationSource"];
|
||||
readonly forceRestart: boolean;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -1073,6 +1081,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const message: OrchestrationV2ConversationMessage = {
|
||||
createdBy: input.createdBy,
|
||||
creationSource: input.creationSource,
|
||||
id: input.messageId,
|
||||
threadId: input.command.threadId,
|
||||
runId: messageInput.runId,
|
||||
@@ -1085,6 +1095,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
updatedAt: now,
|
||||
};
|
||||
const turnItem: OrchestrationV2TurnItem = {
|
||||
createdBy: input.createdBy,
|
||||
creationSource: input.creationSource,
|
||||
id: idAllocator.derive.userTurnItem({ messageId: input.messageId }),
|
||||
threadId: input.command.threadId,
|
||||
runId: messageInput.runId,
|
||||
@@ -1149,6 +1161,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
messageId: input.messageId,
|
||||
text: input.text,
|
||||
attachments: input.attachments,
|
||||
createdBy: input.createdBy,
|
||||
creationSource: input.creationSource,
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
@@ -1416,6 +1430,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
messageId: input.messageId,
|
||||
text: input.text,
|
||||
attachments: input.attachments,
|
||||
createdBy: input.createdBy,
|
||||
creationSource: input.creationSource,
|
||||
},
|
||||
modelSelection: input.modelSelection,
|
||||
runtimePolicy: resolvedRuntimePolicy,
|
||||
@@ -1455,6 +1471,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
messageId: command.messageId,
|
||||
text: command.text,
|
||||
attachments: command.attachments,
|
||||
createdBy: command.createdBy,
|
||||
creationSource: command.creationSource,
|
||||
forceRestart: dispatchMode.type === "restart_active",
|
||||
});
|
||||
return;
|
||||
@@ -1607,6 +1625,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
completedAt: null,
|
||||
};
|
||||
const message: OrchestrationV2ConversationMessage = {
|
||||
createdBy: command.createdBy,
|
||||
creationSource: command.creationSource,
|
||||
id: command.messageId,
|
||||
threadId: command.threadId,
|
||||
runId,
|
||||
@@ -1619,6 +1639,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
updatedAt: now,
|
||||
};
|
||||
const turnItem: OrchestrationV2TurnItem = {
|
||||
createdBy: command.createdBy,
|
||||
creationSource: command.creationSource,
|
||||
id: idAllocator.derive.userTurnItem({ messageId: command.messageId }),
|
||||
threadId: command.threadId,
|
||||
runId,
|
||||
@@ -2228,6 +2250,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
completedAt: null,
|
||||
};
|
||||
const message: OrchestrationV2ConversationMessage = {
|
||||
createdBy: command.createdBy,
|
||||
creationSource: command.creationSource,
|
||||
id: command.messageId,
|
||||
threadId: command.threadId,
|
||||
runId,
|
||||
@@ -2240,6 +2264,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
updatedAt: now,
|
||||
};
|
||||
const turnItem: OrchestrationV2TurnItem = {
|
||||
createdBy: command.createdBy,
|
||||
creationSource: command.creationSource,
|
||||
id: idAllocator.derive.userTurnItem({ messageId: command.messageId }),
|
||||
threadId: command.threadId,
|
||||
runId,
|
||||
@@ -2427,7 +2453,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
: "delta_context",
|
||||
contextHandoffId: providerSwitchHandoff.id,
|
||||
},
|
||||
createdBy: "user",
|
||||
createdBy: command.createdBy,
|
||||
error: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -2629,6 +2655,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
messageId: command.messageId,
|
||||
text: providerMessageText,
|
||||
attachments: command.attachments,
|
||||
createdBy: command.createdBy,
|
||||
creationSource: command.creationSource,
|
||||
},
|
||||
modelSelection,
|
||||
runtimePolicy: resolvedRuntimePolicy,
|
||||
@@ -2715,6 +2743,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
modelSelection: command.modelSelection,
|
||||
title: taskTitle,
|
||||
now,
|
||||
createdBy: command.createdBy,
|
||||
creationSource: command.creationSource,
|
||||
}),
|
||||
runtimeMode: command.runtimeMode,
|
||||
interactionMode: command.interactionMode,
|
||||
@@ -2725,7 +2755,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
runId: parentRun.id,
|
||||
parentNodeId: command.parentNodeId,
|
||||
origin: "app_owned",
|
||||
createdBy: "agent",
|
||||
createdBy: command.createdBy,
|
||||
provider: command.modelSelection.instanceId,
|
||||
providerThreadId: null,
|
||||
childThreadId,
|
||||
@@ -2819,6 +2849,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
|
||||
const childMessageCommand = {
|
||||
type: "message.dispatch",
|
||||
createdBy: command.createdBy,
|
||||
creationSource: command.creationSource,
|
||||
commandId: command.commandId,
|
||||
threadId: childThreadId,
|
||||
messageId: childMessageId,
|
||||
@@ -2868,7 +2900,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
targetRunId: childRun.id,
|
||||
status: "consumed",
|
||||
resolution: null,
|
||||
createdBy: "agent",
|
||||
createdBy: command.createdBy,
|
||||
error: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -3109,6 +3141,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
messageId: queuedMessage.id,
|
||||
text: queuedMessage.text,
|
||||
attachments: queuedMessage.attachments,
|
||||
createdBy: queuedMessage.createdBy,
|
||||
creationSource: queuedMessage.creationSource,
|
||||
forceRestart: false,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -48,6 +48,8 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => {
|
||||
threadId,
|
||||
occurredAt: now,
|
||||
payload: {
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
id: threadId,
|
||||
projectId,
|
||||
title: "Projection shell",
|
||||
@@ -170,6 +172,8 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => {
|
||||
threadId,
|
||||
occurredAt: now,
|
||||
payload: {
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
id: threadId,
|
||||
projectId,
|
||||
title: "Projection rollback prune",
|
||||
@@ -344,6 +348,8 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => {
|
||||
provider: "codex",
|
||||
occurredAt: now,
|
||||
payload: {
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
id: userMessageId,
|
||||
threadId,
|
||||
runId,
|
||||
@@ -365,6 +371,8 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => {
|
||||
provider: "codex",
|
||||
occurredAt: now,
|
||||
payload: {
|
||||
createdBy: "agent",
|
||||
creationSource: "provider",
|
||||
id: assistantMessageId,
|
||||
threadId,
|
||||
runId,
|
||||
@@ -386,6 +394,8 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => {
|
||||
provider: "codex",
|
||||
occurredAt: now,
|
||||
payload: {
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
id: userTurnItemId,
|
||||
threadId,
|
||||
runId,
|
||||
@@ -533,6 +543,8 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => {
|
||||
threadId: sourceThreadId,
|
||||
occurredAt: now,
|
||||
payload: {
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
id: sourceThreadId,
|
||||
projectId,
|
||||
title: "Projection fork source rollback source",
|
||||
@@ -561,6 +573,8 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => {
|
||||
threadId: targetThreadId,
|
||||
occurredAt: now,
|
||||
payload: {
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
id: targetThreadId,
|
||||
projectId,
|
||||
title: "Projection fork source rollback target",
|
||||
@@ -629,6 +643,8 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => {
|
||||
provider: "codex",
|
||||
occurredAt: now,
|
||||
payload: {
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
id: TurnItemId.make(`turn-item:projection-fork-source-rollback:user:${ordinal}`),
|
||||
threadId: sourceThreadId,
|
||||
runId,
|
||||
|
||||
@@ -588,6 +588,8 @@ export function threadShellFromProjection(
|
||||
): OrchestrationV2ThreadShell {
|
||||
const latestRun = projection.runs.at(-1) ?? null;
|
||||
return {
|
||||
createdBy: projection.thread.createdBy,
|
||||
creationSource: projection.thread.creationSource,
|
||||
id: projection.thread.id,
|
||||
projectId: projection.thread.projectId,
|
||||
title: projection.thread.title,
|
||||
@@ -703,6 +705,8 @@ function shellFromState(input: {
|
||||
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,
|
||||
|
||||
@@ -49,6 +49,8 @@ export const ProviderAdapterV2TurnMessage = Schema.Struct({
|
||||
messageId: MessageId,
|
||||
text: Schema.String,
|
||||
attachments: Schema.Array(ChatAttachment),
|
||||
createdBy: OrchestrationV2ConversationMessage.fields.createdBy,
|
||||
creationSource: OrchestrationV2ConversationMessage.fields.creationSource,
|
||||
});
|
||||
export type ProviderAdapterV2TurnMessage = typeof ProviderAdapterV2TurnMessage.Type;
|
||||
|
||||
|
||||
@@ -61,6 +61,8 @@ function threadCreatedEvent(
|
||||
nativeThreadId: "native-thread",
|
||||
});
|
||||
const thread: OrchestrationV2AppThread = {
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
id: threadId,
|
||||
projectId,
|
||||
title: "Provider event ingestor",
|
||||
@@ -263,6 +265,8 @@ layer("ProviderEventIngestorV2", (it) => {
|
||||
type: "message.updated",
|
||||
provider: "codex",
|
||||
message: {
|
||||
createdBy: "agent",
|
||||
creationSource: "provider",
|
||||
id: MessageId.make("message:subagent-response"),
|
||||
threadId: childThreadId,
|
||||
runId: null,
|
||||
|
||||
@@ -112,6 +112,8 @@ function makeThreadCreatedEvent(input: {
|
||||
nativeThreadId: "native-thread",
|
||||
});
|
||||
const thread: OrchestrationV2AppThread = {
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
id: input.threadId,
|
||||
projectId,
|
||||
title: "Provider session manager",
|
||||
@@ -608,6 +610,8 @@ it.effect(
|
||||
rootNodeId,
|
||||
providerThread,
|
||||
message: {
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
messageId: yield* idAllocator.allocate.message({ threadId, ordinal: 1 }),
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
@@ -894,6 +898,8 @@ it.effect(
|
||||
rootNodeId: idAllocator.derive.rootNode({ runId: firstRunId }),
|
||||
providerThread: firstProviderThread,
|
||||
message: {
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
messageId: yield* idAllocator.allocate.message({ threadId: firstThreadId, ordinal: 1 }),
|
||||
text: "first",
|
||||
attachments: [],
|
||||
@@ -911,6 +917,8 @@ it.effect(
|
||||
rootNodeId: idAllocator.derive.rootNode({ runId: secondRunId }),
|
||||
providerThread: secondProviderThread,
|
||||
message: {
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
messageId: yield* idAllocator.allocate.message({
|
||||
threadId: secondThreadId,
|
||||
ordinal: 1,
|
||||
|
||||
@@ -3,7 +3,9 @@ import type {
|
||||
ModelSelection,
|
||||
NodeId,
|
||||
OrchestrationV2AppThread,
|
||||
OrchestrationV2Actor,
|
||||
OrchestrationV2ConversationMessage,
|
||||
OrchestrationV2CreationSource,
|
||||
OrchestrationV2ProviderRef,
|
||||
OrchestrationV2Run,
|
||||
OrchestrationV2ThreadProjection,
|
||||
@@ -44,9 +46,13 @@ export function makeSubagentChildThread(input: {
|
||||
readonly modelSelection: ModelSelection;
|
||||
readonly title: string;
|
||||
readonly now: DateTime.Utc;
|
||||
readonly createdBy: OrchestrationV2Actor;
|
||||
readonly creationSource: OrchestrationV2CreationSource;
|
||||
}): OrchestrationV2AppThread {
|
||||
return {
|
||||
...input.parentThread,
|
||||
createdBy: input.createdBy,
|
||||
creationSource: input.creationSource,
|
||||
id: input.childThreadId,
|
||||
title: input.title,
|
||||
defaultProvider: input.providerInstanceId,
|
||||
@@ -85,6 +91,8 @@ export function makeSubagentConversationArtifacts(input: {
|
||||
readonly turnItem: OrchestrationV2TurnItem;
|
||||
} {
|
||||
const message: OrchestrationV2ConversationMessage = {
|
||||
createdBy: "agent",
|
||||
creationSource: "provider",
|
||||
id: input.messageId,
|
||||
threadId: input.threadId,
|
||||
runId: null,
|
||||
@@ -118,6 +126,8 @@ export function makeSubagentConversationArtifacts(input: {
|
||||
input.role === "user"
|
||||
? {
|
||||
...base,
|
||||
createdBy: "agent",
|
||||
creationSource: "provider",
|
||||
type: "user_message",
|
||||
inputIntent: "turn_start",
|
||||
attachments: [],
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import {
|
||||
CommandId,
|
||||
type OrchestrationV2Command,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
RunId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { withCreationProvenance } from "./ThreadManagementService.ts";
|
||||
|
||||
it("stamps authoritative provenance on commands that create threads or messages", () => {
|
||||
const command: OrchestrationV2Command = {
|
||||
type: "thread.create",
|
||||
createdBy: "agent",
|
||||
creationSource: "mcp",
|
||||
commandId: CommandId.make("command:thread-management:create"),
|
||||
threadId: ThreadId.make("thread:thread-management:create"),
|
||||
projectId: ProjectId.make("project:thread-management"),
|
||||
title: "Thread management",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
};
|
||||
|
||||
expect(
|
||||
withCreationProvenance(command, {
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
}),
|
||||
).toMatchObject({
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
});
|
||||
});
|
||||
|
||||
it("leaves commands that do not create durable authored content unchanged", () => {
|
||||
const command: OrchestrationV2Command = {
|
||||
type: "run.interrupt",
|
||||
commandId: CommandId.make("command:thread-management:interrupt"),
|
||||
threadId: ThreadId.make("thread:thread-management:interrupt"),
|
||||
runId: RunId.make("run:thread-management:interrupt"),
|
||||
};
|
||||
|
||||
expect(
|
||||
withCreationProvenance(command, {
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
}),
|
||||
).toBe(command);
|
||||
});
|
||||
@@ -0,0 +1,460 @@
|
||||
import {
|
||||
type ChatAttachment,
|
||||
type CommandId,
|
||||
type MessageId,
|
||||
type ModelSelection,
|
||||
type OrchestrationV2Actor,
|
||||
type OrchestrationV2Command,
|
||||
type OrchestrationV2ConversationMessage,
|
||||
type OrchestrationV2CreationSource,
|
||||
type OrchestrationV2Run,
|
||||
type OrchestrationV2ShellSnapshot,
|
||||
type OrchestrationV2ThreadProjection,
|
||||
type OrchestrationV2ThreadShell,
|
||||
type OrchestrationV2TurnItem,
|
||||
type ProjectId,
|
||||
type RunId,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import {
|
||||
OrchestratorV2,
|
||||
type OrchestratorV2DispatchResult,
|
||||
type OrchestratorV2Error,
|
||||
} from "./Orchestrator.ts";
|
||||
|
||||
export type ThreadManagementSendMode = "auto" | "queue" | "steer" | "restart";
|
||||
|
||||
export interface ThreadManagementProvenance {
|
||||
readonly createdBy: OrchestrationV2Actor;
|
||||
readonly creationSource: OrchestrationV2CreationSource;
|
||||
}
|
||||
|
||||
export function withCreationProvenance(
|
||||
command: OrchestrationV2Command,
|
||||
provenance: ThreadManagementProvenance,
|
||||
): OrchestrationV2Command {
|
||||
switch (command.type) {
|
||||
case "thread.create":
|
||||
case "message.dispatch":
|
||||
case "thread.fork":
|
||||
case "thread.merge_back":
|
||||
case "delegated_task.request":
|
||||
return { ...command, ...provenance };
|
||||
default:
|
||||
return command;
|
||||
}
|
||||
}
|
||||
|
||||
export type ThreadManagementTerminalRunStatus = Extract<
|
||||
OrchestrationV2Run["status"],
|
||||
"completed" | "failed" | "cancelled" | "interrupted" | "rolled_back"
|
||||
>;
|
||||
|
||||
export interface ThreadManagementSendInput {
|
||||
readonly projectId: ProjectId;
|
||||
readonly commandId: CommandId;
|
||||
readonly threadId: ThreadId;
|
||||
readonly messageId: MessageId;
|
||||
readonly text: string;
|
||||
readonly attachments: ReadonlyArray<ChatAttachment>;
|
||||
readonly modelSelection?: ModelSelection;
|
||||
readonly mode: ThreadManagementSendMode;
|
||||
readonly createdBy: OrchestrationV2Actor;
|
||||
readonly creationSource: OrchestrationV2CreationSource;
|
||||
}
|
||||
|
||||
export interface ThreadManagementSendResult {
|
||||
readonly dispatch: OrchestratorV2DispatchResult;
|
||||
readonly projection: OrchestrationV2ThreadProjection;
|
||||
readonly message: OrchestrationV2ConversationMessage;
|
||||
readonly run: OrchestrationV2Run;
|
||||
readonly turnItem: Extract<OrchestrationV2TurnItem, { readonly type: "user_message" }>;
|
||||
readonly delivery: "started" | "queued" | "steered" | "restarted";
|
||||
}
|
||||
|
||||
export interface ThreadManagementWaitInput {
|
||||
readonly projectId: ProjectId;
|
||||
readonly threadId: ThreadId;
|
||||
readonly runId?: RunId;
|
||||
readonly timeoutMs: number;
|
||||
readonly pollIntervalMs?: number;
|
||||
}
|
||||
|
||||
export interface ThreadManagementWaitResult {
|
||||
readonly threadId: ThreadId;
|
||||
readonly run: OrchestrationV2Run | null;
|
||||
readonly timedOut: boolean;
|
||||
}
|
||||
|
||||
export interface ThreadManagementInterruptInput {
|
||||
readonly projectId: ProjectId;
|
||||
readonly commandId: CommandId;
|
||||
readonly threadId: ThreadId;
|
||||
readonly runId?: RunId;
|
||||
readonly reason?: string;
|
||||
}
|
||||
|
||||
export type ThreadManagementInterruptResult =
|
||||
| {
|
||||
readonly type: "interrupt_requested";
|
||||
readonly run: OrchestrationV2Run;
|
||||
readonly dispatch: OrchestratorV2DispatchResult;
|
||||
}
|
||||
| { readonly type: "no_active_run" }
|
||||
| {
|
||||
readonly type: "already_terminal";
|
||||
readonly run: OrchestrationV2Run & { readonly status: ThreadManagementTerminalRunStatus };
|
||||
};
|
||||
|
||||
export class ThreadManagementError extends Schema.TaggedErrorClass<ThreadManagementError>()(
|
||||
"ThreadManagementError",
|
||||
{
|
||||
code: Schema.Literals([
|
||||
"thread_not_found",
|
||||
"run_not_found",
|
||||
"thread_not_sendable",
|
||||
"thread_not_interruptible",
|
||||
"orchestration_error",
|
||||
]),
|
||||
message: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {}
|
||||
|
||||
type ThreadManagementFailure = ThreadManagementError | OrchestratorV2Error;
|
||||
|
||||
export interface ThreadManagementServiceShape {
|
||||
readonly dispatch: (
|
||||
command: OrchestrationV2Command,
|
||||
) => Effect.Effect<OrchestratorV2DispatchResult, OrchestratorV2Error>;
|
||||
readonly getThreadProjection: (
|
||||
threadId: ThreadId,
|
||||
) => Effect.Effect<OrchestrationV2ThreadProjection, OrchestratorV2Error>;
|
||||
readonly getProjectThread: (input: {
|
||||
readonly projectId: ProjectId;
|
||||
readonly threadId: ThreadId;
|
||||
}) => Effect.Effect<OrchestrationV2ThreadProjection, ThreadManagementError>;
|
||||
readonly getShellSnapshot: () => Effect.Effect<OrchestrationV2ShellSnapshot, OrchestratorV2Error>;
|
||||
readonly listProjectThreads: (input: {
|
||||
readonly projectId: ProjectId;
|
||||
readonly includeSubagents: boolean;
|
||||
}) => Effect.Effect<ReadonlyArray<OrchestrationV2ThreadShell>, ThreadManagementError>;
|
||||
readonly sendToThread: (
|
||||
input: ThreadManagementSendInput,
|
||||
) => Effect.Effect<ThreadManagementSendResult, ThreadManagementFailure>;
|
||||
readonly waitForThread: (
|
||||
input: ThreadManagementWaitInput,
|
||||
) => Effect.Effect<ThreadManagementWaitResult, ThreadManagementError>;
|
||||
readonly interruptThread: (
|
||||
input: ThreadManagementInterruptInput,
|
||||
) => Effect.Effect<ThreadManagementInterruptResult, ThreadManagementFailure>;
|
||||
readonly getThreadEventSequence: OrchestratorV2["Service"]["getThreadEventSequence"];
|
||||
readonly streamStoredEvents: OrchestratorV2["Service"]["streamStoredEvents"];
|
||||
readonly streamDomainEvents: OrchestratorV2["Service"]["streamDomainEvents"];
|
||||
}
|
||||
|
||||
export class ThreadManagementService extends Context.Service<
|
||||
ThreadManagementService,
|
||||
ThreadManagementServiceShape
|
||||
>()("t3/orchestration-v2/ThreadManagementService") {}
|
||||
|
||||
export function isActiveRun(run: OrchestrationV2Run): boolean {
|
||||
return run.status === "starting" || run.status === "running" || run.status === "waiting";
|
||||
}
|
||||
|
||||
export function isTerminalRunStatus(
|
||||
status: OrchestrationV2Run["status"],
|
||||
): status is ThreadManagementTerminalRunStatus {
|
||||
return (
|
||||
status === "completed" ||
|
||||
status === "failed" ||
|
||||
status === "cancelled" ||
|
||||
status === "interrupted" ||
|
||||
status === "rolled_back"
|
||||
);
|
||||
}
|
||||
|
||||
export function latestRun(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
): OrchestrationV2Run | undefined {
|
||||
return projection.runs.toSorted((left, right) => right.ordinal - left.ordinal)[0];
|
||||
}
|
||||
|
||||
export function latestActiveRun(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
): OrchestrationV2Run | undefined {
|
||||
return projection.runs
|
||||
.filter(isActiveRun)
|
||||
.toSorted((left, right) => right.ordinal - left.ordinal)[0];
|
||||
}
|
||||
|
||||
export function latestSteerableRun(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
): OrchestrationV2Run | undefined {
|
||||
return projection.runs
|
||||
.filter(
|
||||
(run) =>
|
||||
run.status === "running" &&
|
||||
run.activeAttemptId !== null &&
|
||||
projection.providerTurns.some(
|
||||
(turn) => turn.runAttemptId === run.activeAttemptId && turn.status === "running",
|
||||
),
|
||||
)
|
||||
.toSorted((left, right) => right.ordinal - left.ordinal)[0];
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
function managementError(
|
||||
code: ThreadManagementError["code"],
|
||||
message: string,
|
||||
cause?: unknown,
|
||||
): ThreadManagementError {
|
||||
return new ThreadManagementError({ code, message, ...(cause === undefined ? {} : { cause }) });
|
||||
}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const orchestrator = yield* OrchestratorV2;
|
||||
|
||||
const getProjectThread: ThreadManagementServiceShape["getProjectThread"] = (input) =>
|
||||
orchestrator.getThreadProjection(input.threadId).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
managementError(
|
||||
"thread_not_found",
|
||||
`Thread ${input.threadId} was not found in project ${input.projectId}.`,
|
||||
cause,
|
||||
),
|
||||
),
|
||||
Effect.flatMap((projection) =>
|
||||
projection.thread.projectId === input.projectId && projection.thread.deletedAt === null
|
||||
? Effect.succeed(projection)
|
||||
: Effect.fail(
|
||||
managementError(
|
||||
"thread_not_found",
|
||||
`Thread ${input.threadId} was not found in project ${input.projectId}.`,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const listProjectThreads: ThreadManagementServiceShape["listProjectThreads"] = (input) =>
|
||||
orchestrator.getShellSnapshot().pipe(
|
||||
Effect.mapError((cause) =>
|
||||
managementError(
|
||||
"orchestration_error",
|
||||
`Unable to list threads in project ${input.projectId}: ${errorMessage(cause)}`,
|
||||
cause,
|
||||
),
|
||||
),
|
||||
Effect.map((snapshot) =>
|
||||
snapshot.threads
|
||||
.filter((thread) => thread.projectId === input.projectId)
|
||||
.filter(
|
||||
(thread) =>
|
||||
input.includeSubagents || thread.lineage.relationshipToParent !== "subagent",
|
||||
)
|
||||
.toSorted(
|
||||
(left, right) =>
|
||||
DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt) ||
|
||||
right.id.localeCompare(left.id),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const sendToThread: ThreadManagementServiceShape["sendToThread"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const target = yield* getProjectThread(input);
|
||||
if (target.thread.archivedAt !== null) {
|
||||
return yield* managementError(
|
||||
"thread_not_sendable",
|
||||
`Thread ${input.threadId} is archived and cannot receive messages.`,
|
||||
);
|
||||
}
|
||||
|
||||
const steerableRun = latestSteerableRun(target);
|
||||
let dispatchMode: Extract<
|
||||
OrchestrationV2Command,
|
||||
{ readonly type: "message.dispatch" }
|
||||
>["dispatchMode"];
|
||||
if (input.mode === "steer" || input.mode === "restart") {
|
||||
if (steerableRun === undefined) {
|
||||
return yield* managementError(
|
||||
"thread_not_sendable",
|
||||
`Thread ${input.threadId} has no running turn that can be ${input.mode === "steer" ? "steered" : "restarted"}.`,
|
||||
);
|
||||
}
|
||||
dispatchMode = {
|
||||
type: input.mode === "steer" ? "steer_active" : "restart_active",
|
||||
targetRunId: steerableRun.id,
|
||||
};
|
||||
} else if (input.mode === "auto" && steerableRun !== undefined) {
|
||||
dispatchMode = { type: "steer_active", targetRunId: steerableRun.id };
|
||||
} else {
|
||||
dispatchMode = {
|
||||
type: input.mode === "queue" ? "queue_after_active" : "start_immediately",
|
||||
};
|
||||
}
|
||||
|
||||
const dispatch = yield* orchestrator.dispatch({
|
||||
type: "message.dispatch",
|
||||
commandId: input.commandId,
|
||||
threadId: input.threadId,
|
||||
messageId: input.messageId,
|
||||
text: input.text,
|
||||
attachments: input.attachments,
|
||||
...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
|
||||
dispatchMode,
|
||||
createdBy: input.createdBy,
|
||||
creationSource: input.creationSource,
|
||||
});
|
||||
const projection = yield* getProjectThread(input);
|
||||
const message = projection.messages.find((candidate) => candidate.id === input.messageId);
|
||||
const run =
|
||||
message?.runId === null || message?.runId === undefined
|
||||
? undefined
|
||||
: projection.runs.find((candidate) => candidate.id === message.runId);
|
||||
const turnItem = projection.turnItems.find(
|
||||
(
|
||||
candidate,
|
||||
): candidate is Extract<OrchestrationV2TurnItem, { readonly type: "user_message" }> =>
|
||||
candidate.type === "user_message" && candidate.messageId === input.messageId,
|
||||
);
|
||||
if (message === undefined || run === undefined || turnItem === undefined) {
|
||||
return yield* managementError(
|
||||
"orchestration_error",
|
||||
`Message ${input.messageId} was accepted without a durable run projection.`,
|
||||
);
|
||||
}
|
||||
const delivery: ThreadManagementSendResult["delivery"] =
|
||||
turnItem.inputIntent === "turn_start"
|
||||
? "started"
|
||||
: turnItem.inputIntent === "queued_turn"
|
||||
? "queued"
|
||||
: input.mode === "restart"
|
||||
? "restarted"
|
||||
: "steered";
|
||||
return { dispatch, projection, message, run, turnItem, delivery };
|
||||
});
|
||||
|
||||
const waitForThread: ThreadManagementServiceShape["waitForThread"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const target = yield* getProjectThread(input);
|
||||
const selectedRun =
|
||||
input.runId === undefined
|
||||
? latestRun(target)
|
||||
: target.runs.find((candidate) => candidate.id === input.runId);
|
||||
if (input.runId !== undefined && selectedRun === undefined) {
|
||||
return yield* managementError(
|
||||
"run_not_found",
|
||||
`Run ${input.runId} does not belong to thread ${input.threadId}.`,
|
||||
);
|
||||
}
|
||||
if (selectedRun === undefined) {
|
||||
return { threadId: input.threadId, run: null, timedOut: false };
|
||||
}
|
||||
if (isTerminalRunStatus(selectedRun.status)) {
|
||||
return { threadId: input.threadId, run: selectedRun, timedOut: false };
|
||||
}
|
||||
|
||||
const wait = Effect.gen(function* () {
|
||||
while (true) {
|
||||
const current = yield* getProjectThread(input);
|
||||
const run = current.runs.find((candidate) => candidate.id === selectedRun.id);
|
||||
if (run === undefined) {
|
||||
return yield* managementError(
|
||||
"run_not_found",
|
||||
`Run ${selectedRun.id} no longer belongs to thread ${input.threadId}.`,
|
||||
);
|
||||
}
|
||||
if (isTerminalRunStatus(run.status)) return run;
|
||||
yield* Effect.sleep(Duration.millis(Math.max(1, input.pollIntervalMs ?? 250)));
|
||||
}
|
||||
}).pipe(Effect.timeoutOption(Duration.millis(Math.max(1, input.timeoutMs))));
|
||||
const waited = yield* wait;
|
||||
if (Option.isSome(waited)) {
|
||||
return { threadId: input.threadId, run: waited.value, timedOut: false };
|
||||
}
|
||||
const current = yield* getProjectThread(input);
|
||||
const run = current.runs.find((candidate) => candidate.id === selectedRun.id);
|
||||
if (run === undefined) {
|
||||
return yield* managementError(
|
||||
"run_not_found",
|
||||
`Run ${selectedRun.id} no longer belongs to thread ${input.threadId}.`,
|
||||
);
|
||||
}
|
||||
return { threadId: input.threadId, run, timedOut: true };
|
||||
});
|
||||
|
||||
const interruptThread: ThreadManagementServiceShape["interruptThread"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const target = yield* getProjectThread(input);
|
||||
const explicitRun =
|
||||
input.runId === undefined
|
||||
? undefined
|
||||
: target.runs.find((candidate) => candidate.id === input.runId);
|
||||
if (input.runId !== undefined && explicitRun === undefined) {
|
||||
return yield* managementError(
|
||||
"run_not_found",
|
||||
`Run ${input.runId} does not belong to thread ${input.threadId}.`,
|
||||
);
|
||||
}
|
||||
if (explicitRun !== undefined && isTerminalRunStatus(explicitRun.status)) {
|
||||
return {
|
||||
type: "already_terminal",
|
||||
run: explicitRun as OrchestrationV2Run & {
|
||||
readonly status: ThreadManagementTerminalRunStatus;
|
||||
},
|
||||
} as const;
|
||||
}
|
||||
const interruptibleRun = latestSteerableRun(target);
|
||||
if (input.runId === undefined && interruptibleRun === undefined) {
|
||||
return { type: "no_active_run" } as const;
|
||||
}
|
||||
if (
|
||||
interruptibleRun === undefined ||
|
||||
(explicitRun !== undefined && interruptibleRun.id !== explicitRun.id)
|
||||
) {
|
||||
return yield* managementError(
|
||||
"thread_not_interruptible",
|
||||
`Run ${explicitRun?.id ?? input.runId} is not currently interruptible.`,
|
||||
);
|
||||
}
|
||||
const dispatch = yield* orchestrator.dispatch({
|
||||
type: "run.interrupt",
|
||||
commandId: input.commandId,
|
||||
threadId: input.threadId,
|
||||
runId: interruptibleRun.id,
|
||||
...(input.reason === undefined ? {} : { reason: input.reason }),
|
||||
});
|
||||
return { type: "interrupt_requested", run: interruptibleRun, dispatch } as const;
|
||||
});
|
||||
|
||||
return ThreadManagementService.of({
|
||||
dispatch: orchestrator.dispatch,
|
||||
getThreadProjection: orchestrator.getThreadProjection,
|
||||
getProjectThread,
|
||||
getShellSnapshot: orchestrator.getShellSnapshot,
|
||||
listProjectThreads,
|
||||
sendToThread,
|
||||
waitForThread,
|
||||
interruptThread,
|
||||
getThreadEventSequence: orchestrator.getThreadEventSequence,
|
||||
streamStoredEvents: orchestrator.streamStoredEvents,
|
||||
streamDomainEvents: orchestrator.streamDomainEvents,
|
||||
});
|
||||
});
|
||||
|
||||
export const layer: Layer.Layer<ThreadManagementService, never, OrchestratorV2> = Layer.effect(
|
||||
ThreadManagementService,
|
||||
make,
|
||||
);
|
||||
@@ -49,6 +49,8 @@ it.layer(TestLayer)("OrchestrationV2LayerLive", (it) => {
|
||||
|
||||
const result = yield* orchestrator.dispatch({
|
||||
type: "thread.create",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("runtime-layer-create"),
|
||||
threadId,
|
||||
projectId,
|
||||
|
||||
@@ -21,6 +21,7 @@ import { layer as providerEventIngestorLayer } from "./ProviderEventIngestor.ts"
|
||||
import { layer as providerSessionManagerLayer } from "./ProviderSessionManager.ts";
|
||||
import { layer as runExecutionServiceLayer } from "./RunExecutionService.ts";
|
||||
import { layer as runtimePolicyLayer } from "./RuntimePolicy.ts";
|
||||
import { layer as threadManagementServiceLayer } from "./ThreadManagementService.ts";
|
||||
|
||||
const storesLayer = Layer.merge(eventStoreLayer, projectionStoreLayer);
|
||||
|
||||
@@ -79,7 +80,7 @@ const runExecutionServiceProvided = runExecutionServiceLayer.pipe(
|
||||
),
|
||||
);
|
||||
|
||||
export const OrchestrationV2LayerLive = orchestratorLayer.pipe(
|
||||
const orchestratorProvided = orchestratorLayer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
checkpointServiceProvided,
|
||||
@@ -96,3 +97,8 @@ export const OrchestrationV2LayerLive = orchestratorLayer.pipe(
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
export const OrchestrationV2LayerLive = Layer.merge(
|
||||
orchestratorProvided,
|
||||
threadManagementServiceLayer.pipe(Layer.provide(orchestratorProvided)),
|
||||
);
|
||||
@@ -259,6 +259,8 @@ describe("orchestration v2 provider switching", () => {
|
||||
const commands = [
|
||||
{
|
||||
type: "thread.create",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command:provider-switch:create"),
|
||||
threadId,
|
||||
projectId,
|
||||
@@ -271,6 +273,8 @@ describe("orchestration v2 provider switching", () => {
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command:provider-switch:codex"),
|
||||
threadId,
|
||||
messageId: MessageId.make("message:provider-switch:codex"),
|
||||
@@ -281,6 +285,8 @@ describe("orchestration v2 provider switching", () => {
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command:provider-switch:claude"),
|
||||
threadId,
|
||||
messageId: MessageId.make("message:provider-switch:claude"),
|
||||
@@ -291,6 +297,8 @@ describe("orchestration v2 provider switching", () => {
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command:provider-switch:return"),
|
||||
threadId,
|
||||
messageId: MessageId.make("message:provider-switch:return"),
|
||||
@@ -417,6 +425,8 @@ describe("orchestration v2 provider switching", () => {
|
||||
const commands = [
|
||||
{
|
||||
type: "thread.create",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command:cross-provider-fork:create"),
|
||||
threadId: sourceThreadId,
|
||||
projectId,
|
||||
@@ -429,6 +439,8 @@ describe("orchestration v2 provider switching", () => {
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command:cross-provider-fork:source"),
|
||||
threadId: sourceThreadId,
|
||||
messageId: MessageId.make("message:cross-provider-fork:source"),
|
||||
@@ -439,6 +451,8 @@ describe("orchestration v2 provider switching", () => {
|
||||
},
|
||||
{
|
||||
type: "thread.fork",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command:cross-provider-fork:fork"),
|
||||
sourceThreadId,
|
||||
targetThreadId,
|
||||
@@ -447,6 +461,8 @@ describe("orchestration v2 provider switching", () => {
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command:cross-provider-fork:target"),
|
||||
threadId: targetThreadId,
|
||||
messageId: MessageId.make("message:cross-provider-fork:target"),
|
||||
@@ -545,6 +561,8 @@ describe("orchestration v2 provider switching", () => {
|
||||
const commands = [
|
||||
{
|
||||
type: "thread.create",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command:cursor-portable-fork:create"),
|
||||
threadId: sourceThreadId,
|
||||
projectId,
|
||||
@@ -557,6 +575,8 @@ describe("orchestration v2 provider switching", () => {
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command:cursor-portable-fork:source"),
|
||||
threadId: sourceThreadId,
|
||||
messageId: MessageId.make("message:cursor-portable-fork:source"),
|
||||
@@ -567,6 +587,8 @@ describe("orchestration v2 provider switching", () => {
|
||||
},
|
||||
{
|
||||
type: "thread.fork",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command:cursor-portable-fork:fork"),
|
||||
sourceThreadId,
|
||||
targetThreadId,
|
||||
@@ -575,6 +597,8 @@ describe("orchestration v2 provider switching", () => {
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command:cursor-portable-fork:target"),
|
||||
threadId: targetThreadId,
|
||||
messageId: MessageId.make("message:cursor-portable-fork:target"),
|
||||
@@ -683,6 +707,8 @@ describe("orchestration v2 provider switching", () => {
|
||||
const commands = [
|
||||
{
|
||||
type: "thread.create",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command:cross-provider-merge:create"),
|
||||
threadId: sourceThreadId,
|
||||
projectId,
|
||||
@@ -695,6 +721,8 @@ describe("orchestration v2 provider switching", () => {
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command:cross-provider-merge:first-source"),
|
||||
threadId: sourceThreadId,
|
||||
messageId: MessageId.make("message:cross-provider-merge:first-source"),
|
||||
@@ -705,6 +733,8 @@ describe("orchestration v2 provider switching", () => {
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command:cross-provider-merge:second-source"),
|
||||
threadId: sourceThreadId,
|
||||
messageId: MessageId.make("message:cross-provider-merge:second-source"),
|
||||
@@ -715,6 +745,8 @@ describe("orchestration v2 provider switching", () => {
|
||||
},
|
||||
{
|
||||
type: "thread.fork",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command:cross-provider-merge:fork"),
|
||||
sourceThreadId,
|
||||
targetThreadId: forkThreadId,
|
||||
@@ -723,6 +755,8 @@ describe("orchestration v2 provider switching", () => {
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command:cross-provider-merge:fork-turn"),
|
||||
threadId: forkThreadId,
|
||||
messageId: MessageId.make("message:cross-provider-merge:fork-turn"),
|
||||
@@ -733,6 +767,8 @@ describe("orchestration v2 provider switching", () => {
|
||||
},
|
||||
{
|
||||
type: "thread.merge_back",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command:cross-provider-merge:merge"),
|
||||
sourceThreadId: forkThreadId,
|
||||
targetThreadId: sourceThreadId,
|
||||
@@ -740,6 +776,8 @@ describe("orchestration v2 provider switching", () => {
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command:cross-provider-merge:consume"),
|
||||
threadId: sourceThreadId,
|
||||
messageId: MessageId.make("message:cross-provider-merge:consume"),
|
||||
|
||||
@@ -420,6 +420,8 @@ describe("orchestration V2 thread fork", () => {
|
||||
const commands = [
|
||||
{
|
||||
type: "thread.create",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native",
|
||||
commandName: "thread-create-source",
|
||||
@@ -435,6 +437,8 @@ describe("orchestration V2 thread fork", () => {
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native",
|
||||
commandName: "source-message",
|
||||
@@ -448,6 +452,8 @@ describe("orchestration V2 thread fork", () => {
|
||||
},
|
||||
{
|
||||
type: "thread.fork",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command-thread-fork-native"),
|
||||
sourceThreadId,
|
||||
targetThreadId,
|
||||
@@ -456,6 +462,8 @@ describe("orchestration V2 thread fork", () => {
|
||||
},
|
||||
{
|
||||
type: "thread.fork",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command-thread-fork-native"),
|
||||
sourceThreadId,
|
||||
targetThreadId,
|
||||
@@ -464,6 +472,8 @@ describe("orchestration V2 thread fork", () => {
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native",
|
||||
commandName: "target-message",
|
||||
@@ -590,6 +600,8 @@ describe("orchestration V2 thread fork", () => {
|
||||
const commands = [
|
||||
{
|
||||
type: "thread.create",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native",
|
||||
commandName: "thread-create-source",
|
||||
@@ -605,6 +617,8 @@ describe("orchestration V2 thread fork", () => {
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native",
|
||||
commandName: "source-message",
|
||||
@@ -618,6 +632,8 @@ describe("orchestration V2 thread fork", () => {
|
||||
},
|
||||
{
|
||||
type: "thread.fork",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command-thread-fork-native"),
|
||||
sourceThreadId,
|
||||
targetThreadId,
|
||||
@@ -626,6 +642,8 @@ describe("orchestration V2 thread fork", () => {
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native",
|
||||
commandName: "target-message",
|
||||
@@ -723,6 +741,8 @@ describe("orchestration V2 thread fork", () => {
|
||||
const commands = [
|
||||
{
|
||||
type: "thread.create",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-prior-turn",
|
||||
commandName: "thread-create-source",
|
||||
@@ -738,6 +758,8 @@ describe("orchestration V2 thread fork", () => {
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-prior-turn",
|
||||
commandName: "source-message-alpha",
|
||||
@@ -751,6 +773,8 @@ describe("orchestration V2 thread fork", () => {
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-prior-turn",
|
||||
commandName: "source-message-beta",
|
||||
@@ -764,6 +788,8 @@ describe("orchestration V2 thread fork", () => {
|
||||
},
|
||||
{
|
||||
type: "thread.fork",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command-thread-fork-native-prior-turn"),
|
||||
sourceThreadId,
|
||||
targetThreadId,
|
||||
@@ -772,6 +798,8 @@ describe("orchestration V2 thread fork", () => {
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-prior-turn",
|
||||
commandName: "target-message-repeat",
|
||||
@@ -894,6 +922,8 @@ describe("orchestration V2 thread fork", () => {
|
||||
const commands = [
|
||||
{
|
||||
type: "thread.create",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-prior-turn",
|
||||
commandName: "thread-create-source",
|
||||
@@ -909,6 +939,8 @@ describe("orchestration V2 thread fork", () => {
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-prior-turn",
|
||||
commandName: "source-message-alpha",
|
||||
@@ -922,6 +954,8 @@ describe("orchestration V2 thread fork", () => {
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-prior-turn",
|
||||
commandName: "source-message-beta",
|
||||
@@ -935,6 +969,8 @@ describe("orchestration V2 thread fork", () => {
|
||||
},
|
||||
{
|
||||
type: "thread.fork",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command-thread-fork-native-prior-turn"),
|
||||
sourceThreadId,
|
||||
targetThreadId,
|
||||
@@ -943,6 +979,8 @@ describe("orchestration V2 thread fork", () => {
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-prior-turn",
|
||||
commandName: "target-message-repeat",
|
||||
@@ -1046,6 +1084,8 @@ describe("orchestration V2 thread fork", () => {
|
||||
const commands = [
|
||||
{
|
||||
type: "thread.create",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-prior-turn-source-rollback",
|
||||
commandName: "thread-create-source",
|
||||
@@ -1061,6 +1101,8 @@ describe("orchestration V2 thread fork", () => {
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-prior-turn-source-rollback",
|
||||
commandName: "source-message-alpha",
|
||||
@@ -1076,6 +1118,8 @@ describe("orchestration V2 thread fork", () => {
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-prior-turn-source-rollback",
|
||||
commandName: "source-message-beta",
|
||||
@@ -1089,6 +1133,8 @@ describe("orchestration V2 thread fork", () => {
|
||||
},
|
||||
{
|
||||
type: "thread.fork",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command-thread-fork-native-prior-turn-source-rollback"),
|
||||
sourceThreadId,
|
||||
targetThreadId,
|
||||
@@ -1097,6 +1143,8 @@ describe("orchestration V2 thread fork", () => {
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-prior-turn-source-rollback",
|
||||
commandName: "target-message-repeat",
|
||||
@@ -1233,6 +1281,8 @@ describe("orchestration V2 thread fork", () => {
|
||||
const commands = [
|
||||
{
|
||||
type: "thread.create",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-fork-local-rollback",
|
||||
commandName: "thread-create-source",
|
||||
@@ -1248,6 +1298,8 @@ describe("orchestration V2 thread fork", () => {
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-fork-local-rollback",
|
||||
commandName: "source-message",
|
||||
@@ -1261,6 +1313,8 @@ describe("orchestration V2 thread fork", () => {
|
||||
},
|
||||
{
|
||||
type: "thread.fork",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command-thread-fork-native-fork-local-rollback"),
|
||||
sourceThreadId,
|
||||
targetThreadId,
|
||||
@@ -1269,6 +1323,8 @@ describe("orchestration V2 thread fork", () => {
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-fork-local-rollback",
|
||||
commandName: "fork-first-message",
|
||||
@@ -1282,6 +1338,8 @@ describe("orchestration V2 thread fork", () => {
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-fork-local-rollback",
|
||||
commandName: "fork-second-message",
|
||||
@@ -1305,6 +1363,8 @@ describe("orchestration V2 thread fork", () => {
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-fork-local-rollback",
|
||||
commandName: "fork-repeat-after-rollback",
|
||||
@@ -1406,6 +1466,8 @@ describe("orchestration V2 thread fork", () => {
|
||||
const commands = [
|
||||
{
|
||||
type: "thread.create",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-prior-turn",
|
||||
commandName: "thread-create-source",
|
||||
@@ -1421,6 +1483,8 @@ describe("orchestration V2 thread fork", () => {
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-prior-turn",
|
||||
commandName: "source-message-alpha",
|
||||
@@ -1434,6 +1498,8 @@ describe("orchestration V2 thread fork", () => {
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-prior-turn",
|
||||
commandName: "source-message-beta",
|
||||
@@ -1447,6 +1513,8 @@ describe("orchestration V2 thread fork", () => {
|
||||
},
|
||||
{
|
||||
type: "thread.fork",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command-thread-fork-native-prior-turn"),
|
||||
sourceThreadId,
|
||||
targetThreadId,
|
||||
@@ -1455,6 +1523,8 @@ describe("orchestration V2 thread fork", () => {
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-prior-turn",
|
||||
commandName: "target-message-repeat",
|
||||
@@ -1468,6 +1538,8 @@ describe("orchestration V2 thread fork", () => {
|
||||
},
|
||||
{
|
||||
type: "thread.merge_back",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command-thread-merge-back-native-prior-turn-stale"),
|
||||
sourceThreadId: targetThreadId,
|
||||
targetThreadId: sourceThreadId,
|
||||
@@ -1475,6 +1547,8 @@ describe("orchestration V2 thread fork", () => {
|
||||
},
|
||||
{
|
||||
type: "thread.merge_back",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("command-thread-merge-back-native-prior-turn"),
|
||||
sourceThreadId: targetThreadId,
|
||||
targetThreadId: sourceThreadId,
|
||||
@@ -1482,6 +1556,8 @@ describe("orchestration V2 thread fork", () => {
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-prior-turn",
|
||||
commandName: "source-message-merge-back",
|
||||
|
||||
@@ -184,6 +184,8 @@ function makeCreateCommand(input: {
|
||||
}): OrchestrationV2Command {
|
||||
return {
|
||||
type: "thread.create",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: input.commandId,
|
||||
threadId: input.threadId,
|
||||
projectId: input.projectId,
|
||||
@@ -224,6 +226,8 @@ describe("orchestration V2 merge-back provider replay", () => {
|
||||
}),
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: `thread-merge-back-${variant.provider}`,
|
||||
commandName: "source",
|
||||
@@ -237,6 +241,8 @@ describe("orchestration V2 merge-back provider replay", () => {
|
||||
},
|
||||
{
|
||||
type: "thread.fork",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make(`command-merge-fork-${variant.provider}`),
|
||||
sourceThreadId,
|
||||
targetThreadId: forkThreadId,
|
||||
@@ -245,6 +251,8 @@ describe("orchestration V2 merge-back provider replay", () => {
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: `thread-merge-back-${variant.provider}`,
|
||||
commandName: "fork-delta",
|
||||
@@ -258,6 +266,8 @@ describe("orchestration V2 merge-back provider replay", () => {
|
||||
},
|
||||
{
|
||||
type: "thread.merge_back",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make(`command-merge-back-${variant.provider}`),
|
||||
sourceThreadId: forkThreadId,
|
||||
targetThreadId: sourceThreadId,
|
||||
@@ -265,6 +275,8 @@ describe("orchestration V2 merge-back provider replay", () => {
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: `thread-merge-back-${variant.provider}`,
|
||||
commandName: "consume-merge",
|
||||
@@ -278,6 +290,8 @@ describe("orchestration V2 merge-back provider replay", () => {
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: `thread-merge-back-${variant.provider}`,
|
||||
commandName: "recall",
|
||||
@@ -404,6 +418,8 @@ describe("orchestration V2 merge-back provider replay", () => {
|
||||
}),
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* commandId("source"),
|
||||
threadId: sourceThreadId,
|
||||
messageId: MessageId.make(`message-${fixtureName}-source`),
|
||||
@@ -414,6 +430,8 @@ describe("orchestration V2 merge-back provider replay", () => {
|
||||
},
|
||||
{
|
||||
type: "thread.fork",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* commandId("first-fork"),
|
||||
sourceThreadId,
|
||||
targetThreadId: firstForkThreadId,
|
||||
@@ -422,6 +440,8 @@ describe("orchestration V2 merge-back provider replay", () => {
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* commandId("first-fork-delta"),
|
||||
threadId: firstForkThreadId,
|
||||
messageId: MessageId.make(`message-${fixtureName}-first-fork`),
|
||||
@@ -432,6 +452,8 @@ describe("orchestration V2 merge-back provider replay", () => {
|
||||
},
|
||||
{
|
||||
type: "thread.fork",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* commandId("second-fork"),
|
||||
sourceThreadId,
|
||||
targetThreadId: secondForkThreadId,
|
||||
@@ -440,6 +462,8 @@ describe("orchestration V2 merge-back provider replay", () => {
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* commandId("second-fork-delta"),
|
||||
threadId: secondForkThreadId,
|
||||
messageId: MessageId.make(`message-${fixtureName}-second-fork`),
|
||||
@@ -450,6 +474,8 @@ describe("orchestration V2 merge-back provider replay", () => {
|
||||
},
|
||||
{
|
||||
type: "thread.merge_back",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* commandId("merge-first"),
|
||||
sourceThreadId: firstForkThreadId,
|
||||
targetThreadId: sourceThreadId,
|
||||
@@ -457,6 +483,8 @@ describe("orchestration V2 merge-back provider replay", () => {
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* commandId("consume-first"),
|
||||
threadId: sourceThreadId,
|
||||
messageId: MessageId.make(`message-${fixtureName}-consume-first`),
|
||||
@@ -467,6 +495,8 @@ describe("orchestration V2 merge-back provider replay", () => {
|
||||
},
|
||||
{
|
||||
type: "thread.merge_back",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* commandId("merge-second"),
|
||||
sourceThreadId: secondForkThreadId,
|
||||
targetThreadId: sourceThreadId,
|
||||
@@ -474,6 +504,8 @@ describe("orchestration V2 merge-back provider replay", () => {
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* commandId("consume-second"),
|
||||
threadId: sourceThreadId,
|
||||
messageId: MessageId.make(`message-${fixtureName}-consume-second`),
|
||||
@@ -484,6 +516,8 @@ describe("orchestration V2 merge-back provider replay", () => {
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: yield* commandId("recall"),
|
||||
threadId: sourceThreadId,
|
||||
messageId: MessageId.make(`message-${fixtureName}-recall`),
|
||||
|
||||
@@ -312,6 +312,8 @@ export function createThreadCommand(input: {
|
||||
}): OrchestrationV2Command {
|
||||
return {
|
||||
type: "thread.create",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: input.commandId,
|
||||
threadId: input.ids.threadId,
|
||||
projectId: input.ids.projectId,
|
||||
@@ -338,6 +340,8 @@ export function dispatchMessageCommand(input: {
|
||||
}): OrchestrationV2Command {
|
||||
return {
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: input.commandId,
|
||||
threadId: input.ids.threadId,
|
||||
messageId: input.messageId,
|
||||
|
||||
@@ -11,6 +11,15 @@ For browser work, first call \`preview_status\`. If no automation-capable previe
|
||||
Do not switch to global browser skills, Chrome, Node REPL browser automation, standalone Playwright, or agent-browser merely because the preview is initially closed or a first call fails. Use an alternative browser system only when the T3 preview tools are absent, the user explicitly requests another browser, or \`preview_open\` returns an explicit unsupported/unavailable error. A failed T3 preview tool call should be inspected and retried with corrected arguments when the error is actionable.
|
||||
`;
|
||||
|
||||
const T3_CODE_THREAD_ORCHESTRATION_INSTRUCTIONS = `
|
||||
|
||||
## T3 Code thread orchestration
|
||||
|
||||
When the \`t3-code\` MCP server exposes \`t3_thread_*\` tools, you can run a bounded orchestration loop without asking the user to relay updates. Start independent work with \`t3_thread_start\` (or \`create_threads\` for a batch), retain the returned thread/run IDs, wait with \`t3_thread_wait\`, and collect durable output with \`t3_thread_read\`. Use \`t3_thread_send\` for follow-up or steering and \`t3_thread_interrupt\` when work is no longer needed. Use stable \`clientRequestId\` values when retrying mutating calls, and use \`t3_thread_list\` to recover IDs after context loss.
|
||||
|
||||
Keep loops bounded by an explicit completion condition and timeout. A wait timeout does not stop the target thread. Do not repeatedly start equivalent threads or send duplicate work when a durable run is already active.
|
||||
`;
|
||||
|
||||
export const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Plan Mode (Conversational)
|
||||
|
||||
You work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions.
|
||||
@@ -146,6 +155,7 @@ The \`request_user_input\` tool is unavailable in Default mode. If you call it w
|
||||
|
||||
In Default mode, strongly prefer making reasonable assumptions and executing the user's request rather than stopping to ask questions. If you absolutely must ask a question because the answer cannot be discovered from local context and a reasonable assumption would be risky, ask the user directly with a concise plain-text question. Never write a multiple choice question as a textual assistant message.
|
||||
${T3_CODE_BROWSER_TOOL_INSTRUCTIONS}
|
||||
${T3_CODE_THREAD_ORCHESTRATION_INSTRUCTIONS}
|
||||
</collaboration_mode>`;
|
||||
|
||||
export interface CodexRuntimeInfo {
|
||||
|
||||
@@ -96,6 +96,9 @@ import {
|
||||
OrchestrationEngineService,
|
||||
type OrchestrationEngineShape,
|
||||
} from "./orchestration/Services/OrchestrationEngine.ts";
|
||||
import { layerUnavailable as OrchestratorV2UnavailableLayer } from "./orchestration-v2/Orchestrator.ts";
|
||||
import { layer as ThreadManagementServiceLayer } from "./orchestration-v2/ThreadManagementService.ts";
|
||||
import { OrchestrationListenerCallbackError } from "./orchestration/Errors.ts";
|
||||
import {
|
||||
OrchestratorV2,
|
||||
layerUnavailable as OrchestratorV2Unavailable,
|
||||
@@ -150,6 +153,11 @@ import * as ResourceAttribution from "./resourceTelemetry/ResourceAttribution.ts
|
||||
import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts";
|
||||
import * as Data from "effect/Data";
|
||||
|
||||
const OrchestrationV2UnavailableTestLayer = Layer.merge(
|
||||
OrchestratorV2UnavailableLayer,
|
||||
ThreadManagementServiceLayer.pipe(Layer.provide(OrchestratorV2UnavailableLayer)),
|
||||
);
|
||||
|
||||
const defaultProjectId = ProjectId.make("project-default");
|
||||
const defaultThreadId = ThreadId.make("thread-default");
|
||||
const defaultDesktopBootstrapToken = "test-desktop-bootstrap-token";
|
||||
@@ -772,6 +780,7 @@ const buildAppUnderTest = (options?: {
|
||||
...options?.layers?.checkpointDiffQuery,
|
||||
}),
|
||||
),
|
||||
Layer.provide(OrchestrationV2UnavailableTestLayer),
|
||||
);
|
||||
|
||||
const appLayer = servedRoutesLayer.pipe(
|
||||
|
||||
+32
-22
@@ -76,7 +76,10 @@ import {
|
||||
import { normalizeDispatchCommand } from "./orchestration/Normalizer.ts";
|
||||
import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { OrchestratorV2 } from "./orchestration-v2/Orchestrator.ts";
|
||||
import {
|
||||
ThreadManagementService,
|
||||
withCreationProvenance,
|
||||
} from "./orchestration-v2/ThreadManagementService.ts";
|
||||
import { userFacingDispatchErrorMessage } from "./orchestration-v2/UserFacingErrors.ts";
|
||||
import {
|
||||
observeRpcEffect as instrumentRpcEffect,
|
||||
@@ -404,7 +407,7 @@ const makeWsRpcLayer = (
|
||||
Effect.gen(function* () {
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const orchestrationV2 = yield* OrchestratorV2;
|
||||
const threadManagement = yield* ThreadManagementService;
|
||||
const checkpointDiffQuery = yield* CheckpointDiffQuery;
|
||||
const keybindings = yield* Keybindings;
|
||||
const open = yield* Open;
|
||||
@@ -970,7 +973,7 @@ const makeWsRpcLayer = (
|
||||
"orchestration_v2.thread_id": input.threadId,
|
||||
});
|
||||
|
||||
const projection = yield* orchestrationV2.getThreadProjection(input.threadId).pipe(
|
||||
const projection = yield* threadManagement.getThreadProjection(input.threadId).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationV2GetThreadProjectionError({
|
||||
@@ -980,7 +983,7 @@ const makeWsRpcLayer = (
|
||||
}),
|
||||
),
|
||||
);
|
||||
const snapshotSequence = yield* orchestrationV2
|
||||
const snapshotSequence = yield* threadManagement
|
||||
.getThreadEventSequence(input.threadId)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
@@ -993,7 +996,7 @@ const makeWsRpcLayer = (
|
||||
),
|
||||
);
|
||||
|
||||
const liveStream = orchestrationV2.streamStoredEvents.pipe(
|
||||
const liveStream = threadManagement.streamStoredEvents.pipe(
|
||||
Stream.filter((stored) => stored.event.threadId === input.threadId),
|
||||
Stream.filter((stored) => stored.sequence > snapshotSequence),
|
||||
Stream.map((stored) => ({
|
||||
@@ -1024,7 +1027,7 @@ const makeWsRpcLayer = (
|
||||
|
||||
const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subscribeShell")(
|
||||
function* () {
|
||||
const snapshot = yield* orchestrationV2.getShellSnapshot().pipe(
|
||||
const snapshot = yield* threadManagement.getShellSnapshot().pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationV2GetShellSnapshotError({
|
||||
@@ -1034,9 +1037,9 @@ const makeWsRpcLayer = (
|
||||
),
|
||||
);
|
||||
|
||||
const liveStream = orchestrationV2.streamDomainEvents.pipe(
|
||||
const liveStream = threadManagement.streamDomainEvents.pipe(
|
||||
Stream.mapEffect((event) =>
|
||||
orchestrationV2.getShellSnapshot().pipe(
|
||||
threadManagement.getShellSnapshot().pipe(
|
||||
Effect.map(
|
||||
(nextSnapshot) =>
|
||||
nextSnapshot.threads.find((thread) => thread.id === event.threadId) ?? null,
|
||||
@@ -1432,19 +1435,26 @@ const makeWsRpcLayer = (
|
||||
[ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command) =>
|
||||
observeRpcEffect(
|
||||
ORCHESTRATION_V2_WS_METHODS.dispatchCommand,
|
||||
orchestrationV2.dispatch(command).pipe(
|
||||
Effect.map((result) => ({ sequence: result.sequence })),
|
||||
Effect.mapError((cause) => {
|
||||
const detail = userFacingDispatchErrorMessage(cause);
|
||||
return new OrchestrationV2DispatchCommandError({
|
||||
commandId: command.commandId,
|
||||
commandType: command.type,
|
||||
message: detail ?? "Failed to dispatch orchestration V2 command",
|
||||
...(detail === undefined ? {} : { detail }),
|
||||
cause,
|
||||
});
|
||||
}),
|
||||
),
|
||||
threadManagement
|
||||
.dispatch(
|
||||
withCreationProvenance(command, {
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
}),
|
||||
)
|
||||
.pipe(
|
||||
Effect.map((result) => ({ sequence: result.sequence })),
|
||||
Effect.mapError((cause) => {
|
||||
const detail = userFacingDispatchErrorMessage(cause);
|
||||
return new OrchestrationV2DispatchCommandError({
|
||||
commandId: command.commandId,
|
||||
commandType: command.type,
|
||||
message: detail ?? "Failed to dispatch orchestration V2 command",
|
||||
...(detail === undefined ? {} : { detail }),
|
||||
cause,
|
||||
});
|
||||
}),
|
||||
),
|
||||
{
|
||||
"rpc.aggregate": "orchestrationV2",
|
||||
"orchestration_v2.command_id": command.commandId,
|
||||
@@ -1463,7 +1473,7 @@ const makeWsRpcLayer = (
|
||||
[ORCHESTRATION_V2_WS_METHODS.getThreadProjection]: (input) =>
|
||||
observeRpcEffect(
|
||||
ORCHESTRATION_V2_WS_METHODS.getThreadProjection,
|
||||
orchestrationV2.getThreadProjection(input.threadId).pipe(
|
||||
threadManagement.getThreadProjection(input.threadId).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationV2GetThreadProjectionError({
|
||||
|
||||
@@ -1824,6 +1824,8 @@ function OrchestrationV2DebugRoute() {
|
||||
const nextThreadId = newThreadId();
|
||||
const result = await api.dispatchCommand({
|
||||
type: "thread.create",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: newCommandId(),
|
||||
threadId: nextThreadId,
|
||||
projectId: newProjectId(),
|
||||
@@ -1878,6 +1880,8 @@ function OrchestrationV2DebugRoute() {
|
||||
const targetRunId = activeTurn?.targetRunId;
|
||||
const result = await api.dispatchCommand({
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: newCommandId(),
|
||||
threadId: activeThreadId,
|
||||
messageId: newMessageId(),
|
||||
@@ -2010,6 +2014,8 @@ function OrchestrationV2DebugRoute() {
|
||||
const targetThreadId = newThreadId();
|
||||
const result = await api.dispatchCommand({
|
||||
type: "thread.fork",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: newCommandId(),
|
||||
sourceThreadId: input.threadId,
|
||||
targetThreadId,
|
||||
@@ -2039,6 +2045,8 @@ function OrchestrationV2DebugRoute() {
|
||||
try {
|
||||
const result = await api.dispatchCommand({
|
||||
type: "thread.merge_back",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: newCommandId(),
|
||||
sourceThreadId: mergeBackCandidate.sourceThreadId,
|
||||
targetThreadId: mergeBackCandidate.targetThreadId,
|
||||
|
||||
@@ -8,13 +8,23 @@ agent can use this endpoint to:
|
||||
- create an app-owned sub-agent on any supported provider instance;
|
||||
- wait for or poll the sub-agent's durable result;
|
||||
- cancel an active delegated task; and
|
||||
- create one or more ordinary top-level T3 threads.
|
||||
- create one or more ordinary top-level T3 threads;
|
||||
- list and incrementally read project threads;
|
||||
- send or steer follow-up messages; and
|
||||
- wait for or interrupt ordinary thread runs.
|
||||
|
||||
These are T3 orchestration operations, not provider-native sub-agent APIs.
|
||||
Delegated tasks always create a T3 child thread and run. The child receives
|
||||
only the supplied task prompt, plus an optional role instruction supplied in
|
||||
the same tool call. Parent conversation history is not copied into the child.
|
||||
|
||||
`ThreadManagementService` is the shared server application boundary for V2
|
||||
WebSocket commands and MCP. It owns project-scoped lookup, listing, send-mode
|
||||
selection, durable send postconditions, wait polling, and interrupt selection;
|
||||
`OrchestratorV2` remains the lower-level command/event processor. Transport
|
||||
adapters only authenticate, resolve transport-specific inputs, and shape
|
||||
responses.
|
||||
|
||||
## Transport And Authentication
|
||||
|
||||
The orchestration tools share the existing authenticated HTTP MCP endpoint:
|
||||
@@ -130,7 +140,7 @@ selection model-visible without allowing a request that cannot run.
|
||||
|
||||
## Tool Surface
|
||||
|
||||
The server exposes five orchestration tools.
|
||||
The server exposes eleven orchestration tools.
|
||||
|
||||
### `orchestrator_capabilities`
|
||||
|
||||
@@ -234,6 +244,64 @@ inherit the parent's project, branch, and worktree path, but they have no
|
||||
sub-agent lineage. Entries with a prompt immediately dispatch a run; entries
|
||||
without a prompt remain idle.
|
||||
|
||||
### `t3_thread_start`
|
||||
|
||||
Creates one ordinary top-level thread and immediately dispatches its first
|
||||
prompt. It is the single-thread convenience form of `create_threads` and
|
||||
returns the created thread and run IDs. Use `clientRequestId` when a caller may
|
||||
retry the request.
|
||||
|
||||
### `t3_thread_list`
|
||||
|
||||
Lists durable thread shells in the calling thread's project, newest first.
|
||||
Callers can filter by title, run status, and whether app-owned sub-agent threads
|
||||
are included. Results are bounded and offset-paginated. Deleted threads and
|
||||
threads from other projects are never exposed.
|
||||
|
||||
### `t3_thread_read`
|
||||
|
||||
Reads a project-scoped thread's durable state, recent runs, and visible
|
||||
timeline. The default `messages` view returns user messages, assistant
|
||||
messages, and proposed plans. The `activity` view also returns summarized tool,
|
||||
reasoning, checkpoint, handoff, and runtime-request items. Large item text is
|
||||
bounded and reports whether it was truncated. `afterPosition` and
|
||||
`nextPosition` support incremental reads.
|
||||
|
||||
Thread and message results include required `createdBy` and `creationSource`
|
||||
provenance. MCP-created threads and user-role messages use `createdBy: "agent"`
|
||||
and `creationSource: "mcp"`; provider output uses `creationSource: "provider"`.
|
||||
Actor and ingress are separate so agent-authored user-role messages remain
|
||||
distinguishable from human-authored messages.
|
||||
|
||||
### `t3_thread_send`
|
||||
|
||||
Sends a message to an ordinary or delegated thread in the calling project:
|
||||
|
||||
- `auto` starts an idle thread, steers a fully active turn, or queues behind a
|
||||
turn that is not yet steerable;
|
||||
- `queue` creates a separate follow-up run after active work;
|
||||
- `steer` requires a steerable active provider turn; and
|
||||
- `restart` requires an active provider turn and uses the orchestrator's
|
||||
interrupt-and-restart path.
|
||||
|
||||
The target runtime and interaction modes may not be broader than the caller's.
|
||||
Stable command and message IDs are derived from `clientRequestId` for
|
||||
idempotent retries.
|
||||
|
||||
### `t3_thread_wait`
|
||||
|
||||
Waits for a selected run to become `completed`, `failed`, `cancelled`,
|
||||
`interrupted`, or `rolled_back`. Without `runId`, it pins the latest run at call
|
||||
time; an idle thread returns immediately. A timeout reports the latest durable
|
||||
status and does not cancel work.
|
||||
|
||||
### `t3_thread_interrupt`
|
||||
|
||||
Interrupts a selected active run through the normal V2 `run.interrupt` command.
|
||||
Without `runId`, it selects the newest interruptible run. A terminal run is
|
||||
returned unchanged, and a thread with no active provider turn returns
|
||||
`no_active_run`.
|
||||
|
||||
## Delegated Task Lifecycle
|
||||
|
||||
The MCP server is a command ingress into V2. It does not call provider adapters
|
||||
@@ -243,6 +311,7 @@ directly.
|
||||
provider model
|
||||
-> MCP tools/call delegate_task
|
||||
-> authenticated OrchestratorMcpService
|
||||
-> shared ThreadManagementService
|
||||
-> V2 delegated_task.request command
|
||||
-> child thread + child run
|
||||
-> parent app_owned subagent projection
|
||||
@@ -273,6 +342,9 @@ falls back to a terminal-status message when no assistant text exists.
|
||||
mode. It may not escalate privileges.
|
||||
- A child interaction mode may stay equal to or narrow from `default` to
|
||||
`plan`. It may not escalate from `plan` to `default`.
|
||||
- General thread management is limited to the calling thread's project. Send
|
||||
additionally enforces the same runtime and interaction privilege ceiling as
|
||||
child creation.
|
||||
- Provider instances must be enabled, installed, available, authenticated, and
|
||||
backed by a V2 adapter.
|
||||
- A requested model must be advertised by the selected provider when the
|
||||
@@ -293,6 +365,10 @@ runtime_mode_escalation_denied
|
||||
interaction_mode_escalation_denied
|
||||
task_not_found
|
||||
task_not_cancellable
|
||||
thread_not_found
|
||||
run_not_found
|
||||
thread_not_sendable
|
||||
thread_not_interruptible
|
||||
invalid_request
|
||||
orchestration_error
|
||||
```
|
||||
@@ -327,6 +403,8 @@ Coverage includes:
|
||||
- async status polling;
|
||||
- cancellation;
|
||||
- batch ordinary-thread creation;
|
||||
- project-scoped thread listing and timeline reads;
|
||||
- ordinary-thread send, wait, steering, and interruption;
|
||||
- inheritance and per-thread provider overrides; and
|
||||
- idempotent retries.
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
@@ -89,6 +89,8 @@ describe("orchestration V2 contracts", () => {
|
||||
it("decodes command and domain event shapes for command-to-projection tests", () => {
|
||||
const command = decodeOrchestrationV2Command({
|
||||
type: "message.dispatch",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: "command-1",
|
||||
threadId: "thread-1",
|
||||
messageId: "message-1",
|
||||
@@ -132,6 +134,8 @@ describe("orchestration V2 contracts", () => {
|
||||
it("decodes app-owned delegated task commands", () => {
|
||||
const command = decodeOrchestrationV2Command({
|
||||
type: "delegated_task.request",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: "command-delegate-1",
|
||||
parentThreadId: "thread-parent-1",
|
||||
parentRunId: "run-parent-1",
|
||||
@@ -295,6 +299,8 @@ describe("orchestration V2 contracts", () => {
|
||||
it("decodes thread projections with an ordered turn item rendering stream", () => {
|
||||
const projection = Schema.decodeUnknownSync(OrchestrationV2ThreadProjection)({
|
||||
thread: {
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
id: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "Thread",
|
||||
|
||||
@@ -36,6 +36,23 @@ import {
|
||||
RuntimeMode,
|
||||
} from "./orchestration.ts";
|
||||
|
||||
export const OrchestrationV2Actor = Schema.Literals(["user", "agent", "system"]);
|
||||
export type OrchestrationV2Actor = typeof OrchestrationV2Actor.Type;
|
||||
|
||||
export const OrchestrationV2CreationSource = Schema.Literals([
|
||||
"web",
|
||||
"mobile",
|
||||
"mcp",
|
||||
"provider",
|
||||
"server",
|
||||
]);
|
||||
export type OrchestrationV2CreationSource = typeof OrchestrationV2CreationSource.Type;
|
||||
|
||||
const OrchestrationV2CreationFields = {
|
||||
createdBy: OrchestrationV2Actor,
|
||||
creationSource: OrchestrationV2CreationSource,
|
||||
} as const;
|
||||
|
||||
export const OrchestrationV2NativeRefStrength = Schema.Literals(["strong", "weak", "none"]);
|
||||
export type OrchestrationV2NativeRefStrength = typeof OrchestrationV2NativeRefStrength.Type;
|
||||
|
||||
@@ -125,7 +142,7 @@ export const OrchestrationV2ContextTransfer = Schema.Struct({
|
||||
"superseded",
|
||||
]),
|
||||
resolution: Schema.NullOr(OrchestrationV2ContextTransferResolution),
|
||||
createdBy: Schema.Literals(["user", "agent", "system"]),
|
||||
createdBy: OrchestrationV2Actor,
|
||||
error: Schema.NullOr(Schema.String),
|
||||
createdAt: Schema.DateTimeUtc,
|
||||
updatedAt: Schema.DateTimeUtc,
|
||||
@@ -260,6 +277,7 @@ export const OrchestrationV2ProviderCapabilities = Schema.Struct({
|
||||
export type OrchestrationV2ProviderCapabilities = typeof OrchestrationV2ProviderCapabilities.Type;
|
||||
|
||||
export const OrchestrationV2AppThread = Schema.Struct({
|
||||
...OrchestrationV2CreationFields,
|
||||
id: ThreadId,
|
||||
projectId: ProjectId,
|
||||
title: TrimmedNonEmptyString,
|
||||
@@ -397,7 +415,7 @@ export const OrchestrationV2Subagent = Schema.Struct({
|
||||
runId: Schema.NullOr(RunId),
|
||||
parentNodeId: NodeId,
|
||||
origin: Schema.Literals(["provider_native", "app_owned"]),
|
||||
createdBy: Schema.Literals(["agent", "user", "system"]),
|
||||
createdBy: OrchestrationV2Actor,
|
||||
provider: ProviderKind,
|
||||
providerThreadId: Schema.NullOr(ProviderThreadId),
|
||||
childThreadId: Schema.NullOr(ThreadId),
|
||||
@@ -540,6 +558,7 @@ export const OrchestrationV2RuntimeRequest = Schema.Struct({
|
||||
export type OrchestrationV2RuntimeRequest = typeof OrchestrationV2RuntimeRequest.Type;
|
||||
|
||||
export const OrchestrationV2ConversationMessage = Schema.Struct({
|
||||
...OrchestrationV2CreationFields,
|
||||
id: MessageId,
|
||||
threadId: ThreadId,
|
||||
runId: Schema.NullOr(RunId),
|
||||
@@ -675,6 +694,7 @@ export type OrchestrationV2WebSearchResult = typeof OrchestrationV2WebSearchResu
|
||||
export const OrchestrationV2TurnItem = Schema.Union([
|
||||
Schema.Struct({
|
||||
...OrchestrationV2TurnItemBaseFields,
|
||||
...OrchestrationV2CreationFields,
|
||||
type: Schema.Literal("user_message"),
|
||||
messageId: MessageId,
|
||||
inputIntent: OrchestrationV2UserMessageInputIntent,
|
||||
@@ -988,6 +1008,7 @@ export const OrchestrationV2ShellThreadStatus = Schema.Union([
|
||||
export type OrchestrationV2ShellThreadStatus = typeof OrchestrationV2ShellThreadStatus.Type;
|
||||
|
||||
export const OrchestrationV2ThreadShell = Schema.Struct({
|
||||
...OrchestrationV2CreationFields,
|
||||
id: ThreadId,
|
||||
projectId: ProjectId,
|
||||
title: Schema.String,
|
||||
@@ -1159,6 +1180,7 @@ const OrchestrationV2TurnItemJsonBaseFields = {
|
||||
export const OrchestrationV2TurnItemJson = Schema.Union([
|
||||
Schema.Struct({
|
||||
...OrchestrationV2TurnItemJsonBaseFields,
|
||||
...OrchestrationV2CreationFields,
|
||||
type: Schema.Literal("user_message"),
|
||||
messageId: MessageId,
|
||||
inputIntent: OrchestrationV2UserMessageInputIntent,
|
||||
@@ -1433,6 +1455,7 @@ export type OrchestrationV2StoredEventJson = typeof OrchestrationV2StoredEventJs
|
||||
export const OrchestrationV2Command = Schema.Union([
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("thread.create"),
|
||||
...OrchestrationV2CreationFields,
|
||||
commandId: CommandId,
|
||||
threadId: ThreadId,
|
||||
projectId: ProjectId,
|
||||
@@ -1445,6 +1468,7 @@ export const OrchestrationV2Command = Schema.Union([
|
||||
}),
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("message.dispatch"),
|
||||
...OrchestrationV2CreationFields,
|
||||
commandId: CommandId,
|
||||
threadId: ThreadId,
|
||||
messageId: MessageId,
|
||||
@@ -1496,6 +1520,7 @@ export const OrchestrationV2Command = Schema.Union([
|
||||
}),
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("thread.fork"),
|
||||
...OrchestrationV2CreationFields,
|
||||
commandId: CommandId,
|
||||
sourceThreadId: ThreadId,
|
||||
targetThreadId: ThreadId,
|
||||
@@ -1505,6 +1530,7 @@ export const OrchestrationV2Command = Schema.Union([
|
||||
}),
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("thread.merge_back"),
|
||||
...OrchestrationV2CreationFields,
|
||||
commandId: CommandId,
|
||||
sourceThreadId: ThreadId,
|
||||
targetThreadId: ThreadId,
|
||||
@@ -1513,6 +1539,7 @@ export const OrchestrationV2Command = Schema.Union([
|
||||
}),
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("delegated_task.request"),
|
||||
...OrchestrationV2CreationFields,
|
||||
commandId: CommandId,
|
||||
parentThreadId: ThreadId,
|
||||
parentRunId: RunId,
|
||||
|
||||
@@ -1,15 +1,27 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import {
|
||||
OrchestratorMcpCreateThreadsInput,
|
||||
OrchestratorMcpDelegateTaskInput,
|
||||
OrchestratorMcpDelegateTaskResult,
|
||||
OrchestratorMcpThreadInterruptInput,
|
||||
OrchestratorMcpThreadListInput,
|
||||
OrchestratorMcpThreadReadInput,
|
||||
OrchestratorMcpThreadSendInput,
|
||||
OrchestratorMcpThreadStartInput,
|
||||
OrchestratorMcpThreadWaitInput,
|
||||
} from "./orchestratorMcp.ts";
|
||||
|
||||
const decodeCreateThreadsInput = Schema.decodeUnknownSync(OrchestratorMcpCreateThreadsInput);
|
||||
const decodeDelegateTaskInput = Schema.decodeUnknownSync(OrchestratorMcpDelegateTaskInput);
|
||||
const decodeDelegateTaskResult = Schema.decodeUnknownSync(OrchestratorMcpDelegateTaskResult);
|
||||
const decodeThreadInterruptInput = Schema.decodeUnknownSync(OrchestratorMcpThreadInterruptInput);
|
||||
const decodeThreadListInput = Schema.decodeUnknownSync(OrchestratorMcpThreadListInput);
|
||||
const decodeThreadReadInput = Schema.decodeUnknownSync(OrchestratorMcpThreadReadInput);
|
||||
const decodeThreadSendInput = Schema.decodeUnknownSync(OrchestratorMcpThreadSendInput);
|
||||
const decodeThreadStartInput = Schema.decodeUnknownSync(OrchestratorMcpThreadStartInput);
|
||||
const decodeThreadWaitInput = Schema.decodeUnknownSync(OrchestratorMcpThreadWaitInput);
|
||||
|
||||
describe("orchestrator MCP contracts", () => {
|
||||
it("decodes cross-provider delegated task requests and durable results", () => {
|
||||
@@ -60,4 +72,48 @@ describe("orchestrator MCP contracts", () => {
|
||||
expect(request.threads[0]?.prompt).toBeUndefined();
|
||||
expect(request.threads[1]?.target?.driverKind).toBe("claudeAgent");
|
||||
});
|
||||
|
||||
it("decodes project-scoped thread orchestration requests", () => {
|
||||
expect(
|
||||
decodeThreadStartInput({
|
||||
prompt: "Run the first loop iteration.",
|
||||
clientRequestId: "start-loop-1",
|
||||
}).prompt,
|
||||
).toBe("Run the first loop iteration.");
|
||||
expect(
|
||||
decodeThreadListInput({
|
||||
statuses: ["running", "completed"],
|
||||
includeSubagents: false,
|
||||
limit: 25,
|
||||
}).statuses,
|
||||
).toEqual(["running", "completed"]);
|
||||
expect(
|
||||
decodeThreadReadInput({
|
||||
threadId: "thread-loop-1",
|
||||
view: "activity",
|
||||
afterPosition: 10,
|
||||
}).afterPosition,
|
||||
).toBe(10);
|
||||
expect(
|
||||
decodeThreadSendInput({
|
||||
threadId: "thread-loop-1",
|
||||
message: "Continue with the next iteration.",
|
||||
mode: "steer",
|
||||
clientRequestId: "send-loop-2",
|
||||
}).mode,
|
||||
).toBe("steer");
|
||||
expect(
|
||||
decodeThreadWaitInput({
|
||||
threadId: "thread-loop-1",
|
||||
runId: "run-loop-2",
|
||||
timeoutMs: 5_000,
|
||||
}).runId,
|
||||
).toBe("run-loop-2");
|
||||
expect(
|
||||
decodeThreadInterruptInput({
|
||||
threadId: "thread-loop-1",
|
||||
reason: "Loop converged.",
|
||||
}).reason,
|
||||
).toBe("Loop converged.");
|
||||
});
|
||||
});
|
||||
@@ -2,12 +2,24 @@ import * as Schema from "effect/Schema";
|
||||
|
||||
import {
|
||||
ContextTransferId,
|
||||
IsoDateTime,
|
||||
MessageId,
|
||||
NodeId,
|
||||
NonNegativeInt,
|
||||
PositiveInt,
|
||||
ProjectId,
|
||||
RunId,
|
||||
ThreadId,
|
||||
TrimmedNonEmptyString,
|
||||
TurnItemId,
|
||||
} from "./baseSchemas.ts";
|
||||
import { ProviderInteractionMode, RuntimeMode } from "./orchestration.ts";
|
||||
import {
|
||||
OrchestrationV2Actor,
|
||||
OrchestrationV2CreationSource,
|
||||
OrchestrationV2RunStatus,
|
||||
OrchestrationV2TurnItemStatus,
|
||||
} from "./orchestrationV2.ts";
|
||||
import { ProviderDriverKind, ProviderInstanceId } from "./providerInstance.ts";
|
||||
|
||||
const OrchestratorMcpPrompt = TrimmedNonEmptyString.check(Schema.isMaxLength(120_000));
|
||||
@@ -127,6 +139,8 @@ export const OrchestratorMcpCreatedThread = Schema.Struct({
|
||||
runId: Schema.NullOr(RunId),
|
||||
status: OrchestratorMcpCreatedThreadStatus,
|
||||
title: Schema.String,
|
||||
createdBy: OrchestrationV2Actor,
|
||||
creationSource: OrchestrationV2CreationSource,
|
||||
providerInstanceId: ProviderInstanceId,
|
||||
model: Schema.String,
|
||||
});
|
||||
@@ -137,6 +151,187 @@ export const OrchestratorMcpCreateThreadsResult = Schema.Struct({
|
||||
});
|
||||
export type OrchestratorMcpCreateThreadsResult = typeof OrchestratorMcpCreateThreadsResult.Type;
|
||||
|
||||
export const OrchestratorMcpThreadStartInput = Schema.Struct({
|
||||
prompt: OrchestratorMcpPrompt,
|
||||
title: Schema.optional(OrchestratorMcpTitle),
|
||||
target: Schema.optional(OrchestratorMcpTarget),
|
||||
clientRequestId: Schema.optional(OrchestratorMcpClientRequestId),
|
||||
runtimeMode: Schema.optional(OrchestratorMcpRuntimeMode),
|
||||
interactionMode: Schema.optional(OrchestratorMcpInteractionMode),
|
||||
});
|
||||
export type OrchestratorMcpThreadStartInput = typeof OrchestratorMcpThreadStartInput.Type;
|
||||
|
||||
export const OrchestratorMcpThreadStatus = Schema.Union([
|
||||
Schema.Literal("idle"),
|
||||
OrchestrationV2RunStatus,
|
||||
]);
|
||||
export type OrchestratorMcpThreadStatus = typeof OrchestratorMcpThreadStatus.Type;
|
||||
|
||||
export const OrchestratorMcpThreadListInput = Schema.Struct({
|
||||
statuses: Schema.optional(
|
||||
Schema.Array(OrchestratorMcpThreadStatus).check(Schema.isMaxLength(10)),
|
||||
),
|
||||
titleContains: Schema.optional(TrimmedNonEmptyString.check(Schema.isMaxLength(256))),
|
||||
includeSubagents: Schema.optional(Schema.Boolean),
|
||||
cursor: Schema.optional(NonNegativeInt),
|
||||
limit: Schema.optional(PositiveInt.check(Schema.isLessThanOrEqualTo(100))),
|
||||
});
|
||||
export type OrchestratorMcpThreadListInput = typeof OrchestratorMcpThreadListInput.Type;
|
||||
|
||||
export const OrchestratorMcpThreadListItem = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
title: Schema.String,
|
||||
createdBy: OrchestrationV2Actor,
|
||||
creationSource: OrchestrationV2CreationSource,
|
||||
status: OrchestratorMcpThreadStatus,
|
||||
latestRunId: Schema.NullOr(RunId),
|
||||
providerInstanceId: ProviderInstanceId,
|
||||
model: Schema.String,
|
||||
runtimeMode: RuntimeMode,
|
||||
interactionMode: ProviderInteractionMode,
|
||||
parentThreadId: Schema.NullOr(ThreadId),
|
||||
relationshipToParent: Schema.NullOr(Schema.Literals(["fork", "subagent"])),
|
||||
itemCount: NonNegativeInt,
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
export type OrchestratorMcpThreadListItem = typeof OrchestratorMcpThreadListItem.Type;
|
||||
|
||||
export const OrchestratorMcpThreadListResult = Schema.Struct({
|
||||
projectId: ProjectId,
|
||||
currentThreadId: ThreadId,
|
||||
threads: Schema.Array(OrchestratorMcpThreadListItem),
|
||||
nextCursor: Schema.NullOr(NonNegativeInt),
|
||||
total: NonNegativeInt,
|
||||
});
|
||||
export type OrchestratorMcpThreadListResult = typeof OrchestratorMcpThreadListResult.Type;
|
||||
|
||||
export const OrchestratorMcpThreadReadInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
view: Schema.optional(Schema.Literals(["messages", "activity"])),
|
||||
afterPosition: Schema.optional(NonNegativeInt),
|
||||
limit: Schema.optional(PositiveInt.check(Schema.isLessThanOrEqualTo(100))),
|
||||
runLimit: Schema.optional(PositiveInt.check(Schema.isLessThanOrEqualTo(50))),
|
||||
maxCharsPerItem: Schema.optional(PositiveInt.check(Schema.isLessThanOrEqualTo(50_000))),
|
||||
});
|
||||
export type OrchestratorMcpThreadReadInput = typeof OrchestratorMcpThreadReadInput.Type;
|
||||
|
||||
export const OrchestratorMcpThreadDetail = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
projectId: ProjectId,
|
||||
title: Schema.String,
|
||||
createdBy: OrchestrationV2Actor,
|
||||
creationSource: OrchestrationV2CreationSource,
|
||||
status: OrchestratorMcpThreadStatus,
|
||||
latestRunId: Schema.NullOr(RunId),
|
||||
activeRunId: Schema.NullOr(RunId),
|
||||
providerInstanceId: ProviderInstanceId,
|
||||
model: Schema.String,
|
||||
runtimeMode: RuntimeMode,
|
||||
interactionMode: ProviderInteractionMode,
|
||||
branch: Schema.NullOr(Schema.String),
|
||||
worktreePath: Schema.NullOr(Schema.String),
|
||||
parentThreadId: Schema.NullOr(ThreadId),
|
||||
relationshipToParent: Schema.NullOr(Schema.Literals(["fork", "subagent"])),
|
||||
runCount: NonNegativeInt,
|
||||
itemCount: NonNegativeInt,
|
||||
pendingRequestCount: NonNegativeInt,
|
||||
archived: Schema.Boolean,
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
export type OrchestratorMcpThreadDetail = typeof OrchestratorMcpThreadDetail.Type;
|
||||
|
||||
export const OrchestratorMcpThreadRun = Schema.Struct({
|
||||
runId: RunId,
|
||||
ordinal: PositiveInt,
|
||||
status: OrchestrationV2RunStatus,
|
||||
providerInstanceId: ProviderInstanceId,
|
||||
model: Schema.String,
|
||||
requestedAt: IsoDateTime,
|
||||
startedAt: Schema.NullOr(IsoDateTime),
|
||||
completedAt: Schema.NullOr(IsoDateTime),
|
||||
});
|
||||
export type OrchestratorMcpThreadRun = typeof OrchestratorMcpThreadRun.Type;
|
||||
|
||||
export const OrchestratorMcpThreadTimelineItem = Schema.Struct({
|
||||
position: NonNegativeInt,
|
||||
visibility: Schema.Literals(["local", "inherited", "synthetic"]),
|
||||
sourceThreadId: ThreadId,
|
||||
itemId: TurnItemId,
|
||||
runId: Schema.NullOr(RunId),
|
||||
messageId: Schema.NullOr(MessageId),
|
||||
createdBy: Schema.NullOr(OrchestrationV2Actor),
|
||||
creationSource: Schema.NullOr(OrchestrationV2CreationSource),
|
||||
type: Schema.String,
|
||||
status: OrchestrationV2TurnItemStatus,
|
||||
title: Schema.NullOr(Schema.String),
|
||||
text: Schema.NullOr(Schema.String),
|
||||
textTruncated: Schema.Boolean,
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
export type OrchestratorMcpThreadTimelineItem = typeof OrchestratorMcpThreadTimelineItem.Type;
|
||||
|
||||
export const OrchestratorMcpThreadReadResult = Schema.Struct({
|
||||
thread: OrchestratorMcpThreadDetail,
|
||||
recentRuns: Schema.Array(OrchestratorMcpThreadRun),
|
||||
items: Schema.Array(OrchestratorMcpThreadTimelineItem),
|
||||
nextPosition: Schema.NullOr(NonNegativeInt),
|
||||
hasMore: Schema.Boolean,
|
||||
});
|
||||
export type OrchestratorMcpThreadReadResult = typeof OrchestratorMcpThreadReadResult.Type;
|
||||
|
||||
export const OrchestratorMcpThreadSendInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
message: OrchestratorMcpPrompt,
|
||||
mode: Schema.optional(Schema.Literals(["auto", "queue", "steer", "restart"])),
|
||||
clientRequestId: Schema.optional(OrchestratorMcpClientRequestId),
|
||||
});
|
||||
export type OrchestratorMcpThreadSendInput = typeof OrchestratorMcpThreadSendInput.Type;
|
||||
|
||||
export const OrchestratorMcpThreadSendResult = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
messageId: MessageId,
|
||||
runId: RunId,
|
||||
status: OrchestrationV2RunStatus,
|
||||
delivery: Schema.Literals(["started", "queued", "steered", "restarted"]),
|
||||
});
|
||||
export type OrchestratorMcpThreadSendResult = typeof OrchestratorMcpThreadSendResult.Type;
|
||||
|
||||
export const OrchestratorMcpThreadWaitInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
runId: Schema.optional(RunId),
|
||||
timeoutMs: Schema.optional(Schema.Number),
|
||||
});
|
||||
export type OrchestratorMcpThreadWaitInput = typeof OrchestratorMcpThreadWaitInput.Type;
|
||||
|
||||
export const OrchestratorMcpThreadWaitResult = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
runId: Schema.NullOr(RunId),
|
||||
status: OrchestratorMcpThreadStatus,
|
||||
timedOut: Schema.Boolean,
|
||||
});
|
||||
export type OrchestratorMcpThreadWaitResult = typeof OrchestratorMcpThreadWaitResult.Type;
|
||||
|
||||
export const OrchestratorMcpThreadInterruptInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
runId: Schema.optional(RunId),
|
||||
reason: Schema.optional(Schema.String.check(Schema.isMaxLength(2_000))),
|
||||
clientRequestId: Schema.optional(OrchestratorMcpClientRequestId),
|
||||
});
|
||||
export type OrchestratorMcpThreadInterruptInput = typeof OrchestratorMcpThreadInterruptInput.Type;
|
||||
|
||||
export const OrchestratorMcpThreadInterruptResult = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
runId: Schema.NullOr(RunId),
|
||||
status: Schema.Union([
|
||||
Schema.Literal("interrupt_requested"),
|
||||
Schema.Literal("no_active_run"),
|
||||
Schema.Literals(["completed", "failed", "cancelled", "interrupted", "rolled_back"]),
|
||||
]),
|
||||
});
|
||||
export type OrchestratorMcpThreadInterruptResult = typeof OrchestratorMcpThreadInterruptResult.Type;
|
||||
|
||||
export const OrchestratorMcpProviderCapability = Schema.Struct({
|
||||
providerInstanceId: ProviderInstanceId,
|
||||
driverKind: ProviderDriverKind,
|
||||
@@ -165,6 +360,8 @@ export const OrchestratorMcpCapabilitiesResult = Schema.Struct({
|
||||
asyncPolling: Schema.Boolean,
|
||||
cancellation: Schema.Boolean,
|
||||
batchThreadCreation: Schema.Boolean,
|
||||
threadManagement: Schema.Boolean,
|
||||
incrementalThreadRead: Schema.Boolean,
|
||||
maxBatchThreads: Schema.Number,
|
||||
}),
|
||||
});
|
||||
@@ -182,6 +379,10 @@ export class OrchestratorMcpFailure extends Schema.TaggedErrorClass<Orchestrator
|
||||
"interaction_mode_escalation_denied",
|
||||
"task_not_found",
|
||||
"task_not_cancellable",
|
||||
"thread_not_found",
|
||||
"run_not_found",
|
||||
"thread_not_sendable",
|
||||
"thread_not_interruptible",
|
||||
"invalid_request",
|
||||
"orchestration_error",
|
||||
]),
|
||||
|
||||
Reference in new issue
Block a user