The best way to control Claude Code, Codex and more from any computer or phone
feat(cli): start, message, and read threads from the terminal with t3 thread (#22732)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Theo Browne committed
Oct 21, 2026 at 01:17 UTC
955b4cc80166fd0bfd01fe2ec40285bd755f986f
8 files changed
+1041
-100
apps/server/src/auth/EnvironmentAuth.ts
+10
-2
@@ -558,7 +558,11 @@ export class EnvironmentAuth extends Context.Service<
558
readonly access: AuthMcpClientAccess;
559
readonly client: AuthClientMetadata;
560
}) => Effect.Effect<
561
- { readonly token: string; readonly expiresAt: DateTime.DateTime },
561
+ {
562
+ readonly sessionId: AuthSessionId;
563
+ readonly token: string;
564
+ readonly expiresAt: DateTime.DateTime;
565
+ },
566
ServerAuthInternalError
567
>;
568
/**
@@ -1292,7 +1296,11 @@ export const make = Effect.gen(function* () {
1296
client: { ...input.client, label: input.label, deviceType: "bot" },
1297
})
1298
.pipe(
1295
- Effect.map((issued) => ({ token: issued.token, expiresAt: issued.expiresAt })),
1299
+ Effect.map((issued) => ({
1300
+ sessionId: issued.sessionId,
1301
+ token: issued.token,
1302
+ expiresAt: issued.expiresAt,
1303
+ })),
1304
Effect.mapError((cause) => new ServerAuthSessionTokenIssueError({ cause })),
1305
Effect.withSpan("EnvironmentAuth.issueMcpClientSession"),
1306
);
apps/server/src/binCli.ts
+2
@@ -18,6 +18,7 @@ import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
18
import { extendConnectionAttemptTimeout, keepOutboundFetchOnHttp1 } from "./outboundHttp.ts";
19
import { sharedServerCommandFlags } from "./cli/config.ts";
20
import { projectCommand } from "./cli/project.ts";
21
+import { threadCommand } from "./cli/thread.ts";
22
import { runDefaultServerCommand, serveCommand, startCommand } from "./cli/server.ts";
23
import { updateCommand } from "./cli/update.ts";
24
import { uninstallCommand } from "./cli/uninstall.ts";
@@ -76,6 +77,7 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>
77
authCommand,
78
browserCommand,
79
projectCommand,
80
+ threadCommand,
81
serviceCommand,
82
updateCommand,
83
uninstallCommand,
apps/server/src/cli/thread.test.ts
new
+75
@@ -0,0 +1,75 @@
1
+import { assert, it } from "@effect/vitest";
2
+import { RunId, ThreadId } from "@t3tools/contracts";
3
+import * as Effect from "effect/Effect";
4
+
5
+import { type ThreadTools, waitForRun } from "./thread.ts";
6
+
7
+const threadId = ThreadId.make("thread-1");
8
+const runId = RunId.make("run-1");
9
+
10
+/** Answers each tool call with the next scripted response for that tool. */
11
+const scriptedTools = (script: Record<string, Array<unknown>>) => {
12
+ const calls: Array<{ readonly tool: string; readonly args: unknown }> = [];
13
+ const call = ((tool: string, args: unknown) => {
14
+ calls.push({ tool, args });
15
+ const next = script[tool]?.shift();
16
+ return next === undefined ? Effect.die(`unscripted ${tool} call`) : Effect.succeed(next);
17
+ }) as ThreadTools["call"];
18
+ return { tools: { call } satisfies ThreadTools, calls };
19
+};
20
+
21
+it.effect("--wait follows the sent run to its continuation's terminal status", () =>
22
+ Effect.gen(function* () {
23
+ const continuation = RunId.make("run-2");
24
+ const { tools, calls } = scriptedTools({
25
+ t3_thread_wait: [
26
+ { threadId, runId, status: "running", timedOut: true },
27
+ { threadId, runId: continuation, status: "failed", timedOut: false },
28
+ ],
29
+ t3_thread_read: [{ thread: { pendingRequestCount: 0 } }],
30
+ });
31
+
32
+ const outcome = yield* waitForRun(tools, threadId, runId);
33
+
34
+ assert.deepStrictEqual(outcome, { type: "ended", runId: continuation, status: "failed" });
35
+ assert.deepStrictEqual(
36
+ calls.filter((entry) => entry.tool === "t3_thread_wait").map((entry) => entry.args),
37
+ [
38
+ { threadId, runId, timeoutMs: 15_000 },
39
+ { threadId, runId, timeoutMs: 15_000 },
40
+ ],
41
+ );
42
+ }),
43
+);
44
+
45
+it.effect("--wait stops when the thread waits for an answer instead of polling forever", () =>
46
+ Effect.gen(function* () {
47
+ const { tools } = scriptedTools({
48
+ t3_thread_wait: [
49
+ { threadId, runId, status: "queued", timedOut: true },
50
+ { threadId, runId, status: "queued", timedOut: true },
51
+ ],
52
+ t3_thread_read: [{ thread: { pendingRequestCount: 1 } }],
53
+ });
54
+
55
+ assert.deepStrictEqual(yield* waitForRun(tools, threadId, runId), { type: "needs_input" });
56
+ }),
57
+);
58
+
59
+it.effect("--wait reports its run's result when a later run is the one waiting", () =>
60
+ Effect.gen(function* () {
61
+ const { tools } = scriptedTools({
62
+ t3_thread_wait: [
63
+ { threadId, runId, status: "running", timedOut: true },
64
+ { threadId, runId, status: "completed", timedOut: false },
65
+ ],
66
+ t3_thread_read: [{ thread: { pendingRequestCount: 1 } }],
67
+ });
68
+
69
+ assert.deepStrictEqual(yield* waitForRun(tools, threadId, runId), {
70
+ type: "ended",
71
+ runId,
72
+ status: "completed",
73
+ });
74
+ }),
75
+);
apps/server/src/cli/thread.ts
new
+710
@@ -0,0 +1,710 @@
1
+import {
2
+ OrchestratorMcpFailure,
3
+ OrchestratorMcpThreadListResult,
4
+ OrchestratorMcpThreadReadResult,
5
+ OrchestratorMcpThreadSendResult,
6
+ OrchestratorMcpThreadWaitResult,
7
+ ProjectId,
8
+ RunId,
9
+ ThreadId,
10
+ TrimmedNonEmptyString,
11
+ type OrchestratorMcpThreadListItem,
12
+ type OrchestratorMcpThreadStatus,
13
+ type OrchestratorMcpThreadTimelineItem,
14
+} from "@t3tools/contracts";
15
+import * as HostProcess from "@t3tools/shared/HostProcess";
16
+import * as Console from "effect/Console";
17
+import * as Effect from "effect/Effect";
18
+import * as FileSystem from "effect/FileSystem";
19
+import * as Layer from "effect/Layer";
20
+import * as Option from "effect/Option";
21
+import * as Path from "effect/Path";
22
+import * as References from "effect/References";
23
+import * as Runtime from "effect/Runtime";
24
+import * as Schema from "effect/Schema";
25
+import * as Stdio from "effect/Stdio";
26
+import * as Stream from "effect/Stream";
27
+import { Argument, Command, Flag, GlobalFlag } from "effect/cli";
28
+
29
+import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
30
+import * as ServerConfig from "../config.ts";
31
+import { mcpToolSession, type McpToolSession } from "../mcp/AcpMcpStdioBridge.ts";
32
+import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
33
+import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
34
+
35
+/**
36
+ * Short enough that a run which stops to ask the user something is noticed
37
+ * soon, since `t3_thread_wait` only returns on a terminal run.
38
+ */
39
+const WAIT_SLICE_MS = 15_000;
40
+const READ_PAGE_LIMIT = 100;
41
+const TITLE_MAX_CHARS = 80;
42
+
43
+export class ThreadServerNotRunningError extends Schema.TaggedError<ThreadServerNotRunningError>()(
44
+ "ThreadServerNotRunningError",
45
+ { baseDir: Schema.String },
46
+) {
47
+ override readonly [Runtime.errorReported] = false;
48
+ override get message(): string {
49
+ return `No running T3 Code server uses ${this.baseDir}. Start T3 Code, then retry.`;
50
+ }
51
+}
52
+
53
+export class ThreadServerUnreachableError extends Schema.TaggedError<ThreadServerUnreachableError>()(
54
+ "ThreadServerUnreachableError",
55
+ { origin: Schema.String, cause: Schema.Defect() },
56
+) {
57
+ override readonly [Runtime.errorReported] = false;
58
+ override get message(): string {
59
+ const reason = this.cause instanceof Error ? ` ${this.cause.message}` : "";
60
+ return `Could not reach the T3 Code server at ${this.origin}.${reason}`;
61
+ }
62
+}
63
+
64
+export class ThreadToolFailedError extends Schema.TaggedError<ThreadToolFailedError>()(
65
+ "ThreadToolFailedError",
66
+ { tool: Schema.String, detail: Schema.String },
67
+) {
68
+ override readonly [Runtime.errorReported] = false;
69
+ override get message(): string {
70
+ return this.detail;
71
+ }
72
+}
73
+
74
+export class ThreadUsageError extends Schema.TaggedError<ThreadUsageError>()("ThreadUsageError", {
75
+ detail: Schema.String,
76
+}) {
77
+ override readonly [Runtime.errorReported] = false;
78
+ override get message(): string {
79
+ return this.detail;
80
+ }
81
+}
82
+
83
+export class ThreadProjectNotFoundError extends Schema.TaggedError<ThreadProjectNotFoundError>()(
84
+ "ThreadProjectNotFoundError",
85
+ { identifier: Schema.String },
86
+) {
87
+ override readonly [Runtime.errorReported] = false;
88
+ override get message(): string {
89
+ return `No T3 Code project matches '${this.identifier}'. Pass a project id or a path inside a project.`;
90
+ }
91
+}
92
+
93
+/** Exit code 2 lets a script tell "needs a human" apart from a failed run. */
94
+export class ThreadNeedsInputError extends Schema.TaggedError<ThreadNeedsInputError>()(
95
+ "ThreadNeedsInputError",
96
+ { threadId: ThreadId },
97
+) {
98
+ override readonly [Runtime.errorReported] = false;
99
+ override readonly [Runtime.errorExitCode] = 2;
100
+
101
+ override get message(): string {
102
+ return `Thread ${this.threadId} is waiting for an answer. Open it in T3 Code to respond.`;
103
+ }
104
+}
105
+
106
+export class ThreadRunEndedError extends Schema.TaggedError<ThreadRunEndedError>()(
107
+ "ThreadRunEndedError",
108
+ { threadId: ThreadId, status: Schema.String, error: Schema.optional(Schema.String) },
109
+) {
110
+ override readonly [Runtime.errorReported] = false;
111
+ override get message(): string {
112
+ const reason = this.error === undefined ? "." : `: ${this.error}`;
113
+ return `Thread ${this.threadId} stopped with status ${this.status}${reason}`;
114
+ }
115
+}
116
+
117
+const ThreadCliError = Schema.Union([
118
+ ThreadServerNotRunningError,
119
+ ThreadServerUnreachableError,
120
+ ThreadToolFailedError,
121
+ ThreadUsageError,
122
+ ThreadProjectNotFoundError,
123
+ ThreadNeedsInputError,
124
+ ThreadRunEndedError,
125
+]);
126
+const isThreadCliError = Schema.is(ThreadCliError);
127
+
128
+/**
129
+ * These errors are expected outcomes for a script, so they print as one line
130
+ * on stderr instead of the runtime's logged stack trace.
131
+ */
132
+const reportThreadErrors = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
133
+ effect.pipe(
134
+ Effect.tapError((error) =>
135
+ isThreadCliError(error) ? Console.error(error.message) : Effect.void,
136
+ ),
137
+ );
138
+
139
+const decodeFailureText = Schema.decodeUnknownOption(Schema.fromJsonString(OrchestratorMcpFailure));
140
+const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
141
+const printJson = (value: unknown) => Console.log(encodeJson(value));
142
+
143
+const ToolResult = Schema.Struct({
144
+ isError: Schema.optional(Schema.Boolean),
145
+ structuredContent: Schema.optional(Schema.Unknown),
146
+ content: Schema.optional(
147
+ Schema.Array(Schema.Struct({ type: Schema.String, text: Schema.optional(Schema.String) })),
148
+ ),
149
+});
150
+
151
+const decodeToolResult = Schema.decodeUnknownEffect(ToolResult);
152
+
153
+const ProjectListResult = Schema.Struct({
154
+ projects: Schema.Array(
155
+ Schema.Struct({ id: ProjectId, title: Schema.String, workspaceRoot: Schema.String }),
156
+ ),
157
+ nextCursor: Schema.NullOr(Schema.Int),
158
+});
159
+
160
+const ThreadLaunchResult = Schema.Struct({
161
+ threadId: ThreadId,
162
+ projectId: ProjectId,
163
+ runId: Schema.NullOr(RunId),
164
+});
165
+
166
+const toolFailureDetail = (result: typeof ToolResult.Type) => {
167
+ const text = result.content?.find((part) => part.text !== undefined)?.text ?? "";
168
+ return Option.match(decodeFailureText(text), {
169
+ onNone: () => text || "The tool call failed.",
170
+ onSome: (failure) => failure.message,
171
+ });
172
+};
173
+
174
+const makeThreadTools = (session: McpToolSession, origin: string) => {
175
+ const unexpected = (tool: string) =>
176
+ new ThreadToolFailedError({
177
+ tool,
178
+ detail: `The server sent an unexpected ${tool} result. Update the t3 CLI to match the server.`,
179
+ });
180
+ return {
181
+ call: Effect.fn("cli.thread.callTool")(function* <S extends Schema.Decoder<unknown>>(
182
+ tool: string,
183
+ args: Readonly<Record<string, unknown>>,
184
+ schema: S,
185
+ ): Effect.fn.Return<S["Type"], ThreadServerUnreachableError | ThreadToolFailedError> {
186
+ const raw = yield* session
187
+ .call(tool, args)
188
+ .pipe(Effect.mapError((cause) => new ThreadServerUnreachableError({ origin, cause })));
189
+ const result = yield* decodeToolResult(raw).pipe(Effect.mapError(() => unexpected(tool)));
190
+ if (result.isError === true) {
191
+ return yield* new ThreadToolFailedError({ tool, detail: toolFailureDetail(result) });
192
+ }
193
+ return yield* Schema.decodeUnknownEffect(schema)(result.structuredContent).pipe(
194
+ Effect.mapError(() => unexpected(tool)),
195
+ );
196
+ }),
197
+ };
198
+};
199
+export type ThreadTools = ReturnType<typeof makeThreadTools>;
200
+
201
+/**
202
+ * Signs in as a short-lived MCP client of the running server, the same way an
203
+ * outside agent does, and revokes that session when the command ends.
204
+ */
205
+const withThreadTools = Effect.fn("cli.thread.withThreadTools")(function* <A, E, R>(
206
+ flags: { readonly baseDir: Option.Option<string> },
207
+ run: (tools: ThreadTools) => Effect.Effect<A, E, R>,
208
+) {
209
+ const logLevel = yield* GlobalFlag.LogLevel;
210
+ const config = yield* resolveCliAuthConfig(flags, logLevel);
211
+ return yield* Effect.gen(function* () {
212
+ const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath);
213
+ if (Option.isNone(runtimeState)) {
214
+ return yield* new ThreadServerNotRunningError({ baseDir: config.baseDir });
215
+ }
216
+ const origin = runtimeState.value.origin;
217
+ const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
218
+ const issued = yield* Effect.acquireRelease(
219
+ environmentAuth.issueMcpClientSession({
220
+ label: "t3 thread cli",
221
+ // The CLI runs as the machine's owner. New threads still start at
222
+ // the project's default mode, never at this ceiling by default.
223
+ access: "full-access",
224
+ client: { deviceType: "bot" },
225
+ }),
226
+ (session) =>
227
+ environmentAuth.revokeSession(session.sessionId).pipe(Effect.ignore({ log: true })),
228
+ );
229
+ const session = yield* mcpToolSession({
230
+ endpoint: new URL("/mcp", origin).href,
231
+ authorization: `Bearer ${issued.token}`,
232
+ clientName: "t3-thread-cli",
233
+ }).pipe(Effect.mapError((cause) => new ThreadServerUnreachableError({ origin, cause })));
234
+ return yield* run(makeThreadTools(session, origin));
235
+ }).pipe(
236
+ Effect.scoped,
237
+ Effect.provide(
238
+ EnvironmentAuth.layerRuntime.pipe(
239
+ Layer.provide(ServerConfig.layer(config)),
240
+ Layer.provide(Layer.succeed(References.MinimumLogLevel, config.logLevel)),
241
+ ),
242
+ ),
243
+ );
244
+});
245
+
246
+const readMessageArgument = Effect.fn("cli.thread.readMessage")(function* (argument: string) {
247
+ const text =
248
+ argument === "-"
249
+ ? yield* Stdio.Stdio.pipe(
250
+ Effect.flatMap((stdio) => stdio.stdin.pipe(Stream.decodeText(), Stream.mkString)),
251
+ )
252
+ : argument;
253
+ if (text.trim().length === 0) {
254
+ return yield* new ThreadUsageError({ detail: "The message is empty." });
255
+ }
256
+ return text;
257
+});
258
+
259
+const listAllProjects = Effect.fn("cli.thread.listAllProjects")(function* (tools: ThreadTools) {
260
+ const projects: Array<(typeof ProjectListResult.Type)["projects"][number]> = [];
261
+ let cursor: number | null = 0;
262
+ while (cursor !== null) {
263
+ const page: typeof ProjectListResult.Type = yield* tools.call(
264
+ "t3_project_list",
265
+ { cursor, limit: 100 },
266
+ ProjectListResult,
267
+ );
268
+ projects.push(...page.projects);
269
+ cursor = page.nextCursor;
270
+ }
271
+ return projects;
272
+});
273
+
274
+/** A project id, or a path inside a project's folder (deepest project wins). */
275
+const resolveProject = Effect.fn("cli.thread.resolveProject")(function* (
276
+ tools: ThreadTools,
277
+ identifier: string,
278
+) {
279
+ const projects = yield* listAllProjects(tools);
280
+ const byId = projects.find((project) => project.id === identifier);
281
+ if (byId !== undefined) return byId;
282
+
283
+ const path = yield* Path.Path;
284
+ const fileSystem = yield* FileSystem.FileSystem;
285
+ // Stored roots keep the path the project was added with, which may pass
286
+ // through a symlink (macOS /tmp), so both sides compare as real paths.
287
+ const realPath = (value: string) =>
288
+ fileSystem.realPath(value).pipe(Effect.orElseSucceed(() => value));
289
+ const target = yield* realPath(path.resolve(yield* HostProcess.WorkingDirectory, identifier));
290
+ const roots = yield* Effect.forEach(projects, (project) =>
291
+ Effect.map(realPath(project.workspaceRoot), (root) => ({ project, root })),
292
+ );
293
+ const containing = roots
294
+ .filter(({ root }) => {
295
+ const relative = path.relative(root, target);
296
+ return (
297
+ relative === "" ||
298
+ (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))
299
+ );
300
+ })
301
+ .toSorted((left, right) => right.root.length - left.root.length)[0];
302
+ if (containing === undefined) {
303
+ return yield* new ThreadProjectNotFoundError({ identifier });
304
+ }
305
+ return containing.project;
306
+});
307
+
308
+/** Every item on a timeline view, oldest first. */
309
+const readTimeline = Effect.fn("cli.thread.readTimeline")(function* (
310
+ tools: ThreadTools,
311
+ threadId: ThreadId,
312
+ view: "messages" | "activity",
313
+) {
314
+ const items: Array<OrchestratorMcpThreadTimelineItem> = [];
315
+ let afterPosition: number | undefined;
316
+ let page: OrchestratorMcpThreadReadResult;
317
+ do {
318
+ page = yield* tools.call(
319
+ "t3_thread_read",
320
+ {
321
+ threadId,
322
+ view,
323
+ limit: READ_PAGE_LIMIT,
324
+ runLimit: 1,
325
+ ...(afterPosition === undefined ? {} : { afterPosition }),
326
+ },
327
+ OrchestratorMcpThreadReadResult,
328
+ );
329
+ items.push(...page.items);
330
+ afterPosition = page.nextPosition ?? undefined;
331
+ } while (page.hasMore && afterPosition !== undefined);
332
+ return { thread: page.thread, items };
333
+});
334
+
335
+/** Item text past the read's per-item cap. */
336
+const readFullText = Effect.fn("cli.thread.readFullText")(function* (
337
+ tools: ThreadTools,
338
+ threadId: ThreadId,
339
+ item: OrchestratorMcpThreadTimelineItem,
340
+) {
341
+ let text = item.text ?? "";
342
+ let nextTextOffset = item.textTruncated ? (item.nextTextOffset ?? null) : null;
343
+ while (nextTextOffset !== null) {
344
+ const page = yield* tools.call(
345
+ "t3_thread_read",
346
+ { threadId, itemId: item.itemId, textOffset: nextTextOffset, runLimit: 1 },
347
+ OrchestratorMcpThreadReadResult,
348
+ );
349
+ const chunk = page.items.find((candidate) => candidate.itemId === item.itemId);
350
+ if (chunk === undefined) break;
351
+ text += chunk.text ?? "";
352
+ nextTextOffset = chunk.textTruncated ? (chunk.nextTextOffset ?? null) : null;
353
+ }
354
+ return text;
355
+});
356
+
357
+/** The run's last assistant message, or its last error when it did not complete. */
358
+const runResultText = Effect.fn("cli.thread.runResultText")(function* (
359
+ tools: ThreadTools,
360
+ threadId: ThreadId,
361
+ runId: RunId,
362
+ type: "assistant_message" | "error",
363
+) {
364
+ const { items } = yield* readTimeline(
365
+ tools,
366
+ threadId,
367
+ type === "assistant_message" ? "messages" : "activity",
368
+ );
369
+ const item = items.findLast((candidate) => candidate.runId === runId && candidate.type === type);
370
+ return item === undefined ? null : yield* readFullText(tools, threadId, item);
371
+});
372
+
373
+type WaitOutcome =
374
+ | {
375
+ readonly type: "ended";
376
+ readonly runId: RunId | null;
377
+ readonly status: OrchestratorMcpThreadStatus;
378
+ }
379
+ | { readonly type: "needs_input" };
380
+
381
+/**
382
+ * Waits for this exact run, following a restart to its continuation, so a
383
+ * message another client sends meanwhile cannot stand in for its result.
384
+ */
385
+export const waitForRun = Effect.fn("cli.thread.waitForRun")(function* (
386
+ tools: ThreadTools,
387
+ threadId: ThreadId,
388
+ runId: RunId,
389
+) {
390
+ const waitSlice = (timeoutMs: number) =>
391
+ tools.call("t3_thread_wait", { threadId, runId, timeoutMs }, OrchestratorMcpThreadWaitResult);
392
+ const ended = (waited: OrchestratorMcpThreadWaitResult) =>
393
+ ({ type: "ended", runId: waited.runId, status: waited.status }) satisfies WaitOutcome;
394
+ while (true) {
395
+ const waited = yield* waitSlice(WAIT_SLICE_MS);
396
+ if (!waited.timedOut) return ended(waited);
397
+ // A pending request on this run, or on an earlier run this one is queued
398
+ // behind, blocks it until someone answers.
399
+ const { thread } = yield* tools.call(
400
+ "t3_thread_read",
401
+ { threadId, limit: 1, runLimit: 1 },
402
+ OrchestratorMcpThreadReadResult,
403
+ );
404
+ if (thread.pendingRequestCount > 0) {
405
+ // The count is thread-wide: if this run ended since the slice, the
406
+ // request belongs to a later run.
407
+ const recheck = yield* waitSlice(1);
408
+ return recheck.timedOut ? ({ type: "needs_input" } satisfies WaitOutcome) : ended(recheck);
409
+ }
410
+ }
411
+});
412
+
413
+/**
414
+ * With --json the result always reaches stdout, so a script keeps the thread
415
+ * id even when the run fails.
416
+ */
417
+const finishRun = Effect.fn("cli.thread.finishRun")(function* (
418
+ tools: ThreadTools,
419
+ input: {
420
+ readonly threadId: ThreadId;
421
+ readonly runId: RunId;
422
+ readonly json: boolean;
423
+ },
424
+) {
425
+ const outcome = yield* waitForRun(tools, input.threadId, input.runId);
426
+ const runId = outcome.type === "ended" ? (outcome.runId ?? input.runId) : input.runId;
427
+ const status = outcome.type === "ended" ? outcome.status : "waiting";
428
+ const reply =
429
+ status === "completed"
430
+ ? yield* runResultText(tools, input.threadId, runId, "assistant_message")
431
+ : null;
432
+ const error =
433
+ status === "completed" || status === "waiting"
434
+ ? null
435
+ : yield* runResultText(tools, input.threadId, runId, "error");
436
+ if (input.json) {
437
+ yield* printJson({ threadId: input.threadId, runId, status, reply, error });
438
+ } else if (reply !== null) {
439
+ yield* Console.log(reply);
440
+ }
441
+ if (outcome.type === "needs_input") {
442
+ return yield* new ThreadNeedsInputError({ threadId: input.threadId });
443
+ }
444
+ if (status !== "completed") {
445
+ return yield* new ThreadRunEndedError({
446
+ threadId: input.threadId,
447
+ status,
448
+ ...(error === null ? {} : { error }),
449
+ });
450
+ }
451
+});
452
+
453
+const titleFromMessage = (message: string) => {
454
+ const firstLine = message.trim().split("\n")[0]?.trim() ?? "";
455
+ return firstLine.length > TITLE_MAX_CHARS
456
+ ? `${firstLine.slice(0, TITLE_MAX_CHARS - 1).trimEnd()}…`
457
+ : firstLine;
458
+};
459
+
460
+const launchWorkspaceStrategy = (input: {
461
+ readonly worktree: Option.Option<string>;
462
+ readonly branch: Option.Option<string>;
463
+}) =>
464
+ Option.match(input.worktree, {
465
+ onNone: () =>
466
+ Option.isSome(input.branch)
467
+ ? Effect.fail(new ThreadUsageError({ detail: "--branch needs --worktree <base-ref>." }))
468
+ : Effect.succeed(undefined),
469
+ onSome: (baseRef) =>
470
+ Effect.succeed({
471
+ type: "worktree" as const,
472
+ baseRef,
473
+ ...Option.match(input.branch, { onNone: () => ({}), onSome: (branch) => ({ branch }) }),
474
+ }),
475
+ });
476
+
477
+const jsonFlag = Flag.Boolean("json").pipe(
478
+ Flag.withDescription("Print JSON instead of text."),
479
+ Flag.withDefault(false),
480
+);
481
+const waitFlag = Flag.Boolean("wait").pipe(
482
+ Flag.withDescription(
483
+ "Wait for the agent to finish and print its reply. Exits 1 if the run fails and 2 if it waits for an answer.",
484
+ ),
485
+ Flag.withDefault(false),
486
+);
487
+const messageArgument = Argument.String("message").pipe(
488
+ Argument.withDescription("Message for the agent, or - to read it from stdin."),
489
+);
490
+const threadArgument = Argument.String("thread").pipe(Argument.withDescription("Thread id."));
491
+
492
+const decodeThreadIdValue = Schema.decodeUnknownEffect(ThreadId);
493
+const decodeTitle = Schema.decodeUnknownEffect(TrimmedNonEmptyString);
494
+const decodeThreadId = (value: string) =>
495
+ decodeThreadIdValue(value.trim()).pipe(
496
+ Effect.mapError(() => new ThreadUsageError({ detail: `'${value}' is not a thread id.` })),
497
+ );
498
+
499
+const threadListCommand = Command.make("list", {
500
+ ...projectLocationFlags,
501
+ project: Flag.String("project").pipe(
502
+ Flag.withDescription("Project id or a path inside the project. Defaults to this directory."),
503
+ Flag.withDefault("."),
504
+ ),
505
+ json: jsonFlag,
506
+}).pipe(
507
+ Command.withDescription("List a project's threads, newest first."),
508
+ Command.withHandler((flags) =>
509
+ withThreadTools(
510
+ flags,
511
+ Effect.fn("cli.thread.list")(function* (tools) {
512
+ const project = yield* resolveProject(tools, flags.project);
513
+ const threads: Array<OrchestratorMcpThreadListItem> = [];
514
+ let cursor: number | null = 0;
515
+ while (cursor !== null) {
516
+ const page: OrchestratorMcpThreadListResult = yield* tools.call(
517
+ "t3_thread_list",
518
+ { projectId: project.id, includeSubagents: false, limit: 100, cursor },
519
+ OrchestratorMcpThreadListResult,
520
+ );
521
+ threads.push(...page.threads);
522
+ cursor = page.nextCursor;
523
+ }
524
+ if (flags.json) {
525
+ return yield* printJson(threads);
526
+ }
527
+ for (const thread of threads) {
528
+ yield* Console.log(`${thread.threadId} ${thread.status.padEnd(11)} ${thread.title}`);
529
+ }
530
+ }),
531
+ ).pipe(reportThreadErrors),
532
+ ),
533
+);
534
+
535
+const threadStartCommand = Command.make("start", {
536
+ ...projectLocationFlags,
537
+ project: Argument.String("project").pipe(
538
+ Argument.withDescription("Project id or a path inside the project, such as ."),
539
+ ),
540
+ message: messageArgument,
541
+ title: Flag.String("title").pipe(
542
+ Flag.withDescription("Thread title. Defaults to the message's first line."),
543
+ Flag.optional,
544
+ ),
545
+ provider: Flag.String("provider").pipe(
546
+ Flag.withDescription("Provider instance id. Pass with --model."),
547
+ Flag.optional,
548
+ ),
549
+ model: Flag.String("model").pipe(
550
+ Flag.withDescription("Model slug. Defaults to the project's default model."),
551
+ Flag.optional,
552
+ ),
553
+ worktree: Flag.String("worktree").pipe(
554
+ Flag.withDescription(
555
+ "Run in a new git worktree based on this branch, tag, or commit, instead of the project folder.",
556
+ ),
557
+ Flag.optional,
558
+ ),
559
+ branch: Flag.String("branch").pipe(
560
+ Flag.withDescription("Branch name for the new worktree."),
561
+ Flag.optional,
562
+ ),
563
+ wait: waitFlag,
564
+ json: jsonFlag,
565
+}).pipe(
566
+ Command.withDescription("Start a thread in a project and print its id."),
567
+ Command.withHandler((flags) =>
568
+ Effect.gen(function* () {
569
+ const message = yield* readMessageArgument(flags.message);
570
+ const workspaceStrategy = yield* launchWorkspaceStrategy(flags);
571
+ if (Option.isSome(flags.provider) !== Option.isSome(flags.model)) {
572
+ return yield* new ThreadUsageError({ detail: "--provider and --model go together." });
573
+ }
574
+ const title = yield* decodeTitle(
575
+ Option.getOrElse(flags.title, () => titleFromMessage(message)),
576
+ ).pipe(Effect.mapError(() => new ThreadUsageError({ detail: "The title is empty." })));
577
+ yield* withThreadTools(
578
+ flags,
579
+ Effect.fn("cli.thread.start")(function* (tools) {
580
+ const project = yield* resolveProject(tools, flags.project);
581
+ const launched = yield* tools.call(
582
+ "t3_thread_launch",
583
+ {
584
+ projectId: project.id,
585
+ title,
586
+ message,
587
+ ...(workspaceStrategy === undefined ? {} : { workspaceStrategy }),
588
+ ...(Option.isSome(flags.provider) && Option.isSome(flags.model)
589
+ ? {
590
+ modelSelection: {
591
+ instanceId: flags.provider.value,
592
+ model: flags.model.value,
593
+ },
594
+ }
595
+ : {}),
596
+ },
597
+ ThreadLaunchResult,
598
+ );
599
+ if (flags.wait && launched.runId !== null) {
600
+ if (!flags.json) yield* Console.error(`Thread ${launched.threadId}`);
601
+ return yield* finishRun(tools, {
602
+ threadId: launched.threadId,
603
+ runId: launched.runId,
604
+ json: flags.json,
605
+ });
606
+ }
607
+ yield* flags.json ? printJson(launched) : Console.log(launched.threadId);
608
+ }),
609
+ );
610
+ }).pipe(reportThreadErrors),
611
+ ),
612
+);
613
+
614
+const threadSendCommand = Command.make("send", {
615
+ ...projectLocationFlags,
616
+ thread: threadArgument,
617
+ message: messageArgument,
618
+ wait: waitFlag,
619
+ json: jsonFlag,
620
+}).pipe(
621
+ Command.withDescription(
622
+ "Send a message to a thread. A busy thread gets it as its next turn; nothing is interrupted.",
623
+ ),
624
+ Command.withHandler((flags) =>
625
+ Effect.gen(function* () {
626
+ const threadId = yield* decodeThreadId(flags.thread);
627
+ const message = yield* readMessageArgument(flags.message);
628
+ yield* withThreadTools(
629
+ flags,
630
+ Effect.fn("cli.thread.send")(function* (tools) {
631
+ const sent = yield* tools.call(
632
+ "t3_thread_send",
633
+ { threadId, message, mode: "queue" },
634
+ OrchestratorMcpThreadSendResult,
635
+ );
636
+ if (flags.wait) {
637
+ return yield* finishRun(tools, { threadId, runId: sent.runId, json: flags.json });
638
+ }
639
+ yield* flags.json
640
+ ? printJson(sent)
641
+ : Console.log(sent.delivery === "queued" ? "Queued." : "Sent.");
642
+ }),
643
+ );
644
+ }).pipe(reportThreadErrors),
645
+ ),
646
+);
647
+
648
+const threadShowCommand = Command.make("show", {
649
+ ...projectLocationFlags,
650
+ thread: threadArgument,
651
+ messages: Flag.Int("messages").pipe(
652
+ Flag.withDescription("How many of the latest messages to print."),
653
+ Flag.withDefault(10),
654
+ ),
655
+ json: jsonFlag,
656
+}).pipe(
657
+ Command.withDescription("Show a thread's state and its latest messages."),
658
+ Command.withHandler((flags) =>
659
+ Effect.gen(function* () {
660
+ const threadId = yield* decodeThreadId(flags.thread);
661
+ yield* withThreadTools(
662
+ flags,
663
+ Effect.fn("cli.thread.show")(function* (tools) {
664
+ const { thread, items } = yield* readTimeline(tools, threadId, "messages");
665
+ const conversation = items.filter(
666
+ (item) => item.type === "user_message" || item.type === "assistant_message",
667
+ );
668
+ const latest = conversation.slice(Math.max(0, conversation.length - flags.messages));
669
+ const messages = yield* Effect.forEach(latest, (item) =>
670
+ readFullText(tools, threadId, item).pipe(
671
+ Effect.map((text) => ({
672
+ role: item.type === "user_message" ? "user" : "assistant",
673
+ runId: item.runId,
674
+ text,
675
+ })),
676
+ ),
677
+ );
678
+ if (flags.json) {
679
+ return yield* printJson({ thread, messages });
680
+ }
681
+ yield* Console.log(thread.title);
682
+ yield* Console.log(
683
+ [thread.threadId, thread.status, `${thread.providerInstanceId}/${thread.model}`].join(
684
+ " ",
685
+ ),
686
+ );
687
+ if (thread.worktreePath !== null) {
688
+ yield* Console.log(`${thread.branch ?? "(no branch)"} ${thread.worktreePath}`);
689
+ }
690
+ if (thread.pendingRequestCount > 0) {
691
+ yield* Console.log(`Waiting for ${thread.pendingRequestCount} answer(s).`);
692
+ }
693
+ for (const entry of messages) {
694
+ yield* Console.log(`\n[${entry.role}]\n${entry.text}`);
695
+ }
696
+ }),
697
+ );
698
+ }).pipe(reportThreadErrors),
699
+ ),
700
+);
701
+
702
+export const threadCommand = Command.make("thread").pipe(
703
+ Command.withDescription("Start, message, and read threads on the running server."),
704
+ Command.withSubcommands([
705
+ threadListCommand,
706
+ threadStartCommand,
707
+ threadSendCommand,
708
+ threadShowCommand,
709
+ ]),
710
+);
apps/server/src/mcp/AcpMcpStdioBridge.ts
+99
-67
@@ -6,6 +6,7 @@ import * as NodeReadline from "node:readline";
6
import * as Cause from "effect/Cause";
7
import * as Effect from "effect/Effect";
8
import * as Fiber from "effect/Fiber";
9
+import * as Scope from "effect/Scope";
10
import * as Stream from "effect/Stream";
11
import { discardResponseBody, responsePayloads } from "@t3tools/shared/mcpResponsePayloads";
12
@@ -14,7 +15,7 @@ import { discardResponseBody, responsePayloads } from "@t3tools/shared/mcpRespon
15
* unevenly implemented.
16
*/
17
17
-class AcpMcpBridgeError extends Error {
18
+export class AcpMcpBridgeError extends Error {
19
readonly _tag = "AcpMcpBridgeError";
20
}
21
@@ -53,94 +54,125 @@ function protocolVersionOf(entry: unknown): string | null {
54
return typeof version === "string" && version.length > 0 ? version : null;
55
}
56
56
-export interface AcpMcpToolCallOptions {
57
+export interface McpToolSessionOptions {
58
readonly endpoint: string;
59
readonly authorization: string;
59
- readonly tool: string;
60
- readonly arguments: Readonly<Record<string, unknown>>;
60
+ readonly clientName: string;
61
readonly fetchImplementation?: (url: string, init?: RequestInit) => Promise<Response>;
62
}
63
64
+export interface McpToolSession {
65
+ /** Resolves to the JSON-RPC `result` of `tools/call`, a `CallToolResult`. */
66
+ readonly call: (
67
+ tool: string,
68
+ args: Readonly<Record<string, unknown>>,
69
+ ) => Effect.Effect<unknown, AcpMcpBridgeError>;
70
+}
71
+
72
/**
65
- * This is the terminal fallback for ACP agents that accept `mcpServers` in
66
- * `session/new` but fail to expose those tools to their model. Compliant ACP
67
- * agents continue to use the stdio bridge above.
73
+ * One initialized MCP session over T3 Code's HTTP endpoint, terminated when
74
+ * the scope closes. Used by the ACP terminal fallback and `t3 thread`.
75
*/
69
-function callAcpMcpTool(options: AcpMcpToolCallOptions): Effect.Effect<unknown, AcpMcpBridgeError> {
76
+export const mcpToolSession = (
77
+ options: McpToolSessionOptions,
78
+): Effect.Effect<McpToolSession, AcpMcpBridgeError, Scope.Scope> => {
79
const fetchImplementation = options.fetchImplementation ?? fetch;
71
- return Effect.gen(function* () {
72
- let sessionId: string | null = null;
73
- let protocolVersion: string | null = null;
80
+ let sessionId: string | null = null;
81
+ let protocolVersion: string | null = null;
82
+ let nextId = 0;
83
75
- const send = Effect.fn("AcpMcpStdioBridge.send")(function* (
76
- message: unknown,
77
- ): Effect.fn.Return<ReadonlyArray<unknown>, AcpMcpBridgeError> {
78
- const response = yield* Effect.tryPromise({
79
- try: () =>
80
- fetchImplementation(options.endpoint, {
81
- method: "POST",
82
- headers: {
83
- "content-type": "application/json",
84
- accept: "application/json, text/event-stream",
85
- authorization: options.authorization,
86
- ...(sessionId === null ? {} : { "mcp-session-id": sessionId }),
87
- ...(protocolVersion === null ? {} : { "mcp-protocol-version": protocolVersion }),
88
- },
89
- body: JSON.stringify(message),
90
- }),
91
- catch: bridgeError,
92
- });
93
- sessionId = response.headers.get("mcp-session-id") ?? sessionId;
94
- if (!response.ok) {
95
- yield* discardResponseBody(response);
96
- return yield* Effect.fail(
97
- new AcpMcpBridgeError(`T3 Code MCP endpoint responded with HTTP ${response.status}.`),
98
- );
99
- }
100
- const payloads = yield* Stream.runCollect(responsePayloads(response, bridgeError));
101
- for (const payload of payloads) {
102
- protocolVersion = protocolVersionOf(payload) ?? protocolVersion;
103
- }
104
- return payloads;
105
- });
84
+ const headers = () => ({
85
+ accept: "application/json, text/event-stream",
86
+ authorization: options.authorization,
87
+ ...(sessionId === null ? {} : { "mcp-session-id": sessionId }),
88
+ ...(protocolVersion === null ? {} : { "mcp-protocol-version": protocolVersion }),
89
+ });
90
107
- const initializeId = "t3-acp-cli-initialize";
108
- const initialized = yield* send({
109
- jsonrpc: "2.0",
110
- id: initializeId,
111
- method: "initialize",
112
- params: {
113
- protocolVersion: MCP_PROTOCOL_VERSION,
114
- capabilities: {},
115
- clientInfo: { name: "t3-code-acp-cli", version: "0.0.0" },
116
- },
91
+ const send = Effect.fn("AcpMcpStdioBridge.send")(function* (
92
+ message: unknown,
93
+ ): Effect.fn.Return<ReadonlyArray<unknown>, AcpMcpBridgeError> {
94
+ const response = yield* Effect.tryPromise({
95
+ try: () =>
96
+ fetchImplementation(options.endpoint, {
97
+ method: "POST",
98
+ headers: { "content-type": "application/json", ...headers() },
99
+ body: JSON.stringify(message),
100
+ }),
101
+ catch: bridgeError,
102
});
118
- const initializeResponse = initialized.find((entry) => asEnvelope(entry)?.id === initializeId);
119
- if (initializeResponse === undefined || asEnvelope(initializeResponse)?.error !== undefined) {
103
+ sessionId = response.headers.get("mcp-session-id") ?? sessionId;
104
+ if (!response.ok) {
105
+ yield* discardResponseBody(response);
106
return yield* Effect.fail(
121
- new AcpMcpBridgeError("T3 Code MCP endpoint rejected initialization."),
107
+ new AcpMcpBridgeError(`T3 Code MCP endpoint responded with HTTP ${response.status}.`),
108
);
109
}
124
- yield* send({ jsonrpc: "2.0", method: "notifications/initialized" });
110
+ const payloads = yield* Stream.runCollect(responsePayloads(response, bridgeError));
111
+ for (const payload of payloads) {
112
+ protocolVersion = protocolVersionOf(payload) ?? protocolVersion;
113
+ }
114
+ return payloads;
115
+ });
116
126
- const callId = "t3-acp-cli-tool-call";
127
- const responses = yield* send({
128
- jsonrpc: "2.0",
129
- id: callId,
130
- method: "tools/call",
131
- params: { name: options.tool, arguments: options.arguments },
132
- });
133
- const response = responses.find((entry) => asEnvelope(entry)?.id === callId);
134
- const envelope = asEnvelope(response);
117
+ const request = Effect.fn("AcpMcpStdioBridge.request")(function* (
118
+ method: string,
119
+ params: unknown,
120
+ ): Effect.fn.Return<JsonRpcEnvelope, AcpMcpBridgeError> {
121
+ const id = `t3-cli-${nextId++}`;
122
+ const responses = yield* send({ jsonrpc: "2.0", id, method, params });
123
+ const envelope = asEnvelope(responses.find((entry) => asEnvelope(entry)?.id === id));
124
if (envelope === null || envelope.error !== undefined) {
125
return yield* Effect.fail(
126
new AcpMcpBridgeError(
138
- `T3 Code MCP tool call failed${envelope?.error === undefined ? "." : `: ${JSON.stringify(envelope.error)}`}`,
127
+ `T3 Code MCP ${method} failed${envelope?.error === undefined ? "." : `: ${JSON.stringify(envelope.error)}`}`,
128
),
129
);
130
}
142
- return envelope.result;
131
+ return envelope;
132
+ });
133
+
134
+ const terminate = Effect.suspend(() =>
135
+ sessionId === null
136
+ ? Effect.void
137
+ : Effect.tryPromise(() =>
138
+ fetchImplementation(options.endpoint, { method: "DELETE", headers: headers() }),
139
+ ).pipe(Effect.flatMap(discardResponseBody), Effect.ignore),
140
+ );
141
+
142
+ // Registered before the handshake so a session the server opened is ended
143
+ // even when the handshake fails, and the handshake stays interruptible.
144
+ return Effect.gen(function* () {
145
+ yield* Effect.addFinalizer(() => terminate);
146
+ yield* request("initialize", {
147
+ protocolVersion: MCP_PROTOCOL_VERSION,
148
+ capabilities: {},
149
+ clientInfo: { name: options.clientName, version: "0.0.0" },
150
+ });
151
+ yield* send({ jsonrpc: "2.0", method: "notifications/initialized" });
152
+ return {
153
+ call: (tool, args) =>
154
+ request("tools/call", { name: tool, arguments: args }).pipe(
155
+ Effect.map((envelope) => envelope.result),
156
+ ),
157
+ } satisfies McpToolSession;
158
});
159
+};
160
+
161
+/**
162
+ * This is the terminal fallback for ACP agents that accept `mcpServers` in
163
+ * `session/new` but fail to expose those tools to their model. Compliant ACP
164
+ * agents continue to use the stdio bridge above.
165
+ */
166
+function callAcpMcpTool(options: {
167
+ readonly endpoint: string;
168
+ readonly authorization: string;
169
+ readonly tool: string;
170
+ readonly arguments: Readonly<Record<string, unknown>>;
171
+}): Effect.Effect<unknown, AcpMcpBridgeError> {
172
+ return mcpToolSession({ ...options, clientName: "t3-code-acp-cli" }).pipe(
173
+ Effect.flatMap((session) => session.call(options.tool, options.arguments)),
174
+ Effect.scoped,
175
+ );
176
}
177
178
export function runAcpMcpStdioBridge(options: AcpMcpStdioBridgeOptions): Effect.Effect<void> {
apps/server/src/mcp/toolkits/project/handlers.test.ts
+96
-29
@@ -4,6 +4,8 @@ import {
4
ProjectId,
5
ProviderInstanceId,
6
type Project as ProjectRecord,
7
+ type ModelSelection,
8
+ type RuntimeMode,
9
} from "@t3tools/contracts";
10
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
11
import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -28,7 +30,10 @@ import * as ProjectHandlers from "./handlers.ts";
30
import { ProjectToolkit } from "./tools.ts";
31
32
const clientLaunchHarness = (input: {
31
- readonly runtimeModeCeiling: "approval-required" | "auto-accept-edits" | "auto" | "full-access";
33
+ readonly runtimeModeCeiling: RuntimeMode;
34
+ readonly defaultRuntimeMode?: RuntimeMode;
35
+ /** Where Settings saves a project's model; the legacy project field stays null. */
36
+ readonly overrideModel?: ModelSelection;
37
readonly launched: Array<ThreadLaunch.ThreadLaunchInput>;
38
readonly workspaceRoot?: string;
39
readonly checkWorktreeBase?: ThreadLaunch.ThreadLaunchService["Service"]["checkWorktreeBase"];
@@ -39,7 +44,19 @@ const clientLaunchHarness = (input: {
44
model: "claude-opus",
45
};
46
const layerDependencies = Layer.mergeAll(
42
- ServerSettings.layerTest(),
47
+ ServerSettings.layerTest({
48
+ ...(input.defaultRuntimeMode === undefined
49
+ ? {}
50
+ : { defaultRuntimeMode: input.defaultRuntimeMode }),
51
+ ...(input.overrideModel === undefined
52
+ ? {}
53
+ : {
54
+ projectSettingsFolded: true,
55
+ projectSettingsOverrides: {
56
+ [projectId]: { defaultModelSelection: input.overrideModel },
57
+ },
58
+ }),
59
+ }),
60
NodeCrypto.layer,
61
Layer.succeed(McpInvocationContext.McpInvocationContext, {
62
environmentId: EnvironmentId.make("environment"),
@@ -79,7 +96,7 @@ const clientLaunchHarness = (input: {
96
? Option.some({
97
id,
98
workspaceRoot: input.workspaceRoot ?? "/projects/client-target",
82
- defaultModelSelection: modelSelection,
99
+ defaultModelSelection: input.overrideModel === undefined ? modelSelection : null,
100
} as unknown as ProjectRecord)
101
: Option.none(),
102
),
@@ -99,35 +116,85 @@ const clientLaunchHarness = (input: {
116
return { projectId, modelSelection, dependencies: layerDependencies };
117
};
118
102
-it.effect("a client launches at its ceiling with the project's default model", () =>
103
- Effect.gen(function* () {
104
- const launched: Array<ThreadLaunch.ThreadLaunchInput> = [];
105
- const { projectId, modelSelection, dependencies } = clientLaunchHarness({
106
- runtimeModeCeiling: "auto-accept-edits",
107
- launched,
108
- });
109
- const toolkit = yield* ProjectToolkit.pipe(
110
- Effect.provide(
111
- McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(Layer.provide(dependencies)),
112
- ),
113
- );
114
- const handle = (params: Parameters<typeof toolkit.handle<"t3_thread_launch">>[1]) =>
115
- toolkit
116
- .handle("t3_thread_launch", params)
117
- .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies));
119
+it.effect(
120
+ "a client launches with the project's default model and mode, capped at its ceiling",
121
+ () =>
122
+ Effect.gen(function* () {
123
+ const launchWith = Effect.fn("test.launchWith")(function* (
124
+ runtimeModeCeiling: RuntimeMode,
125
+ defaultRuntimeMode: RuntimeMode,
126
+ params: {
127
+ readonly title: string;
128
+ readonly message?: string;
129
+ readonly runtimeMode?: RuntimeMode;
130
+ readonly targeted?: false;
131
+ readonly overrideModel?: ModelSelection;
132
+ },
133
+ ) {
134
+ const { targeted, overrideModel, ...input } = params;
135
+ const launched: Array<ThreadLaunch.ThreadLaunchInput> = [];
136
+ const { projectId, modelSelection, dependencies } = clientLaunchHarness({
137
+ runtimeModeCeiling,
138
+ defaultRuntimeMode,
139
+ launched,
140
+ ...(overrideModel === undefined ? {} : { overrideModel }),
141
+ });
142
+ const toolkit = yield* ProjectToolkit.pipe(
143
+ Effect.provide(
144
+ McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(
145
+ Layer.provide(dependencies),
146
+ ),
147
+ ),
148
+ );
149
+ const result = yield* toolkit
150
+ .handle("t3_thread_launch", targeted === false ? input : { ...input, projectId })
151
+ .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies));
152
+ return { result: result.at(-1)?.result, launched, projectId, modelSelection };
153
+ });
154
119
- const result = yield* handle({ title: "Fix", projectId, message: "Fix the bug" });
120
- expect(result.at(-1)?.result).toMatchObject({ projectId, modelSelection });
121
- expect(launched[0]?.runtimeMode).toBe("auto-accept-edits");
122
- expect(launched[0]?.initialMessage?.senderThreadId).toBeUndefined();
155
+ const belowCeiling = yield* launchWith("full-access", "approval-required", {
156
+ title: "Fix",
157
+ message: "Fix the bug",
158
+ });
159
+ expect(belowCeiling.result).toMatchObject({
160
+ projectId: belowCeiling.projectId,
161
+ modelSelection: belowCeiling.modelSelection,
162
+ });
163
+ expect(belowCeiling.launched[0]?.runtimeMode).toBe("approval-required");
164
+ expect(belowCeiling.launched[0]?.initialMessage?.senderThreadId).toBeUndefined();
165
124
- const escalated = yield* handle({ title: "Fix", projectId, runtimeMode: "full-access" });
125
- expect(escalated.at(-1)?.result).toMatchObject({ code: "runtime_mode_escalation_denied" });
166
+ const aboveCeiling = yield* launchWith("auto-accept-edits", "full-access", { title: "Fix" });
167
+ expect(aboveCeiling.launched[0]?.runtimeMode).toBe("auto-accept-edits");
168
127
- const untargeted = yield* handle({ title: "Fix" });
128
- expect(untargeted.at(-1)?.result).toMatchObject({ code: "target_required" });
129
- expect(launched).toHaveLength(1);
130
- }),
169
+ const requested = yield* launchWith("full-access", "approval-required", {
170
+ title: "Fix",
171
+ runtimeMode: "auto",
172
+ });
173
+ expect(requested.launched[0]?.runtimeMode).toBe("auto");
174
+
175
+ const escalated = yield* launchWith("auto-accept-edits", "auto-accept-edits", {
176
+ title: "Fix",
177
+ runtimeMode: "full-access",
178
+ });
179
+ expect(escalated.result).toMatchObject({ code: "runtime_mode_escalation_denied" });
180
+ expect(escalated.launched).toHaveLength(0);
181
+
182
+ const untargeted = yield* launchWith("full-access", "full-access", {
183
+ title: "Fix",
184
+ targeted: false,
185
+ });
186
+ expect(untargeted.result).toMatchObject({ code: "target_required" });
187
+
188
+ const overrideModel = {
189
+ instanceId: ProviderInstanceId.make("codex"),
190
+ model: "gpt-settings",
191
+ };
192
+ const fromSettings = yield* launchWith("full-access", "full-access", {
193
+ title: "Fix",
194
+ overrideModel,
195
+ });
196
+ expect(fromSettings.launched[0]?.modelSelection).toEqual(overrideModel);
197
+ }),
198
);
199
200
it.effect("a launch binds only an existing checkout that is one of the project's worktrees", () =>
apps/server/src/mcp/toolkits/project/handlers.ts
+27
-2
@@ -9,6 +9,9 @@ import * as Project from "../../../project/ProjectService.ts";
9
import * as ManagedProjectFolders from "../../../project/ManagedProjectFolders.ts";
10
import * as Repositories from "../../../sourceControl/SourceControlRepositoryService.ts";
11
import * as GitVcsDriver from "../../../vcs/GitVcsDriver.ts";
12
+import * as ServerSettings from "../../../serverSettings.ts";
13
+import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
14
+import { resolveRuntimeMode } from "../../OrchestratorMcpService.ts";
15
import * as McpToolAccess from "../../McpToolAccess.ts";
16
import { newCommandId, readCaller, resolveProjectId, unavailable } from "../../threadAccess.ts";
17
import { ProjectToolkit } from "./tools.ts";
@@ -122,10 +125,26 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
125
}),
126
),
127
);
128
+ // A caller outside a thread has nothing to inherit, so it starts with the
129
+ // project's effective defaults, as the composer does. Its mode stays
130
+ // within the ceiling it was approved with.
131
+ const projectDefaults =
132
+ caller === undefined
133
+ ? yield* ServerSettings.ServerSettingsService.pipe(
134
+ Effect.flatMap((settings) => settings.getSettings),
135
+ Effect.mapError(unavailable),
136
+ Effect.flatMap((settings) =>
137
+ Effect.map(
138
+ readProject,
139
+ (project) => resolveProjectSettings(settings, projectId, project).settings,
140
+ ),
141
+ ),
142
+ )
143
+ : undefined;
144
const modelSelection =
145
input.modelSelection ??
146
caller?.modelSelection ??
128
- (yield* readProject)?.defaultModelSelection ??
147
+ projectDefaults?.defaultModelSelection ??
148
undefined;
149
if (modelSelection === undefined)
150
return yield* new OrchestratorMcpFailure({
@@ -133,13 +152,19 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
152
message:
153
"Pass modelSelection: the project has no default model. orchestrator_capabilities lists providers and models.",
154
});
155
+ const startedRuntimeMode =
156
+ projectDefaults !== undefined && input.runtimeMode === undefined
157
+ ? yield* resolveRuntimeMode(runtimeMode, projectDefaults.defaultRuntimeMode).pipe(
158
+ Effect.orElseSucceed(() => runtimeMode),
159
+ )
160
+ : runtimeMode;
161
const result = yield* ThreadMessageIntake.launchThread({
162
commandId,
163
threadId,
164
projectId,
165
title: input.title,
166
modelSelection,
142
- runtimeMode,
167
+ runtimeMode: startedRuntimeMode,
168
interactionMode,
169
workspaceStrategy: input.workspaceStrategy ?? { type: "root" },
170
...(input.message === undefined && attachments.length === 0
docs/user/outside-agents.md
+22
@@ -88,6 +88,28 @@ Any agent that supports remote MCP servers over HTTP with OAuth can connect. Giv
88
it the MCP URL and choose OAuth, and the agent finds the sign-in settings itself.
89
Agents without OAuth support cannot connect.
90
91
+## Scripts on the host
92
+
93
+On the machine that runs the environment, `t3 thread` uses the same tools
94
+without a sign-in:
95
+
96
+```sh
97
+id=$(t3 thread start . "Find why the tests are slow")
98
+t3 thread send "$id" "Now fix it" --wait
99
+t3 thread show "$id"
100
+t3 thread list
101
+```
102
+
103
+`.` means the project that contains the current folder; a project id also
104
+works. A new thread uses the project's default model and permission mode, and
105
+runs in the project folder unless you pass `--worktree <base-branch>`. `send`
106
+never interrupts: a busy thread gets the message as its next turn. Pass `-` as
107
+the message to read it from stdin.
108
+
109
+`--wait` prints the agent's reply. It exits 1 when the run fails or stops, and
110
+2 when the agent waits for an answer you give in the app. Add `--json` for a
111
+result that always includes the thread id.
112
+
113
## Remove an agent
114
115
Approved agents appear under **Settings → Connections** like other clients.