Registry Mirror
Skip to content
Merged
1 change: 1 addition & 0 deletions apps/server/src/environment/ServerEnvironment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,7 @@ export const make = Effect.gen(function* () {
linkThreadStream: true,
linkClientPairing: true,
linkPairingForLink: true,
threadImport: true,
mcpApprovalCodes: true,
peerLinkPairingCodes: true,
mcpHostedApproval: true,
Expand Down
10 changes: 10 additions & 0 deletions apps/server/src/mcp/McpInvocationContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,16 @@ export const hiddenFromThreads = (): boolean => {
return scope?.thread === undefined;
};

/**
* `McpSchema.EnabledWhen` for tools one environment calls on another over a link, which no agent
* and no other outside client is offered. Discovery only: the handler refuses the call too.
*/
export const linkedCallersOnly = (): boolean => {
const fiber = Fiber.getCurrent();
const scope = fiber && Context.getOrUndefined(fiber.context, McpInvocationContext);
return scope?.client?.linked === true;
};

/** `McpSchema.EnabledWhen` for tools that only serve links, hidden while the beta is off. */
export const hiddenWhileLinksOff = (): boolean => {
const fiber = Fiber.getCurrent();
Expand Down
8 changes: 7 additions & 1 deletion apps/server/src/mcp/linkOrigin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ import * as McpInvocationContext from "./McpInvocationContext.ts";
import * as PeerForwarding from "../peer/PeerForwarding.ts";
import * as ThreadSearch from "../orchestration-v2/ThreadSearch.ts";
import * as PeerLinkRequests from "../peer/PeerLinkRequests.ts";
import * as ThreadImportService from "../orchestration-v2/ThreadImportService.ts";
import * as PeerLinks from "../peer/PeerLinks.ts";

// A linked environment's session drives this one's real orchestrator through
Expand Down Expand Up @@ -176,7 +177,12 @@ const layerTools = Layer.mergeAll(
Layer.provide(Layer.mock(ProjectCloneTracker.ProjectCloneTracker)({})),
Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
Layer.provide(
Layer.merge(
Layer.mock(PeerLinkRequests.PeerLinkRequests)({}),
Layer.mock(ThreadImportService.ThreadImportService)({}),
),
),
Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
Layer.provide(Layer.mock(ThreadSearch.ThreadSearch)({})),
Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),
Expand Down
67 changes: 66 additions & 1 deletion apps/server/src/mcp/toolkits/project/handlers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import * as TestClock from "effect/testing/TestClock";

import * as DocumentText from "../../../provider/DocumentText.ts";
import { OrchestratorRuntimeModeAboveCeilingError } from "../../../orchestration-v2/Orchestrator.ts";
import * as ThreadImportService from "../../../orchestration-v2/ThreadImportService.ts";
import * as ThreadLaunch from "../../../orchestration-v2/ThreadLaunchService.ts";
import * as ThreadManagement from "../../../orchestration-v2/ThreadManagementService.ts";
import * as ServerConfig from "../../../config.ts";
Expand All @@ -52,6 +53,7 @@ import { ProjectToolkit } from "./tools.ts";

const clientLaunchHarness = (input: {
readonly runtimeModeCeiling: RuntimeMode;
readonly linked?: boolean;
readonly defaultRuntimeMode?: RuntimeMode;
readonly newWorktreesStartFromOrigin?: boolean;
readonly defaultThreadEnvMode?: "local" | "worktree";
Expand Down Expand Up @@ -125,6 +127,7 @@ const clientLaunchHarness = (input: {
sessionId: "session-1",
label: "Claude Code",
access: input.runtimeModeCeiling,
...(input.linked ? { linked: true } : {}),
hostedAppUrl: input.hostedAppUrl,
}
: undefined,
Expand Down Expand Up @@ -847,10 +850,11 @@ it.effect("a launch binds only an existing checkout that is one of the project's
yield* fileSystem.makeDirectory(outside);

const launched: Array<ThreadLaunch.ThreadLaunchInput> = [];
const { projectId, dependencies } = clientLaunchHarness({
const { projectId, modelSelection, dependencies } = clientLaunchHarness({
runtimeModeCeiling: "auto",
launched,
workspaceRoot: repo,
linked: true,
});
const git = yield* GitVcsDriver.GitVcsDriver.pipe(Effect.provide(dependencies));
for (const args of [
Expand Down Expand Up @@ -896,6 +900,33 @@ it.effect("a launch binds only an existing checkout that is one of the project's
{ type: "existing_worktree", worktreePath: worktree },
]);

const imports = Layer.mock(ThreadImportService.ThreadImportService)({
importThread: (input) => {
expect(input.worktreePath).toBe(worktree);
return Effect.succeed({
threadId: ThreadId.make("thread:import:test"),
projectId,
created: true,
runId: null,
});
},
});
const imported = yield* toolkit
.handle("t3_thread_import", {
source: {
environmentId: EnvironmentId.make("elsewhere"),
threadId: ThreadId.make("thread-there"),
handoffId: "handoff-alias",
},
projectId,
title: "Moved",
modelSelection,
messages: [],
worktreePath: alias,
})
.pipe(Stream.unwrap, Stream.runCollect, Effect.provide(Layer.merge(dependencies, imports)));
expect(imported.at(-1)?.result).toMatchObject({ projectId, created: true });

yield* fileSystem.remove(worktree, { recursive: true });
yield* fileSystem.makeDirectory(worktree);
expect((yield* launchInto(worktree)).at(-1)?.result).toMatchObject({
Expand Down Expand Up @@ -1198,6 +1229,40 @@ it.effect("a launch into an unknown project says the project was not found", ()
}),
);

it.effect("a client that is not a linked environment cannot import a thread", () =>
Effect.gen(function* () {
const { modelSelection, dependencies } = clientLaunchHarness({
runtimeModeCeiling: "full-access",
launched: [],
});
const toolkit = yield* ProjectToolkit.pipe(
Effect.provide(
McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(Layer.provide(dependencies)),
),
);
const result = yield* toolkit
.handle("t3_thread_import", {
source: {
environmentId: EnvironmentId.make("elsewhere"),
threadId: ThreadId.make("thread-there"),
handoffId: "handoff-1",
},
projectId: ProjectId.make("project:client-target"),
title: "Moved",
modelSelection,
messages: [],
})
.pipe(
Stream.unwrap,
Stream.runCollect,
Effect.provide(
Layer.merge(dependencies, Layer.mock(ThreadImportService.ThreadImportService)({})),
),
);
expect(result.at(-1)?.result).toMatchObject({ code: "capability_denied" });
}),
);

it.effect("a retried worktree launch replays after its base ref is gone", () =>
Effect.gen(function* () {
const launched: Array<ThreadLaunch.ThreadLaunchInput> = [];
Expand Down
80 changes: 80 additions & 0 deletions apps/server/src/mcp/toolkits/project/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { OrchestratorRuntimeModeAboveCeilingError } from "../../../orchestration-v2/Orchestrator.ts";
import { outputRequestProblem } from "../../../orchestration-v2/runOutput.ts";
import * as ThreadImportService from "../../../orchestration-v2/ThreadImportService.ts";
import * as ThreadLaunch from "../../../orchestration-v2/ThreadLaunchService.ts";
import * as ThreadMessageIntake from "../../../orchestration-v2/ThreadMessageIntake.ts";
import * as Claims from "../../../orchestration-v2/AttachmentClaims.ts";
Expand Down Expand Up @@ -542,6 +543,85 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
// The launched thread carries the caller's link, if it has one.
"stamped",
),
t3_thread_import: McpToolAccess.startsThreads(
(input) => input,
(input, { runtimeMode, interactionMode, linkOrigin }) =>
Effect.gen(function* () {
// The receiving half of a move, which only arrives over a link.
if ((yield* McpInvocationContext.McpInvocationContext).client?.linked !== true)
return yield* new OrchestratorMcpFailure({
code: "capability_denied",
message: "Only a linked environment moving a thread here can import one.",
});
if (input.messages.some((message) => Option.isNone(DateTime.make(message.createdAt))))
return yield* new OrchestratorMcpFailure({
code: "invalid_request",
message: "Every message needs a createdAt that is a date.",
});
const projects = yield* access;
const project = yield* projects
.getById(input.projectId)
.pipe(Effect.mapError(unavailable), Effect.map(Option.getOrUndefined));
if (project === undefined)
return yield* new OrchestratorMcpFailure({
code: "invalid_request",
message: "The project was not found.",
});
const worktreePath =
input.worktreePath === undefined
? undefined
: yield* projectWorktreePath(project.workspaceRoot, input.worktreePath);
const cwd = worktreePath ?? project.workspaceRoot;
const registry = yield* ProviderRegistry.ProviderRegistry;
const { instanceId, options } = input.modelSelection;
let providers = yield* registry.getProviders;
const workspaceSnapshot = providers
.find((candidate) => candidate.instanceId === instanceId)
?.workspaceSnapshots?.find((snapshot) => snapshot.cwd === cwd);
if (runtimeMode !== "full-access" && options?.length && workspaceSnapshot === undefined) {
const scanCwd = yield* projects.workspaceScanDirectory(cwd);
providers = yield* registry.refreshWorkspaceSnapshot({ instanceId, cwd, scanCwd });
}
const provider = OrchestrationMcp.withWorkspaceModels(providers, cwd).find(
(candidate) => candidate.instanceId === instanceId,
);
yield* refuseAgentModePick({
callerRuntimeMode: runtimeMode,
picked: input.modelSelection.options,
descriptors: providerOptionDescriptors(provider),
held: undefined,
});
Comment thread
macroscopeapp[bot] marked this conversation as resolved.
Resolved
// A mode this provider does not offer steps down, so the thread shows what it runs in.
const offeredMode = yield* resolveRuntimeMode(runtimeMode, undefined, {
modelSelection: input.modelSelection,
supportedRuntimeModes: provider?.supportedRuntimeModes,
});
const imports = yield* ThreadImportService.ThreadImportService;
return yield* imports
.importThread({
...input,
...(worktreePath === undefined ? {} : { worktreePath }),
runtimeMode: offeredMode,
interactionMode,
linkOrigin,
})
.pipe(
Effect.mapError(
(error) =>
new OrchestratorMcpFailure({
code:
error._tag === "ThreadImportProjectMismatchError" ||
error._tag === "ThreadImportOtherLinkError"
? "invalid_request"
: "orchestration_error",
message: error.message,
}),
),
);
}),
// A moved thread carries the link that moved it, like a launch.
"stamped",
),
t3_project_list: McpToolAccess.reads((input) =>
Effect.gen(function* () {
const projects = yield* access;
Expand Down
25 changes: 24 additions & 1 deletion apps/server/src/mcp/toolkits/project/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,20 @@ import {
OrchestratorMcpFailure,
SourceControlCloneRepositoryInput,
SourceControlCloneRepositoryResult,
OrchestratorMcpThreadImportInput,
OrchestratorMcpThreadImportResult,
} from "@t3tools/contracts";
import * as FileSystem from "effect/FileSystem";
import * as DocumentText from "../../../provider/DocumentText.ts";
import * as ServerConfig from "../../../config.ts";
import * as ProviderRegistry from "../../../provider/ProviderRegistry.ts";
import * as ServerSettings from "../../../serverSettings.ts";
import * as ThreadImportService from "../../../orchestration-v2/ThreadImportService.ts";
import * as ThreadLaunchService from "../../../orchestration-v2/ThreadLaunchService.ts";
import * as Digest from "effect/crypto/Digest";
import * as SecureRandom from "effect/crypto/SecureRandom";
import * as Schema from "effect/Schema";
import { Tool, Toolkit } from "effect/ai";
import { McpSchema, Tool, Toolkit } from "effect/ai";
import * as ProjectService from "../../../project/ProjectService.ts";
import * as ProjectCloneTracker from "../../../project/ProjectCloneTracker.ts";
import * as ManagedProjectFolders from "../../../project/ManagedProjectFolders.ts";
Expand Down Expand Up @@ -193,8 +196,28 @@ const ThreadLaunchTool = Tool.make("t3_thread_launch", {
.annotate(Tool.Destructive, true)
.annotate(Tool.OpenWorld, true);

const ThreadImportTool = Tool.make("t3_thread_import", {
...shared,
description:
"Create a thread here that continues a conversation handed off from another T3 Code environment. `messages` become its history; `continuationPrompt` starts its first run. A retry with the same `source` returns the same thread.",
parameters: OrchestratorMcpThreadImportInput,
success: OrchestratorMcpThreadImportResult,
dependencies: [
...shared.dependencies,
ThreadImportService.ThreadImportService,
ProviderRegistry.ProviderRegistry,
GitVcsDriver.GitVcsDriver,
FileSystem.FileSystem,
],
})
.annotate(Tool.Destructive, true)
.annotate(Tool.Idempotent, true)
// A linked environment's handoff calls this; nothing else is offered it.
.annotate(McpSchema.EnabledWhen, McpInvocationContext.linkedCallersOnly);

export const ProjectToolkit = Toolkit.make(
ThreadLaunchTool,
ThreadImportTool,
ProjectListTool,
ProjectReadTool,
ProjectCreateTool,
Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/orchestration-v2/ContextHandoffService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -323,7 +323,7 @@ function makeLegacyImportSummary(items: ReadonlyArray<OrchestrationV2TurnItem>):
}
});
const header =
"Imported conversation history from the previous T3 Code orchestrator. Use it as context; do not repeat it unless the user asks.";
"Imported conversation history from before this thread ran here. Use it as context; do not repeat it unless the user asks.";
const maxChars = 32_000;
const selected: Array<string> = [];
let remaining = maxChars - header.length - 2;
Expand Down
Loading
Loading