Skip to content

Commit 90b5d7d

Browse files
committed
feat(threads): hand off Claude CLI conversations through existing T3 services [skip ci]
1 parent cefb544 commit 90b5d7d

34 files changed

Lines changed: 3679 additions & 528 deletions

‎apps/server/src/cli/thread.test.ts‎

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,14 @@ import { assert, it } from "@effect/vitest";
22
import { RunId, ThreadId } from "@t3tools/contracts";
33
import * as Effect from "effect/Effect";
44

5-
import { readLatestMessages, type ThreadTools, titleFromMessage, waitForRun } from "./thread.ts";
5+
import {
6+
handoffThread,
7+
ThreadUsageError,
8+
readLatestMessages,
9+
type ThreadTools,
10+
titleFromMessage,
11+
waitForRun,
12+
} from "./thread.ts";
613

714
const threadId = ThreadId.make("thread-1");
815
const runId = RunId.make("run-1");
@@ -165,3 +172,49 @@ it("titles from a long first line without splitting an emoji", () => {
165172
const title = titleFromMessage(`${"a".repeat(78)}😀 and the rest of a long first line`);
166173
assert.strictEqual(title, `${"a".repeat(78)}…`);
167174
});
175+
it.effect.each(["wait", "interrupt"] as const)(
176+
"handoff asks once before applying the %s policy",
177+
(policy) =>
178+
Effect.gen(function* () {
179+
const blocked = { threadId, attached: true, readOnly: false, blocked: true };
180+
const done = { threadId, attached: false, readOnly: false };
181+
const { tools, calls } = scriptedTools({
182+
t3_thread_attach: policy === "wait" ? [blocked, blocked, done] : [blocked, done],
183+
});
184+
let choices = 0;
185+
const result = yield* handoffThread(
186+
tools,
187+
threadId,
188+
Effect.sync(() => {
189+
choices++;
190+
return policy;
191+
}),
192+
Effect.void,
193+
);
194+
assert.deepStrictEqual(result, done);
195+
assert.strictEqual(choices, 1);
196+
assert.deepStrictEqual(
197+
calls.map((call) => call.args),
198+
policy === "wait"
199+
? [0, 1, 2].map(() => ({ action: "handoff", threadId }))
200+
: [
201+
{ action: "handoff", threadId },
202+
{ action: "handoff", threadId, interrupt: true },
203+
],
204+
);
205+
}),
206+
);
207+
it.effect("cancelled handoff never interrupts the source", () =>
208+
Effect.gen(function* () {
209+
const { tools, calls } = scriptedTools({
210+
t3_thread_attach: [{ threadId, attached: true, readOnly: false, blocked: true }],
211+
});
212+
yield* handoffThread(
213+
tools,
214+
threadId,
215+
Effect.fail(new ThreadUsageError({ detail: "cancelled" })),
216+
Effect.void,
217+
).pipe(Effect.flip);
218+
assert.strictEqual(calls.length, 1);
219+
}),
220+
);

‎apps/server/src/cli/thread.ts‎

