History

fix(mcp): harden queued work controls

Julius Marminge committed 2 months ago

Commit 6ee072f1 parent bb37b6412 files · +486 −67Browse files

Unified · Split

12 files
  1. apps/server/src/mcp/McpModeCeilings.ts +32 −0
  2. apps/server/src/mcp/OrchestratorMcpService.ts +3 −20
  3. apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts +37 −19
  4. apps/server/src/mcp/QueueMcpService.test.ts +270 −0
  5. apps/server/src/mcp/QueueMcpService.ts +96 −23
  6. apps/server/src/orchestration-v2/Orchestrator.ts +4 −1
  7. apps/server/src/orchestration-v2/ThreadManagementService.ts +2 −0
  8. docs/orchestration-v2/orchestrator-mcp-server.md +4 −1
  9. docs/user/composer.md +6 −0
  10. packages/contracts/src/queueMcp.test.ts +21 −0
  11. packages/contracts/src/queueMcp.ts +5 −3
  12. packages/shared/src/t3McpToolPresentation.ts +6 −0
apps/server/src/mcp/McpModeCeilings.ts+32−0
@@ -0,0 +1,32 @@
1import type { ProviderInteractionMode, RuntimeMode } from "@t3tools/contracts";
2
3function runtimeModeRank(mode: RuntimeMode): number {
4 switch (mode) {
5 case "approval-required":
6 return 0;
7 case "auto-accept-edits":
8 return 1;
9 case "auto":
10 return 2;
11 case "full-access":
12 return 3;
13 }
14}
15
16function interactionModeRank(mode: ProviderInteractionMode): number {
17 return mode === "plan" ? 0 : 1;
18}
19
20export function runtimeModeWithinMcpCeiling(
21 callerMode: RuntimeMode,
22 targetMode: RuntimeMode,
23): boolean {
24 return runtimeModeRank(targetMode) <= runtimeModeRank(callerMode);
25}
26
27export function interactionModeWithinMcpCeiling(
28 callerMode: ProviderInteractionMode,
29 targetMode: ProviderInteractionMode,
30): boolean {
31 return interactionModeRank(targetMode) <= interactionModeRank(callerMode);
32}
apps/server/src/mcp/OrchestratorMcpService.ts+3−20
@@ -72,6 +72,7 @@ import { · 71 unmodified lines
72} from "../orchestration-v2/ThreadManagementService.ts";72} from "../orchestration-v2/ThreadManagementService.ts";
73import { ProviderRegistry } from "../provider/Services/ProviderRegistry.ts";73import { ProviderRegistry } from "../provider/Services/ProviderRegistry.ts";
74import { ScheduledTaskService } from "../scheduledTasks/ScheduledTaskService.ts";74import { ScheduledTaskService } from "../scheduledTasks/ScheduledTaskService.ts";
75import { interactionModeWithinMcpCeiling, runtimeModeWithinMcpCeiling } from "./McpModeCeilings.ts";
75import type { McpInvocationScope } from "./McpInvocationContext.ts";76import type { McpInvocationScope } from "./McpInvocationContext.ts";
76 77
77const DEFAULT_WAIT_TIMEOUT_MS = 10 * 60 * 1_000;78const DEFAULT_WAIT_TIMEOUT_MS = 10 * 60 * 1_000;
@@ -402,30 +403,12 @@ function canExposeTaskRunResult(run: OrchestrationV2Run | undefined): run is Orc · 324 unmodified lines
402 run !== undefined && run.status !== "rolled_back" && isTerminalTaskStatus(taskStatusForRun(run))403 run !== undefined && run.status !== "rolled_back" && isTerminalTaskStatus(taskStatusForRun(run))
403 );404 );
404}405}
405
406function runtimeModeRank(mode: RuntimeMode): number {
407 switch (mode) {
408 case "approval-required":
409 return 0;
410 case "auto-accept-edits":
411 return 1;
412 case "auto":
413 return 2;
414 case "full-access":
415 return 3;
416 }
417}
418
419function interactionModeRank(mode: ProviderInteractionMode): number {
420 return mode === "plan" ? 0 : 1;
421}
422
423function resolveRuntimeMode(406function resolveRuntimeMode(
424 parentMode: RuntimeMode,407 parentMode: RuntimeMode,
425 requested: OrchestratorMcpRuntimeMode | undefined,408 requested: OrchestratorMcpRuntimeMode | undefined,
426): Effect.Effect<RuntimeMode, OrchestratorMcpFailure> {409): Effect.Effect<RuntimeMode, OrchestratorMcpFailure> {
427 const resolved = requested === undefined || requested === "inherit" ? parentMode : requested;410 const resolved = requested === undefined || requested === "inherit" ? parentMode : requested;
428 return runtimeModeRank(resolved) > runtimeModeRank(parentMode)411 return !runtimeModeWithinMcpCeiling(parentMode, resolved)
429 ? Effect.fail(412 ? Effect.fail(
430 failure(413 failure(
431 "runtime_mode_escalation_denied",414 "runtime_mode_escalation_denied",
@@ -440,7 +423,7 @@ function resolveInteractionMode( · 8 unmodified lines
440 requested: OrchestratorMcpInteractionMode | undefined,423 requested: OrchestratorMcpInteractionMode | undefined,
441): Effect.Effect<ProviderInteractionMode, OrchestratorMcpFailure> {424): Effect.Effect<ProviderInteractionMode, OrchestratorMcpFailure> {
442 const resolved = requested === undefined || requested === "inherit" ? parentMode : requested;425 const resolved = requested === undefined || requested === "inherit" ? parentMode : requested;
443 return interactionModeRank(resolved) > interactionModeRank(parentMode)426 return !interactionModeWithinMcpCeiling(parentMode, resolved)
444 ? Effect.fail(427 ? Effect.fail(
445 failure(428 failure(
446 "interaction_mode_escalation_denied",429 "interaction_mode_escalation_denied",
apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts+37−19
@@ -1085,7 +1085,7 @@ describe("orchestrator MCP toolkit", () => { · 1084 unmodified lines
1085 const secondQueuedMessageId = MessageId.make(1085 const secondQueuedMessageId = MessageId.make(
1086 "message:mcp-parent:queue-race:user-second",1086 "message:mcp-parent:queue-race:user-second",
1087 );1087 );
1088 yield* orchestrator.dispatch({1088 const secondQueueReceipt = yield* orchestrator.dispatch({
1089 type: "message.dispatch",1089 type: "message.dispatch",
1090 createdBy: "user",1090 createdBy: "user",
1091 creationSource: "web",1091 creationSource: "web",
@@ -1097,17 +1097,16 @@ describe("orchestrator MCP toolkit", () => { · 5 unmodified lines
1097 modelSelection: codexSelection,1097 modelSelection: codexSelection,
1098 dispatchMode: { type: "queue_after_active" },1098 dispatchMode: { type: "queue_after_active" },
1099 });1099 });
1100 const twoUserRunsQueued = yield* waitForProjection(1100 expect(secondQueueReceipt.storedEvents.length).toBeGreaterThan(0);
1101 orchestrator,1101 const twoUserRunsQueued = yield* orchestrator.getThreadProjection(parentThreadId);
1102 parentThreadId,1102 expect(
1103 (projection) =>1103 twoUserRunsQueued.runs.filter(
1104 projection.runs.filter(1104 (run) =>
1105 (run) =>1105 run.status === "queued" &&
1106 run.status === "queued" &&1106 (run.userMessageId === queuedUserMessageId ||
1107 (run.userMessageId === queuedUserMessageId ||1107 run.userMessageId === secondQueuedMessageId),
1108 run.userMessageId === secondQueuedMessageId),1108 ),
1109 ).length === 2,1109 ).toHaveLength(2);
1110 );
1111 const secondQueuedUserRun = twoUserRunsQueued.runs.find(1110 const secondQueuedUserRun = twoUserRunsQueued.runs.find(
1112 (run) => run.userMessageId === secondQueuedMessageId,1111 (run) => run.userMessageId === secondQueuedMessageId,
1113 );1112 );
@@ -1175,7 +1174,8 @@ describe("orchestrator MCP toolkit", () => { · 61 unmodified lines
1175 1174
1176 const queueEditInput = {1175 const queueEditInput = {
1177 queuedRunId: queuedUserRun.id,1176 queuedRunId: queuedUserRun.id,
1178 text: "Edited queued user follow-up.",1177 text: "Edited queued user follow-up.\n",
1178 attachmentIds: ["attachment-queue-race"],
1179 clientRequestId: "queue-edit-race-user",1179 clientRequestId: "queue-edit-race-user",
1180 };1180 };
1181 const queueEditCall = yield* invoke("t3_queue_edit", queueEditInput);1181 const queueEditCall = yield* invoke("t3_queue_edit", queueEditInput);
@@ -1185,22 +1185,40 @@ describe("orchestrator MCP toolkit", () => { · 3 unmodified lines
1185 expect(queueEdit.attachments.map((attachment) => attachment.id)).toEqual([1185 expect(queueEdit.attachments.map((attachment) => attachment.id)).toEqual([
1186 "attachment-queue-race",1186 "attachment-queue-race",
1187 ]);1187 ]);
1188 const repeatedQueueEdit = yield* decodeQueueEditResult(1188 expect(queueEdit.text).toBe("Edited queued user follow-up.\n");
1189 (yield* invoke("t3_queue_edit", queueEditInput)).structuredContent,1189
1190 ).pipe(Effect.orDie);1190 const blankQueueEdit = yield* invoke("t3_queue_edit", {
1191 expect(repeatedQueueEdit.commandId).toBe(queueEdit.commandId);1191 queuedRunId: queuedUserRun.id,
1192 expect(repeatedQueueEdit.receiptSequence).toBe(queueEdit.receiptSequence);1192 text: " \n\t ",
1193 clientRequestId: "queue-edit-race-user-blank",
1194 }).pipe(Effect.flip);
1195 expect(String(blankQueueEdit)).toContain("Queued text must not be blank");
1193 1196
1194 const clearQueueAttachments = yield* decodeQueueEditResult(1197 const clearQueueAttachments = yield* decodeQueueEditResult(
1195 (yield* invoke("t3_queue_edit", {1198 (yield* invoke("t3_queue_edit", {
1196 queuedRunId: queuedUserRun.id,1199 queuedRunId: queuedUserRun.id,
1197 text: "Edited queued user follow-up.",1200 text: "Cleared queued user attachments.",
1198 attachmentIds: [],1201 attachmentIds: [],
1199 clientRequestId: "queue-edit-race-user-clear",1202 clientRequestId: "queue-edit-race-user-clear",
1200 })).structuredContent,1203 })).structuredContent,
1201 ).pipe(Effect.orDie);1204 ).pipe(Effect.orDie);
1202 expect(clearQueueAttachments.attachments).toEqual([]);1205 expect(clearQueueAttachments.attachments).toEqual([]);
1203 1206
1207 const repeatedQueueEdit = yield* decodeQueueEditResult(
1208 (yield* invoke("t3_queue_edit", queueEditInput)).structuredContent,
1209 ).pipe(Effect.orDie);
1210 expect(repeatedQueueEdit.commandId).toBe(queueEdit.commandId);
1211 expect(repeatedQueueEdit.receiptSequence).toBe(queueEdit.receiptSequence);
1212 expect(repeatedQueueEdit.text).toBe("Edited queued user follow-up.\n");
1213 expect(repeatedQueueEdit.attachments.map((attachment) => attachment.id)).toEqual([
1214 "attachment-queue-race",
1215 ]);
1216 expect(
1217 (yield* orchestrator.getThreadProjection(parentThreadId)).messages.find(
1218 (message) => message.id === queuedUserMessageId,
1219 )?.attachments,
1220 ).toEqual([]);
1221
1204 const reorderCall = yield* invoke("t3_queue_reorder", {1222 const reorderCall = yield* invoke("t3_queue_reorder", {
1205 queuedRunId: secondQueuedUserRun.id,1223 queuedRunId: secondQueuedUserRun.id,
1206 beforeRunId: queuedUserRun.id,1224 beforeRunId: queuedUserRun.id,
apps/server/src/mcp/QueueMcpService.test.ts+270−0
@@ -0,0 +1,270 @@
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, describe, it } from "@effect/vitest";
3import {
4 EnvironmentId,
5 MessageId,
6 ProjectId,
7 ProviderInstanceId,
8 RunId,
9 ThreadId,
10 type OrchestrationV2ThreadProjection,
11} from "@t3tools/contracts";
12import * as Effect from "effect/Effect";
13import * as Layer from "effect/Layer";
14import * as Option from "effect/Option";
15import * as Ref from "effect/Ref";
16
17import { OrchestratorProjectionError } from "../orchestration-v2/Orchestrator.ts";
18import { ProjectionStoreThreadNotFoundError } from "../orchestration-v2/ProjectionStore.ts";
19import {
20 ThreadManagementProjectionLoadError,
21 ThreadManagementService,
22 ThreadManagementThreadNotFoundError,
23} from "../orchestration-v2/ThreadManagementService.ts";
24import type { McpInvocationScope } from "./McpInvocationContext.ts";
25import { layer, QueueMcpService } from "./QueueMcpService.ts";
26
27const projectId = ProjectId.make("project:queue-mcp-service");
28const callerThreadId = ThreadId.make("thread:queue-mcp-caller");
29const targetThreadId = ThreadId.make("thread:queue-mcp-target");
30const queuedRunId = RunId.make("run:queue-mcp-target");
31const queuedMessageId = MessageId.make("message:queue-mcp-target");
32
33const scope: McpInvocationScope = {
34 environmentId: EnvironmentId.make("environment:queue-mcp-service"),
35 threadId: callerThreadId,
36 providerSessionId: "provider-session:queue-mcp-service",
37 providerInstanceId: ProviderInstanceId.make("codex"),
38 capabilities: new Set(["orchestration"]),
39 issuedAt: 1,
40};
41
42function projection(input: {
43 readonly threadId: ThreadId;
44 readonly runtimeMode: "approval-required" | "full-access";
45 readonly interactionMode: "plan" | "default";
46 readonly queued?: boolean;
47}): OrchestrationV2ThreadProjection {
48 return {
49 thread: {
50 id: input.threadId,
51 projectId,
52 runtimeMode: input.runtimeMode,
53 interactionMode: input.interactionMode,
54 deletedAt: null,
55 },
56 runs:
57 input.queued === true
58 ? [
59 {
60 id: queuedRunId,
61 ordinal: 1,
62 status: "queued",
63 queuePosition: 1,
64 userMessageId: queuedMessageId,
65 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-test" },
66 },
67 ]
68 : [],
69 messages:
70 input.queued === true
71 ? [
72 {
73 id: queuedMessageId,
74 text: "Queued text",
75 attachments: [],
76 },
77 ]
78 : [],
79 } as unknown as OrchestrationV2ThreadProjection;
80}
81
82function serviceLayer(input: {
83 readonly caller: OrchestrationV2ThreadProjection;
84 readonly target: OrchestrationV2ThreadProjection;
85 readonly dispatchCount: Ref.Ref<number>;
86}) {
87 return layer.pipe(
88 Layer.provide(
89 Layer.merge(
90 NodeServices.layer,
91 Layer.mock(ThreadManagementService)({
92 getThreadProjection: () => Effect.succeed(input.caller),
93 getProjectThread: () => Effect.succeed(input.target),
94 getCommandReceipt: () => Effect.succeed(Option.none()),
95 dispatch: () =>
96 Ref.update(input.dispatchCount, (count) => count + 1).pipe(
97 Effect.as({ sequence: 1, storedEvents: [] }),
98 ),
99 }),
100 ),
101 ),
102 );
103}
104
105describe("QueueMcpService", () => {
106 it.effect("applies the shared runtime and interaction ceilings to edit and promote", () =>
107 Effect.gen(function* () {
108 const dispatchCount = yield* Ref.make(0);
109 const caller = projection({
110 threadId: callerThreadId,
111 runtimeMode: "approval-required",
112 interactionMode: "plan",
113 });
114 const assertDenied = (target: OrchestrationV2ThreadProjection, expectedCode: string) =>
115 Effect.gen(function* () {
116 const service = yield* QueueMcpService;
117 const editError = yield* service
118 .edit(scope, {
119 threadId: targetThreadId,
120 queuedRunId,
121 text: "Edited text",
122 clientRequestId: `edit-${expectedCode}`,
123 })
124 .pipe(Effect.flip);
125 assert.equal(editError.code, expectedCode);
126 const promoteError = yield* service
127 .promote(scope, {
128 threadId: targetThreadId,
129 queuedRunId,
130 targetRunId: RunId.make("run:active-target"),
131 clientRequestId: `promote-${expectedCode}`,
132 })
133 .pipe(Effect.flip);
134 assert.equal(promoteError.code, expectedCode);
135 }).pipe(Effect.provide(serviceLayer({ caller, target, dispatchCount })));
136
137 yield* assertDenied(
138 projection({
139 threadId: targetThreadId,
140 runtimeMode: "full-access",
141 interactionMode: "plan",
142 queued: true,
143 }),
144 "runtime_mode_escalation_denied",
145 );
146 yield* assertDenied(
147 projection({
148 threadId: targetThreadId,
149 runtimeMode: "approval-required",
150 interactionMode: "default",
151 queued: true,
152 }),
153 "interaction_mode_escalation_denied",
154 );
155 assert.equal(yield* Ref.get(dispatchCount), 0);
156 }),
157 );
158
159 it.effect("allows edit and promote when the target stays within both ceilings", () =>
160 Effect.gen(function* () {
161 const dispatchCount = yield* Ref.make(0);
162 const caller = projection({
163 threadId: callerThreadId,
164 runtimeMode: "full-access",
165 interactionMode: "default",
166 });
167 const target = projection({
168 threadId: targetThreadId,
169 runtimeMode: "approval-required",
170 interactionMode: "plan",
171 queued: true,
172 });
173 yield* Effect.gen(function* () {
174 const service = yield* QueueMcpService;
175 yield* service.edit(scope, {
176 threadId: targetThreadId,
177 queuedRunId,
178 text: "Edited text",
179 clientRequestId: "edit-allowed",
180 });
181 yield* service.promote(scope, {
182 threadId: targetThreadId,
183 queuedRunId,
184 targetRunId: RunId.make("run:active-target"),
185 clientRequestId: "promote-allowed",
186 });
187 }).pipe(Effect.provide(serviceLayer({ caller, target, dispatchCount })));
188 assert.equal(yield* Ref.get(dispatchCount), 2);
189 }),
190 );
191
192 it.effect("distinguishes missing threads from projection failures", () =>
193 Effect.gen(function* () {
194 const caller = projection({
195 threadId: callerThreadId,
196 runtimeMode: "full-access",
197 interactionMode: "default",
198 });
199 const invokeListWith = (
200 getProjectThread: ThreadManagementService["Service"]["getProjectThread"],
201 ) =>
202 Effect.gen(function* () {
203 const service = yield* QueueMcpService;
204 return yield* service.list(scope, { threadId: targetThreadId }).pipe(Effect.flip);
205 }).pipe(
206 Effect.provide(
207 layer.pipe(
208 Layer.provide(
209 Layer.merge(
210 NodeServices.layer,
211 Layer.mock(ThreadManagementService)({
212 getThreadProjection: () => Effect.succeed(caller),
213 getProjectThread,
214 }),
215 ),
216 ),
217 ),
218 ),
219 );
220
221 const missing = yield* invokeListWith(() =>
222 Effect.fail(
223 new ThreadManagementThreadNotFoundError({ projectId, threadId: targetThreadId }),
224 ),
225 );
226 assert.equal(missing.code, "thread_not_found");
227 const broken = yield* invokeListWith(() =>
228 Effect.fail(
229 new ThreadManagementProjectionLoadError({
230 projectId,
231 threadId: targetThreadId,
232 cause: new Error("database unavailable"),
233 }),
234 ),
235 );
236 assert.equal(broken.code, "orchestration_error");
237 }),
238 );
239
240 it.effect("does not disguise caller projection failures as scoped not-found results", () =>
241 Effect.gen(function* () {
242 const invokeListWith = (cause: unknown) =>
243 Effect.gen(function* () {
244 const service = yield* QueueMcpService;
245 return yield* service.list(scope, {}).pipe(Effect.flip);
246 }).pipe(
247 Effect.provide(
248 layer.pipe(
249 Layer.provide(
250 Layer.merge(
251 NodeServices.layer,
252 Layer.mock(ThreadManagementService)({
253 getThreadProjection: () =>
254 Effect.fail(
255 new OrchestratorProjectionError({ threadId: callerThreadId, cause }),
256 ),
257 }),
258 ),
259 ),
260 ),
261 ),
262 );
263
264 const projectionFailure = yield* invokeListWith(
265 new ProjectionStoreThreadNotFoundError({ threadId: callerThreadId }),
266 );
267 assert.equal(projectionFailure.code, "orchestration_error");
268 }),
269 );
270});
apps/server/src/mcp/QueueMcpService.ts+96−23
@@ -24,9 +24,15 @@ import * as Crypto from "effect/Crypto"; · 23 unmodified lines
24import * as DateTime from "effect/DateTime";24import * as DateTime from "effect/DateTime";
25import * as Effect from "effect/Effect";25import * as Effect from "effect/Effect";
26import * as Layer from "effect/Layer";26import * as Layer from "effect/Layer";
27import * as Option from "effect/Option";
28import * as Schema from "effect/Schema";
27 29
28import { queuedRunsInDeliveryOrder } from "../orchestration-v2/QueuedRunOrder.ts";30import { queuedRunsInDeliveryOrder } from "../orchestration-v2/QueuedRunOrder.ts";
29import { ThreadManagementService } from "../orchestration-v2/ThreadManagementService.ts";31import {
32 ThreadManagementService,
33 ThreadManagementThreadNotFoundError,
34} from "../orchestration-v2/ThreadManagementService.ts";
35import { interactionModeWithinMcpCeiling, runtimeModeWithinMcpCeiling } from "./McpModeCeilings.ts";
30import type { McpInvocationScope } from "./McpInvocationContext.ts";36import type { McpInvocationScope } from "./McpInvocationContext.ts";
31 37
32const DEFAULT_LIST_LIMIT = 50;38const DEFAULT_LIST_LIMIT = 50;
@@ -89,6 +95,27 @@ function dispatchFailure(error: unknown): QueueMcpFailure { · 56 unmodified lines
89 : failure("orchestration_error", errorMessage(error));95 : failure("orchestration_error", errorMessage(error));
90}96}
91 97
98const isThreadManagementThreadNotFound = Schema.is(ThreadManagementThreadNotFoundError);
99
100function projectionFailure(input: {
101 readonly error: unknown;
102 readonly threadId: ThreadId;
103 readonly projectId?: string;
104}): QueueMcpFailure {
105 if (isThreadManagementThreadNotFound(input.error)) {
106 return failure(
107 "thread_not_found",
108 input.projectId === undefined
109 ? `Thread '${input.threadId}' was not found.`
110 : `Thread '${input.threadId}' was not found in project '${input.projectId}'.`,
111 );
112 }
113 return failure(
114 "orchestration_error",
115 `Unable to load thread '${input.threadId}': ${errorMessage(input.error)}`,
116 );
117}
118
92function truncate(text: string, maxChars: number) {119function truncate(text: string, maxChars: number) {
93 return text.length <= maxChars120 return text.length <= maxChars
94 ? { text, textTruncated: false as const }121 ? { text, textTruncated: false as const }
@@ -210,7 +237,7 @@ const make = Effect.gen(function* () { · 115 unmodified lines
210 237
211 const loadProjection = (threadId: ThreadId) =>238 const loadProjection = (threadId: ThreadId) =>
212 threadManagement.getThreadProjection(threadId).pipe(239 threadManagement.getThreadProjection(threadId).pipe(
213 Effect.mapError(() => failure("thread_not_found", `Thread '${threadId}' was not found.`)),240 Effect.mapError((error) => projectionFailure({ error, threadId })),
214 Effect.filterOrFail(241 Effect.filterOrFail(
215 (projection) => projection.thread.deletedAt === null,242 (projection) => projection.thread.deletedAt === null,
216 () => failure("thread_not_found", `Thread '${threadId}' was not found.`),243 () => failure("thread_not_found", `Thread '${threadId}' was not found.`),
@@ -222,19 +249,42 @@ const make = Effect.gen(function* () { · 5 unmodified lines
222 yield* requireCapability(scope);249 yield* requireCapability(scope);
223 const parent = yield* loadProjection(scope.threadId);250 const parent = yield* loadProjection(scope.threadId);
224 const threadId = requestedThreadId ?? scope.threadId;251 const threadId = requestedThreadId ?? scope.threadId;
225 if (threadId === scope.threadId) return parent;252 if (threadId === scope.threadId) return { caller: parent, target: parent } as const;
226 return yield* threadManagement253 const target = yield* threadManagement
227 .getProjectThread({ projectId: parent.thread.projectId, threadId })254 .getProjectThread({ projectId: parent.thread.projectId, threadId })
228 .pipe(255 .pipe(
229 Effect.mapError(() =>256 Effect.mapError((error) =>
230 failure(257 projectionFailure({ error, threadId, projectId: parent.thread.projectId }),
231 "thread_not_found",
232 `Thread '${threadId}' was not found in project '${parent.thread.projectId}'.`,
233 ),
234 ),258 ),
235 );259 );
260 return { caller: parent, target } as const;
236 });261 });
237 262
263 const requirePromptMutationCeiling = (
264 caller: OrchestrationV2ThreadProjection,
265 target: OrchestrationV2ThreadProjection,
266 ) => {
267 if (!runtimeModeWithinMcpCeiling(caller.thread.runtimeMode, target.thread.runtimeMode)) {
268 return Effect.fail(
269 failure(
270 "runtime_mode_escalation_denied",
271 `Target runtime mode ${target.thread.runtimeMode} is broader than caller mode ${caller.thread.runtimeMode}.`,
272 ),
273 );
274 }
275 return interactionModeWithinMcpCeiling(
276 caller.thread.interactionMode,
277 target.thread.interactionMode,
278 )
279 ? Effect.void
280 : Effect.fail(
281 failure(
282 "interaction_mode_escalation_denied",
283 `Target interaction mode ${target.thread.interactionMode} is broader than caller mode ${caller.thread.interactionMode}.`,
284 ),
285 );
286 };
287
238 const commandId = (input: {288 const commandId = (input: {
239 readonly scope: McpInvocationScope;289 readonly scope: McpInvocationScope;
240 readonly clientRequestId: string | undefined;290 readonly clientRequestId: string | undefined;
@@ -259,7 +309,7 @@ const make = Effect.gen(function* () { · 18 unmodified lines
259 return QueueMcpService.of({309 return QueueMcpService.of({
260 list: (scope, input) =>310 list: (scope, input) =>
261 Effect.gen(function* () {311 Effect.gen(function* () {
262 const projection = yield* loadScopedThread(scope, input.threadId);312 const { target: projection } = yield* loadScopedThread(scope, input.threadId);
263 const ordered = queuedRunsInDeliveryOrder(projection);313 const ordered = queuedRunsInDeliveryOrder(projection);
264 const cursor = input.cursor ?? 0;314 const cursor = input.cursor ?? 0;
265 const limit = input.limit ?? DEFAULT_LIST_LIMIT;315 const limit = input.limit ?? DEFAULT_LIST_LIMIT;
@@ -295,7 +345,7 @@ const make = Effect.gen(function* () { · 29 unmodified lines
295 }),345 }),
296 read: (scope, input) =>346 read: (scope, input) =>
297 Effect.gen(function* () {347 Effect.gen(function* () {
298 const projection = yield* loadScopedThread(scope, input.threadId);348 const { target: projection } = yield* loadScopedThread(scope, input.threadId);
299 const queued = yield* findQueuedRun(projection, input.queuedRunId);349 const queued = yield* findQueuedRun(projection, input.queuedRunId);
300 return queuedRunSummary({350 return queuedRunSummary({
301 projection,351 projection,
@@ -305,11 +355,34 @@ const make = Effect.gen(function* () { · 3 unmodified lines
305 }),355 }),
306 edit: (scope, input) =>356 edit: (scope, input) =>
307 Effect.gen(function* () {357 Effect.gen(function* () {
308 const projection = yield* loadScopedThread(scope, input.threadId);358 const { caller, target: projection } = yield* loadScopedThread(scope, input.threadId);
359 yield* requirePromptMutationCeiling(caller, projection);
309 const queued = yield* findRunMessage(projection, input.queuedRunId);360 const queued = yield* findRunMessage(projection, input.queuedRunId);
361 const id = yield* commandId({
362 scope,
363 clientRequestId: input.clientRequestId,
364 operation: "edit",
365 threadId: projection.thread.id,
366 queuedRunId: input.queuedRunId,
367 });
368 const existingReceipt = yield* threadManagement
369 .getCommandReceipt(id)
370 .pipe(
371 Effect.mapError((error) =>
372 failure(
373 "orchestration_error",
374 `Unable to inspect retry receipt '${id}': ${errorMessage(error)}`,
375 ),
376 ),
377 );
378 const replayingAccepted = Option.isSome(existingReceipt)
379 ? existingReceipt.value.status === "accepted" &&
380 existingReceipt.value.threadId === projection.thread.id &&
381 existingReceipt.value.commandType === "queued-run.edit"
382 : false;
310 const requestedAttachmentIds = input.attachmentIds;383 const requestedAttachmentIds = input.attachmentIds;
311 const attachments =384 const attachments =
312 requestedAttachmentIds === undefined385 replayingAccepted || requestedAttachmentIds === undefined
313 ? undefined386 ? undefined
314 : yield* Effect.gen(function* () {387 : yield* Effect.gen(function* () {
315 const uniqueIds = new Set(requestedAttachmentIds);388 const uniqueIds = new Set(requestedAttachmentIds);
@@ -336,13 +409,6 @@ const make = Effect.gen(function* () { · 20 unmodified lines
336 : Effect.succeed(attachment);409 : Effect.succeed(attachment);
337 });410 });
338 });411 });
339 const id = yield* commandId({
340 scope,
341 clientRequestId: input.clientRequestId,
342 operation: "edit",
343 threadId: projection.thread.id,
344 queuedRunId: input.queuedRunId,
345 });
346 const receipt = yield* threadManagement412 const receipt = yield* threadManagement
347 .dispatch({413 .dispatch({
348 type: "queued-run.edit",414 type: "queued-run.edit",
@@ -358,6 +424,12 @@ const make = Effect.gen(function* () { · 9 unmodified lines
358 stored.event.type === "message.updated" &&424 stored.event.type === "message.updated" &&
359 stored.event.payload.id === queued.message.id,425 stored.event.payload.id === queued.message.id,
360 );426 );
427 if (replayingAccepted && editedMessage?.event.type !== "message.updated") {
428 return yield* failure(
429 "orchestration_error",
430 `Accepted edit receipt '${id}' no longer exposes its durable message result.`,
431 );
432 }
361 const resultMessage =433 const resultMessage =
362 editedMessage?.event.type === "message.updated"434 editedMessage?.event.type === "message.updated"
363 ? editedMessage.event.payload435 ? editedMessage.event.payload
@@ -374,7 +446,7 @@ const make = Effect.gen(function* () { · 10 unmodified lines
374 }),446 }),
375 reorder: (scope, input) =>447 reorder: (scope, input) =>
376 Effect.gen(function* () {448 Effect.gen(function* () {
377 const projection = yield* loadScopedThread(scope, input.threadId);449 const { target: projection } = yield* loadScopedThread(scope, input.threadId);
378 const id = yield* commandId({450 const id = yield* commandId({
379 scope,451 scope,
380 clientRequestId: input.clientRequestId,452 clientRequestId: input.clientRequestId,
@@ -401,7 +473,7 @@ const make = Effect.gen(function* () { · 20 unmodified lines
401 }),473 }),
402 cancel: (scope, input) =>474 cancel: (scope, input) =>
403 Effect.gen(function* () {475 Effect.gen(function* () {
404 const projection = yield* loadScopedThread(scope, input.threadId);476 const { target: projection } = yield* loadScopedThread(scope, input.threadId);
405 const id = yield* commandId({477 const id = yield* commandId({
406 scope,478 scope,
407 clientRequestId: input.clientRequestId,479 clientRequestId: input.clientRequestId,
@@ -427,7 +499,8 @@ const make = Effect.gen(function* () { · 19 unmodified lines
427 }),499 }),
428 promote: (scope, input) =>500 promote: (scope, input) =>
429 Effect.gen(function* () {501 Effect.gen(function* () {
430 const projection = yield* loadScopedThread(scope, input.threadId);502 const { caller, target: projection } = yield* loadScopedThread(scope, input.threadId);
503 yield* requirePromptMutationCeiling(caller, projection);
431 const id = yield* commandId({504 const id = yield* commandId({
432 scope,505 scope,
433 clientRequestId: input.clientRequestId,506 clientRequestId: input.clientRequestId,
apps/server/src/orchestration-v2/Orchestrator.ts+4−1
@@ -41,7 +41,7 @@ import * as Stream from "effect/Stream"; · 40 unmodified lines
41 41
42import { CheckpointServiceV2 } from "./CheckpointService.ts";42import { CheckpointServiceV2 } from "./CheckpointService.ts";
43import { CommandPolicyV2 } from "./CommandPolicy.ts";43import { CommandPolicyV2 } from "./CommandPolicy.ts";
44import { CommandReceiptStoreV2 } from "./CommandReceiptStore.ts";44import { CommandReceiptStoreV2, type CommandReceiptStoreV2Shape } from "./CommandReceiptStore.ts";
45import { ContextHandoffServiceV2 } from "./ContextHandoffService.ts";45import { ContextHandoffServiceV2 } from "./ContextHandoffService.ts";
46import { EventSinkV2 } from "./EventSink.ts";46import { EventSinkV2 } from "./EventSink.ts";
47import type { OrchestrationEffectRequestV2, PendingOrchestrationEffectV2 } from "./EffectOutbox.ts";47import type { OrchestrationEffectRequestV2, PendingOrchestrationEffectV2 } from "./EffectOutbox.ts";
@@ -181,6 +181,7 @@ export interface OrchestratorV2Shape { · 133 unmodified lines
181 readonly dispatch: (181 readonly dispatch: (
182 command: OrchestrationV2Command,182 command: OrchestrationV2Command,
183 ) => Effect.Effect<OrchestratorV2DispatchResult, OrchestratorV2Error>;183 ) => Effect.Effect<OrchestratorV2DispatchResult, OrchestratorV2Error>;
184 readonly getCommandReceipt: CommandReceiptStoreV2Shape["getByCommandId"];
184 readonly getThreadProjection: (185 readonly getThreadProjection: (
185 threadId: ThreadId,186 threadId: ThreadId,
186 ) => Effect.Effect<OrchestrationV2ThreadProjection, OrchestratorV2Error>;187 ) => Effect.Effect<OrchestrationV2ThreadProjection, OrchestratorV2Error>;
@@ -7335,6 +7336,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio · 7148 unmodified lines
7335 return OrchestratorV2.of({7336 return OrchestratorV2.of({
7336 resumeQueuedRuns,7337 resumeQueuedRuns,
7337 dispatch: dispatchWithReceipt,7338 dispatch: dispatchWithReceipt,
7339 getCommandReceipt: commandReceipts.getByCommandId,
7338 getThreadProjection: (threadId) =>7340 getThreadProjection: (threadId) =>
7339 projectionStore7341 projectionStore
7340 .getThreadProjection(threadId)7342 .getThreadProjection(threadId)
@@ -7443,6 +7445,7 @@ export const layerUnavailable: Layer.Layer<OrchestratorV2> = Layer.succeed( · 102 unmodified lines
7443 cause: "Orchestration V2 live runtime is not configured.",7445 cause: "Orchestration V2 live runtime is not configured.",
7444 }),7446 }),
7445 ),7447 ),
7448 getCommandReceipt: () => Effect.succeed(Option.none()),
7446 getThreadProjection: (threadId) =>7449 getThreadProjection: (threadId) =>
7447 Effect.fail(7450 Effect.fail(
7448 new OrchestratorProjectionError({7451 new OrchestratorProjectionError({
apps/server/src/orchestration-v2/ThreadManagementService.ts+2−0
@@ -271,6 +271,7 @@ export interface ThreadManagementServiceShape { · 270 unmodified lines
271 readonly dispatch: (271 readonly dispatch: (
272 command: OrchestrationV2Command,272 command: OrchestrationV2Command,
273 ) => Effect.Effect<OrchestratorV2DispatchResult, OrchestratorV2Error>;273 ) => Effect.Effect<OrchestratorV2DispatchResult, OrchestratorV2Error>;
274 readonly getCommandReceipt: OrchestratorV2["Service"]["getCommandReceipt"];
274 readonly getThreadProjection: (275 readonly getThreadProjection: (
275 threadId: ThreadId,276 threadId: ThreadId,
276 ) => Effect.Effect<OrchestrationV2ThreadProjection, OrchestratorV2Error>;277 ) => Effect.Effect<OrchestrationV2ThreadProjection, OrchestratorV2Error>;
@@ -659,6 +660,7 @@ const make = Effect.gen(function* () { · 382 unmodified lines
659 return ThreadManagementService.of({660 return ThreadManagementService.of({
660 ensureLegacyTranscript,661 ensureLegacyTranscript,
661 dispatch,662 dispatch,
663 getCommandReceipt: orchestrator.getCommandReceipt,
662 getThreadProjection,664 getThreadProjection,
663 getCheckpointContext,665 getCheckpointContext,
664 getThreadSnapshot,666 getThreadSnapshot,
docs/orchestration-v2/orchestrator-mcp-server.md+4−1
@@ -333,7 +333,8 @@ returned unchanged, and a thread with no active provider turn returns · 332 unmodified lines
333`t3_queue_list` and `t3_queue_read` expose queued runs in their durable delivery333`t3_queue_list` and `t3_queue_read` expose queued runs in their durable delivery
334order. Both default to the calling thread; an explicit thread ID is accepted334order. Both default to the calling thread; an explicit thread ID is accepted
335only within the same project. List results are paginated before message detail335only within the same project. List results are paginated before message detail
336is shaped, and both tools bound returned message text. Attachment results are336is shaped; list previews are capped at 8,000 characters per message, while the
337single-run read path supports the larger detail bound. Attachment results are
337metadata references, never file contents.338metadata references, never file contents.
338 339
339`t3_queue_edit` replaces a queued message's text. Omitting `attachmentIds`340`t3_queue_edit` replaces a queued message's text. Omitting `attachmentIds`
@@ -348,6 +349,8 @@ an active-turn interrupt. `t3_queue_promote_to_steer` consumes a queued user · 8 unmodified lines
348message through the existing provider steering policy. The target must still349message through the existing provider steering policy. The target must still
349be an active, steerable run, and the provider's actual serialized steering path350be an active, steerable run, and the provider's actual serialized steering path
350must accept the operation. Failed validation leaves the queued run intact.351must accept the operation. Failed validation leaves the queued run intact.
352Editing or promoting a different thread also applies the caller thread's
353runtime and interaction-mode ceilings, matching `t3_thread_send`.
351 354
352Every mutation accepts `clientRequestId`. Its command ID includes the provider355Every mutation accepts `clientRequestId`. Its command ID includes the provider
353session, operation, thread, and queued run, so retries replay the same durable356session, operation, thread, and queued run, so retries replay the same durable
docs/user/composer.md+6−0
@@ -101,6 +101,12 @@ you had typed in the composer before starting the edit is restored afterwards. I · 100 unmodified lines
101message starts or is removed while you are editing, the edit ends: changed content moves into the101message starts or is removed while you are editing, the edit ends: changed content moves into the
102composer when it is empty, and is discarded otherwise.102composer when it is empty, and is discarded otherwise.
103 103
104Agents connected through T3 Code's built-in orchestration tools can inspect the same queue, edit
105user-authored queued prompts and attachments, reorder or cancel queued work, and promote a queued
106message into steering. These controls use the same project scope and permission ceiling as ordinary
107thread messages. They cannot rewrite T3 Code's automatic completion deliveries or cancel an active
108turn through a queue-only action.
109
104## Commands and skills110## Commands and skills
105 111
106Type `/` for commands or `$` to add a skill from the selected environment and112Type `/` for commands or `$` to add a skill from the selected environment and
packages/contracts/src/queueMcp.test.ts+21−0
@@ -0,0 +1,21 @@
1import { describe, expect, it } from "@effect/vitest";
2import * as Schema from "effect/Schema";
3
4import { QueueMcpEditInput, QueueMcpListInput } from "./queueMcp.ts";
5
6const decodeEdit = Schema.decodeUnknownSync(QueueMcpEditInput);
7const decodeList = Schema.decodeUnknownSync(QueueMcpListInput);
8
9describe("queue MCP contracts", () => {
10 it("preserves nonblank prompt whitespace and rejects blank edits", () => {
11 expect(decodeEdit({ queuedRunId: "run:queued", text: " keep indentation\n" }).text).toBe(
12 " keep indentation\n",
13 );
14 expect(() => decodeEdit({ queuedRunId: "run:queued", text: " \n\t " })).toThrow();
15 });
16
17 it("keeps list text pages compact while read remains the detailed path", () => {
18 expect(decodeList({ maxCharsPerMessage: 8_000 }).maxCharsPerMessage).toBe(8_000);
19 expect(() => decodeList({ maxCharsPerMessage: 8_001 })).toThrow();
20 });
21});
packages/contracts/src/queueMcp.ts+5−3
@@ -23,6 +23,7 @@ const QueueMcpClientRequestId = TrimmedNonEmptyString.check(Schema.isMaxLength(2 · 22 unmodified lines
23const QueueMcpCursor = NonNegativeInt;23const QueueMcpCursor = NonNegativeInt;
24const QueueMcpLimit = PositiveInt.check(Schema.isLessThanOrEqualTo(100));24const QueueMcpLimit = PositiveInt.check(Schema.isLessThanOrEqualTo(100));
25const QueueMcpMaxChars = PositiveInt.check(Schema.isLessThanOrEqualTo(120_000));25const QueueMcpMaxChars = PositiveInt.check(Schema.isLessThanOrEqualTo(120_000));
26const QueueMcpListMaxChars = PositiveInt.check(Schema.isLessThanOrEqualTo(8_000));
26 27
27const QueueMcpThreadTarget = {28const QueueMcpThreadTarget = {
28 threadId: Schema.optional(29 threadId: Schema.optional(
@@ -36,7 +37,7 @@ export const QueueMcpListInput = Schema.Struct({ · 7 unmodified lines
36 ...QueueMcpThreadTarget,37 ...QueueMcpThreadTarget,
37 cursor: Schema.optional(QueueMcpCursor),38 cursor: Schema.optional(QueueMcpCursor),
38 limit: Schema.optional(QueueMcpLimit),39 limit: Schema.optional(QueueMcpLimit),
39 maxCharsPerMessage: Schema.optional(QueueMcpMaxChars),40 maxCharsPerMessage: Schema.optional(QueueMcpListMaxChars),
40});41});
41export type QueueMcpListInput = typeof QueueMcpListInput.Type;42export type QueueMcpListInput = typeof QueueMcpListInput.Type;
42 43
@@ -51,8 +52,7 @@ export const QueueMcpEditInput = Schema.Struct({ · 8 unmodified lines
51 ...QueueMcpThreadTarget,52 ...QueueMcpThreadTarget,
52 queuedRunId: RunId,53 queuedRunId: RunId,
53 text: Schema.String.check(54 text: Schema.String.check(
54 Schema.isTrimmed(),55 Schema.makeFilter((text) => text.trim().length > 0 || "Queued text must not be blank."),
55 Schema.isNonEmpty(),
56 Schema.isMaxLength(PROVIDER_SEND_TURN_MAX_INPUT_CHARS),56 Schema.isMaxLength(PROVIDER_SEND_TURN_MAX_INPUT_CHARS),
57 ),57 ),
58 attachmentIds: Schema.optional(58 attachmentIds: Schema.optional(
@@ -166,6 +166,8 @@ export class QueueMcpFailure extends Schema.TaggedErrorClass<QueueMcpFailure>()( · 107 unmodified lines
166 "queued_run_not_found",166 "queued_run_not_found",
167 "attachment_not_found",167 "attachment_not_found",
168 "invalid_request",168 "invalid_request",
169 "runtime_mode_escalation_denied",
170 "interaction_mode_escalation_denied",
169 "operation_rejected",171 "operation_rejected",
170 "orchestration_error",172 "orchestration_error",
171 ]),173 ]),
packages/shared/src/t3McpToolPresentation.ts+6−0
@@ -52,6 +52,12 @@ const T3_MCP_TOOLS: Record< · 51 unmodified lines
52 t3_thread_send: { displayName: "Send to a T3 thread", summaryAction: "thread-send" },52 t3_thread_send: { displayName: "Send to a T3 thread", summaryAction: "thread-send" },
53 t3_thread_wait: { displayName: "Wait for a T3 thread", summaryAction: "thread-wait" },53 t3_thread_wait: { displayName: "Wait for a T3 thread", summaryAction: "thread-wait" },
54 t3_thread_interrupt: { displayName: "Interrupt a T3 thread", summaryAction: "thread-interrupt" },54 t3_thread_interrupt: { displayName: "Interrupt a T3 thread", summaryAction: "thread-interrupt" },
55 t3_queue_list: { displayName: "List queued T3 work" },
56 t3_queue_read: { displayName: "Read queued T3 work" },
57 t3_queue_edit: { displayName: "Edit queued T3 work" },
58 t3_queue_reorder: { displayName: "Reorder queued T3 work" },
59 t3_queue_cancel: { displayName: "Cancel queued T3 work" },
60 t3_queue_promote_to_steer: { displayName: "Promote queued T3 work to steer" },
55 t3_worktree_handoff: { displayName: "Hand off thread to a git worktree" },61 t3_worktree_handoff: { displayName: "Hand off thread to a git worktree" },
56 t3_worktree_status: { displayName: "Get thread worktree status" },62 t3_worktree_status: { displayName: "Get thread worktree status" },
57 preview_status: { displayName: "Get preview browser status" },63 preview_status: { displayName: "Get preview browser status" },

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t