Skip to content

Commit d2871b3

Browse files
feat(server): hand a thread off to a linked environment
A thread can now move to a linked environment with its conversation and its git work, with exactly one copy live. ThreadHandoff marks it departing, which refuses new turns and keeps queued runs from starting; packs the branch and working tree with HandoffGit; uploads the bundle through the other side's signed attachment route; and calls t3_thread_import there, which now takes the bundle and applies it in a new worktree before creating the thread. Only then is the thread departed here and read-only. A failed move marks it failed, which takes turns again, and nothing is left there. An agent can move its own thread with t3_thread_handoff. The move then waits as pending until its turn ends, starts the thread there with the agent's continuationPrompt, and is cancelled by a user message sent before the turn ends. A startup sweep runs moves that a restart cut short; import ids derive from the handoff, so a retry finds the thread already there. threadHandoff.options / start / cancel serve the clients. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
1 parent 64a099e commit d2871b3

24 files changed

Lines changed: 1752 additions & 73 deletions

‎apps/server/src/auth/RpcAuthorization.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,10 @@ export const RPC_REQUIRED_SCOPES = {
8484
[WS_METHODS.peerLinksList]: AuthAccessReadScope,
8585
[WS_METHODS.peerLinksLink]: AuthAccessWriteScope,
8686
[WS_METHODS.peerLinksUnlink]: AuthAccessWriteScope,
87+
// Moving a thread drives the linked environment through this one's link.
88+
[WS_METHODS.threadHandoffOptions]: AuthOrchestrationReadScope,
89+
[WS_METHODS.threadHandoffStart]: AuthOrchestrationOperateScope,
90+
[WS_METHODS.threadHandoffCancel]: AuthOrchestrationOperateScope,
8791
[WS_METHODS.serverUpdateSettings]: AuthSettingsWriteScope,
8892
[WS_METHODS.serverSearchAcpRegistry]: AuthOrchestrationReadScope,
8993
[WS_METHODS.serverPrepareAcpRegistryAgent]: AuthProvidersManageScope,

‎apps/server/src/mcp/McpHttpServer.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -851,7 +851,7 @@ const layerEnvironmentRegistration = toolkitRegistration(
851851

852852
export const layerProjectRegistration = toolkitRegistration(ProjectToolkit, ProjectHandlers.layer);
853853

854-
const layerAttachmentRegistration = toolkitRegistration(
854+
export const layerAttachmentRegistration = toolkitRegistration(
855855
AttachmentToolkit,
856856
AttachmentHandlers.layer,
857857
);

‎apps/server/src/mcp/toolkits/orchestrator/handlers.ts‎

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
1-
import type { EnvironmentId } from "@t3tools/contracts";
1+
import { type EnvironmentId, OrchestratorMcpFailure } from "@t3tools/contracts";
22
import * as Effect from "effect/Effect";
33
import type { Tool } from "effect/ai";
44

55
import { OrchestratorToolkit } from "./tools.ts";
66

77
import * as PeerForwarding from "../../../peer/PeerForwarding.ts";
88
import * as RemoteDelegation from "../../../peer/RemoteDelegation.ts";
9+
import * as ThreadHandoff from "../../../peer/handoff/ThreadHandoff.ts";
910
import * as McpInvocationContext from "../../McpInvocationContext.ts";
1011
import * as McpToolAccess from "../../McpToolAccess.ts";
1112
import * as OrchestratorMcpService from "../../OrchestratorMcpService.ts";
@@ -191,6 +192,44 @@ const handlers = {
191192
return yield* service.waitForThread(scope, input);
192193
}),
193194
),
195+
t3_thread_handoff: McpToolAccess.writesThreads(
196+
(input) => [input.threadId],
197+
(input) =>
198+
Effect.gen(function* () {
199+
const scope = yield* McpInvocationContext.McpInvocationContext;
200+
const own = input.threadId === undefined || input.threadId === scope.thread?.threadId;
201+
const threadId = input.threadId ?? scope.thread?.threadId;
202+
if (threadId === undefined) {
203+
return yield* new OrchestratorMcpFailure({
204+
code: "target_required",
205+
message: "Pass threadId: this MCP client is not running inside a T3 thread.",
206+
});
207+
}
208+
const handoff = yield* ThreadHandoff.ThreadHandoff;
209+
const state = yield* handoff.start({
210+
threadId,
211+
environmentId: input.environmentId,
212+
projectId: input.projectId,
213+
continuationPrompt: input.continuationPrompt,
214+
// The calling thread is mid-turn: it moves once this turn ends.
215+
whenTurnEnds: own,
216+
});
217+
return {
218+
state: state.state,
219+
environmentId: state.environmentId,
220+
label: state.label,
221+
threadId: state.state === "departed" ? state.threadId : null,
222+
message:
223+
state.state === "pending"
224+
? `This thread moves to ${state.label} when this turn ends. End the turn now; a message to this thread before then cancels the move.`
225+
: state.state === "departed"
226+
? `The thread moved to ${state.label}.`
227+
: state.state === "failed"
228+
? `The move failed: ${state.lastError}`
229+
: `The thread is moving to ${state.label}.`,
230+
};
231+
}),
232+
),
194233
t3_environment_links: McpToolAccess.reads(() =>
195234
Effect.gen(function* () {
196235
const scope = yield* McpInvocationContext.McpInvocationContext;

‎apps/server/src/mcp/toolkits/orchestrator/tools.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ import {
22
OrchestratorMcpCapabilitiesInput,
33
OrchestratorMcpCapabilitiesResult,
44
OrchestratorMcpEnvironmentLinksResult,
5+
OrchestratorMcpThreadHandoffInput,
6+
OrchestratorMcpThreadHandoffResult,
57
OrchestratorMcpCreateThreadsInput,
68
OrchestratorMcpCreateThreadsResult,
79
OrchestratorMcpDelegateTaskInput,
@@ -37,6 +39,7 @@ import { Tool, Toolkit } from "effect/ai";
3739
import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts";
3840
import * as PeerForwarding from "../../../peer/PeerForwarding.ts";
3941
import * as RemoteDelegation from "../../../peer/RemoteDelegation.ts";
42+
import * as ThreadHandoff from "../../../peer/handoff/ThreadHandoff.ts";
4043
import * as McpInvocationContext from "../../McpInvocationContext.ts";
4144
import * as OrchestratorMcpService from "../../OrchestratorMcpService.ts";
4245
import * as ThreadMetadataMcpService from "../../ThreadMetadataMcpService.ts";
@@ -265,6 +268,19 @@ const ThreadInterruptTool = Tool.make("t3_thread_interrupt", {
265268
.annotate(Tool.Title, "Interrupt a T3 thread")
266269
.annotate(Tool.Destructive, true);
267270

271+
const ThreadHandoffTool = Tool.make("t3_thread_handoff", {
272+
description:
273+
"Move a thread to a linked environment (t3_environment_links), such as the user's VPS, with its conversation and its git work: unpushed commits, uncommitted edits and new files. It continues there in a new worktree of the project with the same repository, and the copy here becomes read-only. Omit threadId to move the calling thread: the move then happens as soon as this turn ends, and continuationPrompt becomes its first message there, so end the turn after saying what you will do there. A message to the thread before then cancels the move. Another thread must be idle to move.",
274+
parameters: OrchestratorMcpThreadHandoffInput,
275+
success: OrchestratorMcpThreadHandoffResult,
276+
failure: OrchestratorMcpFailure,
277+
failureMode: "return",
278+
dependencies: [...dependencies, ThreadHandoff.ThreadHandoff],
279+
})
280+
.annotate(Tool.Title, "Move a thread to a linked environment")
281+
.annotate(Tool.Destructive, true)
282+
.annotate(Tool.OpenWorld, true);
283+
268284
const EnvironmentLinksTool = Tool.make("t3_environment_links", {
269285
description:
270286
"List the other T3 Code environments this one is linked to, such as the user's other machines, and whether each answers now. Pass one's environmentId to t3_project_list, t3_thread_launch, t3_thread_list, t3_thread_read, t3_thread_send, t3_thread_wait, t3_thread_interrupt, or orchestrator_capabilities to act there. A linked environment lets this one's agents do at most its access there, and never more than the calling agent may do here. An expired link has to be linked again from a new pairing code.",
@@ -296,4 +312,5 @@ export const OrchestratorToolkit = Toolkit.make(
296312
ThreadWaitTool,
297313
ThreadInterruptTool,
298314
EnvironmentLinksTool,
315+
ThreadHandoffTool,
299316
);

‎apps/server/src/mcp/toolkits/project/handlers.ts‎

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,10 @@ import {
99
import { formatThreadLink } from "@t3tools/shared/threadLinks";
1010
import * as Effect from "effect/Effect";
1111
import * as FileSystem from "effect/FileSystem";
12+
import * as Path from "effect/Path";
1213
import * as Option from "effect/Option";
1314
import * as ThreadImportService from "../../../orchestration-v2/ThreadImportService.ts";
15+
import * as HandoffImport from "../../../peer/handoff/HandoffImport.ts";
1416
import * as ThreadMessageIntake from "../../../orchestration-v2/ThreadMessageIntake.ts";
1517
import * as Claims from "../../../orchestration-v2/AttachmentClaims.ts";
1618
import * as Project from "../../../project/ProjectService.ts";
@@ -20,6 +22,9 @@ import * as Repositories from "../../../sourceControl/SourceControlRepositorySer
2022
import * as PeerForwarding from "../../../peer/PeerForwarding.ts";
2123
import * as GitVcsDriver from "../../../vcs/GitVcsDriver.ts";
2224
import * as McpInvocationContext from "../../McpInvocationContext.ts";
25+
import * as ServerConfig from "../../../config.ts";
26+
import * as Settings from "../../../serverSettings.ts";
27+
import * as VcsProcess from "../../../vcs/VcsProcess.ts";
2328
import * as McpToolAccess from "../../McpToolAccess.ts";
2429
import { newCommandId, readCaller, resolveProjectId, unavailable } from "../../threadAccess.ts";
2530
import { ProjectToolkit } from "./tools.ts";
@@ -223,10 +228,37 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
223228
code: "invalid_request",
224229
message: "The project was not found.",
225230
});
231+
if (input.worktreePath !== undefined && input.bundle !== undefined)
232+
return yield* new OrchestratorMcpFailure({
233+
code: "invalid_request",
234+
message: "A bundle lands in a new worktree; omit worktreePath.",
235+
});
226236
if (input.worktreePath !== undefined)
227237
yield* assertProjectWorktree(project.workspaceRoot, input.worktreePath);
228238
const imports = yield* ThreadImportService.ThreadImportService;
229-
return yield* imports.importThread({ ...input, runtimeMode, interactionMode, linkOrigin });
239+
const bundle = input.bundle;
240+
const context = yield* Effect.context<
241+
| ServerConfig.ServerConfig
242+
| Settings.ServerSettingsService
243+
| VcsProcess.VcsProcess
244+
| FileSystem.FileSystem
245+
| Path.Path
246+
>();
247+
const workspace =
248+
bundle === undefined
249+
? undefined
250+
: HandoffImport.applyBundle({
251+
repoRoot: project.workspaceRoot,
252+
handoffId: input.source.handoffId,
253+
bundle,
254+
}).pipe(Effect.provideContext(context));
255+
return yield* imports.importThread({
256+
...input,
257+
runtimeMode,
258+
interactionMode,
259+
linkOrigin,
260+
...(workspace === undefined ? {} : { workspace }),
261+
});
230262
}),
231263
// A moved thread carries the link that moved it, like a launch.
232264
"stamped",

‎apps/server/src/mcp/toolkits/project/tools.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import {
2323
SourceControlCloneRepositoryResult,
2424
} from "@t3tools/contracts";
2525
import * as FileSystem from "effect/FileSystem";
26+
import * as Path from "effect/Path";
2627
import * as ServerConfig from "../../../config.ts";
2728
import * as ThreadImportService from "../../../orchestration-v2/ThreadImportService.ts";
2829
import * as ThreadLaunchService from "../../../orchestration-v2/ThreadLaunchService.ts";
@@ -35,7 +36,9 @@ import * as ManagedProjectFolders from "../../../project/ManagedProjectFolders.t
3536
import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts";
3637
import * as PeerForwarding from "../../../peer/PeerForwarding.ts";
3738
import * as SourceControlRepositoryService from "../../../sourceControl/SourceControlRepositoryService.ts";
39+
import * as Settings from "../../../serverSettings.ts";
3840
import * as GitVcsDriver from "../../../vcs/GitVcsDriver.ts";
41+
import * as VcsProcess from "../../../vcs/VcsProcess.ts";
3942
import * as McpInvocationContext from "../../McpInvocationContext.ts";
4043

4144
const shared = {
@@ -181,6 +184,10 @@ const ThreadImportTool = Tool.make("t3_thread_import", {
181184
ThreadImportService.ThreadImportService,
182185
GitVcsDriver.GitVcsDriver,
183186
FileSystem.FileSystem,
187+
Path.Path,
188+
ServerConfig.ServerConfig,
189+
Settings.ServerSettingsService,
190+
VcsProcess.VcsProcess,
184191
],
185192
})
186193
.annotate(Tool.Destructive, true)

‎apps/server/src/observability/RpcInstrumentation.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,9 @@ const RPC_AGGREGATES = {
5656
[WS_METHODS.peerLinksList]: "peerLinks",
5757
[WS_METHODS.peerLinksLink]: "peerLinks",
5858
[WS_METHODS.peerLinksUnlink]: "peerLinks",
59+
[WS_METHODS.threadHandoffOptions]: "threadHandoff",
60+
[WS_METHODS.threadHandoffStart]: "threadHandoff",
61+
[WS_METHODS.threadHandoffCancel]: "threadHandoff",
5962
[WS_METHODS.serverUpdateSettings]: "server",
6063
[WS_METHODS.serverSearchAcpRegistry]: "server",
6164
[WS_METHODS.serverPrepareAcpRegistryAgent]: "server",

‎apps/server/src/orchestration-v2/Orchestrator.ts‎

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,23 @@ export class OrchestratorSubagentThreadReadOnlyError extends Schema.TaggedError<
190190
}
191191
}
192192

193+
/** The thread is moving, or has moved, to a linked environment and takes no new turns here. */
194+
export class OrchestratorThreadMovedError extends Schema.TaggedError<OrchestratorThreadMovedError>()(
195+
"OrchestratorThreadMovedError",
196+
{
197+
commandId: CommandId,
198+
threadId: ThreadId,
199+
label: Schema.String,
200+
state: Schema.Literals(["departing", "departed"]),
201+
},
202+
) {
203+
override get message(): string {
204+
return this.state === "departed"
205+
? `This thread moved to ${this.label}. Continue it there.`
206+
: `This thread is moving to ${this.label}.`;
207+
}
208+
}
209+
193210
/** The command's thread runs above the modes its sender may touch (see `DispatchModeLimit`). */
194211
export class OrchestratorThreadAboveModeLimitError extends Schema.TaggedError<OrchestratorThreadAboveModeLimitError>()(
195212
"OrchestratorThreadAboveModeLimitError",
@@ -255,6 +272,7 @@ export const OrchestratorV2Error = Schema.Union([
255272
OrchestratorCommandPreviouslyRejectedError,
256273
OrchestratorCommandIdConflictError,
257274
OrchestratorSubagentThreadReadOnlyError,
275+
OrchestratorThreadMovedError,
258276
OrchestratorThreadAboveModeLimitError,
259277
]);
260278
export type OrchestratorV2Error = typeof OrchestratorV2Error.Type;
@@ -449,6 +467,7 @@ function commandThreadId(command: OrchestrationV2ServerCommand): ThreadId {
449467
case "checkpoint.rollback.fail":
450468
case "thread.background-work.settle":
451469
case "thread.stop":
470+
case "thread.handoff.update":
452471
case "provider.switch":
453472
return command.threadId;
454473
case "delegated_task.request":
@@ -1251,6 +1270,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
12511270
if (
12521271
projection.thread.archivedAt !== null ||
12531272
projection.thread.deletedAt !== null ||
1273+
// A thread waiting to move, moving or moved starts nothing more here.
1274+
(projection.thread.handoff !== undefined && projection.thread.handoff.state !== "failed") ||
12541275
projection.runs.some(isBlockingRun) ||
12551276
projection.runs.some((run) => run.status === "queued" && run.queueHeld === true)
12561277
) {
@@ -6720,6 +6741,61 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
67206741
},
67216742
);
67226743

6744+
/** Moves a thread through a handoff to a linked environment; see the command. */
6745+
const dispatchThreadHandoffUpdate = Effect.fn("orchestrationV2.dispatch.threadHandoffUpdate")(
6746+
function* (
6747+
command: Extract<OrchestrationV2InternalCommand, { readonly type: "thread.handoff.update" }>,
6748+
events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
6749+
) {
6750+
const projection = yield* projectionStore
6751+
.getThreadRecords(command.threadId, ["runs"])
6752+
.pipe(
6753+
Effect.mapError(
6754+
(cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }),
6755+
),
6756+
);
6757+
const thread = projection.thread;
6758+
const reject = (cause: string) =>
6759+
new OrchestratorDispatchError({
6760+
commandId: command.commandId,
6761+
commandType: command.type,
6762+
cause,
6763+
});
6764+
if (thread.deletedAt !== null) return yield* reject(`Thread ${thread.id} is deleted.`);
6765+
const current = thread.handoff?.state ?? null;
6766+
if (current !== command.expected) {
6767+
return yield* reject(
6768+
current === null
6769+
? "This thread is not being moved."
6770+
: `This thread's move is ${current}, not ${command.expected ?? "absent"}.`,
6771+
);
6772+
}
6773+
const next = command.handoff?.state ?? null;
6774+
if (
6775+
next === "departing" &&
6776+
projection.runs.some((run) => isBlockingRun(run) || run.status === "queued")
6777+
) {
6778+
return yield* reject("A thread moves only while no turn runs or waits on it.");
6779+
}
6780+
const now = yield* DateTime.now;
6781+
const { handoff: _previous, ...rest } = thread;
6782+
yield* emit(
6783+
events,
6784+
command,
6785+
)({
6786+
type: "thread.metadata-updated",
6787+
threadId: command.threadId,
6788+
providerInstanceId: thread.providerInstanceId,
6789+
occurredAt: now,
6790+
payload: {
6791+
...rest,
6792+
...(command.handoff === null ? {} : { handoff: command.handoff }),
6793+
updatedAt: now,
6794+
},
6795+
});
6796+
},
6797+
);
6798+
67236799
/**
67246800
* Records a task that runs in a linked environment on its parent: the
67256801
* task, its node and its turn item, as a local delegation does, but no child
@@ -10518,6 +10594,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1051810594
threadId: command.threadId,
1051910595
});
1052010596
}
10597+
// A thread moving away, or gone, takes no new turns here.
10598+
if (thread.handoff?.state === "departing" || thread.handoff?.state === "departed") {
10599+
return yield* new OrchestratorThreadMovedError({
10600+
commandId: command.commandId,
10601+
threadId: command.threadId,
10602+
label: thread.handoff.label,
10603+
state: thread.handoff.state,
10604+
});
10605+
}
1052110606
yield* dispatchMessage(command, events, effects);
1052210607
break;
1052310608
}
@@ -10653,6 +10738,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1065310738
case "delegated_task.remote.request":
1065410739
yield* dispatchRemoteDelegatedTaskRequest(command, events);
1065510740
break;
10741+
case "thread.handoff.update":
10742+
yield* dispatchThreadHandoffUpdate(command, events);
10743+
break;
1065610744
case "delegated_task.remote.complete":
1065710745
yield* dispatchRemoteDelegatedTaskComplete(command, events);
1065810746
break;

‎apps/server/src/orchestration-v2/ProjectionStore.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1428,6 +1428,7 @@ export function threadShellFromProjection(
14281428
...(projection.thread.delegatedFrom === undefined
14291429
? {}
14301430
: { delegatedFrom: projection.thread.delegatedFrom }),
1431+
...(projection.thread.handoff === undefined ? {} : { handoff: projection.thread.handoff }),
14311432
latestRunId: latestRun?.id ?? null,
14321433
latestRunRequestedAt: latestRun?.requestedAt ?? null,
14331434
latestRunStartedAt: latestRun?.startedAt ?? null,
@@ -1702,6 +1703,7 @@ function shellFromState(input: {
17021703
...(input.state.thread.delegatedFrom === undefined
17031704
? {}
17041705
: { delegatedFrom: input.state.thread.delegatedFrom }),
1706+
...(input.state.thread.handoff === undefined ? {} : { handoff: input.state.thread.handoff }),
17051707
latestRunId: input.state.latestRunId,
17061708
latestRunRequestedAt: input.state.latestRunRequestedAt,
17071709
latestRunStartedAt: input.state.latestRunStartedAt,

0 commit comments

Comments
 (0)