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 @@
1+import type { ProviderInteractionMode, RuntimeMode } from "@t3tools/contracts";
2+
3+function 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+
16+function interactionModeRank(mode: ProviderInteractionMode): number {
17+ return mode === "plan" ? 0 : 1;
18+}
19+
20+export function runtimeModeWithinMcpCeiling(
21+ callerMode: RuntimeMode,
22+ targetMode: RuntimeMode,
23+): boolean {
24+ return runtimeModeRank(targetMode) <= runtimeModeRank(callerMode);
25+}
26+
27+export 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
7272 } from "../orchestration-v2/ThreadManagementService.ts";
7373 import { ProviderRegistry } from "../provider/Services/ProviderRegistry.ts";
7474 import { ScheduledTaskService } from "../scheduledTasks/ScheduledTaskService.ts";
75+import { interactionModeWithinMcpCeiling, runtimeModeWithinMcpCeiling } from "./McpModeCeilings.ts";
7576 import type { McpInvocationScope } from "./McpInvocationContext.ts";
7677
7778 const DEFAULT_WAIT_TIMEOUT_MS = 10 * 60 * 1_000;
@@ -402,30 +403,12 @@ function canExposeTaskRunResult(run: OrchestrationV2Run | undefined): run is Orc · 324 unmodified lines
402403 run !== undefined && run.status !== "rolled_back" && isTerminalTaskStatus(taskStatusForRun(run))
403404 );
404405 }
405−
406−function 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−
419−function interactionModeRank(mode: ProviderInteractionMode): number {
420− return mode === "plan" ? 0 : 1;
421−}
422−
423406 function resolveRuntimeMode(
424407 parentMode: RuntimeMode,
425408 requested: OrchestratorMcpRuntimeMode | undefined,
426409 ): Effect.Effect<RuntimeMode, OrchestratorMcpFailure> {
427410 const resolved = requested === undefined || requested === "inherit" ? parentMode : requested;
428− return runtimeModeRank(resolved) > runtimeModeRank(parentMode)
411+ return !runtimeModeWithinMcpCeiling(parentMode, resolved)
429412 ? Effect.fail(
430413 failure(
431414 "runtime_mode_escalation_denied",
@@ -440,7 +423,7 @@ function resolveInteractionMode( · 8 unmodified lines
440423 requested: OrchestratorMcpInteractionMode | undefined,
441424 ): Effect.Effect<ProviderInteractionMode, OrchestratorMcpFailure> {
442425 const resolved = requested === undefined || requested === "inherit" ? parentMode : requested;
443− return interactionModeRank(resolved) > interactionModeRank(parentMode)
426+ return !interactionModeWithinMcpCeiling(parentMode, resolved)
444427 ? Effect.fail(
445428 failure(
446429 "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
10851085 const secondQueuedMessageId = MessageId.make(
10861086 "message:mcp-parent:queue-race:user-second",
10871087 );
1088− yield* orchestrator.dispatch({
1088+ const secondQueueReceipt = yield* orchestrator.dispatch({
10891089 type: "message.dispatch",
10901090 createdBy: "user",
10911091 creationSource: "web",
@@ -1097,17 +1097,16 @@ describe("orchestrator MCP toolkit", () => { · 5 unmodified lines
10971097 modelSelection: codexSelection,
10981098 dispatchMode: { type: "queue_after_active" },
10991099 });
1100− const twoUserRunsQueued = yield* waitForProjection(
1101− orchestrator,
1102− parentThreadId,
1103− (projection) =>
1104− projection.runs.filter(
1105− (run) =>
1106− run.status === "queued" &&
1107− (run.userMessageId === queuedUserMessageId ||
1108− run.userMessageId === secondQueuedMessageId),
1109− ).length === 2,
1110− );
1100+ expect(secondQueueReceipt.storedEvents.length).toBeGreaterThan(0);
1101+ const twoUserRunsQueued = yield* orchestrator.getThreadProjection(parentThreadId);
1102+ expect(
1103+ twoUserRunsQueued.runs.filter(
1104+ (run) =>
1105+ run.status === "queued" &&
1106+ (run.userMessageId === queuedUserMessageId ||
1107+ run.userMessageId === secondQueuedMessageId),
1108+ ),
1109+ ).toHaveLength(2);
11111110 const secondQueuedUserRun = twoUserRunsQueued.runs.find(
11121111 (run) => run.userMessageId === secondQueuedMessageId,
11131112 );
@@ -1175,7 +1174,8 @@ describe("orchestrator MCP toolkit", () => { · 61 unmodified lines
11751174
11761175 const queueEditInput = {
11771176 queuedRunId: queuedUserRun.id,
1178− text: "Edited queued user follow-up.",
1177+ text: "Edited queued user follow-up.\n",
1178+ attachmentIds: ["attachment-queue-race"],
11791179 clientRequestId: "queue-edit-race-user",
11801180 };
11811181 const queueEditCall = yield* invoke("t3_queue_edit", queueEditInput);
@@ -1185,22 +1185,40 @@ describe("orchestrator MCP toolkit", () => { · 3 unmodified lines
11851185 expect(queueEdit.attachments.map((attachment) => attachment.id)).toEqual([
11861186 "attachment-queue-race",
11871187 ]);
1188− const repeatedQueueEdit = yield* decodeQueueEditResult(
1189− (yield* invoke("t3_queue_edit", queueEditInput)).structuredContent,
1190− ).pipe(Effect.orDie);
1191− expect(repeatedQueueEdit.commandId).toBe(queueEdit.commandId);
1192− expect(repeatedQueueEdit.receiptSequence).toBe(queueEdit.receiptSequence);
1188+ expect(queueEdit.text).toBe("Edited queued user follow-up.\n");
1189+
1190+ const blankQueueEdit = yield* invoke("t3_queue_edit", {
1191+ queuedRunId: queuedUserRun.id,
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");
11931196
11941197 const clearQueueAttachments = yield* decodeQueueEditResult(
11951198 (yield* invoke("t3_queue_edit", {
11961199 queuedRunId: queuedUserRun.id,
1197− text: "Edited queued user follow-up.",
1200+ text: "Cleared queued user attachments.",
11981201 attachmentIds: [],
11991202 clientRequestId: "queue-edit-race-user-clear",
12001203 })).structuredContent,
12011204 ).pipe(Effect.orDie);
12021205 expect(clearQueueAttachments.attachments).toEqual([]);
12031206
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+
12041222 const reorderCall = yield* invoke("t3_queue_reorder", {
12051223 queuedRunId: secondQueuedUserRun.id,
12061224 beforeRunId: queuedUserRun.id,
apps/server/src/mcp/QueueMcpService.test.ts+270−0
@@ -0,0 +1,270 @@
1+import * as NodeServices from "@effect/platform-node/NodeServices";
2+import { assert, describe, it } from "@effect/vitest";
3+import {
4+ EnvironmentId,
5+ MessageId,
6+ ProjectId,
7+ ProviderInstanceId,
8+ RunId,
9+ ThreadId,
10+ type OrchestrationV2ThreadProjection,
11+} from "@t3tools/contracts";
12+import * as Effect from "effect/Effect";
13+import * as Layer from "effect/Layer";
14+import * as Option from "effect/Option";
15+import * as Ref from "effect/Ref";
16+
17+import { OrchestratorProjectionError } from "../orchestration-v2/Orchestrator.ts";
18+import { ProjectionStoreThreadNotFoundError } from "../orchestration-v2/ProjectionStore.ts";
19+import {
20+ ThreadManagementProjectionLoadError,
21+ ThreadManagementService,
22+ ThreadManagementThreadNotFoundError,
23+} from "../orchestration-v2/ThreadManagementService.ts";
24+import type { McpInvocationScope } from "./McpInvocationContext.ts";
25+import { layer, QueueMcpService } from "./QueueMcpService.ts";
26+
27+const projectId = ProjectId.make("project:queue-mcp-service");
28+const callerThreadId = ThreadId.make("thread:queue-mcp-caller");
29+const targetThreadId = ThreadId.make("thread:queue-mcp-target");
30+const queuedRunId = RunId.make("run:queue-mcp-target");
31+const queuedMessageId = MessageId.make("message:queue-mcp-target");
32+
33+const 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+
42+function 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+
82+function 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+
105+describe("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
2424 import * as DateTime from "effect/DateTime";
2525 import * as Effect from "effect/Effect";
2626 import * as Layer from "effect/Layer";
27+import * as Option from "effect/Option";
28+import * as Schema from "effect/Schema";
2729
2830 import { queuedRunsInDeliveryOrder } from "../orchestration-v2/QueuedRunOrder.ts";
29−import { ThreadManagementService } from "../orchestration-v2/ThreadManagementService.ts";
31+import {
32+ ThreadManagementService,
33+ ThreadManagementThreadNotFoundError,
34+} from "../orchestration-v2/ThreadManagementService.ts";
35+import { interactionModeWithinMcpCeiling, runtimeModeWithinMcpCeiling } from "./McpModeCeilings.ts";
3036 import type { McpInvocationScope } from "./McpInvocationContext.ts";
3137
3238 const DEFAULT_LIST_LIMIT = 50;
@@ -89,6 +95,27 @@ function dispatchFailure(error: unknown): QueueMcpFailure { · 56 unmodified lines
8995 : failure("orchestration_error", errorMessage(error));
9096 }
9197
98+const isThreadManagementThreadNotFound = Schema.is(ThreadManagementThreadNotFoundError);
99+
100+function 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+
92119 function truncate(text: string, maxChars: number) {
93120 return text.length <= maxChars
94121 ? { text, textTruncated: false as const }
@@ -210,7 +237,7 @@ const make = Effect.gen(function* () { · 115 unmodified lines
210237
211238 const loadProjection = (threadId: ThreadId) =>
212239 threadManagement.getThreadProjection(threadId).pipe(
213− Effect.mapError(() => failure("thread_not_found", `Thread '${threadId}' was not found.`)),
240+ Effect.mapError((error) => projectionFailure({ error, threadId })),
214241 Effect.filterOrFail(
215242 (projection) => projection.thread.deletedAt === null,
216243 () => failure("thread_not_found", `Thread '${threadId}' was not found.`),
@@ -222,19 +249,42 @@ const make = Effect.gen(function* () { · 5 unmodified lines
222249 yield* requireCapability(scope);
223250 const parent = yield* loadProjection(scope.threadId);
224251 const threadId = requestedThreadId ?? scope.threadId;
225− if (threadId === scope.threadId) return parent;
226− return yield* threadManagement
252+ if (threadId === scope.threadId) return { caller: parent, target: parent } as const;
253+ const target = yield* threadManagement
227254 .getProjectThread({ projectId: parent.thread.projectId, threadId })
228255 .pipe(
229− Effect.mapError(() =>
230− failure(
231− "thread_not_found",
232− `Thread '${threadId}' was not found in project '${parent.thread.projectId}'.`,
233− ),
256+ Effect.mapError((error) =>
257+ projectionFailure({ error, threadId, projectId: parent.thread.projectId }),
234258 ),
235259 );
260+ return { caller: parent, target } as const;
236261 });
237262
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+
238288 const commandId = (input: {
239289 readonly scope: McpInvocationScope;
240290 readonly clientRequestId: string | undefined;
@@ -259,7 +309,7 @@ const make = Effect.gen(function* () { · 18 unmodified lines
259309 return QueueMcpService.of({
260310 list: (scope, input) =>
261311 Effect.gen(function* () {
262− const projection = yield* loadScopedThread(scope, input.threadId);
312+ const { target: projection } = yield* loadScopedThread(scope, input.threadId);
263313 const ordered = queuedRunsInDeliveryOrder(projection);
264314 const cursor = input.cursor ?? 0;
265315 const limit = input.limit ?? DEFAULT_LIST_LIMIT;
@@ -295,7 +345,7 @@ const make = Effect.gen(function* () { · 29 unmodified lines
295345 }),
296346 read: (scope, input) =>
297347 Effect.gen(function* () {
298− const projection = yield* loadScopedThread(scope, input.threadId);
348+ const { target: projection } = yield* loadScopedThread(scope, input.threadId);
299349 const queued = yield* findQueuedRun(projection, input.queuedRunId);
300350 return queuedRunSummary({
301351 projection,
@@ -305,11 +355,34 @@ const make = Effect.gen(function* () { · 3 unmodified lines
305355 }),
306356 edit: (scope, input) =>
307357 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);
309360 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;
310383 const requestedAttachmentIds = input.attachmentIds;
311384 const attachments =
312− requestedAttachmentIds === undefined
385+ replayingAccepted || requestedAttachmentIds === undefined
313386 ? undefined
314387 : yield* Effect.gen(function* () {
315388 const uniqueIds = new Set(requestedAttachmentIds);
@@ -336,13 +409,6 @@ const make = Effect.gen(function* () { · 20 unmodified lines
336409 : Effect.succeed(attachment);
337410 });
338411 });
339− const id = yield* commandId({
340− scope,
341− clientRequestId: input.clientRequestId,
342− operation: "edit",
343− threadId: projection.thread.id,
344− queuedRunId: input.queuedRunId,
345− });
346412 const receipt = yield* threadManagement
347413 .dispatch({
348414 type: "queued-run.edit",
@@ -358,6 +424,12 @@ const make = Effect.gen(function* () { · 9 unmodified lines
358424 stored.event.type === "message.updated" &&
359425 stored.event.payload.id === queued.message.id,
360426 );
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+ }
361433 const resultMessage =
362434 editedMessage?.event.type === "message.updated"
363435 ? editedMessage.event.payload
@@ -374,7 +446,7 @@ const make = Effect.gen(function* () { · 10 unmodified lines
374446 }),
375447 reorder: (scope, input) =>
376448 Effect.gen(function* () {
377− const projection = yield* loadScopedThread(scope, input.threadId);
449+ const { target: projection } = yield* loadScopedThread(scope, input.threadId);
378450 const id = yield* commandId({
379451 scope,
380452 clientRequestId: input.clientRequestId,
@@ -401,7 +473,7 @@ const make = Effect.gen(function* () { · 20 unmodified lines
401473 }),
402474 cancel: (scope, input) =>
403475 Effect.gen(function* () {
404− const projection = yield* loadScopedThread(scope, input.threadId);
476+ const { target: projection } = yield* loadScopedThread(scope, input.threadId);
405477 const id = yield* commandId({
406478 scope,
407479 clientRequestId: input.clientRequestId,
@@ -427,7 +499,8 @@ const make = Effect.gen(function* () { · 19 unmodified lines
427499 }),
428500 promote: (scope, input) =>
429501 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);
431504 const id = yield* commandId({
432505 scope,
433506 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
4141
4242 import { CheckpointServiceV2 } from "./CheckpointService.ts";
4343 import { CommandPolicyV2 } from "./CommandPolicy.ts";
44−import { CommandReceiptStoreV2 } from "./CommandReceiptStore.ts";
44+import { CommandReceiptStoreV2, type CommandReceiptStoreV2Shape } from "./CommandReceiptStore.ts";
4545 import { ContextHandoffServiceV2 } from "./ContextHandoffService.ts";
4646 import { EventSinkV2 } from "./EventSink.ts";
4747 import type { OrchestrationEffectRequestV2, PendingOrchestrationEffectV2 } from "./EffectOutbox.ts";
@@ -181,6 +181,7 @@ export interface OrchestratorV2Shape { · 133 unmodified lines
181181 readonly dispatch: (
182182 command: OrchestrationV2Command,
183183 ) => Effect.Effect<OrchestratorV2DispatchResult, OrchestratorV2Error>;
184+ readonly getCommandReceipt: CommandReceiptStoreV2Shape["getByCommandId"];
184185 readonly getThreadProjection: (
185186 threadId: ThreadId,
186187 ) => Effect.Effect<OrchestrationV2ThreadProjection, OrchestratorV2Error>;
@@ -7335,6 +7336,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio · 7148 unmodified lines
73357336 return OrchestratorV2.of({
73367337 resumeQueuedRuns,
73377338 dispatch: dispatchWithReceipt,
7339+ getCommandReceipt: commandReceipts.getByCommandId,
73387340 getThreadProjection: (threadId) =>
73397341 projectionStore
73407342 .getThreadProjection(threadId)
@@ -7443,6 +7445,7 @@ export const layerUnavailable: Layer.Layer<OrchestratorV2> = Layer.succeed( · 102 unmodified lines
74437445 cause: "Orchestration V2 live runtime is not configured.",
74447446 }),
74457447 ),
7448+ getCommandReceipt: () => Effect.succeed(Option.none()),
74467449 getThreadProjection: (threadId) =>
74477450 Effect.fail(
74487451 new OrchestratorProjectionError({
apps/server/src/orchestration-v2/ThreadManagementService.ts+2−0
@@ -271,6 +271,7 @@ export interface ThreadManagementServiceShape { · 270 unmodified lines
271271 readonly dispatch: (
272272 command: OrchestrationV2Command,
273273 ) => Effect.Effect<OrchestratorV2DispatchResult, OrchestratorV2Error>;
274+ readonly getCommandReceipt: OrchestratorV2["Service"]["getCommandReceipt"];
274275 readonly getThreadProjection: (
275276 threadId: ThreadId,
276277 ) => Effect.Effect<OrchestrationV2ThreadProjection, OrchestratorV2Error>;
@@ -659,6 +660,7 @@ const make = Effect.gen(function* () { · 382 unmodified lines
659660 return ThreadManagementService.of({
660661 ensureLegacyTranscript,
661662 dispatch,
663+ getCommandReceipt: orchestrator.getCommandReceipt,
662664 getThreadProjection,
663665 getCheckpointContext,
664666 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
333333 `t3_queue_list` and `t3_queue_read` expose queued runs in their durable delivery
334334 order. Both default to the calling thread; an explicit thread ID is accepted
335335 only within the same project. List results are paginated before message detail
336−is shaped, and both tools bound returned message text. Attachment results are
336+is shaped; list previews are capped at 8,000 characters per message, while the
337+single-run read path supports the larger detail bound. Attachment results are
337338 metadata references, never file contents.
338339
339340 `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
348349 message through the existing provider steering policy. The target must still
349350 be an active, steerable run, and the provider's actual serialized steering path
350351 must accept the operation. Failed validation leaves the queued run intact.
352+Editing or promoting a different thread also applies the caller thread's
353+runtime and interaction-mode ceilings, matching `t3_thread_send`.
351354
352355 Every mutation accepts `clientRequestId`. Its command ID includes the provider
353356 session, 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
101101 message starts or is removed while you are editing, the edit ends: changed content moves into the
102102 composer when it is empty, and is discarded otherwise.
103103
104+Agents connected through T3 Code's built-in orchestration tools can inspect the same queue, edit
105+user-authored queued prompts and attachments, reorder or cancel queued work, and promote a queued
106+message into steering. These controls use the same project scope and permission ceiling as ordinary
107+thread messages. They cannot rewrite T3 Code's automatic completion deliveries or cancel an active
108+turn through a queue-only action.
109+
104110 ## Commands and skills
105111
106112 Type `/` for commands or `$` to add a skill from the selected environment and
packages/contracts/src/queueMcp.test.ts+21−0
@@ -0,0 +1,21 @@
1+import { describe, expect, it } from "@effect/vitest";
2+import * as Schema from "effect/Schema";
3+
4+import { QueueMcpEditInput, QueueMcpListInput } from "./queueMcp.ts";
5+
6+const decodeEdit = Schema.decodeUnknownSync(QueueMcpEditInput);
7+const decodeList = Schema.decodeUnknownSync(QueueMcpListInput);
8+
9+describe("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
2323 const QueueMcpCursor = NonNegativeInt;
2424 const QueueMcpLimit = PositiveInt.check(Schema.isLessThanOrEqualTo(100));
2525 const QueueMcpMaxChars = PositiveInt.check(Schema.isLessThanOrEqualTo(120_000));
26+const QueueMcpListMaxChars = PositiveInt.check(Schema.isLessThanOrEqualTo(8_000));
2627
2728 const QueueMcpThreadTarget = {
2829 threadId: Schema.optional(
@@ -36,7 +37,7 @@ export const QueueMcpListInput = Schema.Struct({ · 7 unmodified lines
3637 ...QueueMcpThreadTarget,
3738 cursor: Schema.optional(QueueMcpCursor),
3839 limit: Schema.optional(QueueMcpLimit),
39− maxCharsPerMessage: Schema.optional(QueueMcpMaxChars),
40+ maxCharsPerMessage: Schema.optional(QueueMcpListMaxChars),
4041 });
4142 export type QueueMcpListInput = typeof QueueMcpListInput.Type;
4243
@@ -51,8 +52,7 @@ export const QueueMcpEditInput = Schema.Struct({ · 8 unmodified lines
5152 ...QueueMcpThreadTarget,
5253 queuedRunId: RunId,
5354 text: Schema.String.check(
54− Schema.isTrimmed(),
55− Schema.isNonEmpty(),
55+ Schema.makeFilter((text) => text.trim().length > 0 || "Queued text must not be blank."),
5656 Schema.isMaxLength(PROVIDER_SEND_TURN_MAX_INPUT_CHARS),
5757 ),
5858 attachmentIds: Schema.optional(
@@ -166,6 +166,8 @@ export class QueueMcpFailure extends Schema.TaggedErrorClass<QueueMcpFailure>()( · 107 unmodified lines
166166 "queued_run_not_found",
167167 "attachment_not_found",
168168 "invalid_request",
169+ "runtime_mode_escalation_denied",
170+ "interaction_mode_escalation_denied",
169171 "operation_rejected",
170172 "orchestration_error",
171173 ]),
packages/shared/src/t3McpToolPresentation.ts+6−0
@@ -52,6 +52,12 @@ const T3_MCP_TOOLS: Record< · 51 unmodified lines
5252 t3_thread_send: { displayName: "Send to a T3 thread", summaryAction: "thread-send" },
5353 t3_thread_wait: { displayName: "Wait for a T3 thread", summaryAction: "thread-wait" },
5454 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" },
5561 t3_worktree_handoff: { displayName: "Hand off thread to a git worktree" },
5662 t3_worktree_status: { displayName: "Get thread worktree status" },
5763 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