Add worktree handoff and status tools to the t3-code MCP server (#3754)
Expose MCP tools for worktree handoff and status inspection, with focused server and contract coverage. Co-authored-by: codex <[email protected]>
This commit is contained in:
1 parent
d957b368d6
commit
dee3de20fd
19 files changed
+2494
-47
No files matched your search
@@ -65,6 +65,7 @@ export class GitWorkflowService extends Context.Service<
|
||||
readonly createWorktree: (
|
||||
input: VcsCreateWorktreeInput,
|
||||
) => Effect.Effect<VcsCreateWorktreeResult, GitCommandError>;
|
||||
readonly listLocalBranchNames: (cwd: string) => Effect.Effect<string[], GitCommandError>;
|
||||
readonly fetchRemote: (input: {
|
||||
readonly cwd: string;
|
||||
readonly remoteName: string;
|
||||
@@ -303,6 +304,10 @@ export const make = Effect.gen(function* () {
|
||||
ensureGitCommand("GitWorkflowService.createWorktree", input.cwd).pipe(
|
||||
Effect.andThen(git.createWorktree(input)),
|
||||
),
|
||||
listLocalBranchNames: (cwd) =>
|
||||
ensureGitCommand("GitWorkflowService.listLocalBranchNames", cwd).pipe(
|
||||
Effect.andThen(git.listLocalBranchNames(cwd)),
|
||||
),
|
||||
fetchRemote: (input) =>
|
||||
ensureGitCommand("GitWorkflowService.fetchRemote", input.cwd).pipe(
|
||||
Effect.andThen(git.fetchRemote(input)),
|
||||
|
||||
@@ -25,6 +25,9 @@ import {
|
||||
PreviewSnapshotToolkit,
|
||||
PreviewStandardToolkit,
|
||||
} from "./toolkits/preview/tools.ts";
|
||||
import { WorktreeToolkitHandlersLive } from "./toolkits/worktree/handlers.ts";
|
||||
import { WorktreeToolkit } from "./toolkits/worktree/tools.ts";
|
||||
import * as WorktreeMcpService from "./WorktreeMcpService.ts";
|
||||
|
||||
const unauthorized = HttpServerResponse.jsonUnsafe(
|
||||
{
|
||||
@@ -224,6 +227,11 @@ export const OrchestratorToolkitRegistrationLive = McpServer.toolkit(Orchestrato
|
||||
Layer.provide(OrchestratorMcpService.layer),
|
||||
);
|
||||
|
||||
export const WorktreeToolkitRegistrationLive = McpServer.toolkit(WorktreeToolkit).pipe(
|
||||
Layer.provide(WorktreeToolkitHandlersLive),
|
||||
Layer.provide(WorktreeMcpService.layer),
|
||||
);
|
||||
|
||||
const McpTransportLive = McpServer.layerHttp({
|
||||
name: "T3 Code",
|
||||
version: packageJson.version,
|
||||
@@ -234,4 +242,5 @@ const McpTransportLive = McpServer.layerHttp({
|
||||
export const layer = Layer.mergeAll(
|
||||
PreviewToolkitRegistrationLive,
|
||||
OrchestratorToolkitRegistrationLive,
|
||||
).pipe(Layer.provideMerge(McpTransportLive), Layer.provide(PreviewAutomationBroker.layer));
|
||||
WorktreeToolkitRegistrationLive,
|
||||
).pipe(Layer.provideMerge(McpTransportLive));
|
||||
@@ -7,7 +7,8 @@ import {
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
export type McpCapability = "preview" | "orchestration";
|
||||
export const ALL_MCP_CAPABILITIES = ["preview", "orchestration", "worktree"] as const;
|
||||
export type McpCapability = (typeof ALL_MCP_CAPABILITIES)[number];
|
||||
|
||||
export interface McpInvocationScope {
|
||||
readonly environmentId: EnvironmentId;
|
||||
|
||||
@@ -43,7 +43,7 @@ it.effect("stores only a token hash, resolves the bearer token, and revokes by t
|
||||
|
||||
const resolved = yield* registry.resolve(token);
|
||||
expect(resolved?.threadId).toBe(threadId);
|
||||
expect(resolved?.capabilities).toEqual(new Set(["preview", "orchestration"]));
|
||||
expect(resolved?.capabilities).toEqual(new Set(["preview", "orchestration", "worktree"]));
|
||||
|
||||
yield* registry.revokeThread(threadId);
|
||||
expect(yield* registry.resolve(token)).toBeUndefined();
|
||||
|
||||
@@ -100,7 +100,7 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
|
||||
threadId: ThreadId.make(request.threadId),
|
||||
providerSessionId,
|
||||
providerInstanceId: ProviderInstanceId.make(request.providerInstanceId),
|
||||
capabilities: new Set(["preview", "orchestration"]),
|
||||
capabilities: new Set(McpInvocationContext.ALL_MCP_CAPABILITIES),
|
||||
issuedAt,
|
||||
};
|
||||
yield* SynchronizedRef.update(state, ({ records }) => {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,481 @@
|
||||
import {
|
||||
CommandId,
|
||||
MessageId,
|
||||
type ProjectId,
|
||||
WorktreeMcpFailure,
|
||||
type WorktreeMcpContinuationStatus,
|
||||
type WorktreeMcpHandoffInput,
|
||||
type WorktreeMcpHandoffResult,
|
||||
type WorktreeMcpSetupScriptStatus,
|
||||
type WorktreeMcpStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
|
||||
import * as GitWorkflowService from "../git/GitWorkflowService.ts";
|
||||
import { ThreadManagementService } from "../orchestration-v2/ThreadManagementService.ts";
|
||||
import * as ProjectService from "../project/ProjectService.ts";
|
||||
import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
|
||||
import * as ServerSettings from "../serverSettings.ts";
|
||||
import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts";
|
||||
import type { McpInvocationScope } from "./McpInvocationContext.ts";
|
||||
|
||||
export class WorktreeMcpService extends Context.Service<
|
||||
WorktreeMcpService,
|
||||
{
|
||||
readonly handoff: (
|
||||
scope: McpInvocationScope,
|
||||
input: WorktreeMcpHandoffInput,
|
||||
) => Effect.Effect<WorktreeMcpHandoffResult, WorktreeMcpFailure>;
|
||||
readonly status: (
|
||||
scope: McpInvocationScope,
|
||||
) => Effect.Effect<WorktreeMcpStatusResult, WorktreeMcpFailure>;
|
||||
}
|
||||
>()("t3/mcp/WorktreeMcpService") {}
|
||||
|
||||
function failure(code: WorktreeMcpFailure["code"], message: string): WorktreeMcpFailure {
|
||||
return new WorktreeMcpFailure({ code, message });
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
if (error instanceof Error) return error.message;
|
||||
if (typeof error === "object" && error !== null && "message" in error) {
|
||||
return String((error as { message: unknown }).message);
|
||||
}
|
||||
return String(error);
|
||||
}
|
||||
|
||||
const asOperationFailed = (prefix: string) =>
|
||||
Effect.mapError((error: unknown) =>
|
||||
failure("operation_failed", `${prefix}: ${errorMessage(error)}`),
|
||||
);
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const path = yield* Path.Path;
|
||||
const threadManagement = yield* ThreadManagementService;
|
||||
const projects = yield* ProjectService.ProjectService;
|
||||
const serverSettings = yield* ServerSettings.ServerSettingsService;
|
||||
const gitWorkflow = yield* GitWorkflowService.GitWorkflowService;
|
||||
const setupScriptRunner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
|
||||
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
|
||||
|
||||
// Serializes handoffs per thread: two concurrent calls could otherwise both
|
||||
// pass the worktreePath === null check and each create a worktree, leaving
|
||||
// one untracked on disk.
|
||||
const handoffThreadsInFlight = new Set<string>();
|
||||
|
||||
const requireCapability = (scope: McpInvocationScope) =>
|
||||
scope.capabilities.has("worktree")
|
||||
? Effect.void
|
||||
: Effect.fail(
|
||||
failure("capability_denied", "This MCP credential does not grant worktree capabilities."),
|
||||
);
|
||||
|
||||
const loadThread = (scope: McpInvocationScope) =>
|
||||
threadManagement.getThreadProjection(scope.threadId).pipe(
|
||||
Effect.mapError((error) =>
|
||||
error._tag === "OrchestratorProjectionError"
|
||||
? failure("thread_not_found", `Thread '${scope.threadId}' was not found.`)
|
||||
: failure(
|
||||
"operation_failed",
|
||||
`Unable to read thread ${scope.threadId}: ${errorMessage(error)}`,
|
||||
),
|
||||
),
|
||||
Effect.filterOrFail(
|
||||
(projection) => projection.thread.deletedAt === null,
|
||||
() => failure("thread_not_found", `Thread '${scope.threadId}' was not found.`),
|
||||
),
|
||||
);
|
||||
|
||||
const loadProject = (scope: McpInvocationScope, projectId: ProjectId) =>
|
||||
projects.getById(projectId).pipe(
|
||||
asOperationFailed(`Unable to read project ${projectId}`),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
failure(
|
||||
"project_not_found",
|
||||
`Project '${projectId}' was not found for thread '${scope.threadId}'.`,
|
||||
),
|
||||
),
|
||||
onSome: Effect.succeed,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const readDefaultStartFromOrigin = serverSettings.getSettings.pipe(
|
||||
Effect.map((settings) => settings.newWorktreesStartFromOrigin),
|
||||
asOperationFailed("Unable to read server settings"),
|
||||
);
|
||||
|
||||
const handoffIds = (scope: McpInvocationScope) =>
|
||||
crypto.randomUUIDv4.pipe(
|
||||
Effect.map((uuid) => {
|
||||
const part = (kind: string, operation: string) =>
|
||||
[kind, "mcp", encodeURIComponent(scope.providerSessionId), operation, uuid].join(":");
|
||||
return {
|
||||
commandId: CommandId.make(part("command", "worktree-handoff")),
|
||||
continuationCommandId: CommandId.make(part("command", "worktree-continuation")),
|
||||
continuationMessageId: MessageId.make(part("message", "worktree-continuation")),
|
||||
};
|
||||
}),
|
||||
Effect.orDie,
|
||||
);
|
||||
|
||||
const performHandoff = Effect.fn("WorktreeMcpService.performHandoff")(function* (
|
||||
scope: McpInvocationScope,
|
||||
input: WorktreeMcpHandoffInput,
|
||||
) {
|
||||
const alreadyInWorktree = (worktreePath: string) =>
|
||||
failure(
|
||||
"already_in_worktree",
|
||||
`Thread '${scope.threadId}' is already attached to worktree '${worktreePath}'.`,
|
||||
);
|
||||
|
||||
const projection = yield* loadThread(scope);
|
||||
if (projection.thread.worktreePath !== null) {
|
||||
return yield* alreadyInWorktree(projection.thread.worktreePath);
|
||||
}
|
||||
// An archived thread would accept the binding but refuse the continuation
|
||||
// message (and any other follow-up), so reject the handoff outright.
|
||||
if (projection.thread.archivedAt !== null) {
|
||||
return yield* failure(
|
||||
"invalid_request",
|
||||
`Thread '${scope.threadId}' is archived and cannot be handed off to a worktree.`,
|
||||
);
|
||||
}
|
||||
|
||||
const project = yield* loadProject(scope, projection.thread.projectId);
|
||||
const projectCwd = project.workspaceRoot;
|
||||
|
||||
if (input.path !== undefined && !path.isAbsolute(input.path)) {
|
||||
return yield* failure(
|
||||
"invalid_request",
|
||||
`path must be an absolute filesystem path, got '${input.path}'. A relative path would be created relative to the project workspace but stored verbatim as the thread's worktree binding.`,
|
||||
);
|
||||
}
|
||||
|
||||
// The repo check runs regardless of whether baseRef was supplied, so a
|
||||
// non-repository workspace fails with an actionable error instead of an
|
||||
// opaque git failure further down.
|
||||
const localStatus = yield* gitWorkflow
|
||||
.localStatus({ cwd: projectCwd })
|
||||
.pipe(asOperationFailed("Unable to read git status"));
|
||||
if (!localStatus.isRepo) {
|
||||
return yield* failure(
|
||||
"invalid_request",
|
||||
`Project workspace '${projectCwd}' is not a git repository.`,
|
||||
);
|
||||
}
|
||||
|
||||
// Fail fast with an actionable message when the branch already exists:
|
||||
// the git driver deliberately keeps stderr out of its errors, so letting
|
||||
// `git worktree add` fail would surface only an opaque failure. The
|
||||
// existence check uses the complete local branch list (exact match); the
|
||||
// paginated substring search only enriches the message with the checkout
|
||||
// location when available.
|
||||
const localBranchNames = yield* gitWorkflow
|
||||
.listLocalBranchNames(projectCwd)
|
||||
.pipe(asOperationFailed("Unable to list branches"));
|
||||
if (localBranchNames.includes(input.branch)) {
|
||||
const existingRef = yield* gitWorkflow
|
||||
.listRefs({ cwd: projectCwd, query: input.branch, refKind: "local" })
|
||||
.pipe(
|
||||
Effect.map((result) =>
|
||||
result.refs.find((ref) => ref.name === input.branch && ref.isRemote !== true),
|
||||
),
|
||||
Effect.orElseSucceed(() => undefined),
|
||||
);
|
||||
const checkoutPath = existingRef?.worktreePath ?? null;
|
||||
return yield* failure(
|
||||
"invalid_request",
|
||||
`Branch '${input.branch}' already exists${
|
||||
checkoutPath === null ? "" : ` and is checked out at '${checkoutPath}'`
|
||||
}. Choose a different branch name, or delete the existing branch${
|
||||
checkoutPath === null ? "" : " and its worktree"
|
||||
} first.`,
|
||||
);
|
||||
}
|
||||
|
||||
let baseRef = input.baseRef;
|
||||
if (baseRef === undefined) {
|
||||
if (localStatus.refName === null) {
|
||||
return yield* failure(
|
||||
"invalid_request",
|
||||
"Could not determine the current branch of the project workspace (detached HEAD?). Pass baseRef explicitly.",
|
||||
);
|
||||
}
|
||||
baseRef = localStatus.refName;
|
||||
}
|
||||
|
||||
const startFromOrigin = input.startFromOrigin ?? (yield* readDefaultStartFromOrigin);
|
||||
|
||||
let worktreeBaseRef = baseRef;
|
||||
if (startFromOrigin) {
|
||||
yield* gitWorkflow
|
||||
.fetchRemote({ cwd: projectCwd, remoteName: "origin" })
|
||||
.pipe(asOperationFailed("Unable to fetch origin"));
|
||||
const resolvedRemoteBase = yield* gitWorkflow
|
||||
.resolveRemoteTrackingCommit({
|
||||
cwd: projectCwd,
|
||||
refName: baseRef,
|
||||
fallbackRemoteName: "origin",
|
||||
})
|
||||
.pipe(asOperationFailed(`Unable to resolve the remote-tracking commit of '${baseRef}'`));
|
||||
worktreeBaseRef = resolvedRemoteBase.commitSha;
|
||||
}
|
||||
|
||||
const ids = yield* handoffIds(scope);
|
||||
|
||||
// uninterruptibleMask: only the potentially slow worktree creation itself
|
||||
// stays interruptible (restore). From the moment it succeeds, through the
|
||||
// binding, continuation queue, setup script launch, and result
|
||||
// construction, there is no interruptible gap: a client cancel can
|
||||
// therefore neither orphan the created worktree before the rollback is
|
||||
// armed, nor skip setting up a worktree the thread was just bound to
|
||||
// (once the binding commits, the scheduled session detach can sever this
|
||||
// request's connection and interrupt the fiber).
|
||||
return yield* Effect.uninterruptibleMask((restore) =>
|
||||
Effect.gen(function* () {
|
||||
const worktree = yield* restore(
|
||||
gitWorkflow
|
||||
.createWorktree({
|
||||
cwd: projectCwd,
|
||||
refName: worktreeBaseRef,
|
||||
newRefName: input.branch,
|
||||
baseRefName: baseRef,
|
||||
path: input.path ?? null,
|
||||
})
|
||||
.pipe(asOperationFailed("Unable to create the worktree")),
|
||||
);
|
||||
const worktreePath = worktree.worktree.path;
|
||||
|
||||
// Shared shape for "the handoff already succeeded, so report the failure
|
||||
// in the result instead of failing the call" (continuation, setup script).
|
||||
const reportFailed = (logMessage: string) =>
|
||||
Effect.catchCause((cause: Cause.Cause<unknown>) => {
|
||||
const detail = errorMessage(Cause.squash(cause));
|
||||
return Effect.logWarning(logMessage, {
|
||||
threadId: scope.threadId,
|
||||
worktreePath,
|
||||
detail,
|
||||
}).pipe(Effect.as({ status: "failed", detail } as const));
|
||||
});
|
||||
|
||||
// suspend: build the removal call only if cleanup actually runs.
|
||||
const removeCreatedWorktree = Effect.suspend(() =>
|
||||
gitWorkflow.removeWorktree({ cwd: projectCwd, path: worktreePath, force: true }),
|
||||
).pipe(Effect.ignoreCause({ log: true }));
|
||||
|
||||
const recheckAndBind = Effect.gen(function* () {
|
||||
// The projection was read before the potentially slow git work
|
||||
// above; a concurrent binding (for example from the UI) could have
|
||||
// attached the thread in the meantime. Re-check before committing so
|
||||
// the race cannot leave a second, untracked worktree.
|
||||
const recheck = yield* loadThread(scope);
|
||||
if (recheck.thread.worktreePath !== null) {
|
||||
return yield* alreadyInWorktree(recheck.thread.worktreePath);
|
||||
}
|
||||
// Mirror the up-front archived check: the thread may have been
|
||||
// archived during the slow git work, and an archived thread must
|
||||
// not be bound to a fresh worktree it can never use.
|
||||
if (recheck.thread.archivedAt !== null) {
|
||||
return yield* failure(
|
||||
"invalid_request",
|
||||
`Thread '${scope.threadId}' was archived while the worktree was being created; the handoff was rolled back.`,
|
||||
);
|
||||
}
|
||||
yield* threadManagement
|
||||
.dispatch({
|
||||
type: "thread.metadata.update",
|
||||
commandId: ids.commandId,
|
||||
threadId: scope.threadId,
|
||||
branch: worktree.worktree.refName,
|
||||
worktreePath,
|
||||
})
|
||||
.pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
// Interrupt-only causes propagate unchanged: whether the
|
||||
// dispatch committed is unknown, so neither a typed failure
|
||||
// nor a rollback would be correct. Failures and defects
|
||||
// (including mixed causes) map to a typed operation_failed.
|
||||
Cause.hasInterruptsOnly(cause)
|
||||
? Effect.failCause(cause as Cause.Cause<never>)
|
||||
: Effect.fail(
|
||||
failure(
|
||||
"operation_failed",
|
||||
`Unable to re-point the thread at the worktree: ${errorMessage(Cause.squash(cause))}`,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(
|
||||
// onError: the worktree was already created, so any failure between
|
||||
// here and the committed binding (recheck read, recheck race,
|
||||
// dispatch typed failure or defect) must remove it again so a failed
|
||||
// handoff leaves nothing behind on disk. Interrupt-only causes skip
|
||||
// the removal: the binding may have committed, and force-deleting a
|
||||
// worktree the thread now points at would be worse than leaking one.
|
||||
Effect.onError((cause) =>
|
||||
Cause.hasInterruptsOnly(cause) ? Effect.void : removeCreatedWorktree,
|
||||
),
|
||||
);
|
||||
|
||||
// Queue the continuation right after the binding commits: the detach
|
||||
// that the metadata update schedules will terminate the calling
|
||||
// session, and a durably queued message is what guarantees the thread
|
||||
// re-launches inside the worktree. When the dying run reaches a
|
||||
// terminal state the orchestrator promotes the queued run, which
|
||||
// derives its cwd from the updated projection.
|
||||
// suspend: build the send effect only when the binding has succeeded,
|
||||
// so a failed dispatch never even constructs the continuation call.
|
||||
const queueContinuation: Effect.Effect<WorktreeMcpContinuationStatus, WorktreeMcpFailure> =
|
||||
Effect.suspend(() =>
|
||||
input.continuationPrompt === undefined
|
||||
? Effect.succeed<WorktreeMcpContinuationStatus>({ status: "skipped" })
|
||||
: threadManagement
|
||||
.sendToThread({
|
||||
projectId: projection.thread.projectId,
|
||||
commandId: ids.continuationCommandId,
|
||||
threadId: scope.threadId,
|
||||
messageId: ids.continuationMessageId,
|
||||
text: input.continuationPrompt,
|
||||
attachments: [],
|
||||
mode: "queue",
|
||||
createdBy: "agent",
|
||||
creationSource: "mcp",
|
||||
})
|
||||
.pipe(
|
||||
Effect.map(
|
||||
(sendResult): WorktreeMcpContinuationStatus => ({
|
||||
status: "scheduled",
|
||||
delivery: sendResult.delivery,
|
||||
}),
|
||||
),
|
||||
// catchCause via reportFailed: the binding is already recorded,
|
||||
// so a failed continuation must be reported, not fail the handoff.
|
||||
reportFailed("worktree handoff continuation failed to queue"),
|
||||
),
|
||||
);
|
||||
|
||||
const continuation = yield* recheckAndBind.pipe(Effect.andThen(queueContinuation));
|
||||
|
||||
yield* vcsStatusBroadcaster
|
||||
.refreshStatus(worktreePath)
|
||||
.pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach);
|
||||
|
||||
let setupScript: WorktreeMcpSetupScriptStatus = { status: "skipped" };
|
||||
if (input.runSetupScript ?? true) {
|
||||
setupScript = yield* setupScriptRunner
|
||||
.runForThread({
|
||||
threadId: scope.threadId,
|
||||
projectId: projection.thread.projectId,
|
||||
projectCwd,
|
||||
worktreePath,
|
||||
project: {
|
||||
workspaceRoot: project.workspaceRoot,
|
||||
scripts: project.scripts,
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.map(
|
||||
(result): WorktreeMcpSetupScriptStatus =>
|
||||
result.status === "started"
|
||||
? {
|
||||
status: "started",
|
||||
scriptName: result.scriptName,
|
||||
terminalId: result.terminalId,
|
||||
}
|
||||
: { status: "no-script" },
|
||||
),
|
||||
// catchCause via reportFailed: the thread is already re-pointed at the
|
||||
// worktree, so even a defect in the setup runner must not fail the handoff.
|
||||
reportFailed("worktree handoff setup script failed"),
|
||||
);
|
||||
}
|
||||
|
||||
const result: WorktreeMcpHandoffResult = {
|
||||
worktreePath,
|
||||
branch: worktree.worktree.refName,
|
||||
baseRef,
|
||||
startedFromOrigin: startFromOrigin,
|
||||
setupScript,
|
||||
continuation,
|
||||
note:
|
||||
continuation.status === "scheduled"
|
||||
? "Handoff recorded. Changing the workspace detaches this provider session, so the current turn ends shortly after this call; the queued continuation prompt then starts the next turn inside the worktree with the conversation preserved. The worktree is not removed automatically when the thread is deleted."
|
||||
: "Handoff recorded. Changing the workspace detaches this provider session, so the current turn ends shortly after this call; the conversation continues inside the worktree when the thread receives its next message. Pass continuationPrompt to resume automatically. The worktree is not removed automatically when the thread is deleted.",
|
||||
};
|
||||
return result;
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const handoff: WorktreeMcpService["Service"]["handoff"] = Effect.fn("WorktreeMcpService.handoff")(
|
||||
function* (scope, input) {
|
||||
yield* requireCapability(scope);
|
||||
// uninterruptibleMask: the guard acquisition and the registration of the
|
||||
// releasing finalizer happen with no interruptible gap in between. An
|
||||
// interrupt landing between a bare add() and the start of an ensured
|
||||
// effect would otherwise leak the guard entry and block every future
|
||||
// handoff for this thread until restart.
|
||||
return yield* Effect.uninterruptibleMask((restore) =>
|
||||
Effect.suspend(() => {
|
||||
if (handoffThreadsInFlight.has(scope.threadId)) {
|
||||
return Effect.fail(
|
||||
failure(
|
||||
"handoff_in_progress",
|
||||
`A worktree handoff is already in progress for thread '${scope.threadId}'.`,
|
||||
),
|
||||
);
|
||||
}
|
||||
handoffThreadsInFlight.add(scope.threadId);
|
||||
return restore(performHandoff(scope, input)).pipe(
|
||||
Effect.ensuring(Effect.sync(() => handoffThreadsInFlight.delete(scope.threadId))),
|
||||
);
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
const status: WorktreeMcpService["Service"]["status"] = Effect.fn("WorktreeMcpService.status")(
|
||||
function* (scope) {
|
||||
yield* requireCapability(scope);
|
||||
const projection = yield* loadThread(scope);
|
||||
const project = yield* loadProject(scope, projection.thread.projectId);
|
||||
|
||||
const defaultStartFromOrigin = yield* readDefaultStartFromOrigin;
|
||||
|
||||
const result: WorktreeMcpStatusResult = {
|
||||
attached: projection.thread.worktreePath !== null,
|
||||
worktreePath: projection.thread.worktreePath,
|
||||
branch: projection.thread.branch,
|
||||
projectWorkspaceRoot: project.workspaceRoot,
|
||||
defaultStartFromOrigin,
|
||||
};
|
||||
return result;
|
||||
},
|
||||
);
|
||||
|
||||
return WorktreeMcpService.of({ handoff, status });
|
||||
});
|
||||
|
||||
export const layer: Layer.Layer<
|
||||
WorktreeMcpService,
|
||||
never,
|
||||
| Crypto.Crypto
|
||||
| Path.Path
|
||||
| ThreadManagementService
|
||||
| ProjectService.ProjectService
|
||||
| ServerSettings.ServerSettingsService
|
||||
| GitWorkflowService.GitWorkflowService
|
||||
| ProjectSetupScriptRunner.ProjectSetupScriptRunner
|
||||
| VcsStatusBroadcaster.VcsStatusBroadcaster
|
||||
> = Layer.effect(WorktreeMcpService, make);
|
||||
@@ -0,0 +1,22 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import { McpInvocationContext } from "../../McpInvocationContext.ts";
|
||||
import { WorktreeMcpService } from "../../WorktreeMcpService.ts";
|
||||
import { WorktreeToolkit } from "./tools.ts";
|
||||
|
||||
const handlers = {
|
||||
t3_worktree_handoff: (input) =>
|
||||
Effect.gen(function* () {
|
||||
const scope = yield* McpInvocationContext;
|
||||
const service = yield* WorktreeMcpService;
|
||||
return yield* service.handoff(scope, input);
|
||||
}),
|
||||
t3_worktree_status: () =>
|
||||
Effect.gen(function* () {
|
||||
const scope = yield* McpInvocationContext;
|
||||
const service = yield* WorktreeMcpService;
|
||||
return yield* service.status(scope);
|
||||
}),
|
||||
} satisfies Parameters<typeof WorktreeToolkit.toLayer>[0];
|
||||
|
||||
export const WorktreeToolkitHandlersLive = WorktreeToolkit.toLayer(handlers);
|
||||
@@ -0,0 +1,136 @@
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { NodeHttpServer } from "@effect/platform-node";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { HttpBody, HttpClient, HttpRouter } from "effect/unstable/http";
|
||||
|
||||
import * as ServerEnvironment from "../../../environment/ServerEnvironment.ts";
|
||||
import * as GitWorkflowService from "../../../git/GitWorkflowService.ts";
|
||||
import { ThreadManagementService } from "../../../orchestration-v2/ThreadManagementService.ts";
|
||||
import * as ProjectService from "../../../project/ProjectService.ts";
|
||||
import * as ProjectSetupScriptRunner from "../../../project/ProjectSetupScriptRunner.ts";
|
||||
import { ProviderRegistry } from "../../../provider/Services/ProviderRegistry.ts";
|
||||
import { ScheduledTaskService } from "../../../scheduledTasks/ScheduledTaskService.ts";
|
||||
import * as ServerSettings from "../../../serverSettings.ts";
|
||||
import { VcsStatusBroadcaster } from "../../../vcs/VcsStatusBroadcaster.ts";
|
||||
import * as McpHttpServer from "../../McpHttpServer.ts";
|
||||
import * as McpSessionRegistry from "../../McpSessionRegistry.ts";
|
||||
import * as PreviewAutomationBroker from "../../PreviewAutomationBroker.ts";
|
||||
|
||||
const StubServicesLive = Layer.mergeAll(
|
||||
Layer.mock(ThreadManagementService)({}),
|
||||
Layer.mock(ProviderRegistry)({}),
|
||||
Layer.mock(ScheduledTaskService)({}),
|
||||
Layer.mock(ProjectService.ProjectService)({}),
|
||||
ServerSettings.layerTest({}),
|
||||
Layer.mock(GitWorkflowService.GitWorkflowService)({}),
|
||||
Layer.mock(ProjectSetupScriptRunner.ProjectSetupScriptRunner)({}),
|
||||
Layer.mock(VcsStatusBroadcaster)({}),
|
||||
);
|
||||
|
||||
it.effect("production mcp layer lists worktree tools over http", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const routes = McpHttpServer.layer.pipe(Layer.provide(McpSessionRegistry.layer));
|
||||
yield* HttpRouter.serve(routes, {
|
||||
disableListenLog: true,
|
||||
disableLogger: true,
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
Layer.mock(ServerEnvironment.ServerEnvironment)({
|
||||
getEnvironmentId: Effect.succeed("environment-scratch" as never),
|
||||
}),
|
||||
),
|
||||
Layer.provide(PreviewAutomationBroker.layer),
|
||||
Layer.provide(StubServicesLive),
|
||||
Layer.build,
|
||||
);
|
||||
|
||||
const registry = McpSessionRegistry.issueActiveMcpCredential({
|
||||
threadId: ThreadId.make("thread-scratch"),
|
||||
providerInstanceId: ProviderInstanceId.make("claudeAgent"),
|
||||
});
|
||||
const credential = yield* registry;
|
||||
expect(credential).toBeDefined();
|
||||
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const auth = credential!.config.authorizationHeader;
|
||||
const initResponse = yield* httpClient.post("/mcp", {
|
||||
headers: {
|
||||
accept: "application/json, text/event-stream",
|
||||
authorization: auth,
|
||||
},
|
||||
body: HttpBody.text(
|
||||
`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"scratch","version":"1.0.0"}}}`,
|
||||
"application/json",
|
||||
),
|
||||
});
|
||||
expect(initResponse.status).toBe(200);
|
||||
const sessionId = initResponse.headers["mcp-session-id"];
|
||||
|
||||
const listResponse = yield* httpClient.post("/mcp", {
|
||||
headers: {
|
||||
accept: "application/json, text/event-stream",
|
||||
authorization: auth,
|
||||
...(sessionId ? { "mcp-session-id": sessionId } : {}),
|
||||
},
|
||||
body: HttpBody.text(
|
||||
`{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}`,
|
||||
"application/json",
|
||||
),
|
||||
});
|
||||
const bodyText = yield* listResponse.text;
|
||||
const ToolsListPayload = Schema.fromJsonString(
|
||||
Schema.Struct({
|
||||
result: Schema.Struct({
|
||||
tools: Schema.Array(
|
||||
Schema.Struct({
|
||||
name: Schema.String,
|
||||
inputSchema: Schema.Struct({ type: Schema.optional(Schema.String) }),
|
||||
annotations: Schema.optional(
|
||||
Schema.Struct({
|
||||
readOnlyHint: Schema.optional(Schema.Boolean),
|
||||
destructiveHint: Schema.optional(Schema.Boolean),
|
||||
openWorldHint: Schema.optional(Schema.Boolean),
|
||||
}),
|
||||
),
|
||||
}),
|
||||
),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
const payload = yield* Schema.decodeUnknownEffect(ToolsListPayload)(
|
||||
bodyText.match(/\{.*\}/s)![0],
|
||||
);
|
||||
const tools = payload.result.tools;
|
||||
const toolNames = tools.map((tool) => tool.name);
|
||||
expect(toolNames).toContain("t3_worktree_handoff");
|
||||
expect(toolNames).toContain("t3_worktree_status");
|
||||
// The worktree registration merges alongside the other toolkits rather
|
||||
// than replacing them.
|
||||
expect(toolNames).toContain("preview_status");
|
||||
expect(toolNames).toContain("delegate_task");
|
||||
|
||||
// The handoff tool mutates thread state, reaches the network (origin
|
||||
// fetch), and runs project setup scripts, so its MCP hints must not
|
||||
// promise a read-only, closed-world, non-destructive tool.
|
||||
const handoff = tools.find((tool) => tool.name === "t3_worktree_handoff");
|
||||
expect(handoff?.annotations?.readOnlyHint).toBe(false);
|
||||
expect(handoff?.annotations?.destructiveHint).toBe(true);
|
||||
expect(handoff?.annotations?.openWorldHint).toBe(true);
|
||||
const status = tools.find((tool) => tool.name === "t3_worktree_status");
|
||||
expect(status?.annotations?.readOnlyHint).toBe(true);
|
||||
expect(status?.annotations?.destructiveHint).toBe(false);
|
||||
|
||||
// MCP requires every tool input schema to be a top-level object schema.
|
||||
// A non-object schema (e.g. the anyOf produced by an empty
|
||||
// Schema.Struct({})) makes clients reject the entire server.
|
||||
for (const tool of tools) {
|
||||
expect(tool.inputSchema.type, `inputSchema.type of ${tool.name}`).toBe("object");
|
||||
}
|
||||
}),
|
||||
).pipe(Effect.provide(Layer.mergeAll(NodeHttpServer.layerTest, NodeServices.layer))),
|
||||
);
|
||||
@@ -0,0 +1,47 @@
|
||||
import {
|
||||
WorktreeMcpFailure,
|
||||
WorktreeMcpHandoffInput,
|
||||
WorktreeMcpHandoffResult,
|
||||
WorktreeMcpStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { Tool, Toolkit } from "effect/unstable/ai";
|
||||
|
||||
import * as McpInvocationContext from "../../McpInvocationContext.ts";
|
||||
import { WorktreeMcpService } from "../../WorktreeMcpService.ts";
|
||||
|
||||
const dependencies = [McpInvocationContext.McpInvocationContext, WorktreeMcpService];
|
||||
|
||||
export const WorktreeHandoffTool = Tool.make("t3_worktree_handoff", {
|
||||
description:
|
||||
"Move this agent thread into a new git worktree. Creates the worktree branch (optionally from origin), re-points the thread at the worktree, and by default runs the project's setup script there. Changing the workspace detaches the live provider session, so the current turn ends shortly after the handoff is recorded; call this as the last action of the turn. To keep working after the handoff, pass continuationPrompt with the remaining work: it is queued as the thread's next message and starts a new turn inside the worktree with the conversation preserved. Without it the thread stays idle until the next message. The worktree is not removed automatically when the thread is deleted. Fails if the thread is already attached to a worktree.",
|
||||
parameters: WorktreeMcpHandoffInput,
|
||||
success: WorktreeMcpHandoffResult,
|
||||
failure: WorktreeMcpFailure,
|
||||
failureMode: "return",
|
||||
dependencies,
|
||||
})
|
||||
.annotate(Tool.Title, "Hand off thread to a git worktree")
|
||||
.annotate(Tool.Readonly, false)
|
||||
.annotate(Tool.Destructive, true)
|
||||
.annotate(Tool.Idempotent, false)
|
||||
.annotate(Tool.OpenWorld, true);
|
||||
|
||||
export const WorktreeStatusTool = Tool.make("t3_worktree_status", {
|
||||
description:
|
||||
"Report this agent thread's worktree binding: whether it is attached to a git worktree, the worktree path and branch, the project's main workspace root, and the server default for t3_worktree_handoff's startFromOrigin. Call this before t3_worktree_handoff to check whether a handoff is possible or has already happened.",
|
||||
// No `parameters`: Tool.make defaults to Tool.EmptyParams, which serializes
|
||||
// to a top-level `type: "object"` JSON Schema. An explicit empty
|
||||
// Schema.Struct({}) serializes to `anyOf: [object, array]`, which is not a
|
||||
// valid MCP tool input schema and makes clients reject the whole server.
|
||||
success: WorktreeMcpStatusResult,
|
||||
failure: WorktreeMcpFailure,
|
||||
failureMode: "return",
|
||||
dependencies,
|
||||
})
|
||||
.annotate(Tool.Title, "Get thread worktree status")
|
||||
.annotate(Tool.Readonly, true)
|
||||
.annotate(Tool.Destructive, false)
|
||||
.annotate(Tool.Idempotent, true)
|
||||
.annotate(Tool.OpenWorld, false);
|
||||
|
||||
export const WorktreeToolkit = Toolkit.make(WorktreeHandoffTool, WorktreeStatusTool);
|
||||
@@ -28,6 +28,8 @@ export const OrchestrationEffectRequestV2 = Schema.Union([
|
||||
type: Schema.Literal("provider-session.detach"),
|
||||
providerSessionId: ProviderSessionId,
|
||||
detail: Schema.optional(Schema.String),
|
||||
/** Set on terminal detaches (thread archive/delete): revoke the thread's MCP credentials. */
|
||||
revokeMcpCredential: Schema.optional(Schema.Boolean),
|
||||
}),
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("provider-turn.start"),
|
||||
|
||||
@@ -88,6 +88,9 @@ export const executorLayer: Layer.Layer<
|
||||
providerSessionId: effect.request.providerSessionId,
|
||||
threadId: effect.threadId,
|
||||
...(effect.request.detail === undefined ? {} : { detail: effect.request.detail }),
|
||||
...(effect.request.revokeMcpCredential === undefined
|
||||
? {}
|
||||
: { revokeMcpCredential: effect.request.revokeMcpCredential }),
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
|
||||
@@ -1053,6 +1053,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
: command.type === "thread.runtime-mode.set"
|
||||
? "Runtime mode changed."
|
||||
: "Provider or model selection changed.",
|
||||
// Terminal detaches revoke the thread's MCP credentials; other
|
||||
// detach reasons keep them so a re-attaching provider process
|
||||
// stays authorized.
|
||||
...(command.type === "thread.archive" || command.type === "thread.delete"
|
||||
? { revokeMcpCredential: true }
|
||||
: {}),
|
||||
},
|
||||
} satisfies PendingOrchestrationEffectV2;
|
||||
yield* Ref.update(effects, (existing) => [...existing, pendingEffect]);
|
||||
|
||||
@@ -762,7 +762,7 @@ it.effect(
|
||||
assert.isDefined(token);
|
||||
const resolved = yield* registry.resolve(token!);
|
||||
assert.equal(resolved?.threadId, threadId);
|
||||
assert.deepEqual(resolved?.capabilities, new Set(["preview", "orchestration"]));
|
||||
assert.deepEqual(resolved?.capabilities, new Set(["preview", "orchestration", "worktree"]));
|
||||
|
||||
yield* manager.close(providerSessionId);
|
||||
assert.isUndefined(McpProviderSession.readMcpProviderSession(threadId));
|
||||
@@ -903,6 +903,333 @@ it.effect("ProviderSessionManagerV2 duplicate detach preserves replacement MCP c
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"ProviderSessionManagerV2 detach of a superseded live session preserves replacement MCP credentials",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const state = yield* Ref.make(emptyState);
|
||||
const mcpConfigs = yield* Ref.make<
|
||||
ReadonlyArray<McpProviderSession.McpProviderSessionConfig | undefined>
|
||||
>([]);
|
||||
const effect = Effect.gen(function* () {
|
||||
const eventSink = yield* EventSinkV2;
|
||||
const idAllocator = yield* IdAllocatorV2;
|
||||
const manager = yield* ProviderSessionManagerV2;
|
||||
const registry = yield* McpSessionRegistry.McpSessionRegistry;
|
||||
const now = yield* DateTime.now;
|
||||
const threadId = ThreadId.make("thread-provider-session-manager-superseded-mcp");
|
||||
const oldSessionId = yield* idAllocator.allocate.providerSession({
|
||||
providerInstanceId: modelSelection.instanceId,
|
||||
threadId,
|
||||
});
|
||||
const replacementSessionId = yield* idAllocator.allocate.providerSession({
|
||||
providerInstanceId: modelSelection.instanceId,
|
||||
threadId,
|
||||
});
|
||||
|
||||
yield* eventSink.write({
|
||||
events: [yield* makeThreadCreatedEvent({ idAllocator, threadId, now })],
|
||||
});
|
||||
yield* manager.open({
|
||||
threadId,
|
||||
providerSessionId: oldSessionId,
|
||||
modelSelection,
|
||||
runtimePolicy,
|
||||
});
|
||||
// The replacement opens while the old session is still attached: this is
|
||||
// the workspace-handoff sequence, where the queued continuation run can
|
||||
// start its session before the outbox executes the old session's detach.
|
||||
yield* manager.open({
|
||||
threadId,
|
||||
providerSessionId: replacementSessionId,
|
||||
modelSelection,
|
||||
runtimePolicy,
|
||||
});
|
||||
|
||||
const replacement = (yield* Ref.get(mcpConfigs)).at(-1);
|
||||
assert.isDefined(replacement);
|
||||
const replacementToken = replacement?.authorizationHeader.replace(/^Bearer\s+/, "");
|
||||
assert.isDefined(replacementToken);
|
||||
assert.equal(
|
||||
McpProviderSession.readMcpProviderSession(threadId)?.providerSessionId,
|
||||
replacement?.providerSessionId,
|
||||
);
|
||||
|
||||
// First (non-duplicate) detach of the superseded session must not revoke
|
||||
// the replacement's credential or clear its config slot.
|
||||
yield* manager.detach({ providerSessionId: oldSessionId, threadId });
|
||||
|
||||
assert.equal(
|
||||
McpProviderSession.readMcpProviderSession(threadId)?.providerSessionId,
|
||||
replacement?.providerSessionId,
|
||||
);
|
||||
assert.equal((yield* registry.resolve(replacementToken!))?.threadId, threadId);
|
||||
});
|
||||
|
||||
yield* effect.pipe(
|
||||
Effect.provide(
|
||||
makeTestLayer({
|
||||
state,
|
||||
idleTimeoutMs: 1_000,
|
||||
capabilities: ExclusiveCapabilities,
|
||||
mcpConfigs,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"ProviderSessionManagerV2 keeps a thread's MCP credential stable across detach and re-attach on a shared session",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const state = yield* Ref.make(emptyState);
|
||||
const mcpConfigs = yield* Ref.make<
|
||||
ReadonlyArray<McpProviderSession.McpProviderSessionConfig | undefined>
|
||||
>([]);
|
||||
const effect = Effect.gen(function* () {
|
||||
const eventSink = yield* EventSinkV2;
|
||||
const idAllocator = yield* IdAllocatorV2;
|
||||
const manager = yield* ProviderSessionManagerV2;
|
||||
const registry = yield* McpSessionRegistry.McpSessionRegistry;
|
||||
const now = yield* DateTime.now;
|
||||
const threadId = ThreadId.make("thread-provider-session-manager-stable-mcp");
|
||||
const providerSessionId = yield* idAllocator.allocate.providerSession({
|
||||
providerInstanceId: modelSelection.instanceId,
|
||||
threadId,
|
||||
});
|
||||
|
||||
yield* eventSink.write({
|
||||
events: [yield* makeThreadCreatedEvent({ idAllocator, threadId, now })],
|
||||
});
|
||||
yield* manager.open({
|
||||
threadId,
|
||||
providerSessionId,
|
||||
modelSelection,
|
||||
runtimePolicy,
|
||||
});
|
||||
|
||||
const original = (yield* Ref.get(mcpConfigs)).at(-1);
|
||||
assert.isDefined(original);
|
||||
const originalToken = original?.authorizationHeader.replace(/^Bearer\s+/, "");
|
||||
assert.isDefined(originalToken);
|
||||
|
||||
// Workspace-change handoff on a shared multi-thread session (codex):
|
||||
// the thread detaches while the provider process keeps running, and the
|
||||
// process's MCP client keeps using the credential it was started with.
|
||||
yield* manager.detach({ providerSessionId, threadId, detail: "Workspace changed." });
|
||||
assert.equal(
|
||||
(yield* registry.resolve(originalToken!))?.threadId,
|
||||
threadId,
|
||||
"detach must not revoke the credential the live provider process still holds",
|
||||
);
|
||||
|
||||
// The continuation run re-attaches the same thread to the same session;
|
||||
// the credential must be reused, not rotated, so the provider process's
|
||||
// long-lived MCP client stays authorized.
|
||||
yield* manager.open({
|
||||
threadId,
|
||||
providerSessionId,
|
||||
modelSelection,
|
||||
runtimePolicy,
|
||||
});
|
||||
assert.equal(
|
||||
McpProviderSession.readMcpProviderSession(threadId)?.providerSessionId,
|
||||
original?.providerSessionId,
|
||||
"re-attach must reuse the existing credential, not rotate it",
|
||||
);
|
||||
assert.equal((yield* registry.resolve(originalToken!))?.threadId, threadId);
|
||||
|
||||
// Releasing the session (provider process gone) still revokes.
|
||||
yield* manager.close(providerSessionId);
|
||||
assert.isUndefined(yield* registry.resolve(originalToken!));
|
||||
});
|
||||
|
||||
yield* effect.pipe(
|
||||
Effect.provide(
|
||||
makeTestLayer({
|
||||
state,
|
||||
idleTimeoutMs: 1_000,
|
||||
mcpConfigs,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"ProviderSessionManagerV2 revokes a rotated credential despite a stale record on another live session",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const state = yield* Ref.make(emptyState);
|
||||
const mcpConfigs = yield* Ref.make<
|
||||
ReadonlyArray<McpProviderSession.McpProviderSessionConfig | undefined>
|
||||
>([]);
|
||||
const effect = Effect.gen(function* () {
|
||||
const eventSink = yield* EventSinkV2;
|
||||
const idAllocator = yield* IdAllocatorV2;
|
||||
const manager = yield* ProviderSessionManagerV2;
|
||||
const registry = yield* McpSessionRegistry.McpSessionRegistry;
|
||||
const now = yield* DateTime.now;
|
||||
const threadId = ThreadId.make("thread-provider-session-manager-stale-record");
|
||||
const s1 = yield* idAllocator.allocate.providerSession({
|
||||
providerInstanceId: modelSelection.instanceId,
|
||||
threadId,
|
||||
});
|
||||
const s2 = yield* idAllocator.allocate.providerSession({
|
||||
providerInstanceId: modelSelection.instanceId,
|
||||
threadId,
|
||||
});
|
||||
|
||||
yield* eventSink.write({
|
||||
events: [yield* makeThreadCreatedEvent({ idAllocator, threadId, now })],
|
||||
});
|
||||
// S1 (shared session) records credential C1 for the thread, then the
|
||||
// thread detaches; S1 stays alive with the stale record.
|
||||
yield* manager.open({ threadId, providerSessionId: s1, modelSelection, runtimePolicy });
|
||||
yield* manager.detach({ providerSessionId: s1, threadId });
|
||||
|
||||
// The credential dies externally, so S2's attach must rotate to C2.
|
||||
yield* registry.revokeThread(threadId);
|
||||
yield* manager.open({ threadId, providerSessionId: s2, modelSelection, runtimePolicy });
|
||||
const rotated = McpProviderSession.readMcpProviderSession(threadId);
|
||||
assert.isDefined(rotated);
|
||||
const rotatedToken = rotated?.authorizationHeader.replace(/^Bearer\s+/, "");
|
||||
assert.isDefined(yield* registry.resolve(rotatedToken!));
|
||||
|
||||
// Releasing S2 must revoke C2 even though S1 still carries a stale
|
||||
// record (of dead C1) for the same thread.
|
||||
yield* manager.close(s2);
|
||||
assert.isUndefined(
|
||||
yield* registry.resolve(rotatedToken!),
|
||||
"stale record on S1 must not veto revoking S2's rotated credential",
|
||||
);
|
||||
yield* manager.close(s1);
|
||||
});
|
||||
|
||||
yield* effect.pipe(
|
||||
Effect.provide(makeTestLayer({ state, idleTimeoutMs: 1_000, mcpConfigs })),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"ProviderSessionManagerV2 protects a reused credential from a predecessor release during open",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const state = yield* Ref.make(emptyState);
|
||||
const mcpConfigs = yield* Ref.make<
|
||||
ReadonlyArray<McpProviderSession.McpProviderSessionConfig | undefined>
|
||||
>([]);
|
||||
const duringOpen = yield* Ref.make<Effect.Effect<void>>(Effect.void);
|
||||
const effect = Effect.gen(function* () {
|
||||
const eventSink = yield* EventSinkV2;
|
||||
const idAllocator = yield* IdAllocatorV2;
|
||||
const manager = yield* ProviderSessionManagerV2;
|
||||
const registry = yield* McpSessionRegistry.McpSessionRegistry;
|
||||
const now = yield* DateTime.now;
|
||||
const threadId = ThreadId.make("thread-provider-session-manager-open-race");
|
||||
const s1 = yield* idAllocator.allocate.providerSession({
|
||||
providerInstanceId: modelSelection.instanceId,
|
||||
threadId,
|
||||
});
|
||||
const s2 = yield* idAllocator.allocate.providerSession({
|
||||
providerInstanceId: modelSelection.instanceId,
|
||||
threadId,
|
||||
});
|
||||
|
||||
yield* eventSink.write({
|
||||
events: [yield* makeThreadCreatedEvent({ idAllocator, threadId, now })],
|
||||
});
|
||||
yield* manager.open({ threadId, providerSessionId: s1, modelSelection, runtimePolicy });
|
||||
const original = (yield* Ref.get(mcpConfigs)).at(-1);
|
||||
const originalToken = original?.authorizationHeader.replace(/^Bearer\s+/, "");
|
||||
assert.isDefined(originalToken);
|
||||
yield* manager.detach({ providerSessionId: s1, threadId });
|
||||
|
||||
// While S2's provider process is spawning (after prepare reused the
|
||||
// credential, before the entry is visible), the predecessor session
|
||||
// releases. Eager adapters (ACP, OpenCode) bake the credential into
|
||||
// the process during openSession, so the release must not revoke it;
|
||||
// rotating afterwards cannot repair those adapters.
|
||||
yield* Ref.set(duringOpen, manager.close(s1).pipe(Effect.orDie));
|
||||
yield* manager.open({ threadId, providerSessionId: s2, modelSelection, runtimePolicy });
|
||||
|
||||
const slot = McpProviderSession.readMcpProviderSession(threadId);
|
||||
assert.equal(
|
||||
slot?.providerSessionId,
|
||||
original?.providerSessionId,
|
||||
"the credential the adapter was configured with must remain current",
|
||||
);
|
||||
assert.equal(
|
||||
(yield* registry.resolve(originalToken!))?.threadId,
|
||||
threadId,
|
||||
"the predecessor release must not revoke a credential reserved by an in-flight open",
|
||||
);
|
||||
yield* manager.close(s2);
|
||||
});
|
||||
|
||||
yield* effect.pipe(
|
||||
Effect.provide(
|
||||
makeTestLayer({
|
||||
state,
|
||||
idleTimeoutMs: 1_000,
|
||||
mcpConfigs,
|
||||
beforeOpen: (input) =>
|
||||
input.providerSessionId === undefined
|
||||
? Effect.void
|
||||
: Ref.get(duringOpen).pipe(
|
||||
Effect.flatten,
|
||||
Effect.tap(() => Ref.set(duringOpen, Effect.void)),
|
||||
),
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("ProviderSessionManagerV2 terminal detach revokes the thread's MCP credential", () =>
|
||||
Effect.gen(function* () {
|
||||
const state = yield* Ref.make(emptyState);
|
||||
const mcpConfigs = yield* Ref.make<
|
||||
ReadonlyArray<McpProviderSession.McpProviderSessionConfig | undefined>
|
||||
>([]);
|
||||
const effect = Effect.gen(function* () {
|
||||
const eventSink = yield* EventSinkV2;
|
||||
const idAllocator = yield* IdAllocatorV2;
|
||||
const manager = yield* ProviderSessionManagerV2;
|
||||
const registry = yield* McpSessionRegistry.McpSessionRegistry;
|
||||
const now = yield* DateTime.now;
|
||||
const threadId = ThreadId.make("thread-provider-session-manager-terminal-detach");
|
||||
const providerSessionId = yield* idAllocator.allocate.providerSession({
|
||||
providerInstanceId: modelSelection.instanceId,
|
||||
threadId,
|
||||
});
|
||||
|
||||
yield* eventSink.write({
|
||||
events: [yield* makeThreadCreatedEvent({ idAllocator, threadId, now })],
|
||||
});
|
||||
yield* manager.open({ threadId, providerSessionId, modelSelection, runtimePolicy });
|
||||
const issued = (yield* Ref.get(mcpConfigs)).at(-1);
|
||||
const token = issued?.authorizationHeader.replace(/^Bearer\s+/, "");
|
||||
assert.isDefined(yield* registry.resolve(token!));
|
||||
|
||||
// Archive/delete detaches carry revokeMcpCredential: the token must die
|
||||
// with the thread even though the shared provider process lives on.
|
||||
yield* manager.detach({
|
||||
providerSessionId,
|
||||
threadId,
|
||||
detail: "Thread deleted.",
|
||||
revokeMcpCredential: true,
|
||||
});
|
||||
assert.isUndefined(yield* registry.resolve(token!));
|
||||
assert.isUndefined(McpProviderSession.readMcpProviderSession(threadId));
|
||||
});
|
||||
|
||||
yield* effect.pipe(Effect.provide(makeTestLayer({ state, idleTimeoutMs: 1_000, mcpConfigs })));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("ProviderSessionManagerV2 releases idle sessions without sweeping all sessions", () =>
|
||||
Effect.gen(function* () {
|
||||
const state = yield* Ref.make(emptyState);
|
||||
|
||||
@@ -154,6 +154,12 @@ export interface ProviderSessionManagerV2Shape {
|
||||
readonly providerSessionId: ProviderSessionId;
|
||||
readonly threadId: ThreadId;
|
||||
readonly detail?: string;
|
||||
/**
|
||||
* True for terminal detaches (thread archived or deleted): the thread's
|
||||
* MCP credentials are revoked immediately instead of surviving for a
|
||||
* potential re-attach.
|
||||
*/
|
||||
readonly revokeMcpCredential?: boolean;
|
||||
}) => Effect.Effect<void, ProviderSessionManagerV2Error>;
|
||||
}
|
||||
|
||||
@@ -165,6 +171,14 @@ export class ProviderSessionManagerV2 extends Context.Service<
|
||||
interface LiveSessionEntry {
|
||||
readonly attachedThreadIds: ReadonlySet<ThreadId>;
|
||||
readonly loadedProviderThreadKeyByThread: ReadonlyMap<ThreadId, string>;
|
||||
/**
|
||||
* MCP credential session id issued for each attached thread. Revocation on
|
||||
* detach/release is scoped to these ids so tearing down a superseded
|
||||
* session cannot revoke a replacement session's credential for the same
|
||||
* thread (the workspace-handoff sequence opens the replacement before the
|
||||
* outbox executes the old session's detach).
|
||||
*/
|
||||
readonly mcpCredentialIdByThread: ReadonlyMap<ThreadId, string>;
|
||||
readonly supportsMultipleProviderThreads: boolean;
|
||||
readonly runtime: ProviderAdapterV2SessionRuntime;
|
||||
readonly exposedRuntime: ProviderAdapterV2SessionRuntime;
|
||||
@@ -259,23 +273,116 @@ export const layerWithOptions = (
|
||||
const sessionOpen = yield* makeKeyedSerialExecutor<ProviderSessionId>();
|
||||
const idleTimeoutMs = Math.max(1, options.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS);
|
||||
const maxIdlePinMs = Math.max(0, options.maxIdlePinMs ?? DEFAULT_MAX_IDLE_PIN_MS);
|
||||
const prepareMcpSession = (threadId: ThreadId, providerInstanceId: ProviderInstanceId) =>
|
||||
interface PreparedMcpCredential {
|
||||
readonly mcpCredentialId: string | undefined;
|
||||
/** True when this call minted the credential (vs reusing a live one). */
|
||||
readonly issued: boolean;
|
||||
}
|
||||
/**
|
||||
* Reservations protect a credential between prepareMcpSession handing it
|
||||
* out and the owning session entry becoming visible in `sessions`.
|
||||
* Adapters like ACP and OpenCode consume the credential eagerly during
|
||||
* openSession, so a racing release must not revoke it in that window
|
||||
* (rotating afterwards cannot repair an already-configured process).
|
||||
* The holder MUST drop the reservation once the entry is recorded or the
|
||||
* open fails.
|
||||
*/
|
||||
const mcpCredentialReservations = new Map<string, number>();
|
||||
const mcpReservationKey = (threadId: ThreadId, mcpCredentialId: string) =>
|
||||
`${threadId} | ||||