Skip to content

Commit de43a6a

Browse files
feat(server): t3_thread_import, conversation only
A thread moving here from a linked environment needs its conversation. t3_thread_import creates the thread with that history as runless, imported messages, so its first run gets it as a text context handoff whatever the provider, then sends continuationPrompt as that run's message. The thread id is a hash of the source environment, thread and handoff id, and the continuation's command id derives from the thread, so a retried import returns the thread the first created and starts nothing new. The tool goes through startsThreads: modes are capped by the caller's, and a link's import carries its linkOrigin. worktreePath, when given, must be one of the project's worktrees. The imported-history header no longer names "the previous T3 Code orchestrator", since history now also arrives from other environments. The capturing Codex adapter from the V1 cutover test moves to a testkit. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
1 parent b2918cf commit de43a6a

12 files changed

Lines changed: 699 additions & 165 deletions

File tree

‎apps/server/src/environment/ServerEnvironment.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,7 @@ export const make = Effect.gen(function* () {
261261
serverBrowser: true,
262262
peerLinks: true,
263263
mcpModeLimitHeader: true,
264+
threadImport: true,
264265
},
265266
};
266267

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

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { formatThreadLink } from "@t3tools/shared/threadLinks";
1010
import * as Effect from "effect/Effect";
1111
import * as FileSystem from "effect/FileSystem";
1212
import * as Option from "effect/Option";
13+
import * as ThreadImportService from "../../../orchestration-v2/ThreadImportService.ts";
1314
import * as ThreadMessageIntake from "../../../orchestration-v2/ThreadMessageIntake.ts";
1415
import * as Claims from "../../../orchestration-v2/AttachmentClaims.ts";
1516
import * as Project from "../../../project/ProjectService.ts";
@@ -209,6 +210,27 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
209210
// The launched thread carries the caller's link, if it has one.
210211
"stamped",
211212
),
213+
t3_thread_import: McpToolAccess.startsThreads(
214+
(input) => input,
215+
(input, { runtimeMode, interactionMode, linkOrigin }) =>
216+
Effect.gen(function* () {
217+
const projects = yield* access;
218+
const project = yield* projects
219+
.getById(input.projectId)
220+
.pipe(Effect.mapError(unavailable), Effect.map(Option.getOrUndefined));
221+
if (project === undefined)
222+
return yield* new OrchestratorMcpFailure({
223+
code: "invalid_request",
224+
message: "The project was not found.",
225+
});
226+
if (input.worktreePath !== undefined)
227+
yield* assertProjectWorktree(project.workspaceRoot, input.worktreePath);
228+
const imports = yield* ThreadImportService.ThreadImportService;
229+
return yield* imports.importThread({ ...input, runtimeMode, interactionMode, linkOrigin });
230+
}),
231+
// A moved thread carries the link that moved it, like a launch.
232+
"stamped",
233+
),
212234
t3_project_list: McpToolAccess.reads((input) =>
213235
Effect.gen(function* () {
214236
const { scope, target } = yield* remoteTarget(input);

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

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,14 @@ import {
1717
OrchestratorMcpClientRequestId,
1818
OrchestratorMcpEnvironmentTarget,
1919
OrchestratorMcpFailure,
20+
OrchestratorMcpThreadImportInput,
21+
OrchestratorMcpThreadImportResult,
2022
SourceControlCloneRepositoryInput,
2123
SourceControlCloneRepositoryResult,
2224
} from "@t3tools/contracts";
2325
import * as FileSystem from "effect/FileSystem";
2426
import * as ServerConfig from "../../../config.ts";
27+
import * as ThreadImportService from "../../../orchestration-v2/ThreadImportService.ts";
2528
import * as ThreadLaunchService from "../../../orchestration-v2/ThreadLaunchService.ts";
2629
import * as Crypto from "effect/Crypto";
2730
import * as Schema from "effect/Schema";
@@ -167,8 +170,25 @@ const ThreadLaunchTool = Tool.make("t3_thread_launch", {
167170
.annotate(Tool.Destructive, true)
168171
.annotate(Tool.OpenWorld, true);
169172

173+
const ThreadImportTool = Tool.make("t3_thread_import", {
174+
...shared,
175+
description:
176+
"Create a thread here that continues a conversation from another T3 Code environment, as when a thread is handed off to this one. The messages become the thread's history and its first run gets them as context; continuationPrompt, if given, starts that run. Retrying with the same source returns the thread the first call created. It runs within the caller's modes.",
177+
parameters: OrchestratorMcpThreadImportInput,
178+
success: OrchestratorMcpThreadImportResult,
179+
dependencies: [
180+
...shared.dependencies,
181+
ThreadImportService.ThreadImportService,
182+
GitVcsDriver.GitVcsDriver,
183+
FileSystem.FileSystem,
184+
],
185+
})
186+
.annotate(Tool.Destructive, true)
187+
.annotate(Tool.Idempotent, true);
188+
170189
export const ProjectToolkit = Toolkit.make(
171190
ThreadLaunchTool,
191+
ThreadImportTool,
172192
ProjectListTool,
173193
ProjectReadTool,
174194
ProjectCreateTool,

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ function makeLegacyImportSummary(items: ReadonlyArray<OrchestrationV2TurnItem>):
153153
}
154154
});
155155
const header =
156-
"Imported conversation history from the previous T3 Code orchestrator. Use it as context; do not repeat it unless the user asks.";
156+
"Imported conversation history from before this thread ran here. Use it as context; do not repeat it unless the user asks.";
157157
const maxChars = 32_000;
158158
const selected: Array<string> = [];
159159
let remaining = maxChars - header.length - 2;
Lines changed: 160 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
1+
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2+
import { assert, it } from "@effect/vitest";
3+
import {
4+
EnvironmentId,
5+
ProjectId,
6+
ProviderInstanceId,
7+
ThreadId,
8+
type OrchestrationV2ThreadProjection,
9+
} from "@t3tools/contracts";
10+
import * as Effect from "effect/Effect";
11+
import * as Layer from "effect/Layer";
12+
import * as Ref from "effect/Ref";
13+
14+
import * as SqlitePersistence from "../persistence/Sqlite.ts";
15+
import * as EventSink from "./EventSink.ts";
16+
import * as EventStore from "./EventStore.ts";
17+
import * as Orchestrator from "./Orchestrator.ts";
18+
import * as ProjectionStore from "./ProjectionStore.ts";
19+
import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
20+
import * as ThreadImportService from "./ThreadImportService.ts";
21+
import * as ThreadManagement from "./ThreadManagementService.ts";
22+
import { type CapturedTurn, makeCapturingCodexAdapter } from "./testkit/CapturingCodexAdapter.ts";
23+
import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts";
24+
import { checkpointWorkspace } from "./testkit/ReplayFixtureWorkspace.ts";
25+
26+
// A thread moved here from another environment arrives with its conversation.
27+
// Its first run here gets that history as a context handoff, so the agent
28+
// picks up where it left off, and a retried import changes nothing.
29+
30+
const modelSelection = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" };
31+
const source = {
32+
environmentId: EnvironmentId.make("environment:laptop"),
33+
threadId: ThreadId.make("thread:on-the-laptop"),
34+
handoffId: "handoff-1",
35+
};
36+
const history = [
37+
{
38+
role: "user" as const,
39+
text: "Find why the login test flakes.",
40+
createdAt: "2026-10-06T10:00:00.000Z",
41+
},
42+
{
43+
role: "assistant" as const,
44+
text: "EARLIER_FINDING: the session cookie races the redirect.",
45+
createdAt: "2026-10-06T10:01:00.000Z",
46+
},
47+
];
48+
const continuation = "Carry on from where you stopped on the laptop.";
49+
50+
const layerFor = (workspace: string, captured: Ref.Ref<ReadonlyArray<CapturedTurn>>) => {
51+
const layerDatabase = SqlitePersistence.layerMemory;
52+
const layerStores = Layer.mergeAll(
53+
layerDatabase,
54+
EventStore.layer.pipe(Layer.provideMerge(layerDatabase)),
55+
ProjectionStore.layer.pipe(Layer.provideMerge(layerDatabase)),
56+
);
57+
const layerOrchestrator = ProviderReplayHarness.layerWithRegistry(
58+
{
59+
name: "thread-import",
60+
runtimePolicyOverride: {
61+
cwd: workspace,
62+
approvalPolicy: "never",
63+
sandboxPolicy: { type: "readOnly", access: { type: "fullAccess" }, networkAccess: false },
64+
},
65+
},
66+
ProviderAdapterRegistry.layerSingle(
67+
makeCapturingCodexAdapter(captured, { response: "Picked it up.", modelSelection }),
68+
),
69+
{ databaseLayer: layerDatabase },
70+
);
71+
const layerThreads = ThreadManagement.layer.pipe(Layer.provideMerge(layerOrchestrator));
72+
return ThreadImportService.layer.pipe(
73+
Layer.provideMerge(layerThreads),
74+
Layer.provideMerge(EventSink.layer.pipe(Layer.provide(layerStores))),
75+
Layer.provideMerge(layerStores),
76+
Layer.provide(NodeCrypto.layer),
77+
);
78+
};
79+
80+
const waitForIdle = (threadId: ThreadId) =>
81+
Effect.gen(function* () {
82+
const orchestrator = yield* Orchestrator.OrchestratorV2;
83+
for (let attempt = 0; attempt < 1_000; attempt += 1) {
84+
const projection: OrchestrationV2ThreadProjection =
85+
yield* orchestrator.getThreadProjection(threadId);
86+
if (
87+
projection.runs.length > 0 &&
88+
projection.runs.every(
89+
(run) => !["queued", "starting", "running", "waiting"].includes(run.status),
90+
)
91+
) {
92+
return projection;
93+
}
94+
yield* Effect.sleep("5 millis");
95+
}
96+
return yield* Effect.die(new Error("The imported thread never went idle."));
97+
});
98+
99+
it.live(
100+
"an imported thread's first run continues with its history, and re-importing is a no-op",
101+
() =>
102+
Effect.scoped(
103+
Effect.gen(function* () {
104+
const workspace = yield* checkpointWorkspace("thread-import");
105+
const captured = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
106+
yield* Effect.gen(function* () {
107+
const imports = yield* ThreadImportService.ThreadImportService;
108+
const request = {
109+
source,
110+
projectId: ProjectId.make("project:box"),
111+
title: "Flaky login test",
112+
modelSelection,
113+
runtimeMode: "full-access" as const,
114+
interactionMode: "default" as const,
115+
linkOrigin: { sessionId: "session-laptop", label: "T3 Code · Laptop" },
116+
messages: history,
117+
continuationPrompt: continuation,
118+
};
119+
const first = yield* imports.importThread(request);
120+
assert.isTrue(first.created);
121+
const projection = yield* waitForIdle(first.threadId);
122+
123+
// The history is there, before the first run, and marked as imported.
124+
assert.equal(projection.thread.historyOrigin, "v1_import");
125+
assert.deepEqual(projection.thread.linkOrigin, request.linkOrigin);
126+
const runless = projection.messages.filter((message) => message.runId === null);
127+
assert.deepEqual(
128+
runless.map((message) => [message.role, message.text]),
129+
history.map((message) => [message.role, message.text]),
130+
);
131+
// The first run got the history as context, then the continuation.
132+
assert.equal(projection.contextHandoffs.length, 1);
133+
const turns = yield* Ref.get(captured);
134+
assert.equal(turns.length, 1);
135+
assert.include(turns[0]!.text, "Context handoff (manual_context):");
136+
assert.include(turns[0]!.text, "EARLIER_FINDING");
137+
assert.include(turns[0]!.text, `User message:\n${continuation}`);
138+
139+
// Retrying the same import creates nothing and runs nothing new.
140+
const retried = yield* imports.importThread(request);
141+
assert.deepEqual(retried, { ...first, created: false });
142+
const after = yield* Orchestrator.OrchestratorV2.pipe(
143+
Effect.flatMap((orchestrator) => orchestrator.getThreadProjection(first.threadId)),
144+
);
145+
assert.equal(after.messages.length, projection.messages.length);
146+
assert.equal(after.runs.length, 1);
147+
assert.equal((yield* Ref.get(captured)).length, 1);
148+
149+
// A different handoff of the same source thread is a new thread.
150+
const again = yield* imports.importThread({
151+
...request,
152+
source: { ...source, handoffId: "handoff-2" },
153+
continuationPrompt: undefined,
154+
});
155+
assert.notEqual(again.threadId, first.threadId);
156+
assert.isNull(again.runId);
157+
}).pipe(Effect.provide(layerFor(workspace, captured)));
158+
}),
159+
),
160+
);

0 commit comments

Comments
 (0)