Lines changed: 155 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import {
2+
ClaudeSessionAttachmentResult,
23
OrchestratorMcpFailure,
34
OrchestratorMcpThreadListResult,
45
OrchestratorMcpThreadReadResult,
@@ -24,7 +25,7 @@ import * as Runtime from "effect/Runtime";
2425
import * as Schema from "effect/Schema";
2526
import * as Stdio from "effect/Stdio";
2627
import * as Stream from "effect/Stream";
27-
import { Argument, Command, Flag, GlobalFlag } from "effect/cli";
28+
import { Argument, Command, Flag, GlobalFlag, Prompt } from "effect/cli";
2829

2930
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
3031
import * as ServerConfig from "../config.ts";
@@ -696,7 +697,7 @@ const threadSendCommand = Command.make("send", {
696697
{ threadId, message, mode: "queue" },
697698
OrchestratorMcpThreadSendResult,
698699
);
699-
if (flags.wait) {
700+
if (flags.wait && sent.runId !== null) {
700701
return yield* finishRun(tools, { threadId, runId: sent.runId, json: flags.json });
701702
}
702703
yield* flags.json
@@ -762,9 +763,161 @@ const threadShowCommand = Command.make("show", {
762763
),
763764
);
764765

766+
type HandoffFlags = { readonly wait: boolean; readonly interrupt: boolean; readonly json: boolean };
767+
const handoffFlags = {
768+
wait: Flag.Boolean("wait").pipe(
769+
Flag.withDescription("Wait for the source CLI and its agents to exit."),
770+
Flag.withDefault(false),
771+
),
772+
interrupt: Flag.Boolean("interrupt").pipe(
773+
Flag.withDescription("Stop the source CLI and its agents, then resume work in T3 (Linux)."),
774+
Flag.withDefault(false),
775+
),
776+
};
777+
const validateHandoffFlags = (flags: HandoffFlags) =>
778+
flags.wait && flags.interrupt
779+
? Effect.fail(new ThreadUsageError({ detail: "Choose --wait or --interrupt, not both." }))
780+
: Effect.void;
781+
const runHandoff = Effect.fn("cli.thread.runHandoff")(function* (
782+
tools: ThreadTools,
783+
threadId: ThreadId,
784+
flags: HandoffFlags,
785+
) {
786+
yield* validateHandoffFlags(flags);
787+
const choose = flags.interrupt
788+
? Effect.succeed("interrupt" as const)
789+
: flags.wait
790+
? Effect.succeed("wait" as const)
791+
: Effect.gen(function* () {
792+
if (flags.json || !process.stdin.isTTY || !process.stdout.isTTY)
793+
return yield* new ThreadUsageError({
794+
detail:
795+
"The source CLI is still running. Use --wait to wait for it and its agents to exit, or --interrupt to stop them and resume the conversation in T3.",
796+
});
797+
const interrupt = yield* Prompt.run(
798+
Prompt.Confirm({
799+
message:
800+
"The source CLI is still running. Interrupt it and its agents, transfer the conversation, and resume work in T3? Choose No to wait for them to exit.",
801+
initial: false,
802+
}),
803+
).pipe(
804+
Effect.mapError(
805+
() =>
806+
new ThreadUsageError({
807+
detail: "Handoff cancelled; the source was not interrupted.",
808+
}),
809+
),
810+
);
811+
return interrupt ? ("interrupt" as const) : ("wait" as const);
812+
});
813+
const result = yield* handoffThread(
814+
tools,
815+
threadId,
816+
choose.pipe(
817+
Effect.tap((policy) =>
818+
flags.json
819+
? Effect.void
820+
: Console.error(
821+
policy === "wait"
822+
? "Waiting for the source CLI and its agents to exit. Ctrl+C cancels this wait."
823+
: "Stopping the source and its agents, then importing history and resuming in T3.",
824+
),
825+
),
826+
),
827+
);
828+
return result;
829+
});
830+
831+
const threadAttachCommand = Command.make("attach", {
832+
...projectLocationFlags,
833+
...handoffFlags,
834+
session: Argument.String("session"),
835+
provider: Flag.String("provider").pipe(Flag.optional),
836+
project: Flag.String("project").pipe(Flag.withDefault(".")),
837+
json: jsonFlag,
838+
}).pipe(
839+
Command.withDescription(
840+
"Move a local Claude conversation into T3, waiting or explicitly interrupting its source CLI.",
841+
),
842+
Command.withHandler((flags) =>
843+
withThreadTools(
844+
flags,
845+
Effect.fn("cli.thread.attach")(function* (tools) {
846+
yield* validateHandoffFlags(flags);
847+
const project = yield* resolveProject(tools, flags.project);
848+
const attached = yield* tools.call(
849+
"t3_thread_attach",
850+
{
851+
action: "attach",
852+
projectId: project.id,
853+
session: flags.session,
854+
...Option.match(flags.provider, {
855+
onNone: () => ({}),
856+
onSome: (providerInstanceId) => ({ providerInstanceId }),
857+
}),
858+
},
859+
ClaudeSessionAttachmentResult,
860+
);
861+
const result = yield* runHandoff(tools, attached.threadId, flags);
862+
yield* flags.json
863+
? printJson(result)
864+
: Console.log(`Handoff complete. Continue in ${result.link ?? result.threadId}.`);
865+
}),
866+
).pipe(reportThreadErrors),
867+
),
868+
);
869+
export const handoffThread = Effect.fn("cli.thread.handoffThread")(function* <R>(
870+
tools: ThreadTools,
871+
threadId: ThreadId,
872+
choose: Effect.Effect<"wait" | "interrupt", ThreadUsageError, R>,
873+
wait = Effect.sleep("1 second"),
874+
) {
875+
let policy: "wait" | "interrupt" | undefined;
876+
while (true) {
877+
const result = yield* tools.call(
878+
"t3_thread_attach",
879+
{ action: "handoff", threadId, ...(policy === "interrupt" ? { interrupt: true } : {}) },
880+
ClaudeSessionAttachmentResult,
881+
);
882+
if (!result.blocked) return result;
883+
if (policy === "interrupt") {
884+
return yield* new ThreadUsageError({
885+
detail: "The source did not stop; handoff was not completed.",
886+
});
887+
}
888+
policy ??= yield* choose;
889+
if (policy === "wait") yield* wait;
890+
}
891+
});
892+
893+
const threadHandoffCommand = Command.make("handoff", {
894+
...projectLocationFlags,
895+
thread: threadArgument,
896+
json: jsonFlag,
897+
...handoffFlags,
898+
}).pipe(
899+
Command.withDescription(
900+
"Continue an attached Claude conversation through T3 after Claude and its agents have exited.",
901+
),
902+
Command.withHandler((flags) =>
903+
withThreadTools(
904+
flags,
905+
Effect.fn("cli.thread.handoff")(function* (tools) {
906+
const threadId = yield* decodeThreadId(flags.thread);
907+
const result = yield* runHandoff(tools, threadId, flags);
908+
yield* flags.json
909+
? printJson(result)
910+
: Console.log(`Handoff complete. Continue in ${result.link ?? result.threadId}.`);
911+
}),
912+
).pipe(reportThreadErrors),
913+
),
914+
);
915+
765916
export const threadCommand = Command.make("thread").pipe(
766917
Command.withDescription("Start, message, and read threads on the running server."),
767918
Command.withSubcommands([
919+
threadAttachCommand,
920+
threadHandoffCommand,
768921
threadListCommand,
769922
threadStartCommand,
770923
threadSendCommand,

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

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import * as ClaudeAttachment from "../../../project/ClaudeSessionAttachment.ts";
12
import * as ProviderRegistry from "../../../provider/ProviderRegistry.ts";
23
import { expect, it } from "@effect/vitest";
34
import {
@@ -664,3 +665,46 @@ it.effect("deleting a project through MCP also discards its clone record", () =>
664665
expect(discarded).toEqual([harness.projectId]);
665666
}),
666667
);
668+
669+
it.effect("captures the attachment service and links only after handoff", () =>
670+
Effect.gen(function* () {
671+
const { projectId, dependencies } = clientLaunchHarness({
672+
runtimeModeCeiling: "full-access",
673+
launched: [],
674+
});
675+
const threadId = ThreadId.make("attached-thread");
676+
const requests: string[] = [];
677+
const attachment = Layer.mock(ClaudeAttachment.ClaudeSessionAttachment)({
678+
change: (input) =>
679+
Effect.sync(() => {
680+
requests.push(input.action);
681+
return { threadId, attached: input.action === "attach", readOnly: false };
682+
}),
683+
});
684+
const toolkit = yield* ProjectToolkit.pipe(
685+
Effect.provide(
686+
McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(
687+
Layer.provide(Layer.merge(dependencies, attachment)),
688+
),
689+
),
690+
);
691+
const result = yield* toolkit
692+
.handle("t3_thread_attach", { action: "attach", projectId, session: "repair-session" })
693+
.pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies));
694+
expect(result.at(-1)?.result).not.toHaveProperty("link");
695+
const completed = yield* toolkit
696+
.handle("t3_thread_attach", { action: "handoff", threadId })
697+
.pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies));
698+
expect(completed.at(-1)?.result).toMatchObject({
699+
threadId,
700+
attached: false,
701+
link: expect.any(String),
702+
});
703+
expect(requests).toEqual(["attach", "handoff"]);
704+
expect(result.at(-1)?.result).toMatchObject({
705+
threadId,
706+
attached: true,
707+
readOnly: false,
708+
});
709+
}),
710+
);

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

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1+
import * as ClaudeAttachment from "../../../project/ClaudeSessionAttachment.ts";
12
import {
3+
ClaudeSessionAttachmentInput,
24
CommandId,
35
MessageId,
46
ThreadId,
@@ -81,7 +83,36 @@ const access = Effect.gen(function* () {
8183
yield* readCaller();
8284
return yield* Project.ProjectService;
8385
});
86+
const decodeAttachmentInput = Schema.decodeUnknownEffect(ClaudeSessionAttachmentInput);
87+
8488
export const layer = McpToolAccess.toLayer(ProjectToolkit, {
89+
t3_thread_attach: McpToolAccess.writesEnvironment((input) =>
90+
Effect.gen(function* () {
91+
const service = yield* Effect.serviceOption(ClaudeAttachment.ClaudeSessionAttachment);
92+
if (Option.isNone(service)) return yield* unavailable();
93+
const decoded = yield* decodeAttachmentInput(input).pipe(
94+
Effect.mapError(
95+
() =>
96+
new OrchestratorMcpFailure({
97+
code: "invalid_request",
98+
message: "Attach requires projectId and session; handoff requires threadId.",
99+
}),
100+
),
101+
);
102+
const result = yield* service.value
103+
.change(decoded)
104+
.pipe(
105+
Effect.mapError(
106+
(error) =>
107+
new OrchestratorMcpFailure({ code: "invalid_request", message: error.message }),
108+
),
109+
);
110+
const scope = yield* McpInvocationContext.McpInvocationContext;
111+
return result.attached
112+
? result
113+
: { ...result, link: McpInvocationContext.threadLinkFor(scope, result.threadId) };
114+
}),
115+
),
85116
t3_thread_launch: McpToolAccess.startsThreads(
86117
(input) => input,
87118
(input, { runtimeMode, interactionMode, linkOrigin }) =>

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

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { McpAttachmentInput } from "../attachment/input.ts";
22
import {
3+
ClaudeSessionAttachmentResult,
34
NonNegativeInt,
45
ModelSelection,
56
TrimmedNonEmptyString,
@@ -14,6 +15,7 @@ import {
1415
ProjectCreatePayload,
1516
ProjectUpdatePayload,
1617
ProjectId,
18+
ProviderInstanceId,
1719
OrchestratorMcpClientRequestId,
1820
OrchestratorMcpEnvironmentTarget,
1921
OrchestratorMcpFailure,
@@ -178,7 +180,24 @@ const ThreadLaunchTool = Tool.make("t3_thread_launch", {
178180
.annotate(Tool.Destructive, true)
179181
.annotate(Tool.OpenWorld, true);
180182

183+
const ThreadAttachTool = Tool.make("t3_thread_attach", {
184+
...shared,
185+
description:
186+
"Import a local Claude conversation and its subagent history into normal T3 controls. Attach prepares the transfer using an exact session name or ID; handoff completes it after the source CLI exits. A blocked result leaves the source running. Only with explicit user authorization, set interrupt to stop the source and its agents and resume work through T3.",
187+
parameters: Schema.Struct({
188+
action: Schema.Literals(["attach", "handoff"]),
189+
projectId: Schema.optional(ProjectId),
190+
session: Schema.optional(TrimmedNonEmptyString),
191+
providerInstanceId: Schema.optional(ProviderInstanceId),
192+
threadId: Schema.optional(ThreadId),
193+
interrupt: Schema.optional(Schema.Boolean),
194+
}),
195+
success: ClaudeSessionAttachmentResult,
196+
dependencies: shared.dependencies,
197+
}).annotate(Tool.Destructive, true);
198+
181199
export const ProjectToolkit = Toolkit.make(
200+
ThreadAttachTool,
182201
ThreadLaunchTool,
183202
ProjectListTool,
184203
ProjectReadTool,

0 commit comments

Comments
 (0)