Skip to content
TypeScript

feat(cli): start, message, and read threads from the terminal with t3 thread (#22732)

Theo Browne955b4cc80166
diff --git a/apps/server/src/auth/EnvironmentAuth.ts b/apps/server/src/auth/EnvironmentAuth.ts
index 569ae75907d..1a6d3206833 100644
--- a/apps/server/src/auth/EnvironmentAuth.ts
+++ b/apps/server/src/auth/EnvironmentAuth.ts
@@ -558,7 +558,11 @@ export class EnvironmentAuth extends Context.Service<
readonly access: AuthMcpClientAccess;
readonly client: AuthClientMetadata;
}) => Effect.Effect<
- { readonly token: string; readonly expiresAt: DateTime.DateTime },
+ {
+ readonly sessionId: AuthSessionId;
+ readonly token: string;
+ readonly expiresAt: DateTime.DateTime;
+ },
ServerAuthInternalError
>;
/**
@@ -1292,7 +1296,11 @@ export const make = Effect.gen(function* () {
client: { ...input.client, label: input.label, deviceType: "bot" },
})
.pipe(
- Effect.map((issued) => ({ token: issued.token, expiresAt: issued.expiresAt })),
+ Effect.map((issued) => ({
+ sessionId: issued.sessionId,
+ token: issued.token,
+ expiresAt: issued.expiresAt,
+ })),
Effect.mapError((cause) => new ServerAuthSessionTokenIssueError({ cause })),
Effect.withSpan("EnvironmentAuth.issueMcpClientSession"),
);
diff --git a/apps/server/src/binCli.ts b/apps/server/src/binCli.ts
index b0a2ceffef8..2f7c24536ca 100644
--- a/apps/server/src/binCli.ts
+++ b/apps/server/src/binCli.ts
@@ -18,6 +18,7 @@ import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
import { extendConnectionAttemptTimeout, keepOutboundFetchOnHttp1 } from "./outboundHttp.ts";
import { sharedServerCommandFlags } from "./cli/config.ts";
import { projectCommand } from "./cli/project.ts";
+import { threadCommand } from "./cli/thread.ts";
import { runDefaultServerCommand, serveCommand, startCommand } from "./cli/server.ts";
import { updateCommand } from "./cli/update.ts";
import { uninstallCommand } from "./cli/uninstall.ts";
@@ -76,6 +77,7 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>
authCommand,
browserCommand,
projectCommand,
+ threadCommand,
serviceCommand,
updateCommand,
uninstallCommand,
diff --git a/apps/server/src/cli/thread.test.ts b/apps/server/src/cli/thread.test.ts
new file mode 100644
index 00000000000..c2e4bc5c816
--- /dev/null
+++ b/apps/server/src/cli/thread.test.ts
@@ -0,0 +1,75 @@
+import { assert, it } from "@effect/vitest";
+import { RunId, ThreadId } from "@t3tools/contracts";
+import * as Effect from "effect/Effect";
+
+import { type ThreadTools, waitForRun } from "./thread.ts";
+
+const threadId = ThreadId.make("thread-1");
+const runId = RunId.make("run-1");
+
+/** Answers each tool call with the next scripted response for that tool. */
+const scriptedTools = (script: Record<string, Array<unknown>>) => {
+ const calls: Array<{ readonly tool: string; readonly args: unknown }> = [];
+ const call = ((tool: string, args: unknown) => {
+ calls.push({ tool, args });
+ const next = script[tool]?.shift();
+ return next === undefined ? Effect.die(`unscripted ${tool} call`) : Effect.succeed(next);
+ }) as ThreadTools["call"];
+ return { tools: { call } satisfies ThreadTools, calls };
+};
+
+it.effect("--wait follows the sent run to its continuation's terminal status", () =>
+ Effect.gen(function* () {
+ const continuation = RunId.make("run-2");
+ const { tools, calls } = scriptedTools({
+ t3_thread_wait: [
+ { threadId, runId, status: "running", timedOut: true },
+ { threadId, runId: continuation, status: "failed", timedOut: false },
+ ],
+ t3_thread_read: [{ thread: { pendingRequestCount: 0 } }],
+ });
+
+ const outcome = yield* waitForRun(tools, threadId, runId);
+
+ assert.deepStrictEqual(outcome, { type: "ended", runId: continuation, status: "failed" });
+ assert.deepStrictEqual(
+ calls.filter((entry) => entry.tool === "t3_thread_wait").map((entry) => entry.args),
+ [
+ { threadId, runId, timeoutMs: 15_000 },
+ { threadId, runId, timeoutMs: 15_000 },
+ ],
+ );
+ }),
+);
+
+it.effect("--wait stops when the thread waits for an answer instead of polling forever", () =>
+ Effect.gen(function* () {
+ const { tools } = scriptedTools({
+ t3_thread_wait: [
+ { threadId, runId, status: "queued", timedOut: true },
+ { threadId, runId, status: "queued", timedOut: true },
+ ],
+ t3_thread_read: [{ thread: { pendingRequestCount: 1 } }],
+ });
+
+ assert.deepStrictEqual(yield* waitForRun(tools, threadId, runId), { type: "needs_input" });
+ }),
+);
+
+it.effect("--wait reports its run's result when a later run is the one waiting", () =>
+ Effect.gen(function* () {
+ const { tools } = scriptedTools({
+ t3_thread_wait: [
+ { threadId, runId, status: "running", timedOut: true },
+ { threadId, runId, status: "completed", timedOut: false },
+ ],
+ t3_thread_read: [{ thread: { pendingRequestCount: 1 } }],
+ });
+
+ assert.deepStrictEqual(yield* waitForRun(tools, threadId, runId), {
+ type: "ended",
+ runId,
+ status: "completed",
+ });
+ }),
+);
diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts
new file mode 100644
index 00000000000..989028afccb
--- /dev/null
+++ b/apps/server/src/cli/thread.ts
@@ -0,0 +1,710 @@
+import {
+ OrchestratorMcpFailure,
+ OrchestratorMcpThreadListResult,
+ OrchestratorMcpThreadReadResult,
+ OrchestratorMcpThreadSendResult,
+ OrchestratorMcpThreadWaitResult,
+ ProjectId,
+ RunId,
+ ThreadId,
+ TrimmedNonEmptyString,
+ type OrchestratorMcpThreadListItem,
+ type OrchestratorMcpThreadStatus,
+ type OrchestratorMcpThreadTimelineItem,
+} from "@t3tools/contracts";
+import * as HostProcess from "@t3tools/shared/HostProcess";
+import * as Console from "effect/Console";
+import * as Effect from "effect/Effect";
+import * as FileSystem from "effect/FileSystem";
+import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
+import * as Path from "effect/Path";
+import * as References from "effect/References";
+import * as Runtime from "effect/Runtime";
+import * as Schema from "effect/Schema";
+import * as Stdio from "effect/Stdio";
+import * as Stream from "effect/Stream";
+import { Argument, Command, Flag, GlobalFlag } from "effect/cli";
+
+import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
+import * as ServerConfig from "../config.ts";
+import { mcpToolSession, type McpToolSession } from "../mcp/AcpMcpStdioBridge.ts";
+import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
+import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
+
+/**
+ * Short enough that a run which stops to ask the user something is noticed
+ * soon, since `t3_thread_wait` only returns on a terminal run.
+ */
+const WAIT_SLICE_MS = 15_000;
+const READ_PAGE_LIMIT = 100;
+const TITLE_MAX_CHARS = 80;
+
+export class ThreadServerNotRunningError extends Schema.TaggedError<ThreadServerNotRunningError>()(
+ "ThreadServerNotRunningError",
+ { baseDir: Schema.String },
+) {
+ override readonly [Runtime.errorReported] = false;
+ override get message(): string {
+ return `No running T3 Code server uses ${this.baseDir}. Start T3 Code, then retry.`;
+ }
+}
+
+export class ThreadServerUnreachableError extends Schema.TaggedError<ThreadServerUnreachableError>()(
+ "ThreadServerUnreachableError",
+ { origin: Schema.String, cause: Schema.Defect() },
+) {
+ override readonly [Runtime.errorReported] = false;
+ override get message(): string {
+ const reason = this.cause instanceof Error ? ` ${this.cause.message}` : "";
+ return `Could not reach the T3 Code server at ${this.origin}.${reason}`;
+ }
+}
+
+export class ThreadToolFailedError extends Schema.TaggedError<ThreadToolFailedError>()(
+ "ThreadToolFailedError",
+ { tool: Schema.String, detail: Schema.String },
+) {
+ override readonly [Runtime.errorReported] = false;
+ override get message(): string {
+ return this.detail;
+ }
+}
+
+export class ThreadUsageError extends Schema.TaggedError<ThreadUsageError>()("ThreadUsageError", {
+ detail: Schema.String,
+}) {
+ override readonly [Runtime.errorReported] = false;
+ override get message(): string {
+ return this.detail;
+ }
+}
+
+export class ThreadProjectNotFoundError extends Schema.TaggedError<ThreadProjectNotFoundError>()(
+ "ThreadProjectNotFoundError",
+ { identifier: Schema.String },
+) {
+ override readonly [Runtime.errorReported] = false;
+ override get message(): string {
+ return `No T3 Code project matches '${this.identifier}'. Pass a project id or a path inside a project.`;
+ }
+}
+
+/** Exit code 2 lets a script tell "needs a human" apart from a failed run. */
+export class ThreadNeedsInputError extends Schema.TaggedError<ThreadNeedsInputError>()(
+ "ThreadNeedsInputError",
+ { threadId: ThreadId },
+) {
+ override readonly [Runtime.errorReported] = false;
+ override readonly [Runtime.errorExitCode] = 2;
+
+ override get message(): string {
+ return `Thread ${this.threadId} is waiting for an answer. Open it in T3 Code to respond.`;
+ }
+}
+
+export class ThreadRunEndedError extends Schema.TaggedError<ThreadRunEndedError>()(
+ "ThreadRunEndedError",
+ { threadId: ThreadId, status: Schema.String, error: Schema.optional(Schema.String) },
+) {
+ override readonly [Runtime.errorReported] = false;
+ override get message(): string {
+ const reason = this.error === undefined ? "." : `: ${this.error}`;
+ return `Thread ${this.threadId} stopped with status ${this.status}${reason}`;
+ }
+}
+
+const ThreadCliError = Schema.Union([
+ ThreadServerNotRunningError,
+ ThreadServerUnreachableError,
+ ThreadToolFailedError,
+ ThreadUsageError,
+ ThreadProjectNotFoundError,
+ ThreadNeedsInputError,
+ ThreadRunEndedError,
+]);
+const isThreadCliError = Schema.is(ThreadCliError);
+
+/**
+ * These errors are expected outcomes for a script, so they print as one line
+ * on stderr instead of the runtime's logged stack trace.
+ */
+const reportThreadErrors = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
+ effect.pipe(
+ Effect.tapError((error) =>
+ isThreadCliError(error) ? Console.error(error.message) : Effect.void,
+ ),
+ );
+
+const decodeFailureText = Schema.decodeUnknownOption(Schema.fromJsonString(OrchestratorMcpFailure));
+const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
+const printJson = (value: unknown) => Console.log(encodeJson(value));
+
+const ToolResult = Schema.Struct({
+ isError: Schema.optional(Schema.Boolean),
+ structuredContent: Schema.optional(Schema.Unknown),
+ content: Schema.optional(
+ Schema.Array(Schema.Struct({ type: Schema.String, text: Schema.optional(Schema.String) })),
+ ),
+});
+
+const decodeToolResult = Schema.decodeUnknownEffect(ToolResult);
+
+const ProjectListResult = Schema.Struct({
+ projects: Schema.Array(
+ Schema.Struct({ id: ProjectId, title: Schema.String, workspaceRoot: Schema.String }),
+ ),
+ nextCursor: Schema.NullOr(Schema.Int),
+});
+
+const ThreadLaunchResult = Schema.Struct({
+ threadId: ThreadId,
+ projectId: ProjectId,
+ runId: Schema.NullOr(RunId),
+});
+
+const toolFailureDetail = (result: typeof ToolResult.Type) => {
+ const text = result.content?.find((part) => part.text !== undefined)?.text ?? "";
+ return Option.match(decodeFailureText(text), {
+ onNone: () => text || "The tool call failed.",
+ onSome: (failure) => failure.message,
+ });
+};
+
+const makeThreadTools = (session: McpToolSession, origin: string) => {
+ const unexpected = (tool: string) =>
+ new ThreadToolFailedError({
+ tool,
+ detail: `The server sent an unexpected ${tool} result. Update the t3 CLI to match the server.`,
+ });
+ return {
+ call: Effect.fn("cli.thread.callTool")(function* <S extends Schema.Decoder<unknown>>(
+ tool: string,
+ args: Readonly<Record<string, unknown>>,
+ schema: S,
+ ): Effect.fn.Return<S["Type"], ThreadServerUnreachableError | ThreadToolFailedError> {
+ const raw = yield* session
+ .call(tool, args)
+ .pipe(Effect.mapError((cause) => new ThreadServerUnreachableError({ origin, cause })));
+ const result = yield* decodeToolResult(raw).pipe(Effect.mapError(() => unexpected(tool)));
+ if (result.isError === true) {
+ return yield* new ThreadToolFailedError({ tool, detail: toolFailureDetail(result) });
+ }
+ return yield* Schema.decodeUnknownEffect(schema)(result.structuredContent).pipe(
+ Effect.mapError(() => unexpected(tool)),
+ );
+ }),
+ };
+};
+export type ThreadTools = ReturnType<typeof makeThreadTools>;
+
+/**
+ * Signs in as a short-lived MCP client of the running server, the same way an
+ * outside agent does, and revokes that session when the command ends.
+ */
+const withThreadTools = Effect.fn("cli.thread.withThreadTools")(function* <A, E, R>(
+ flags: { readonly baseDir: Option.Option<string> },
+ run: (tools: ThreadTools) => Effect.Effect<A, E, R>,
+) {
+ const logLevel = yield* GlobalFlag.LogLevel;
+ const config = yield* resolveCliAuthConfig(flags, logLevel);
+ return yield* Effect.gen(function* () {
+ const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath);
+ if (Option.isNone(runtimeState)) {
+ return yield* new ThreadServerNotRunningError({ baseDir: config.baseDir });
+ }
+ const origin = runtimeState.value.origin;
+ const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
+ const issued = yield* Effect.acquireRelease(
+ environmentAuth.issueMcpClientSession({
+ label: "t3 thread cli",
+ // The CLI runs as the machine's owner. New threads still start at
+ // the project's default mode, never at this ceiling by default.
+ access: "full-access",
+ client: { deviceType: "bot" },
+ }),
+ (session) =>
+ environmentAuth.revokeSession(session.sessionId).pipe(Effect.ignore({ log: true })),
+ );
+ const session = yield* mcpToolSession({
+ endpoint: new URL("/mcp", origin).href,
+ authorization: `Bearer ${issued.token}`,
+ clientName: "t3-thread-cli",
+ }).pipe(Effect.mapError((cause) => new ThreadServerUnreachableError({ origin, cause })));
+ return yield* run(makeThreadTools(session, origin));
+ }).pipe(
+ Effect.scoped,
+ Effect.provide(
+ EnvironmentAuth.layerRuntime.pipe(
+ Layer.provide(ServerConfig.layer(config)),
+ Layer.provide(Layer.succeed(References.MinimumLogLevel, config.logLevel)),
+ ),
+ ),
+ );
+});
+
+const readMessageArgument = Effect.fn("cli.thread.readMessage")(function* (argument: string) {
+ const text =
+ argument === "-"
+ ? yield* Stdio.Stdio.pipe(
+ Effect.flatMap((stdio) => stdio.stdin.pipe(Stream.decodeText(), Stream.mkString)),
+ )
+ : argument;
+ if (text.trim().length === 0) {
+ return yield* new ThreadUsageError({ detail: "The message is empty." });
+ }
+ return text;
+});
+
+const listAllProjects = Effect.fn("cli.thread.listAllProjects")(function* (tools: ThreadTools) {
+ const projects: Array<(typeof ProjectListResult.Type)["projects"][number]> = [];
+ let cursor: number | null = 0;
+ while (cursor !== null) {
+ const page: typeof ProjectListResult.Type = yield* tools.call(
+ "t3_project_list",
+ { cursor, limit: 100 },
+ ProjectListResult,
+ );
+ projects.push(...page.projects);
+ cursor = page.nextCursor;
+ }
+ return projects;
+});
+
+/** A project id, or a path inside a project's folder (deepest project wins). */
+const resolveProject = Effect.fn("cli.thread.resolveProject")(function* (
+ tools: ThreadTools,
+ identifier: string,
+) {
+ const projects = yield* listAllProjects(tools);
+ const byId = projects.find((project) => project.id === identifier);
+ if (byId !== undefined) return byId;
+
+ const path = yield* Path.Path;
+ const fileSystem = yield* FileSystem.FileSystem;
+ // Stored roots keep the path the project was added with, which may pass
+ // through a symlink (macOS /tmp), so both sides compare as real paths.
+ const realPath = (value: string) =>
+ fileSystem.realPath(value).pipe(Effect.orElseSucceed(() => value));
+ const target = yield* realPath(path.resolve(yield* HostProcess.WorkingDirectory, identifier));
+ const roots = yield* Effect.forEach(projects, (project) =>
+ Effect.map(realPath(project.workspaceRoot), (root) => ({ project, root })),
+ );
+ const containing = roots
+ .filter(({ root }) => {
+ const relative = path.relative(root, target);
+ return (
+ relative === "" ||
+ (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))
+ );
+ })
+ .toSorted((left, right) => right.root.length - left.root.length)[0];
+ if (containing === undefined) {
+ return yield* new ThreadProjectNotFoundError({ identifier });
+ }
+ return containing.project;
+});
+
+/** Every item on a timeline view, oldest first. */
+const readTimeline = Effect.fn("cli.thread.readTimeline")(function* (
+ tools: ThreadTools,
+ threadId: ThreadId,
+ view: "messages" | "activity",
+) {
+ const items: Array<OrchestratorMcpThreadTimelineItem> = [];
+ let afterPosition: number | undefined;
+ let page: OrchestratorMcpThreadReadResult;
+ do {
+ page = yield* tools.call(
+ "t3_thread_read",
+ {
+ threadId,
+ view,
+ limit: READ_PAGE_LIMIT,
+ runLimit: 1,
+ ...(afterPosition === undefined ? {} : { afterPosition }),
+ },
+ OrchestratorMcpThreadReadResult,
+ );
+ items.push(...page.items);
+ afterPosition = page.nextPosition ?? undefined;
+ } while (page.hasMore && afterPosition !== undefined);
+ return { thread: page.thread, items };
+});
+
+/** Item text past the read's per-item cap. */
+const readFullText = Effect.fn("cli.thread.readFullText")(function* (
+ tools: ThreadTools,
+ threadId: ThreadId,
+ item: OrchestratorMcpThreadTimelineItem,
+) {
+ let text = item.text ?? "";
+ let nextTextOffset = item.textTruncated ? (item.nextTextOffset ?? null) : null;
+ while (nextTextOffset !== null) {
+ const page = yield* tools.call(
+ "t3_thread_read",
+ { threadId, itemId: item.itemId, textOffset: nextTextOffset, runLimit: 1 },
+ OrchestratorMcpThreadReadResult,
+ );
+ const chunk = page.items.find((candidate) => candidate.itemId === item.itemId);
+ if (chunk === undefined) break;
+ text += chunk.text ?? "";
+ nextTextOffset = chunk.textTruncated ? (chunk.nextTextOffset ?? null) : null;
+ }
+ return text;
+});
+
+/** The run's last assistant message, or its last error when it did not complete. */
+const runResultText = Effect.fn("cli.thread.runResultText")(function* (
+ tools: ThreadTools,
+ threadId: ThreadId,
+ runId: RunId,
+ type: "assistant_message" | "error",
+) {
+ const { items } = yield* readTimeline(
+ tools,
+ threadId,
+ type === "assistant_message" ? "messages" : "activity",
+ );
+ const item = items.findLast((candidate) => candidate.runId === runId && candidate.type === type);
+ return item === undefined ? null : yield* readFullText(tools, threadId, item);
+});
+
+type WaitOutcome =
+ | {
+ readonly type: "ended";
+ readonly runId: RunId | null;
+ readonly status: OrchestratorMcpThreadStatus;
+ }
+ | { readonly type: "needs_input" };
+
+/**
+ * Waits for this exact run, following a restart to its continuation, so a
+ * message another client sends meanwhile cannot stand in for its result.
+ */
+export const waitForRun = Effect.fn("cli.thread.waitForRun")(function* (
+ tools: ThreadTools,
+ threadId: ThreadId,
+ runId: RunId,
+) {
+ const waitSlice = (timeoutMs: number) =>
+ tools.call("t3_thread_wait", { threadId, runId, timeoutMs }, OrchestratorMcpThreadWaitResult);
+ const ended = (waited: OrchestratorMcpThreadWaitResult) =>
+ ({ type: "ended", runId: waited.runId, status: waited.status }) satisfies WaitOutcome;
+ while (true) {
+ const waited = yield* waitSlice(WAIT_SLICE_MS);
+ if (!waited.timedOut) return ended(waited);
+ // A pending request on this run, or on an earlier run this one is queued
+ // behind, blocks it until someone answers.
+ const { thread } = yield* tools.call(
+ "t3_thread_read",
+ { threadId, limit: 1, runLimit: 1 },
+ OrchestratorMcpThreadReadResult,
+ );
+ if (thread.pendingRequestCount > 0) {
+ // The count is thread-wide: if this run ended since the slice, the
+ // request belongs to a later run.
+ const recheck = yield* waitSlice(1);
+ return recheck.timedOut ? ({ type: "needs_input" } satisfies WaitOutcome) : ended(recheck);
+ }
+ }
+});
+
+/**
+ * With --json the result always reaches stdout, so a script keeps the thread
+ * id even when the run fails.
+ */
+const finishRun = Effect.fn("cli.thread.finishRun")(function* (
+ tools: ThreadTools,
+ input: {
+ readonly threadId: ThreadId;
+ readonly runId: RunId;
+ readonly json: boolean;
+ },
+) {
+ const outcome = yield* waitForRun(tools, input.threadId, input.runId);
+ const runId = outcome.type === "ended" ? (outcome.runId ?? input.runId) : input.runId;
+ const status = outcome.type === "ended" ? outcome.status : "waiting";
+ const reply =
+ status === "completed"
+ ? yield* runResultText(tools, input.threadId, runId, "assistant_message")
+ : null;
+ const error =
+ status === "completed" || status === "waiting"
+ ? null
+ : yield* runResultText(tools, input.threadId, runId, "error");
+ if (input.json) {
+ yield* printJson({ threadId: input.threadId, runId, status, reply, error });
+ } else if (reply !== null) {
+ yield* Console.log(reply);
+ }
+ if (outcome.type === "needs_input") {
+ return yield* new ThreadNeedsInputError({ threadId: input.threadId });
+ }
+ if (status !== "completed") {
+ return yield* new ThreadRunEndedError({
+ threadId: input.threadId,
+ status,
+ ...(error === null ? {} : { error }),
+ });
+ }
+});
+
+const titleFromMessage = (message: string) => {
+ const firstLine = message.trim().split("\n")[0]?.trim() ?? "";
+ return firstLine.length > TITLE_MAX_CHARS
+ ? `${firstLine.slice(0, TITLE_MAX_CHARS - 1).trimEnd()}…`
+ : firstLine;
+};
+
+const launchWorkspaceStrategy = (input: {
+ readonly worktree: Option.Option<string>;
+ readonly branch: Option.Option<string>;
+}) =>
+ Option.match(input.worktree, {
+ onNone: () =>
+ Option.isSome(input.branch)
+ ? Effect.fail(new ThreadUsageError({ detail: "--branch needs --worktree <base-ref>." }))
+ : Effect.succeed(undefined),
+ onSome: (baseRef) =>
+ Effect.succeed({
+ type: "worktree" as const,
+ baseRef,
+ ...Option.match(input.branch, { onNone: () => ({}), onSome: (branch) => ({ branch }) }),
+ }),
+ });
+
+const jsonFlag = Flag.Boolean("json").pipe(
+ Flag.withDescription("Print JSON instead of text."),
+ Flag.withDefault(false),
+);
+const waitFlag = Flag.Boolean("wait").pipe(
+ Flag.withDescription(
+ "Wait for the agent to finish and print its reply. Exits 1 if the run fails and 2 if it waits for an answer.",
+ ),
+ Flag.withDefault(false),
+);
+const messageArgument = Argument.String("message").pipe(
+ Argument.withDescription("Message for the agent, or - to read it from stdin."),
+);
+const threadArgument = Argument.String("thread").pipe(Argument.withDescription("Thread id."));
+
+const decodeThreadIdValue = Schema.decodeUnknownEffect(ThreadId);
+const decodeTitle = Schema.decodeUnknownEffect(TrimmedNonEmptyString);
+const decodeThreadId = (value: string) =>
+ decodeThreadIdValue(value.trim()).pipe(
+ Effect.mapError(() => new ThreadUsageError({ detail: `'${value}' is not a thread id.` })),
+ );
+
+const threadListCommand = Command.make("list", {
+ ...projectLocationFlags,
+ project: Flag.String("project").pipe(
+ Flag.withDescription("Project id or a path inside the project. Defaults to this directory."),
+ Flag.withDefault("."),
+ ),
+ json: jsonFlag,
+}).pipe(
+ Command.withDescription("List a project's threads, newest first."),
+ Command.withHandler((flags) =>
+ withThreadTools(
+ flags,
+ Effect.fn("cli.thread.list")(function* (tools) {
+ const project = yield* resolveProject(tools, flags.project);
+ const threads: Array<OrchestratorMcpThreadListItem> = [];
+ let cursor: number | null = 0;
+ while (cursor !== null) {
+ const page: OrchestratorMcpThreadListResult = yield* tools.call(
+ "t3_thread_list",
+ { projectId: project.id, includeSubagents: false, limit: 100, cursor },
+ OrchestratorMcpThreadListResult,
+ );
+ threads.push(...page.threads);
+ cursor = page.nextCursor;
+ }
+ if (flags.json) {
+ return yield* printJson(threads);
+ }
+ for (const thread of threads) {
+ yield* Console.log(`${thread.threadId} ${thread.status.padEnd(11)} ${thread.title}`);
+ }
+ }),
+ ).pipe(reportThreadErrors),
+ ),
+);
+
+const threadStartCommand = Command.make("start", {
+ ...projectLocationFlags,
+ project: Argument.String("project").pipe(
+ Argument.withDescription("Project id or a path inside the project, such as ."),
+ ),
+ message: messageArgument,
+ title: Flag.String("title").pipe(
+ Flag.withDescription("Thread title. Defaults to the message's first line."),
+ Flag.optional,
+ ),
+ provider: Flag.String("provider").pipe(
+ Flag.withDescription("Provider instance id. Pass with --model."),
+ Flag.optional,
+ ),
+ model: Flag.String("model").pipe(
+ Flag.withDescription("Model slug. Defaults to the project's default model."),
+ Flag.optional,
+ ),
+ worktree: Flag.String("worktree").pipe(
+ Flag.withDescription(
+ "Run in a new git worktree based on this branch, tag, or commit, instead of the project folder.",
+ ),
+ Flag.optional,
+ ),
+ branch: Flag.String("branch").pipe(
+ Flag.withDescription("Branch name for the new worktree."),
+ Flag.optional,
+ ),
+ wait: waitFlag,
+ json: jsonFlag,
+}).pipe(
+ Command.withDescription("Start a thread in a project and print its id."),
+ Command.withHandler((flags) =>
+ Effect.gen(function* () {
+ const message = yield* readMessageArgument(flags.message);
+ const workspaceStrategy = yield* launchWorkspaceStrategy(flags);
+ if (Option.isSome(flags.provider) !== Option.isSome(flags.model)) {
+ return yield* new ThreadUsageError({ detail: "--provider and --model go together." });
+ }
+ const title = yield* decodeTitle(
+ Option.getOrElse(flags.title, () => titleFromMessage(message)),
+ ).pipe(Effect.mapError(() => new ThreadUsageError({ detail: "The title is empty." })));
+ yield* withThreadTools(
+ flags,
+ Effect.fn("cli.thread.start")(function* (tools) {
+ const project = yield* resolveProject(tools, flags.project);
+ const launched = yield* tools.call(
+ "t3_thread_launch",
+ {
+ projectId: project.id,
+ title,
+ message,
+ ...(workspaceStrategy === undefined ? {} : { workspaceStrategy }),
+ ...(Option.isSome(flags.provider) && Option.isSome(flags.model)
+ ? {
+ modelSelection: {
+ instanceId: flags.provider.value,
+ model: flags.model.value,
+ },
+ }
+ : {}),
+ },
+ ThreadLaunchResult,
+ );
+ if (flags.wait && launched.runId !== null) {
+ if (!flags.json) yield* Console.error(`Thread ${launched.threadId}`);
+ return yield* finishRun(tools, {
+ threadId: launched.threadId,
+ runId: launched.runId,
+ json: flags.json,
+ });
+ }
+ yield* flags.json ? printJson(launched) : Console.log(launched.threadId);
+ }),
+ );
+ }).pipe(reportThreadErrors),
+ ),
+);
+
+const threadSendCommand = Command.make("send", {
+ ...projectLocationFlags,
+ thread: threadArgument,
+ message: messageArgument,
+ wait: waitFlag,
+ json: jsonFlag,
+}).pipe(
+ Command.withDescription(
+ "Send a message to a thread. A busy thread gets it as its next turn; nothing is interrupted.",
+ ),
+ Command.withHandler((flags) =>
+ Effect.gen(function* () {
+ const threadId = yield* decodeThreadId(flags.thread);
+ const message = yield* readMessageArgument(flags.message);
+ yield* withThreadTools(
+ flags,
+ Effect.fn("cli.thread.send")(function* (tools) {
+ const sent = yield* tools.call(
+ "t3_thread_send",
+ { threadId, message, mode: "queue" },
+ OrchestratorMcpThreadSendResult,
+ );
+ if (flags.wait) {
+ return yield* finishRun(tools, { threadId, runId: sent.runId, json: flags.json });
+ }
+ yield* flags.json
+ ? printJson(sent)
+ : Console.log(sent.delivery === "queued" ? "Queued." : "Sent.");
+ }),
+ );
+ }).pipe(reportThreadErrors),
+ ),
+);
+
+const threadShowCommand = Command.make("show", {
+ ...projectLocationFlags,
+ thread: threadArgument,
+ messages: Flag.Int("messages").pipe(
+ Flag.withDescription("How many of the latest messages to print."),
+ Flag.withDefault(10),
+ ),
+ json: jsonFlag,
+}).pipe(
+ Command.withDescription("Show a thread's state and its latest messages."),
+ Command.withHandler((flags) =>
+ Effect.gen(function* () {
+ const threadId = yield* decodeThreadId(flags.thread);
+ yield* withThreadTools(
+ flags,
+ Effect.fn("cli.thread.show")(function* (tools) {
+ const { thread, items } = yield* readTimeline(tools, threadId, "messages");
+ const conversation = items.filter(
+ (item) => item.type === "user_message" || item.type === "assistant_message",
+ );
+ const latest = conversation.slice(Math.max(0, conversation.length - flags.messages));
+ const messages = yield* Effect.forEach(latest, (item) =>
+ readFullText(tools, threadId, item).pipe(
+ Effect.map((text) => ({
+ role: item.type === "user_message" ? "user" : "assistant",
+ runId: item.runId,
+ text,
+ })),
+ ),
+ );
+ if (flags.json) {
+ return yield* printJson({ thread, messages });
+ }
+ yield* Console.log(thread.title);
+ yield* Console.log(
+ [thread.threadId, thread.status, `${thread.providerInstanceId}/${thread.model}`].join(
+ " ",
+ ),
+ );
+ if (thread.worktreePath !== null) {
+ yield* Console.log(`${thread.branch ?? "(no branch)"} ${thread.worktreePath}`);
+ }
+ if (thread.pendingRequestCount > 0) {
+ yield* Console.log(`Waiting for ${thread.pendingRequestCount} answer(s).`);
+ }
+ for (const entry of messages) {
+ yield* Console.log(`\n[${entry.role}]\n${entry.text}`);
+ }
+ }),
+ );
+ }).pipe(reportThreadErrors),
+ ),
+);
+
+export const threadCommand = Command.make("thread").pipe(
+ Command.withDescription("Start, message, and read threads on the running server."),
+ Command.withSubcommands([
+ threadListCommand,
+ threadStartCommand,
+ threadSendCommand,
+ threadShowCommand,
+ ]),
+);
diff --git a/apps/server/src/mcp/AcpMcpStdioBridge.ts b/apps/server/src/mcp/AcpMcpStdioBridge.ts
index 7338190ca56..2db36ce5abc 100644
--- a/apps/server/src/mcp/AcpMcpStdioBridge.ts
+++ b/apps/server/src/mcp/AcpMcpStdioBridge.ts
@@ -6,6 +6,7 @@ import * as NodeReadline from "node:readline";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
+import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import { discardResponseBody, responsePayloads } from "@t3tools/shared/mcpResponsePayloads";
@@ -14,7 +15,7 @@ import { discardResponseBody, responsePayloads } from "@t3tools/shared/mcpRespon
* unevenly implemented.
*/
-class AcpMcpBridgeError extends Error {
+export class AcpMcpBridgeError extends Error {
readonly _tag = "AcpMcpBridgeError";
}
@@ -53,94 +54,125 @@ function protocolVersionOf(entry: unknown): string | null {
return typeof version === "string" && version.length > 0 ? version : null;
}
-export interface AcpMcpToolCallOptions {
+export interface McpToolSessionOptions {
readonly endpoint: string;
readonly authorization: string;
- readonly tool: string;
- readonly arguments: Readonly<Record<string, unknown>>;
+ readonly clientName: string;
readonly fetchImplementation?: (url: string, init?: RequestInit) => Promise<Response>;
}
+export interface McpToolSession {
+ /** Resolves to the JSON-RPC `result` of `tools/call`, a `CallToolResult`. */
+ readonly call: (
+ tool: string,
+ args: Readonly<Record<string, unknown>>,
+ ) => Effect.Effect<unknown, AcpMcpBridgeError>;
+}
+
/**
- * This is the terminal fallback for ACP agents that accept `mcpServers` in
- * `session/new` but fail to expose those tools to their model. Compliant ACP
- * agents continue to use the stdio bridge above.
+ * One initialized MCP session over T3 Code's HTTP endpoint, terminated when
+ * the scope closes. Used by the ACP terminal fallback and `t3 thread`.
*/
-function callAcpMcpTool(options: AcpMcpToolCallOptions): Effect.Effect<unknown, AcpMcpBridgeError> {
+export const mcpToolSession = (
+ options: McpToolSessionOptions,
+): Effect.Effect<McpToolSession, AcpMcpBridgeError, Scope.Scope> => {
const fetchImplementation = options.fetchImplementation ?? fetch;
- return Effect.gen(function* () {
- let sessionId: string | null = null;
- let protocolVersion: string | null = null;
+ let sessionId: string | null = null;
+ let protocolVersion: string | null = null;
+ let nextId = 0;
- const send = Effect.fn("AcpMcpStdioBridge.send")(function* (
- message: unknown,
- ): Effect.fn.Return<ReadonlyArray<unknown>, AcpMcpBridgeError> {
- const response = yield* Effect.tryPromise({
- try: () =>
- fetchImplementation(options.endpoint, {
- method: "POST",
- headers: {
- "content-type": "application/json",
- accept: "application/json, text/event-stream",
- authorization: options.authorization,
- ...(sessionId === null ? {} : { "mcp-session-id": sessionId }),
- ...(protocolVersion === null ? {} : { "mcp-protocol-version": protocolVersion }),
- },
- body: JSON.stringify(message),
- }),
- catch: bridgeError,
- });
- sessionId = response.headers.get("mcp-session-id") ?? sessionId;
- if (!response.ok) {
- yield* discardResponseBody(response);
- return yield* Effect.fail(
- new AcpMcpBridgeError(`T3 Code MCP endpoint responded with HTTP ${response.status}.`),
- );
- }
- const payloads = yield* Stream.runCollect(responsePayloads(response, bridgeError));
- for (const payload of payloads) {
- protocolVersion = protocolVersionOf(payload) ?? protocolVersion;
- }
- return payloads;
- });
+ const headers = () => ({
+ accept: "application/json, text/event-stream",
+ authorization: options.authorization,
+ ...(sessionId === null ? {} : { "mcp-session-id": sessionId }),
+ ...(protocolVersion === null ? {} : { "mcp-protocol-version": protocolVersion }),
+ });
- const initializeId = "t3-acp-cli-initialize";
- const initialized = yield* send({
- jsonrpc: "2.0",
- id: initializeId,
- method: "initialize",
- params: {
- protocolVersion: MCP_PROTOCOL_VERSION,
- capabilities: {},
- clientInfo: { name: "t3-code-acp-cli", version: "0.0.0" },
- },
+ const send = Effect.fn("AcpMcpStdioBridge.send")(function* (
+ message: unknown,
+ ): Effect.fn.Return<ReadonlyArray<unknown>, AcpMcpBridgeError> {
+ const response = yield* Effect.tryPromise({
+ try: () =>
+ fetchImplementation(options.endpoint, {
+ method: "POST",
+ headers: { "content-type": "application/json", ...headers() },
+ body: JSON.stringify(message),
+ }),
+ catch: bridgeError,
});
- const initializeResponse = initialized.find((entry) => asEnvelope(entry)?.id === initializeId);
- if (initializeResponse === undefined || asEnvelope(initializeResponse)?.error !== undefined) {
+ sessionId = response.headers.get("mcp-session-id") ?? sessionId;
+ if (!response.ok) {
+ yield* discardResponseBody(response);
return yield* Effect.fail(
- new AcpMcpBridgeError("T3 Code MCP endpoint rejected initialization."),
+ new AcpMcpBridgeError(`T3 Code MCP endpoint responded with HTTP ${response.status}.`),
);
}
- yield* send({ jsonrpc: "2.0", method: "notifications/initialized" });
+ const payloads = yield* Stream.runCollect(responsePayloads(response, bridgeError));
+ for (const payload of payloads) {
+ protocolVersion = protocolVersionOf(payload) ?? protocolVersion;
+ }
+ return payloads;
+ });
- const callId = "t3-acp-cli-tool-call";
- const responses = yield* send({
- jsonrpc: "2.0",
- id: callId,
- method: "tools/call",
- params: { name: options.tool, arguments: options.arguments },
- });
- const response = responses.find((entry) => asEnvelope(entry)?.id === callId);
- const envelope = asEnvelope(response);
+ const request = Effect.fn("AcpMcpStdioBridge.request")(function* (
+ method: string,
+ params: unknown,
+ ): Effect.fn.Return<JsonRpcEnvelope, AcpMcpBridgeError> {
+ const id = `t3-cli-${nextId++}`;
+ const responses = yield* send({ jsonrpc: "2.0", id, method, params });
+ const envelope = asEnvelope(responses.find((entry) => asEnvelope(entry)?.id === id));
if (envelope === null || envelope.error !== undefined) {
return yield* Effect.fail(
new AcpMcpBridgeError(
- `T3 Code MCP tool call failed${envelope?.error === undefined ? "." : `: ${JSON.stringify(envelope.error)}`}`,
+ `T3 Code MCP ${method} failed${envelope?.error === undefined ? "." : `: ${JSON.stringify(envelope.error)}`}`,
),
);
}
- return envelope.result;
+ return envelope;
+ });
+
+ const terminate = Effect.suspend(() =>
+ sessionId === null
+ ? Effect.void
+ : Effect.tryPromise(() =>
+ fetchImplementation(options.endpoint, { method: "DELETE", headers: headers() }),
+ ).pipe(Effect.flatMap(discardResponseBody), Effect.ignore),
+ );
+
+ // Registered before the handshake so a session the server opened is ended
+ // even when the handshake fails, and the handshake stays interruptible.
+ return Effect.gen(function* () {
+ yield* Effect.addFinalizer(() => terminate);
+ yield* request("initialize", {
+ protocolVersion: MCP_PROTOCOL_VERSION,
+ capabilities: {},
+ clientInfo: { name: options.clientName, version: "0.0.0" },
+ });
+ yield* send({ jsonrpc: "2.0", method: "notifications/initialized" });
+ return {
+ call: (tool, args) =>
+ request("tools/call", { name: tool, arguments: args }).pipe(
+ Effect.map((envelope) => envelope.result),
+ ),
+ } satisfies McpToolSession;
});
+};
+
+/**
+ * This is the terminal fallback for ACP agents that accept `mcpServers` in
+ * `session/new` but fail to expose those tools to their model. Compliant ACP
+ * agents continue to use the stdio bridge above.
+ */
+function callAcpMcpTool(options: {
+ readonly endpoint: string;
+ readonly authorization: string;
+ readonly tool: string;
+ readonly arguments: Readonly<Record<string, unknown>>;
+}): Effect.Effect<unknown, AcpMcpBridgeError> {
+ return mcpToolSession({ ...options, clientName: "t3-code-acp-cli" }).pipe(
+ Effect.flatMap((session) => session.call(options.tool, options.arguments)),
+ Effect.scoped,
+ );
}
export function runAcpMcpStdioBridge(options: AcpMcpStdioBridgeOptions): Effect.Effect<void> {
diff --git a/apps/server/src/mcp/toolkits/project/handlers.test.ts b/apps/server/src/mcp/toolkits/project/handlers.test.ts
index aecc99f7dda..4c22393bf47 100644
--- a/apps/server/src/mcp/toolkits/project/handlers.test.ts
+++ b/apps/server/src/mcp/toolkits/project/handlers.test.ts
@@ -4,6 +4,8 @@ import {
ProjectId,
ProviderInstanceId,
type Project as ProjectRecord,
+ type ModelSelection,
+ type RuntimeMode,
} from "@t3tools/contracts";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -28,7 +30,10 @@ import * as ProjectHandlers from "./handlers.ts";
import { ProjectToolkit } from "./tools.ts";
const clientLaunchHarness = (input: {
- readonly runtimeModeCeiling: "approval-required" | "auto-accept-edits" | "auto" | "full-access";
+ readonly runtimeModeCeiling: RuntimeMode;
+ readonly defaultRuntimeMode?: RuntimeMode;
+ /** Where Settings saves a project's model; the legacy project field stays null. */
+ readonly overrideModel?: ModelSelection;
readonly launched: Array<ThreadLaunch.ThreadLaunchInput>;
readonly workspaceRoot?: string;
readonly checkWorktreeBase?: ThreadLaunch.ThreadLaunchService["Service"]["checkWorktreeBase"];
@@ -39,7 +44,19 @@ const clientLaunchHarness = (input: {
model: "claude-opus",
};
const layerDependencies = Layer.mergeAll(
- ServerSettings.layerTest(),
+ ServerSettings.layerTest({
+ ...(input.defaultRuntimeMode === undefined
+ ? {}
+ : { defaultRuntimeMode: input.defaultRuntimeMode }),
+ ...(input.overrideModel === undefined
+ ? {}
+ : {
+ projectSettingsFolded: true,
+ projectSettingsOverrides: {
+ [projectId]: { defaultModelSelection: input.overrideModel },
+ },
+ }),
+ }),
NodeCrypto.layer,
Layer.succeed(McpInvocationContext.McpInvocationContext, {
environmentId: EnvironmentId.make("environment"),
@@ -79,7 +96,7 @@ const clientLaunchHarness = (input: {
? Option.some({
id,
workspaceRoot: input.workspaceRoot ?? "/projects/client-target",
- defaultModelSelection: modelSelection,
+ defaultModelSelection: input.overrideModel === undefined ? modelSelection : null,
} as unknown as ProjectRecord)
: Option.none(),
),
@@ -99,35 +116,85 @@ const clientLaunchHarness = (input: {
return { projectId, modelSelection, dependencies: layerDependencies };
};
-it.effect("a client launches at its ceiling with the project's default model", () =>
- Effect.gen(function* () {
- const launched: Array<ThreadLaunch.ThreadLaunchInput> = [];
- const { projectId, modelSelection, dependencies } = clientLaunchHarness({
- runtimeModeCeiling: "auto-accept-edits",
- launched,
- });
- const toolkit = yield* ProjectToolkit.pipe(
- Effect.provide(
- McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(Layer.provide(dependencies)),
- ),
- );
- const handle = (params: Parameters<typeof toolkit.handle<"t3_thread_launch">>[1]) =>
- toolkit
- .handle("t3_thread_launch", params)
- .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies));
+it.effect(
+ "a client launches with the project's default model and mode, capped at its ceiling",
+ () =>
+ Effect.gen(function* () {
+ const launchWith = Effect.fn("test.launchWith")(function* (
+ runtimeModeCeiling: RuntimeMode,
+ defaultRuntimeMode: RuntimeMode,
+ params: {
+ readonly title: string;
+ readonly message?: string;
+ readonly runtimeMode?: RuntimeMode;
+ readonly targeted?: false;
+ readonly overrideModel?: ModelSelection;
+ },
+ ) {
+ const { targeted, overrideModel, ...input } = params;
+ const launched: Array<ThreadLaunch.ThreadLaunchInput> = [];
+ const { projectId, modelSelection, dependencies } = clientLaunchHarness({
+ runtimeModeCeiling,
+ defaultRuntimeMode,
+ launched,
+ ...(overrideModel === undefined ? {} : { overrideModel }),
+ });
+ const toolkit = yield* ProjectToolkit.pipe(
+ Effect.provide(
+ McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(
+ Layer.provide(dependencies),
+ ),
+ ),
+ );
+ const result = yield* toolkit
+ .handle("t3_thread_launch", targeted === false ? input : { ...input, projectId })
+ .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies));
+ return { result: result.at(-1)?.result, launched, projectId, modelSelection };
+ });
- const result = yield* handle({ title: "Fix", projectId, message: "Fix the bug" });
- expect(result.at(-1)?.result).toMatchObject({ projectId, modelSelection });
- expect(launched[0]?.runtimeMode).toBe("auto-accept-edits");
- expect(launched[0]?.initialMessage?.senderThreadId).toBeUndefined();
+ const belowCeiling = yield* launchWith("full-access", "approval-required", {
+ title: "Fix",
+ message: "Fix the bug",
+ });
+ expect(belowCeiling.result).toMatchObject({
+ projectId: belowCeiling.projectId,
+ modelSelection: belowCeiling.modelSelection,
+ });
+ expect(belowCeiling.launched[0]?.runtimeMode).toBe("approval-required");
+ expect(belowCeiling.launched[0]?.initialMessage?.senderThreadId).toBeUndefined();
- const escalated = yield* handle({ title: "Fix", projectId, runtimeMode: "full-access" });
- expect(escalated.at(-1)?.result).toMatchObject({ code: "runtime_mode_escalation_denied" });
+ const aboveCeiling = yield* launchWith("auto-accept-edits", "full-access", { title: "Fix" });
+ expect(aboveCeiling.launched[0]?.runtimeMode).toBe("auto-accept-edits");
- const untargeted = yield* handle({ title: "Fix" });
- expect(untargeted.at(-1)?.result).toMatchObject({ code: "target_required" });
- expect(launched).toHaveLength(1);
- }),
+ const requested = yield* launchWith("full-access", "approval-required", {
+ title: "Fix",
+ runtimeMode: "auto",
+ });
+ expect(requested.launched[0]?.runtimeMode).toBe("auto");
+
+ const escalated = yield* launchWith("auto-accept-edits", "auto-accept-edits", {
+ title: "Fix",
+ runtimeMode: "full-access",
+ });
+ expect(escalated.result).toMatchObject({ code: "runtime_mode_escalation_denied" });
+ expect(escalated.launched).toHaveLength(0);
+
+ const untargeted = yield* launchWith("full-access", "full-access", {
+ title: "Fix",
+ targeted: false,
+ });
+ expect(untargeted.result).toMatchObject({ code: "target_required" });
+
+ const overrideModel = {
+ instanceId: ProviderInstanceId.make("codex"),
+ model: "gpt-settings",
+ };
+ const fromSettings = yield* launchWith("full-access", "full-access", {
+ title: "Fix",
+ overrideModel,
+ });
+ expect(fromSettings.launched[0]?.modelSelection).toEqual(overrideModel);
+ }),
);
it.effect("a launch binds only an existing checkout that is one of the project's worktrees", () =>
diff --git a/apps/server/src/mcp/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.ts
index 912d6ad127f..380a1b52ec9 100644
--- a/apps/server/src/mcp/toolkits/project/handlers.ts
+++ b/apps/server/src/mcp/toolkits/project/handlers.ts
@@ -9,6 +9,9 @@ import * as Project from "../../../project/ProjectService.ts";
import * as ManagedProjectFolders from "../../../project/ManagedProjectFolders.ts";
import * as Repositories from "../../../sourceControl/SourceControlRepositoryService.ts";
import * as GitVcsDriver from "../../../vcs/GitVcsDriver.ts";
+import * as ServerSettings from "../../../serverSettings.ts";
+import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
+import { resolveRuntimeMode } from "../../OrchestratorMcpService.ts";
import * as McpToolAccess from "../../McpToolAccess.ts";
import { newCommandId, readCaller, resolveProjectId, unavailable } from "../../threadAccess.ts";
import { ProjectToolkit } from "./tools.ts";
@@ -122,10 +125,26 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
}),
),
);
+ // A caller outside a thread has nothing to inherit, so it starts with the
+ // project's effective defaults, as the composer does. Its mode stays
+ // within the ceiling it was approved with.
+ const projectDefaults =
+ caller === undefined
+ ? yield* ServerSettings.ServerSettingsService.pipe(
+ Effect.flatMap((settings) => settings.getSettings),
+ Effect.mapError(unavailable),
+ Effect.flatMap((settings) =>
+ Effect.map(
+ readProject,
+ (project) => resolveProjectSettings(settings, projectId, project).settings,
+ ),
+ ),
+ )
+ : undefined;
const modelSelection =
input.modelSelection ??
caller?.modelSelection ??
- (yield* readProject)?.defaultModelSelection ??
+ projectDefaults?.defaultModelSelection ??
undefined;
if (modelSelection === undefined)
return yield* new OrchestratorMcpFailure({
@@ -133,13 +152,19 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
message:
"Pass modelSelection: the project has no default model. orchestrator_capabilities lists providers and models.",
});
+ const startedRuntimeMode =
+ projectDefaults !== undefined && input.runtimeMode === undefined
+ ? yield* resolveRuntimeMode(runtimeMode, projectDefaults.defaultRuntimeMode).pipe(
+ Effect.orElseSucceed(() => runtimeMode),
+ )
+ : runtimeMode;
const result = yield* ThreadMessageIntake.launchThread({
commandId,
threadId,
projectId,
title: input.title,
modelSelection,
- runtimeMode,
+ runtimeMode: startedRuntimeMode,
interactionMode,
workspaceStrategy: input.workspaceStrategy ?? { type: "root" },
...(input.message === undefined && attachments.length === 0
diff --git a/docs/user/outside-agents.md b/docs/user/outside-agents.md
index 7cc6692e38f..1e7b80cde94 100644
--- a/docs/user/outside-agents.md
+++ b/docs/user/outside-agents.md
@@ -88,6 +88,28 @@ Any agent that supports remote MCP servers over HTTP with OAuth can connect. Giv
it the MCP URL and choose OAuth, and the agent finds the sign-in settings itself.
Agents without OAuth support cannot connect.
+## Scripts on the host
+
+On the machine that runs the environment, `t3 thread` uses the same tools
+without a sign-in:
+
+```sh
+id=$(t3 thread start . "Find why the tests are slow")
+t3 thread send "$id" "Now fix it" --wait
+t3 thread show "$id"
+t3 thread list
+```
+
+`.` means the project that contains the current folder; a project id also
+works. A new thread uses the project's default model and permission mode, and
+runs in the project folder unless you pass `--worktree <base-branch>`. `send`
+never interrupts: a busy thread gets the message as its next turn. Pass `-` as
+the message to read it from stdin.
+
+`--wait` prints the agent's reply. It exits 1 when the run fails or stops, and
+2 when the agent waits for an answer you give in the app. Add `--json` for a
+result that always includes the thread id.
+
## Remove an agent
Approved agents appear under **Settings → Connections** like other clients.