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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
394 changes: 328 additions & 66 deletions apps/server/src/mcp/OrchestratorMcpService.test.ts

Large diffs are not rendered by default.

340 changes: 294 additions & 46 deletions apps/server/src/mcp/OrchestratorMcpService.ts

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,12 @@ describe("orchestrator MCP toolkit", () => {
Layer.provide(layerOrchestration),
),
),
Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),
Layer.provide(
Layer.mock(RemoteDelegation.RemoteDelegation)({
place: (scope) => Effect.succeed(scope.environmentId),
placed: () => Effect.succeedNone,
}),
),
Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
);

Expand Down
11 changes: 9 additions & 2 deletions apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -233,10 +233,17 @@ const cancelBackgroundOnlyTask = (
layerAdapters,
Layer.mock(ProviderRegistry.ProviderRegistry)({
getProviders: Effect.succeed([provider]),
refreshWorkspaceSnapshot: () => Effect.succeed([provider]),
}),
Layer.mock(ProjectService.ProjectService)({
getById: () => Effect.succeedNone,
workspaceScanDirectory: Effect.succeed,
}),
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({
place: (scope) => Effect.succeed(scope.environmentId),
placed: () => Effect.succeedNone,
}),
ServerSettings.layerTest(),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
NodeServices.layer,
Expand Down
604 changes: 600 additions & 4 deletions apps/server/src/peer/RemoteDelegation.test.ts

Large diffs are not rendered by default.

87 changes: 63 additions & 24 deletions apps/server/src/peer/RemoteDelegation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
type OrchestratorMcpThreadTimelineItem,
type OrchestrationV2RemoteTaskChild,
type OrchestrationV2Subagent,
type OrchestrationV2ThreadLaunchWorkspaceStrategy,
type OrchestrationV2WorkerAlert,
type PeerLink,
OrchestrationV2ThreadPlacementAdmitError,
Expand Down Expand Up @@ -167,6 +168,8 @@ export class RemoteDelegation extends Context.Service<
readonly target: NonNullable<OrchestratorMcpDelegateTaskInput["target"]> & {
readonly environmentId: EnvironmentId;
};
/** Closura: pushed-ref worktree strategy so `isolation: "worktree"` can run on a headless host. */
readonly workspaceStrategy?: OrchestrationV2ThreadLaunchWorkspaceStrategy | undefined;
},
) => Effect.Effect<{ readonly taskId: NodeId }, OrchestratorMcpFailure>;
/**
Expand Down Expand Up @@ -984,15 +987,17 @@ const make = Effect.gen(function* () {

const delegate: RemoteDelegation["Service"]["delegate"] = Effect.fn("RemoteDelegation.delegate")(
function* (scope, input) {
const parent = yield* threads.getThreadRecords(scope.thread.threadId, ["runs"]).pipe(
Effect.mapError(
() =>
new OrchestratorMcpFailure({
code: "thread_not_found",
message: "The calling thread was not found.",
}),
),
);
const parent = yield* threads
.getThreadRecords(scope.thread.threadId, ["runs", "subagents"])
.pipe(
Effect.mapError(
() =>
new OrchestratorMcpFailure({
code: "thread_not_found",
message: "The calling thread was not found.",
}),
),
);
const parentRun = parent.runs
.filter(ThreadManagement.isActiveRun)
.toSorted((left, right) => right.ordinal - left.ordinal)[0];
Expand All @@ -1008,13 +1013,53 @@ const make = Effect.gen(function* () {
}
const parentNodeId = parentRun.rootNodeId;
const { target } = input;
// A worktree there would branch from a commit this checkout has and the
// other may not, so a remote task runs in that project's checkout.
if (input.isolation === "worktree") {
// One key for the launch there and the record here, so a retry finds both.
// Both are scoped to the provider session, as every key a caller passes is:
// the forwarder scopes the launch's, and the record's names it.
const key = input.clientRequestId ?? (yield* random.uuidV4());
const keyed = (operation: string) =>
CommandId.make(
`command:mcp:${encodeURIComponent(scope.requestNamespace)}:${operation}:${encodeURIComponent(key)}`,
);
const commandId = keyed("remote-delegate");
const launchId = keyed("remote-launch");
const childId = keyed("remote-child");
// Reconcile an already-launched/recorded remote task even when local HEAD has since
// moved to an unpushed commit and no pushed worktree ref is provided.
const priorLaunch =
input.clientRequestId === undefined
? Option.none<string>()
: yield* threads
.intentOf(launchId)
.pipe(Effect.orElseSucceed(() => Option.none<string>()));
const priorChild =
input.clientRequestId === undefined
? Option.none<string>()
: yield* threads
.intentOf(childId)
.pipe(Effect.orElseSucceed(() => Option.none<string>()));
if (Option.isSome(priorChild)) {
const recordedTask = parent.subagents.find(
(task) =>
task.remoteChild?.environmentId === target.environmentId &&
task.remoteChild.threadId === priorChild.value,
);
if (recordedTask !== undefined) return { taskId: recordedTask.id };
}
// Closura: allow `isolation: "worktree"` on a headless peer when given a pushed-ref
// strategy (`startFromOrigin: true`); refuse local-only worktrees the peer cannot fetch.
const remoteWorktreeStrategy =
input.isolation === "worktree" ? input.workspaceStrategy : undefined;
if (
input.isolation === "worktree" &&
Option.isNone(priorLaunch) &&
(remoteWorktreeStrategy?.type !== "worktree" ||
remoteWorktreeStrategy.startFromOrigin !== true)
) {
return yield* new OrchestratorMcpFailure({
code: "invalid_request",
message:
'A task in a linked environment runs in that project\'s checkout; isolation "worktree" is not supported there. Omit isolation, or use t3_thread_launch with environmentId and a worktree workspaceStrategy.',
'A task in a linked environment with isolation "worktree" requires a pushed ref (startFromOrigin: true). Push the branch first, omit isolation, or set needsLocalCheckout: true.',
});
}
// The provider and model inherit as they do for a task here. Another
Expand Down Expand Up @@ -1058,15 +1103,6 @@ const make = Effect.gen(function* () {
parent.thread.projectId,
target.projectId,
);
// One key for the launch there and the record here, so a retry finds both.
// Both are scoped to the provider session, as every key a caller passes is:
// the forwarder scopes the launch's, and the record's names it.
const key = input.clientRequestId ?? (yield* random.uuidV4());
const keyed = (operation: string) =>
CommandId.make(
`command:mcp:${encodeURIComponent(scope.requestNamespace)}:${operation}:${encodeURIComponent(key)}`,
);
const commandId = keyed("remote-delegate");
const link = yield* links.get(target.environmentId).pipe(
Effect.map(Option.getOrUndefined),
Effect.orElseSucceed(() => undefined),
Expand All @@ -1077,15 +1113,18 @@ const make = Effect.gen(function* () {
const sent = yield* launchThere(scope, {
environmentId: target.environmentId,
label,
launchId: keyed("remote-launch"),
childId: keyed("remote-child"),
launchId,
childId,
threadId: parent.thread.id,
params: {
projectId,
title,
modelSelection: { instanceId, model, ...(options === undefined ? {} : { options }) },
...(runtimeMode === undefined ? {} : { runtimeMode }),
...(interactionMode === undefined ? {} : { interactionMode }),
...(remoteWorktreeStrategy === undefined
? {}
: { workspaceStrategy: remoteWorktreeStrategy }),
message: task,
clientRequestId: `delegate:${scope.thread.threadId}:${key}`,
// The thread there shows it is this thread's subagent, with a way back.
Expand Down
17 changes: 17 additions & 0 deletions packages/contracts/src/orchestratorMcp.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,4 +81,21 @@ describe("orchestrator MCP contracts", () => {
}).next,
).toBe(next);
});

it("decodes placement and needsLocalCheckout options on delegated task requests", () => {
expect(
decodeDelegateTaskInput({
task: "Inspect uncommitted files.",
placement: "here",
needsLocalCheckout: true,
}),
).toMatchObject({ placement: "here", needsLocalCheckout: true });
expect(
decodeDelegateTaskInput({
task: "Review PR 2261.",
isolation: "worktree",
placement: "auto",
}),
).toMatchObject({ isolation: "worktree", placement: "auto" });
});
});
14 changes: 11 additions & 3 deletions packages/contracts/src/orchestratorMcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,13 +190,21 @@ export const OrchestratorMcpDelegateTaskInput = Schema.Struct({
isolation: Schema.optional(
Schema.Literals(["shared", "worktree"]).annotate({
description:
"'shared' (default): parent checkout. 'worktree': new prepared checkout from the parent commit, for a separate checkout or PR per child. Uncommitted edits stay out.",
"'shared' (default): parent checkout. 'worktree': new prepared checkout from the pushed ref on a headless host when placed, or from the parent commit locally. Uncommitted edits stay out.",
}),
),
// Closura: omitted placement defaults to 'auto' when automaticPlacementByDefault is on.
placement: Schema.optional(
Schema.Literals(["auto"]).annotate({
Schema.Literals(["auto", "here"]).annotate({
description:
"'auto': use for any work that needs none of your checkout's changes. Runs on the least-loaded headless machine, here or linked, with spare capacity, this repository's project and your exact provider and model; there, in that project's checkout. Ignored with target.environmentId or isolation. Reuse clientRequestId on retry to keep the environment chosen.",
"'auto' (default): runs on the least-loaded headless machine, here or linked, with spare capacity, this repository's project and your exact provider and model; when isolation is set to worktree, creates the checkout there from the pushed ref. 'here': keeps the task on this environment (refused on an interactive host while its human is active without needsLocalCheckout). Ignored with target.environmentId. Reuse clientRequestId on retry to keep the environment chosen.",
}),
),
// Closura: explicit exception for agent-origin children that must use this checkout while a human is active.
needsLocalCheckout: Schema.optional(
Schema.Boolean.annotate({
description:
"Set true only when the child must read or edit uncommitted state in this checkout. On an interactive host while its human is active, agent-origin children are refused unless this is true (at most one active child at a time).",
}),
),
mode: Schema.optional(
Expand Down
Loading