@devries-cameron20 / t3code Mirror · read-only / commits / 2bc2d80e79
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 22:00 UTC

revert: #15464 (MCP agents respond to approvals) (#22152)

Co-authored-by: Julius Marminge <julius@marminge.se> Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>

Julius Marminge committed Oct 19, 2026 at 22:40 UTC 2bc2d80e79c6051fcd26adcbfd579a1d8813b638
20 files changed +61 -685
apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts
-15
@@ -1745,21 +1745,6 @@ describe("orchestrator MCP toolkit", () => {
1745 result: delegatedResult,
1746 });
1747 const child = yield* orchestrator.getThreadProjection(delegated.childThreadId);
1748 - const organizeChild = (action: string) =>
1749 - invoke("t3_thread_organize", { threadId: delegated.childThreadId, action });
1750 - expect((yield* organizeChild("mark_unread")).isError).toBe(false);
1751 - const unread = yield* orchestrator.getThreadShell(delegated.childThreadId);
1752 - expect(unread?.lastVisitedAt).toEqual(
1753 - DateTime.subtract(child.runs.at(-1)!.completedAt!, { milliseconds: 1 }),
1754 - );
1755 - expect((yield* organizeChild("mark_read")).isError).toBe(false);
1756 - expect(
1757 - (yield* orchestrator.getThreadShell(delegated.childThreadId))?.lastVisitedAt,
1758 - ).toEqual(unread?.updatedAt);
1759 - expect((yield* organizeChild("mark_unread")).isError).toBe(false);
1760 - expect(
1761 - (yield* orchestrator.getThreadShell(delegated.childThreadId))?.lastVisitedAt,
1762 - ).toEqual(unread?.lastVisitedAt);
1748 expect(child.thread.lineage).toEqual({
1749 parentThreadId,
1750 relationshipToParent: "subagent",
apps/server/src/mcp/WorktreeMcpService.test.ts
-2
@@ -30,7 +30,6 @@ import {
30 import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
31 import * as ProjectService from "../project/ProjectService.ts";
32 import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
33 -import * as ReviewService from "../review/ReviewService.ts";
33 import * as ServerSettings from "../serverSettings.ts";
34 import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts";
35 import type * as McpInvocationContext from "./McpInvocationContext.ts";
@@ -292,7 +291,6 @@ const makeHarness = (options: HarnessOptions = {}) => {
291 const layer = WorktreeMcpService.layer.pipe(
292 Layer.provide(
293 Layer.mergeAll(
295 - Layer.mock(ReviewService.ReviewService)({}),
294 Layer.mock(ThreadManagementService.ThreadManagementService)({
295 dispatch,
296 getThreadRecords,
apps/server/src/mcp/WorktreeMcpService.ts
+11 -103
@@ -2,10 +2,6 @@ import {
2 CommandId,
3 MessageId,
4 type ProjectId,
5 - OrchestratorMcpFailure,
6 - type ReviewDiffFileStat,
7 - type ReviewDiffPreviewSourceKind,
8 - type ThreadId,
5 WorktreeMcpFailure,
6 type WorktreeMcpContinuationStatus,
7 type WorktreeMcpHandoffInput,
@@ -24,46 +20,19 @@ import * as GitWorkflowService from "../git/GitWorkflowService.ts";
20 import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
21 import * as ProjectService from "../project/ProjectService.ts";
22 import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
27 -import * as ReviewService from "../review/ReviewService.ts";
23 import * as ServerSettings from "../serverSettings.ts";
24 import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts";
30 -import * as McpInvocationContext from "./McpInvocationContext.ts";
31 -import { readThread, unavailable } from "./threadAccess.ts";
32 -
33 -const MAX_DIFF_FILES = 500;
25 +import type { McpInvocationScope, McpThreadInvocationScope } from "./McpInvocationContext.ts";
26
27 export class WorktreeMcpService extends Context.Service<
28 WorktreeMcpService,
29 {
38 - readonly getThreadDiff: (
39 - scope: McpInvocationContext.McpInvocationScope,
40 - input: {
41 - readonly threadId?: ThreadId | undefined;
42 - readonly baseRef?: string | undefined;
43 - readonly source?: ReviewDiffPreviewSourceKind | undefined;
44 - readonly maxCharacters?: number | undefined;
45 - },
46 - ) => Effect.Effect<
47 - {
48 - readonly threadId: ThreadId;
49 - readonly cwd: string;
50 - readonly sources: ReadonlyArray<{
51 - readonly kind: ReviewDiffPreviewSourceKind;
52 - readonly baseRef: string | null;
53 - readonly headRef: string | null;
54 - readonly files: ReadonlyArray<ReviewDiffFileStat> | null;
55 - readonly diff: string;
56 - readonly truncated: boolean;
57 - }>;
58 - },
59 - OrchestratorMcpFailure
60 - >;
30 readonly handoff: (
62 - scope: McpInvocationContext.McpInvocationScope,
31 + scope: McpInvocationScope,
32 input: WorktreeMcpHandoffInput,
33 ) => Effect.Effect<WorktreeMcpHandoffResult, WorktreeMcpFailure>;
34 readonly status: (
66 - scope: McpInvocationContext.McpInvocationScope,
35 + scope: McpInvocationScope,
36 ) => Effect.Effect<WorktreeMcpStatusResult, WorktreeMcpFailure>;
37 }
38 >()("t3/mcp/WorktreeMcpService") {}
@@ -87,7 +56,6 @@ const asOperationFailed = (prefix: string) =>
56
57 const make = Effect.gen(function* () {
58 const crypto = yield* Crypto.Crypto;
90 - const review = yield* ReviewService.ReviewService;
59 const threadManagement = yield* ThreadManagementService.ThreadManagementService;
60 const projects = yield* ProjectService.ProjectService;
61 const serverSettings = yield* ServerSettings.ServerSettingsService;
@@ -95,68 +63,12 @@ const make = Effect.gen(function* () {
63 const setupScriptRunner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
64 const vcsStatusBroadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
65
98 - const getThreadDiff: WorktreeMcpService["Service"]["getThreadDiff"] = Effect.fn(
99 - "WorktreeMcpService.getThreadDiff",
100 - )(function* (scope, input) {
101 - const {
102 - projection: { thread },
103 - } = yield* readThread(input.threadId).pipe(
104 - Effect.provideService(McpInvocationContext.McpInvocationContext, scope),
105 - Effect.provideService(ThreadManagementService.ThreadManagementService, threadManagement),
106 - );
107 - const project = yield* projects.getById(thread.projectId).pipe(Effect.mapError(unavailable));
108 - if (Option.isNone(project))
109 - return yield* new OrchestratorMcpFailure({
110 - code: "invalid_request",
111 - message: "The project was not found.",
112 - });
113 - const preview = yield* review
114 - .getDiffPreview({
115 - cwd: thread.worktreePath ?? project.value.workspaceRoot,
116 - ...(input.baseRef === undefined ? {} : { baseRef: input.baseRef }),
117 - ...(input.source === undefined ? {} : { sourceKind: input.source }),
118 - })
119 - .pipe(
120 - Effect.mapError((error) =>
121 - error._tag === "VcsRepositoryDetectionError" ||
122 - error._tag === "VcsUnsupportedOperationError" ||
123 - (error._tag === "GitCommandError" &&
124 - input.baseRef !== undefined &&
125 - error.operation === "GitVcsDriver.resolveReviewMergeBase" &&
126 - error.exitCode !== undefined)
127 - ? new OrchestratorMcpFailure({ code: "invalid_request", message: error.detail })
128 - : unavailable(),
129 - ),
130 - );
131 - if (preview.sources.length === 0)
132 - return yield* new OrchestratorMcpFailure({
133 - code: "invalid_request",
134 - message: "The thread's checkout is not a repository.",
135 - });
136 - const maxCharacters = input.maxCharacters ?? 20_000;
137 - return {
138 - threadId: thread.id,
139 - cwd: preview.cwd,
140 - sources: preview.sources.map((source) => ({
141 - kind: source.kind,
142 - baseRef: source.baseRef,
143 - headRef: source.headRef,
144 - files: source.files?.slice(0, MAX_DIFF_FILES) ?? null,
145 - diff: source.diff.slice(0, maxCharacters),
146 - truncated:
147 - source.truncated ||
148 - source.diff.length > maxCharacters ||
149 - (source.files?.length ?? 0) > MAX_DIFF_FILES,
150 - })),
151 - };
152 - });
153 -
66 // Serializes handoffs per thread: two concurrent calls could otherwise both
67 // pass the worktreePath === null check and each create a worktree, leaving
68 // one untracked on disk.
69 const handoffThreadsInFlight = new Set<string>();
70
159 - const requireThreadScope = (scope: McpInvocationContext.McpInvocationScope) =>
71 + const requireThreadScope = (scope: McpInvocationScope) =>
72 scope.thread === undefined
73 ? Effect.fail(
74 failure(
@@ -164,16 +76,16 @@ const make = Effect.gen(function* () {
76 "Worktree handoff and status act as the calling T3 thread, so they need an agent running inside T3 Code.",
77 ),
78 )
167 - : Effect.succeed(scope as McpInvocationContext.McpThreadInvocationScope);
79 + : Effect.succeed(scope as McpThreadInvocationScope);
80
169 - const requireCapability = (scope: McpInvocationContext.McpInvocationScope) =>
81 + const requireCapability = (scope: McpInvocationScope) =>
82 scope.capabilities.has("worktree")
83 ? Effect.void
84 : Effect.fail(
85 failure("capability_denied", "This MCP credential does not grant worktree capabilities."),
86 );
87
176 - const loadThread = (scope: McpInvocationContext.McpThreadInvocationScope) =>
88 + const loadThread = (scope: McpThreadInvocationScope) =>
89 threadManagement.getThreadRecords(scope.thread.threadId, []).pipe(
90 Effect.mapError((error) =>
91 error._tag === "OrchestratorProjectionError"
@@ -189,10 +101,7 @@ const make = Effect.gen(function* () {
101 ),
102 );
103
192 - const loadProject = (
193 - scope: McpInvocationContext.McpThreadInvocationScope,
194 - projectId: ProjectId,
195 - ) =>
104 + const loadProject = (scope: McpThreadInvocationScope, projectId: ProjectId) =>
105 projects.getById(projectId).pipe(
106 asOperationFailed(`Unable to read project ${projectId}`),
107 Effect.flatMap(
@@ -214,7 +123,7 @@ const make = Effect.gen(function* () {
123 asOperationFailed("Unable to read server settings"),
124 );
125
217 - const handoffIds = (scope: McpInvocationContext.McpThreadInvocationScope) =>
126 + const handoffIds = (scope: McpThreadInvocationScope) =>
127 crypto.randomUUIDv4().pipe(
128 Effect.map((uuid) => {
129 const part = (kind: string, operation: string) =>
@@ -231,7 +140,7 @@ const make = Effect.gen(function* () {
140 );
141
142 const performHandoff = Effect.fn("WorktreeMcpService.performHandoff")(function* (
234 - scope: McpInvocationContext.McpThreadInvocationScope,
143 + scope: McpThreadInvocationScope,
144 input: WorktreeMcpHandoffInput,
145 ) {
146 const alreadyInWorktree = (worktreePath: string) =>
@@ -538,14 +447,13 @@ const make = Effect.gen(function* () {
447 },
448 );
449
541 - return WorktreeMcpService.of({ getThreadDiff, handoff, status });
450 + return WorktreeMcpService.of({ handoff, status });
451 });
452
453 export const layer: Layer.Layer<
454 WorktreeMcpService,
455 never,
456 | Crypto.Crypto
548 - | ReviewService.ReviewService
457 | ThreadManagementService.ThreadManagementService
458 | ProjectService.ProjectService
459 | ServerSettings.ServerSettingsService
apps/server/src/mcp/threadAccess.ts
+1 -1
@@ -163,7 +163,7 @@ export const readThread = Effect.fn("mcp.readThread")(function* <
163 }
164 const projection = yield* context.threads
165 .getProjectThreadRecords({ projectId: shell.projectId, threadId: targetId }, fields, {
166 - turnItemTypes: ["user_input_request", "approval_request"],
166 + turnItemTypes: ["user_input_request"],
167 })
168 .pipe(
169 Effect.mapError((error) =>
apps/server/src/mcp/toolkits/core.test.ts
-183
@@ -13,13 +13,10 @@ import {
13 ProviderDriverKind,
14 ProviderInstanceId,
15 RunId,
16 - RuntimeRequestId,
16 ThreadId,
17 TurnItemId,
18 type OrchestrationV2ProjectedTurnItem,
19 type OrchestrationV2ThreadShell,
21 - type OrchestrationV2RuntimeRequest,
22 - type OrchestrationV2TurnItem,
20 } from "@t3tools/contracts";
21 import * as Deferred from "effect/Deferred";
22 import * as Effect from "effect/Effect";
@@ -622,186 +619,6 @@ it.effect("a client caller targets any thread within its ceiling and cannot act
619 ),
620 );
621
625 -it.effect("lists, reads and resolves approvals with offered decisions and caller limits", () => {
626 - const targetId = ThreadId.make("other-project-thread");
627 - let target = McpToolAccessTestkit.liveThreadShell(targetId, { runtimeMode: "auto" });
628 - const projection = {
629 - ...McpToolAccessTestkit.idleThreadProjection(target),
630 - runtimeRequests: [] as Array<OrchestrationV2RuntimeRequest>,
631 - turnItems: [] as Array<OrchestrationV2TurnItem>,
632 - };
633 - const options = [
634 - { decision: "accept" as const, label: "Allow" },
635 - { decision: "decline" as const, label: "Deny" },
636 - { decision: "cancel" as const, label: "Cancel" },
637 - ];
638 - for (const id of ["approve", "approve-client", "decline", "cancel", "question"]) {
639 - const requestId = RuntimeRequestId.make(id);
640 - projection.runtimeRequests.push({
641 - id: requestId,
642 - nodeId: NodeId.make("node:approval"),
643 - providerTurnId: null,
644 - nativeRequestRef: null,
645 - kind: id === "question" ? "user_input" : "command",
646 - status: "pending",
647 - responseCapability: { type: "message" },
648 - createdAt: target.updatedAt,
649 - resolvedAt: null,
650 - });
651 - if (id !== "question") {
652 - projection.turnItems.push({
653 - id: TurnItemId.make(id),
654 - threadId: targetId,
655 - runId: null,
656 - nodeId: null,
657 - providerThreadId: null,
658 - providerTurnId: null,
659 - nativeItemRef: null,
660 - parentItemId: null,
661 - ordinal: projection.turnItems.length,
662 - status: "running",
663 - title: null,
664 - startedAt: target.updatedAt,
665 - completedAt: null,
666 - updatedAt: target.updatedAt,
667 - type: "approval_request",
668 - requestId,
669 - requestKind: "command",
670 - prompt:
671 - id === "approve-client" ? `${"🙂".repeat(3999)}🚀hidden warning` : "Run the command?",
672 - ...(id === "approve-client" ? { appName: "Fixture app" } : {}),
673 - options,
674 - });
675 - }
676 - }
677 - const responses: Array<string> = [];
678 - let caller = McpToolAccessTestkit.liveThreadShell(threadId);
679 - return Effect.gen(function* () {
680 - const server = yield* McpServer.McpServer;
681 - const call = (
682 - name: string,
683 - args: Record<string, unknown> = {},
684 - invocation = clientScope("read-only"),
685 - ) =>
686 - server
687 - .callTool({ name, arguments: { threadId: targetId, ...args } })
688 - .pipe(
689 - Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
690 - Effect.provideService(McpSchema.McpServerClient, client),
691 - );
692 - expect((yield* call("t3_pending_request_list")).structuredContent).toEqual({
693 - requestIds: ["question"],
694 - requests: [
695 - { requestId: "approve", kind: "command" },
696 - { requestId: "approve-client", kind: "command" },
697 - { requestId: "decline", kind: "command" },
698 - { requestId: "cancel", kind: "command" },
699 - { requestId: "question", kind: "user_input" },
700 - ],
701 - });
702 - expect(
703 - (yield* call("t3_pending_request_read", { requestId: "approve" })).structuredContent,
704 - ).toEqual({ requestId: "approve", kind: "command", prompt: "Run the command?", options });
705 -
706 - const clipped = (yield* call("t3_pending_request_read", { requestId: "approve-client" }))
707 - .structuredContent;
708 - expect(clipped).toEqual({
709 - requestId: "approve-client",
710 - kind: "command",
711 - prompt: `${"🙂".repeat(3999)}🚀`,
712 - promptTruncated: true,
713 - appName: "Fixture app",
714 - options,
715 - });
716 -
717 - const respond = (
718 - requestId: string,
719 - decision: string,
720 - invocation: McpInvocationContext.McpInvocationScope,
721 - ) => call("t3_pending_request_respond", { requestId, decision }, invocation);
722 - expect(declaredFailure(yield* respond("approve", "accept", clientScope("auto")))).toMatchObject(
723 - {
724 - code: "capability_denied",
725 - },
726 - );
727 - expect(
728 - declaredFailure(yield* respond("decline", "decline", clientScope("read-only"))),
729 - ).toMatchObject({
730 - code: "capability_denied",
731 - });
732 - expect(
733 - declaredFailure(yield* respond("approve", "acceptForSession", clientScope("full-access"))),
734 - ).toMatchObject({
735 - code: "invalid_request",
736 - });
737 - caller = { ...caller, interactionMode: "plan" };
738 - target = { ...target, interactionMode: "plan" };
739 - expect(declaredFailure(yield* respond("approve", "accept", scope))).toMatchObject({
740 - code: "capability_denied",
741 - });
742 - target = { ...target, interactionMode: "default" };
743 - expect(responses).toEqual([]);
744 -
745 - expect((yield* respond("decline", "decline", clientScope("auto"))).isError).toBe(false);
746 - expect((yield* respond("cancel", "cancel", clientScope("auto"))).isError).toBe(false);
747 - caller = { ...caller, interactionMode: "default" };
748 - expect((yield* respond("approve", "accept", scope)).isError).toBe(false);
749 - expect((yield* respond("approve-client", "accept", clientScope("full-access"))).isError).toBe(
750 - false,
751 - );
752 - expect(responses).toEqual(["decline", "cancel", "accept", "accept"]);
753 - expect((yield* call("t3_pending_request_list")).structuredContent).toEqual({
754 - requestIds: ["question"],
755 - requests: [{ requestId: "question", kind: "user_input" }],
756 - });
757 - expect(
758 - declaredFailure(yield* call("t3_pending_request_read", { requestId: "approve" })),
759 - ).toMatchObject({
760 - code: "invalid_request",
761 - });
762 - expect(
763 - declaredFailure(yield* respond("approve", "accept", clientScope("full-access"))),
764 - ).toMatchObject({
765 - code: "invalid_request",
766 - });
767 - expect(responses).toHaveLength(4);
768 - }).pipe(
769 - Effect.provide(
770 - layerThreadToolkit.pipe(
771 - Layer.provideMerge(McpServer.McpServer.layer),
772 - Layer.provide(NodeCrypto.layer),
773 - Layer.provide(
774 - Layer.mock(ThreadManagement.ThreadManagementService)({
775 - getThreadShell: (id) => Effect.sync(() => (id === threadId ? caller : target)),
776 - getProjectThreadRecords: (_input, _fields, query) =>
777 - Effect.sync(() => ({
778 - ...projection,
779 - turnItems: projection.turnItems.filter((item) =>
780 - query?.turnItemTypes?.includes(item.type),
781 - ),
782 - })),
783 - dispatch: (command) =>
784 - Effect.sync(() => {
785 - if (command.type !== "runtime-request.respond" || command.decision === undefined)
786 - throw new Error("Expected an approval response");
787 - const request = projection.runtimeRequests.find(
788 - (request) => request.id === command.requestId,
789 - )!;
790 - projection.runtimeRequests = projection.runtimeRequests.map((candidate) =>
791 - candidate === request
792 - ? { ...candidate, status: "resolved", decision: command.decision }
793 - : candidate,
794 - );
795 - responses.push(command.decision);
796 - return { sequence: responses.length, storedEvents: [] };
797 - }),
798 - }),
799 - ),
800 - ),
801 - ),
802 - );
803 -});
804 -
622 it.effect("a read-only client reads threads and is refused every write before it runs", () =>
623 Effect.gen(function* () {
624 const server = yield* McpServer.McpServer;
apps/server/src/mcp/toolkits/orchestrator/tools.ts
+2 -2
@@ -65,7 +65,7 @@ const OrchestratorCapabilitiesTool = Tool.make("orchestrator_capabilities", {
65
66 export const DelegateTaskTool = Tool.make("delegate_task", {
67 description:
68 - "Needs an agent running inside a T3 thread. Delegate one task to a T3-owned child agent/subagent of THIS thread and run it with only the supplied task prompt, without copying parent conversation history. Choose providers and models from orchestrator_capabilities, which uses the same live catalog as the composer. Prefer native subagent tools for same-provider work only when they support the chosen model and no model options are requested or inherited. Use this for any model missing from the native tool, including same-provider work, for cross-provider work, or for explicitly T3-owned child tasks. For every T3 delegated review round, call delegate_task again with the original brief, prior findings, responses, and unresolved objections in the task prompt. Track each round by its own taskId and use a distinct clientRequestId per round, stable across retries of that round. The childThreadId is backing storage, not the target for starting another delegated review round through t3_thread_send. Set isolation to worktree for a separate checkout based on the parent local commit, with project setup completed before the child starts. Uncommitted edits are not copied; omitted isolation shares the parent checkout. Use delegate_task when model options are requested or the child keeps the parent's provider instance and model with nonempty inheritedOptions from orchestrator_capabilities, even for native-supported models. Native subagents cannot reliably apply T3 model options. Set target.options using advertised IDs: Claude {effort: 'max', fastMode: true}; Codex {reasoningEffort: 'max', serviceTier: 'priority'}. Check providerInstanceId, model, and options in the result. Provider/model and modes inherit unless overridden. Options inherit only for the same instance and model; explicit entries override individual values and [] or {} clears them. A requested runtimeMode must be one the target provider lists in orchestrator_capabilities runtimeModes; an inherited one steps down to the broadest mode it offers. Leave runtimeMode unset unless the user asks for a supervised child: approval-required and auto-accept-edits usually make the child wait for a person at each action that needs approval. Prefer mode='async' for long work; mode='wait' blocks until completion, a blocking question, a pending approval, or timeout. If hasPendingQuestion, pass threadId=childThreadId to t3_pending_request_list, t3_pending_request_read (with requestId) and t3_pending_request_respond, or ask the user; the task's completion still wakes this thread. If pendingApproval is set, read the fresh full request in childThreadId before responding: the record can outlive its provider callback. It grants no approval authority. Use t3_pending_request_read to read the fresh request and t3_pending_request_respond with decision to respond; accepting needs a full-access/default caller, while declining or cancelling does not. The child keeps running and its completion still wakes this thread. timeoutMs on mode=wait is only the parent's wait budget and does not cancel the child. waitTimedOut on that wait call means the timeout fired; keep that taskId and read status on later task_status. An async child's completion wakes this thread through a notification, steered into active turns where supported or queued otherwise, so end the turn instead of polling or spawning watchers; use task_status only when the result is needed mid-turn.",
68 + "Needs an agent running inside a T3 thread. Delegate one task to a T3-owned child agent/subagent of THIS thread and run it with only the supplied task prompt, without copying parent conversation history. Choose providers and models from orchestrator_capabilities, which uses the same live catalog as the composer. Prefer native subagent tools for same-provider work only when they support the chosen model and no model options are requested or inherited. Use this for any model missing from the native tool, including same-provider work, for cross-provider work, or for explicitly T3-owned child tasks. For every T3 delegated review round, call delegate_task again with the original brief, prior findings, responses, and unresolved objections in the task prompt. Track each round by its own taskId and use a distinct clientRequestId per round, stable across retries of that round. The childThreadId is backing storage, not the target for starting another delegated review round through t3_thread_send. Set isolation to worktree for a separate checkout based on the parent local commit, with project setup completed before the child starts. Uncommitted edits are not copied; omitted isolation shares the parent checkout. Use delegate_task when model options are requested or the child keeps the parent's provider instance and model with nonempty inheritedOptions from orchestrator_capabilities, even for native-supported models. Native subagents cannot reliably apply T3 model options. Set target.options using advertised IDs: Claude {effort: 'max', fastMode: true}; Codex {reasoningEffort: 'max', serviceTier: 'priority'}. Check providerInstanceId, model, and options in the result. Provider/model and modes inherit unless overridden. Options inherit only for the same instance and model; explicit entries override individual values and [] or {} clears them. A requested runtimeMode must be one the target provider lists in orchestrator_capabilities runtimeModes; an inherited one steps down to the broadest mode it offers. Leave runtimeMode unset unless the user asks for a supervised child: approval-required and auto-accept-edits usually make the child wait for a person at each action that needs approval. Prefer mode='async' for long work; mode='wait' blocks until completion, a blocking question, a pending approval, or timeout. If hasPendingQuestion, pass threadId=childThreadId to t3_pending_request_list, t3_pending_request_read (with requestId) and t3_pending_request_respond, or ask the user; the task's completion still wakes this thread. If pendingApproval is set, read the fresh full request in childThreadId before responding: the record can outlive its provider callback. It grants no approval authority; decisions remain with the child's existing approval holder, and pending request tools answer questions only. The child keeps running and its completion still wakes this thread. timeoutMs on mode=wait is only the parent's wait budget and does not cancel the child. waitTimedOut on that wait call means the timeout fired; keep that taskId and read status on later task_status. An async child's completion wakes this thread through a notification, steered into active turns where supported or queued otherwise, so end the turn instead of polling or spawning watchers; use task_status only when the result is needed mid-turn.",
69 parameters: OrchestratorMcpDelegateTaskInput,
70 success: OrchestratorMcpDelegateTaskResult,
71 failure: OrchestratorMcpFailure,
@@ -78,7 +78,7 @@ export const DelegateTaskTool = Tool.make("delegate_task", {
78
79 const TaskStatusTool = Tool.make("task_status", {
80 description:
81 - "Needs an agent running inside a T3 thread. Read a T3-owned delegated task created by this parent thread. childRunId identifies the original delegated run. workState distinguishes working, waiting_for_children, and result_available; a completed turn with live nested work is not a completed task. summary is the final task result, including provider errors on failure, and remains stable after publication. hasPendingChildRuns reports later queued or executing turns in the backing child thread, even after the task is terminal; it does not reopen the task, and task_cancel stops those turns too. Turns held in a stopped queue wait for the user and do not count. latestTerminal* provides later non-monitor turn results; latestTerminalSummary and latestTerminalResultContextTransferId are independently null when they exactly repeat summary and resultContextTransferId, respectively. pendingApproval identifies the oldest pending live approval for this task's own unfinished work. Read the fresh full request in childThreadId before responding: the record can outlive its provider callback and grants no approval authority. Use t3_pending_request_read to read the fresh request and t3_pending_request_respond with decision to respond; accepting needs a full-access/default caller, while declining or cancelling does not. Reading a terminal result acknowledges its automatic parent delivery.",
81 + "Needs an agent running inside a T3 thread. Read a T3-owned delegated task created by this parent thread. childRunId identifies the original delegated run. workState distinguishes working, waiting_for_children, and result_available; a completed turn with live nested work is not a completed task. summary is the final task result, including provider errors on failure, and remains stable after publication. hasPendingChildRuns reports later queued or executing turns in the backing child thread, even after the task is terminal; it does not reopen the task, and task_cancel stops those turns too. Turns held in a stopped queue wait for the user and do not count. latestTerminal* provides later non-monitor turn results; latestTerminalSummary and latestTerminalResultContextTransferId are independently null when they exactly repeat summary and resultContextTransferId, respectively. pendingApproval identifies the oldest pending live approval for this task's own unfinished work. Read the fresh full request in childThreadId before responding: the record can outlive its provider callback and grants no approval authority. Decisions remain with the child's existing approval holder. Reading a terminal result acknowledges its automatic parent delivery.",
82 parameters: OrchestratorMcpTaskStatusInput,
83 success: OrchestratorMcpDelegateTaskResult,
84 failure: OrchestratorMcpFailure,
apps/server/src/mcp/toolkits/thread/handlers.ts
+15 -86
@@ -6,19 +6,13 @@ import {
6 type RunId,
7 OrchestratorMcpFailure,
8 type OrchestrationV2Command,
9 - type ProviderApprovalDecision,
10 - ProviderRequestKind,
9 } from "@t3tools/contracts";
12 -import * as DateTime from "effect/DateTime";
10 import * as Effect from "effect/Effect";
14 -import * as Schema from "effect/Schema";
11 import { modelSelectionCommandType } from "@t3tools/shared/model";
12
13 import * as McpToolAccess from "../../McpToolAccess.ts";
14 import {
19 - assertFullAccess,
15 dispatchFailure,
21 - loadCaller,
16 newCommandId,
17 readCaller,
18 readThread,
@@ -55,36 +49,24 @@ const dispatch = Effect.fn("mcp.dispatchThreadCommand")(function* (
49 return { sequence: result.sequence };
50 });
51
58 -const isApprovalKind = Schema.is(ProviderRequestKind);
59 -const isPendingRequest = (request: OrchestrationV2ThreadProjection["runtimeRequests"][number]) =>
60 - request.status === "pending" && (request.kind === "user_input" || isApprovalKind(request.kind));
61 -const DEFAULT_APPROVAL_DECISIONS: ReadonlyArray<ProviderApprovalDecision> = [
62 - "cancel",
63 - "decline",
64 - "acceptForSession",
65 - "accept",
66 -];
67 -
68 -const readPendingRequest = Effect.fn("mcp.readPendingRequest")(function* (input: {
52 +const readQuestion = Effect.fn("mcp.readQuestion")(function* (input: {
53 threadId?: ThreadId | undefined;
54 requestId: RuntimeRequestId;
55 }) {
56 const context = yield* readThread(input.threadId, ["runtimeRequests", "turnItems"]);
57 const request = context.projection.runtimeRequests.find(
74 - (request) => request.id === input.requestId && isPendingRequest(request),
58 + (request) =>
59 + request.id === input.requestId &&
60 + request.kind === "user_input" &&
61 + request.status === "pending",
62 );
63 const item = context.projection.turnItems.find(
77 - (item) =>
78 - (item.type === "user_input_request" || item.type === "approval_request") &&
79 - item.requestId === input.requestId,
64 + (item) => item.type === "user_input_request" && item.requestId === input.requestId,
65 );
81 - if (
82 - request === undefined ||
83 - (request.kind === "user_input" && item?.type !== "user_input_request")
84 - )
66 + if (request === undefined || item?.type !== "user_input_request")
67 return yield* new OrchestratorMcpFailure({
68 code: "invalid_request",
87 - message: "The pending request was not found.",
69 + message: "The pending user-input request was not found.",
70 });
71 return { ...context, request, item };
72 });
@@ -218,75 +200,29 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, {
200 t3_pending_request_list: McpToolAccess.reads((input) =>
201 Effect.gen(function* () {
202 const { projection } = yield* readThread(input.threadId, ["runtimeRequests"]);
221 - const requests = projection.runtimeRequests
222 - .filter(isPendingRequest)
223 - .map((request) => ({ requestId: request.id, kind: request.kind }));
203 return {
225 - requestIds: requests
226 - .filter((request) => request.kind === "user_input")
227 - .map((request) => request.requestId),
228 - requests,
204 + requestIds: projection.runtimeRequests
205 + .filter((request) => request.kind === "user_input" && request.status === "pending")
206 + .map((request) => request.id),
207 };
208 }),
209 ),
210 t3_pending_request_read: McpToolAccess.reads((input) =>
211 Effect.gen(function* () {
234 - const { request, item } = yield* readPendingRequest(input);
235 - if (item?.type === "user_input_request")
236 - return { requestId: input.requestId, kind: request.kind, questions: item.questions };
237 - const approval = item?.type === "approval_request" ? item : undefined;
238 - const prompt = approval?.prompt === undefined ? undefined : Array.from(approval.prompt);
239 - return {
240 - requestId: input.requestId,
241 - kind: request.kind,
242 - ...(prompt === undefined ? {} : { prompt: prompt.slice(0, 4000).join("") }),
243 - ...(prompt !== undefined && prompt.length > 4000 ? { promptTruncated: true } : {}),
244 - ...(approval?.appName === undefined ? {} : { appName: approval.appName }),
245 - ...(approval?.options === undefined ? {} : { options: approval.options }),
246 - };
212 + const { item } = yield* readQuestion(input);
213 + return { requestId: input.requestId, questions: item.questions };
214 }),
215 ),
216 t3_pending_request_respond: writesThread((input) =>
217 Effect.gen(function* () {
251 - const { threads, projection, request, item } = yield* readPendingRequest(input);
252 - let response;
253 - if (request.kind === "user_input") {
254 - if (input.answers === undefined)
255 - return yield* new OrchestratorMcpFailure({
256 - code: "invalid_request",
257 - message: "User questions need answers.",
258 - });
259 - response = { answers: input.answers };
260 - } else {
261 - const decision = input.decision;
262 - if (decision === undefined)
263 - return yield* new OrchestratorMcpFailure({
264 - code: "invalid_request",
265 - message: "Approvals need a decision.",
266 - });
267 - const offered =
268 - item?.type === "approval_request"
269 - ? item.options?.map((option) => option.decision)
270 - : undefined;
271 - if (!(offered ?? DEFAULT_APPROVAL_DECISIONS).includes(decision))
272 - return yield* new OrchestratorMcpFailure({
273 - code: "invalid_request",
274 - message: "That decision was not offered for this approval.",
275 - });
276 - if (decision !== "decline" && decision !== "cancel")
277 - yield* assertFullAccess(
278 - yield* loadCaller(),
279 - "Approving needs a live full-access/default thread or a full-access client.",
280 - );
281 - response = { decision };
282 - }
218 + const { threads, projection } = yield* readQuestion(input);
219 const result = yield* threads
220 .dispatch({
221 type: "runtime-request.respond",
222 threadId: projection.thread.id,
223 commandId: yield* newCommandId(),
224 requestId: input.requestId,
289 - ...response,
225 + answers: input.answers,
226 })
227 .pipe(Effect.mapError(dispatchFailure));
228 return { sequence: result.sequence };
@@ -378,13 +314,6 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, {
314 case "mark_unread":
315 command = { ...common, type: "thread.mark-unread" };
316 break;
381 - case "mark_read":
382 - command = {
383 - ...common,
384 - type: "thread.visit",
385 - visitedAt: DateTime.formatIso(projection.thread.updatedAt),
386 - };
387 - break;
317 default:
318 command = { ...common, type: `thread.${input.action}` };
319 }
apps/server/src/mcp/toolkits/thread/tools.ts
+7 -26
@@ -11,9 +11,6 @@ import {
11 ProviderInteractionMode,
12 RuntimeRequestId,
13 ProviderUserInputAnswers,
14 - ProviderApprovalDecision,
15 - ProviderApprovalOption,
16 - OrchestrationV2RuntimeRequest,
14 IsoDateTime,
15 OrchestratorMcpFailure,
16 OrchestrationV2DispatchCommandResult,
@@ -33,7 +30,7 @@ import * as McpInvocationContext from "../../McpInvocationContext.ts";
30
31 const ThreadOrganizeTool = Tool.make("t3_thread_organize", {
32 description:
36 - "Pin, snooze, settle, archive, or mark a thread read or unread. Omit threadId for this thread. snooze requires snoozedUntil. Existing thread lifecycle rules apply. Settling this thread takes effect when your turn completes, returning settlesWhenTurnEnds=true; a turn that fails or is interrupted, or a queued message, leaves it active.",
33 + "Pin, snooze, settle, archive, or mark a thread unread. Omit threadId for this thread. snooze requires snoozedUntil. Existing thread lifecycle rules apply. Settling this thread takes effect when your turn completes, returning settlesWhenTurnEnds=true; a turn that fails or is interrupted, or a queued message, leaves it active.",
34 parameters: Schema.Struct({
35 threadId: Schema.optional(ThreadId),
36 action: Schema.Literals([
@@ -45,7 +42,6 @@ const ThreadOrganizeTool = Tool.make("t3_thread_organize", {
42 "unsettle",
43 "archive",
44 "unarchive",
48 - "mark_read",
45 "mark_unread",
46 ]),
47 snoozedUntil: Schema.optional(IsoDateTime),
@@ -148,34 +144,23 @@ const question = Schema.Struct({
144 initialAnswer: Schema.optional(Schema.String),
145 required: Schema.optional(Schema.Boolean),
146 });
151 -const pendingRequestKind = OrchestrationV2RuntimeRequest.fields.kind;
147 const pendingRequest = Schema.Struct({
148 requestId: RuntimeRequestId,
154 - kind: pendingRequestKind,
155 - questions: Schema.optional(Schema.Array(question)),
156 - prompt: Schema.optional(Schema.String),
157 - promptTruncated: Schema.optional(Schema.Boolean),
158 - appName: Schema.optional(Schema.String),
159 - options: Schema.optional(Schema.Array(ProviderApprovalOption)),
149 + questions: Schema.Array(question),
150 });
151 const PendingRequestListTool = Tool.make("t3_pending_request_list", {
152 ...commandTool,
153 description:
164 - "List pending user questions and approval requests in a thread. Omit threadId for this thread. requestIds holds only the questions.",
154 + "List pending user questions in a thread. Omit threadId for this thread. Approval requests are not included.",
155 parameters: Schema.Struct({ threadId: Schema.optional(ThreadId) }),
166 - success: Schema.Struct({
167 - requestIds: Schema.Array(RuntimeRequestId),
168 - requests: Schema.Array(
169 - Schema.Struct({ requestId: RuntimeRequestId, kind: pendingRequestKind }),
170 - ),
171 - }),
156 + success: Schema.Struct({ requestIds: Schema.Array(RuntimeRequestId) }),
157 })
158 .annotate(Tool.Readonly, true)
159 .annotate(Tool.Destructive, false);
160 const PendingRequestReadTool = Tool.make("t3_pending_request_read", {
161 ...commandTool,
162 description:
178 - "Read a pending user question or approval request. Respond with t3_pending_request_respond; existing live or message response handling is used.",
163 + "Read a pending user question. Answer with t3_pending_request_respond; existing live or message response handling is used.",
164 parameters: Schema.Struct(requestTarget),
165 success: pendingRequest,
166 })
@@ -184,12 +169,8 @@ const PendingRequestReadTool = Tool.make("t3_pending_request_read", {
169 const PendingRequestRespondTool = Tool.make("t3_pending_request_respond", {
170 ...commandTool,
171 description:
187 - "Respond to a pending request using the existing runtime response command: answers for a user question, decision for an approval (one of its offered options, else cancel, decline, acceptForSession, or accept). Approving needs a full-access/default caller; declining or cancelling does not.",
188 - parameters: Schema.Struct({
189 - ...requestTarget,
190 - answers: Schema.optional(ProviderUserInputAnswers),
191 - decision: Schema.optional(ProviderApprovalDecision),
192 - }),
172 + "Answer a pending user-input request using the existing runtime response command. This cannot approve a permission request.",
173 + parameters: Schema.Struct({ ...requestTarget, answers: ProviderUserInputAnswers }),
174 })
175 .annotate(Tool.Destructive, true)
176 .annotate(Tool.OpenWorld, true);
apps/server/src/mcp/toolkits/worktree/handlers.ts
-7
@@ -36,13 +36,6 @@ const handlers = {
36 .pipe(Effect.mapError(unavailable));
37 }),
38 ),
39 - t3_thread_diff: McpToolAccess.reads((input) =>
40 - Effect.gen(function* () {
41 - const scope = yield* McpInvocationContext.McpInvocationContext;
42 - const service = yield* WorktreeMcpService.WorktreeMcpService;
43 - return yield* service.getThreadDiff(scope, input);
44 - }),
45 - ),
39 t3_worktree_handoff: McpToolAccess.actsAsCaller((input) =>
40 Effect.gen(function* () {
41 const scope = yield* McpInvocationContext.McpInvocationContext;
apps/server/src/mcp/toolkits/worktree/registration.test.ts
+1 -182
@@ -5,11 +5,8 @@ import * as ServerConfig from "../../../config.ts";
5 import { expect, it } from "@effect/vitest";
6 import { NodeHttpServer } from "@effect/platform-node";
7 import * as NodeServices from "@effect/platform-node/NodeServices";
8 -import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
8 +import { ProviderInstanceId, ThreadId } from "@t3tools/contracts";
9 import * as Effect from "effect/Effect";
10 -import * as FileSystem from "effect/FileSystem";
11 -import * as Option from "effect/Option";
12 -import * as Stream from "effect/Stream";
10 import * as Layer from "effect/Layer";
11 import * as Schema from "effect/Schema";
12 import { HttpBody, HttpClient, HttpRouter } from "effect/http";
@@ -21,7 +18,6 @@ import * as ThreadManagementService from "../../../orchestration-v2/ThreadManage
18 import * as ProjectService from "../../../project/ProjectService.ts";
19 import * as PullRequestReviewGuideService from "../../../pullRequest/PullRequestReviewGuideService.ts";
20 import * as ProjectSetupScriptRunner from "../../../project/ProjectSetupScriptRunner.ts";
24 -import * as ReviewService from "../../../review/ReviewService.ts";
21 import * as ProviderRegistry from "../../../provider/ProviderRegistry.ts";
22 import * as ScheduledTaskService from "../../../scheduledTasks/ScheduledTaskService.ts";
23 import * as SecretRequests from "../../../secrets/SecretRequests.ts";
@@ -38,17 +34,6 @@ import * as McpHttpServer from "../../McpHttpServer.ts";
34 import * as McpSessionRegistry from "../../McpSessionRegistry.ts";
35 import * as PreviewAutomationBroker from "../../PreviewAutomationBroker.ts";
36 import * as PreviewBrowser from "../../../preview/PreviewBrowser.ts";
41 -import * as ProjectStore from "../../../orchestration-v2/ProjectStore.ts";
42 -import * as SqlitePersistence from "../../../persistence/Sqlite.ts";
43 -import * as VcsProcess from "../../../vcs/VcsProcess.ts";
44 -import * as VcsDriverRegistry from "../../../vcs/VcsDriverRegistry.ts";
45 -import * as KnownWorkspaces from "../../../workspace/KnownWorkspaces.ts";
46 -import * as McpInvocationContext from "../../McpInvocationContext.ts";
47 -import * as McpToolAccess from "../../McpToolAccess.ts";
48 -import * as McpToolAccessTestkit from "../../McpToolAccess.testkit.ts";
49 -import * as WorktreeMcpService from "../../WorktreeMcpService.ts";
50 -import * as WorktreeHandlers from "./handlers.ts";
51 -import { WorktreeToolkit } from "./tools.ts";
37
38 const layerStubServices = Layer.mergeAll(
39 Layer.mock(Orchestrator.OrchestratorV2)({}),
@@ -65,7 +50,6 @@ const layerStubServices = Layer.mergeAll(
50 Layer.mock(GitWorkflowService.GitWorkflowService)({}),
51 Layer.mock(ProjectSetupScriptRunner.ProjectSetupScriptRunner)({}),
52 Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({}),
68 - Layer.mock(ReviewService.ReviewService)({}),
53 Layer.mock(GitVcsDriver.GitVcsDriver)({}),
54 Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/unused" }),
55 Layer.mock(PreviewManager.PreviewManager)({}),
@@ -185,168 +169,3 @@ it.effect("production mcp layer lists worktree tools over http", () =>
169 ),
170 ),
171 );
188 -
189 -it.effect("reads another thread checkout with selected and bounded diff sources", () =>
190 - Effect.gen(function* () {
191 - const fs = yield* FileSystem.FileSystem;
192 - const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-mcp-diff-" });
193 - const serverCwd = `${root}/server`;
194 - const cwd = `${root}/project`;
195 - const checkout = `${cwd}/checkout`;
196 - yield* fs.makeDirectory(serverCwd);
197 - yield* fs.makeDirectory(cwd);
198 - const targetId = ThreadId.make("thread:diff-target");
199 - const shell = {
200 - ...McpToolAccessTestkit.liveThreadShell(targetId),
201 - projectId: ProjectId.make("project:diff"),
202 - worktreePath: checkout,
203 - };
204 - const config = ServerConfig.layerTest(serverCwd, `${root}/state`);
205 - const gitLayer = GitVcsDriver.layer.pipe(
206 - Layer.provide(config),
207 - Layer.provide(NodeServices.layer),
208 - );
209 - const dependencies = Layer.mergeAll(
210 - ReviewService.layer.pipe(
211 - Layer.provide(KnownWorkspaces.layer),
212 - Layer.provide(VcsDriverRegistry.layer),
213 - Layer.provide(VcsProcess.layer),
214 - Layer.provide(gitLayer),
215 - Layer.provide(config),
216 - Layer.provide(ServerSettings.layerTest()),
217 - Layer.provide(SqlitePersistence.layerMemory),
218 - Layer.provide(
219 - Layer.mock(ProjectStore.ProjectStoreV2)({
220 - listShells: () =>
221 - Effect.succeed([
222 - {
223 - id: shell.projectId,
224 - title: "Diff",
225 - workspaceRoot: cwd,
226 - defaultModelSelection: null,
227 - scripts: [],
228 - createdAt: "2026-01-01T00:00:00.000Z",
229 - updatedAt: "2026-01-01T00:00:00.000Z",
230 - },
231 - ]),
232 - }),
233 - ),
234 - Layer.provide(NodeServices.layer),
235 - ),
236 - Layer.mock(ThreadManagementService.ThreadManagementService)({
237 - getThreadShell: (id) =>
238 - Effect.succeed(id === targetId ? shell : McpToolAccessTestkit.liveThreadShell(id)),
239 - getProjectThreadRecords: () =>
240 - Effect.succeed(McpToolAccessTestkit.idleThreadProjection(shell)),
241 - }),
242 - Layer.mock(ProjectService.ProjectService)({
243 - getById: () =>
244 - Effect.succeed(
245 - Option.some({
246 - id: shell.projectId,
247 - title: "Diff",
248 - workspaceRoot: cwd,
249 - deletedAt: null,
250 - defaultModelSelection: null,
251 - scripts: [],
252 - createdAt: "2026-01-01T00:00:00.000Z",
253 - updatedAt: "2026-01-01T00:00:00.000Z",
254 - }),
255 - ),
256 - }),
257 - Layer.mock(GitWorkflowService.GitWorkflowService)({}),
258 - Layer.mock(ProjectSetupScriptRunner.ProjectSetupScriptRunner)({}),
259 - Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({}),
260 - ServerSettings.layerTest(),
261 - Layer.succeed(McpInvocationContext.McpInvocationContext, {
262 - environmentId: EnvironmentId.make("environment:diff"),
263 - requestNamespace: "diff-session",
264 - thread: {
265 - threadId: ThreadId.make("thread:diff-caller"),
266 - providerSessionId: "diff-session",
267 - providerInstanceId: ProviderInstanceId.make("codex"),
268 - },
269 - client: undefined,
270 - issuedAt: 0,
271 - capabilities: new Set(["orchestration" as const, "worktree" as const]),
272 - }),
273 - );
274 - const git = yield* GitVcsDriver.GitVcsDriver.pipe(Effect.provide(gitLayer));
275 - const run = (at: string, args: ReadonlyArray<string>) =>
276 - git.execute({ cwd: at, args, operation: "mcp-diff-test" });
277 - yield* run(cwd, ["init", "-b", "main"]);
278 - yield* run(cwd, ["config", "user.name", "Test"]);
279 - yield* run(cwd, ["config", "user.email", "test@example.com"]);
280 - yield* fs.writeFileString(`${cwd}/file.txt`, "original\n");
281 - yield* run(cwd, ["add", "file.txt"]);
282 - yield* run(cwd, ["commit", "-m", "base"]);
283 - yield* run(cwd, ["worktree", "add", "-b", "feature", checkout]);
284 - yield* fs.writeFileString(`${checkout}/file.txt`, "committed change\n");
285 - yield* run(checkout, ["commit", "-am", "feature"]);
286 - yield* fs.writeFileString(`${checkout}/file.txt`, "working change\n");
287 -
288 - yield* Effect.gen(function* () {
289 - const toolkit = yield* WorktreeToolkit;
290 - const read = (
291 - input: {
292 - source?: "working-tree" | "branch-range";
293 - baseRef?: string;
294 - maxCharacters?: number;
295 - } = {},
296 - ) =>
297 - toolkit.handle("t3_thread_diff", { threadId: targetId, baseRef: "main", ...input }).pipe(
298 - Stream.unwrap,
299 - Stream.runCollect,
300 - Effect.map((chunks) => chunks.at(-1)!.result),
301 - );
302 - const all = yield* read();
303 - expect(all).toMatchObject({ threadId: targetId, cwd: checkout });
304 - if (!("sources" in all)) throw new Error("Expected a diff result");
305 - expect(all.sources.map((source) => source.kind)).toEqual(["working-tree", "branch-range"]);
306 - const working = all.sources[0]!;
307 - const branch = all.sources[1]!;
308 - expect(working.diff).toContain("+working change");
309 - expect(working.diff).toContain("-committed change");
310 - expect(branch.diff).toContain("+working change");
311 - expect(branch.diff).toContain("-original");
312 - expect(branch.diff).not.toContain("-committed change");
313 - expect(working.files).toEqual([expect.objectContaining({ additions: 1, deletions: 1 })]);
314 - expect(working.truncated).toBe(false);
315 - expect(branch.truncated).toBe(false);
316 - expect(yield* read({ source: "working-tree" })).toEqual({ ...all, sources: [working] });
317 - expect(yield* read({ source: "working-tree", baseRef: "missing-base" })).toEqual({
318 - ...all,
319 - sources: [working],
320 - });
321 - expect(yield* read({ baseRef: "missing-base" })).toMatchObject({
322 - code: "invalid_request",
323 - message: "Could not find a common commit between 'missing-base' and HEAD.",
324 - });
325 - expect(yield* read({ source: "branch-range", baseRef: "missing-base" })).toMatchObject({
326 - code: "invalid_request",
327 - message: "Could not find a common commit between 'missing-base' and HEAD.",
328 - });
329 - expect(yield* read({ source: "branch-range" })).toEqual({ ...all, sources: [branch] });
330 - expect(yield* read({ source: "branch-range", maxCharacters: 24 })).toEqual({
331 - ...all,
332 - sources: [{ ...branch, diff: branch.diff.slice(0, 24), truncated: true }],
333 - });
334 - yield* Effect.forEach(
335 - Array.from({ length: 500 }, (_, index) => index),
336 - (index) => fs.writeFileString(`${checkout}/extra-${index}.txt`, "extra\n"),
337 - );
338 - const capped = yield* read({ source: "working-tree", maxCharacters: 100_000 });
339 - if (!("sources" in capped)) throw new Error("Expected a diff result");
340 - expect(capped.sources[0]!.files).toHaveLength(500);
341 - expect(capped.sources[0]!.diff.length).toBeLessThan(100_000);
342 - expect(capped.sources[0]!.truncated).toBe(true);
343 - }).pipe(
344 - Effect.provide(
345 - McpToolAccess.HandlersLayer.layer(WorktreeHandlers.layer).pipe(
346 - Layer.provideMerge(WorktreeMcpService.layer.pipe(Layer.provide(dependencies))),
347 - Layer.provideMerge(dependencies),
348 - ),
349 - ),
350 - );
351 - }).pipe(Effect.provide(NodeServices.layer)),
352 -);
apps/server/src/mcp/toolkits/worktree/tools.ts
-44
@@ -1,8 +1,4 @@
1 import {
2 - ReviewDiffFileStat,
3 - ReviewDiffPreviewSource,
4 - ReviewDiffPreviewSourceKind,
5 - TrimmedNonEmptyString,
2 WorktreeMcpFailure,
3 OrchestratorMcpFailure,
4 VcsListRefsInput,
@@ -85,48 +81,8 @@ const WorktreeListTool = Tool.make("t3_worktree_list", {
81 })
82 .annotate(Tool.Readonly, true)
83 .annotate(Tool.Destructive, false);
88 -
89 -const MAX_DIFF_CHARACTERS = 100_000;
90 -
91 -const ThreadDiffTool = Tool.make("t3_thread_diff", {
92 - description:
93 - "Show what a thread changed in its checkout (omit threadId for this thread), as the diff panel does. Returns working-tree (uncommitted changes vs HEAD) and branch-range (changes since the merge base with baseRef, or the detected base branch), each with stats for up to 500 files and a unified diff cut to maxCharacters (default 20,000), with truncated set when cut. Pass source to return one.",
94 - parameters: Schema.Struct({
95 - threadId: Schema.optional(ThreadId),
96 - baseRef: Schema.optional(TrimmedNonEmptyString),
97 - source: Schema.optional(ReviewDiffPreviewSourceKind),
98 - maxCharacters: Schema.optional(
99 - Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: MAX_DIFF_CHARACTERS })),
100 - ),
101 - }),
102 - success: Schema.Struct({
103 - threadId: ThreadId,
104 - cwd: Schema.String,
105 - sources: Schema.Array(
106 - Schema.Struct({
107 - kind: ReviewDiffPreviewSource.fields.kind,
108 - baseRef: ReviewDiffPreviewSource.fields.baseRef,
109 - headRef: ReviewDiffPreviewSource.fields.headRef,
110 - // Null when there were too many untracked files to count.
111 - files: Schema.NullOr(Schema.Array(ReviewDiffFileStat)),
112 - diff: Schema.String,
113 - truncated: Schema.Boolean,
114 - }),
115 - ),
116 - }),
117 - failure: OrchestratorMcpFailure,
118 - failureMode: "return",
119 - dependencies,
120 -})
121 - .annotate(Tool.Title, "Show thread diff")
122 - .annotate(Tool.Readonly, true)
123 - .annotate(Tool.Destructive, false)
124 - .annotate(Tool.Idempotent, true)
125 - .annotate(Tool.OpenWorld, false);
126 -
84 export const WorktreeToolkit = Toolkit.make(
85 WorktreeHandoffTool,
86 WorktreeStatusTool,
87 WorktreeListTool,
131 - ThreadDiffTool,
88 );
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
-1
@@ -1420,7 +1420,6 @@ export const CLAUDE_READ_ONLY_T3_MCP_ALLOWED_TOOLS: ReadonlyArray<string> = [
1420 "mcp__t3-code__t3_thread_transfers",
1421 "mcp__t3-code__t3_worktree_status",
1422 "mcp__t3-code__t3_worktree_list",
1423 - "mcp__t3-code__t3_thread_diff",
1423 "mcp__t3-code__t3_project_list",
1424 "mcp__t3-code__t3_project_read",
1425 "mcp__t3-code__t3_thread_search",
apps/server/src/vcs/GitVcsDriverCore.ts
+3 -7
@@ -3072,10 +3072,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3072 }
3073
3074 const cwd = repository.worktreeRoot;
3075 - const sourceKind = input.file?.sourceKind ?? input.sourceKind;
3076 - const dirtyRef = sourceKind === "branch-range" ? null : "HEAD";
3075 + const dirtyRef = input.file?.sourceKind === "branch-range" ? null : "HEAD";
3076 const review =
3078 - sourceKind === "working-tree"
3077 + input.file?.sourceKind === "working-tree"
3078 ? { baseRef: input.baseRef ?? null, mergeBase: null }
3079 : yield* resolveReviewMergeBase(cwd, repository.currentBranch, input.baseRef);
3080
@@ -3198,10 +3197,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3197 return {
3198 cwd: input.cwd,
3199 generatedAt: yield* DateTime.now,
3201 - sources:
3202 - input.file === undefined && sourceKind !== undefined
3203 - ? sources.filter((source) => source.kind === sourceKind)
3204 - : sources,
3200 + sources,
3201 };
3202 });
3203
docs/orchestration-v2/orchestrator-mcp-server.md
+3 -5
@@ -266,10 +266,8 @@ If `hasPendingQuestion`, pass `threadId=childThreadId` to `t3_pending_request_li
266 the user; the task's completion still wakes this thread. A pending live approval for the
267 task's own unfinished work also ends the wait. Its identity appears in `pendingApproval`;
268 it grants no approval authority. Read the fresh full request in the child thread before
269 -responding, since the durable record can outlive its provider callback. Read it with
270 -`t3_pending_request_read` and respond through `t3_pending_request_respond` using
271 -`decision`. Accepting requires a full-access/default caller; declining or cancelling
272 -does not. Async questions do not end the wait.
269 +responding, since the durable record can outlive its provider callback. Async questions
270 +do not end the wait.
271
272 ```ts
273 type DelegateTaskResult = {
@@ -476,7 +474,7 @@ a notification message telling it to answer with the pending request tools or
474 ask the user. The message says whether the child is blocked or, for a Codex
475 async question, still working. If the question is answered or dismissed before
476 the notification starts a turn, that queued turn is cancelled. Approvals are not
479 -routed to the parent automatically.
477 +routed, because those tools cannot answer them.
478 A parent still blocked in a `delegate_task` wait gets the blocking question
479 through that wait instead.
480 If the provider cuts that wait short, a still-pending live question wakes the
packages/client-runtime/src/t3ToolSummary.test.ts
+1 -1
@@ -67,7 +67,7 @@ describe("summarizeT3ToolCalls", () => {
67 completed({ requestId: "request-1" }),
68 completed({ requestId: "request-2" }),
69 ]).label,
70 - ).toBe("Responded to 2 pending requests");
70 + ).toBe("Answered 2 pending question requests");
71 });
72
73 it("counts attachments in distinct messages and falls back when attachment counts are missing", () => {
packages/client-runtime/src/t3ToolSummary.ts
+5 -5
@@ -273,20 +273,20 @@ export function summarizeT3ToolCalls(
273 );
274 break;
275 case "question-list":
276 - label = phrase("Listed", "list", `pending requests ${times}`);
276 + label = phrase("Listed", "list", `pending questions ${times}`);
277 break;
278 case "question-read":
279 label = phrase(
280 "Read",
281 "read",
282 - quantity(countEntities(entityIds("requestId")), "pending request"),
282 + quantity(countEntities(entityIds("requestId")), "pending question request"),
283 );
284 break;
285 case "question-respond":
286 label = phrase(
287 - "Responded to",
288 - "respond to",
289 - quantity(countEntities(entityIds("requestId")), "pending request"),
287 + "Answered",
288 + "answer",
289 + quantity(countEntities(entityIds("requestId")), "pending question request"),
290 );
291 break;
292 case "secret-request":
packages/client-runtime/src/work-log/presentation.test.ts
+1 -5
@@ -357,11 +357,7 @@ describe("resolveWorkEntryToolPresentation", () => {
357 ["t3_project_create", "Registering a project", "Registered a project"],
358 ["t3_thread_launch", "Launching a project thread", "Launched a project thread"],
359 ["t3_queue_edit", "Editing a queued message", "Edited a queued message"],
360 - [
361 - "t3_pending_request_respond",
362 - "Responding to pending requests",
363 - "Responded to pending requests",
364 - ],
360 + ["t3_pending_request_respond", "Answering pending questions", "Answered pending questions"],
361 ["t3_thread_configure", "Setting thread model", "Set thread model"],
362 ["t3_thread_fork", "Forking this thread", "Requested a fork of this thread"],
363 ["t3_thread_send_attachments", "Sending attachments", "Sent attachments"],
packages/contracts/src/orchestratorMcp.ts
+1 -1
@@ -225,7 +225,7 @@ export const OrchestratorMcpDelegateTaskResult = Schema.Struct({
225 Schema.Struct({ requestId: RuntimeRequestId, kind: ProviderRequestKind, runId: RunId }),
226 ).annotate({
227 description:
228 - "Identity of the oldest pending live approval for this task's own unfinished work, or null. Ends mode=wait without cancelling the child; completion still wakes this thread. This grants no approval authority. Read the fresh full request in childThreadId before responding: the record can outlive its provider callback. Use t3_pending_request_read to read the fresh request and t3_pending_request_respond with decision to respond; accepting needs a full-access/default caller, while declining or cancelling does not.",
228 + "Identity of the oldest pending live approval for this task's own unfinished work, or null. Ends mode=wait without cancelling the child; completion still wakes this thread. This grants no approval authority. Read the fresh full request in childThreadId before responding: the record can outlive its provider callback. Decisions remain with the child's existing approval holder; pending request tools answer questions only.",
229 }),
230 waitTimedOut: Schema.Boolean.annotate({
231 description:
packages/contracts/src/review.ts
+4 -5
@@ -3,24 +3,23 @@ import { TrimmedNonEmptyString } from "./baseSchemas.ts";
3 import { GitCommandError } from "./git.ts";
4 import { VcsError } from "./vcs.ts";
5
6 -export const ReviewDiffPreviewSourceKind = Schema.Literals(["working-tree", "branch-range"]);
7 -export type ReviewDiffPreviewSourceKind = typeof ReviewDiffPreviewSourceKind.Type;
8 -
6 export const ReviewDiffPreviewInput = Schema.Struct({
7 cwd: TrimmedNonEmptyString,
8 baseRef: Schema.optional(TrimmedNonEmptyString),
12 - sourceKind: Schema.optionalKey(ReviewDiffPreviewSourceKind),
9 ignoreWhitespace: Schema.optionalKey(Schema.Boolean),
10 file: Schema.optionalKey(
11 Schema.Struct({
12 path: Schema.NonEmptyString,
13 previousPath: Schema.NullOr(Schema.NonEmptyString),
18 - sourceKind: ReviewDiffPreviewSourceKind,
14 + sourceKind: Schema.Literals(["working-tree", "branch-range"]),
15 }),
16 ),
17 });
18 export type ReviewDiffPreviewInput = typeof ReviewDiffPreviewInput.Type;
19
20 +export const ReviewDiffPreviewSourceKind = Schema.Literals(["working-tree", "branch-range"]);
21 +export type ReviewDiffPreviewSourceKind = typeof ReviewDiffPreviewSourceKind.Type;
22 +
23 export const ReviewDiffFileStat = Schema.Struct({
24 path: Schema.String,
25 previousPath: Schema.NullOr(Schema.String),
packages/shared/src/t3McpToolPresentation.ts
+6 -4
@@ -279,13 +279,15 @@ const T3_MCP_TOOLS: Readonly<Record<string, T3McpToolDefinition>> = {
279 ["Steer with", "Steering with", "Requested steering with", "a queued message"],
280 "queue-steer",
281 ),
282 - t3_pending_request_list: tool(["List", "Listing", "Listed", "pending requests"], "question-list"),
283 - t3_pending_request_read: tool(["Read", "Reading", "Read", "pending requests"], "question-read"),
282 + t3_pending_request_list: tool(
283 + ["List", "Listing", "Listed", "pending questions"],
284 + "question-list",
285 + ),
286 + t3_pending_request_read: tool(["Read", "Reading", "Read", "pending questions"], "question-read"),
287 t3_pending_request_respond: tool(
285 - ["Respond to", "Responding to", "Responded to", "pending requests"],
288 + ["Answer", "Answering", "Answered", "pending questions"],
289 "question-respond",
290 ),
288 - t3_thread_diff: tool(["Read", "Reading", "Read", "a thread diff"], "thread-read"),
291 t3_thread_configuration: tool(
292 ["Read", "Reading", "Read", "thread configuration"],
293 "thread-configuration",