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 21, 03:37 UTC
feat(server): a thread turn can return a typed result (#38874)
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
Julius Marminge committed
Nov 20, 2026 at 15:44 UTC
2770bf3c61c4d6b7bb1f5d3df74aacf54ac7a159
25 files changed
+938
-20
apps/server/src/cli/thread.ts
+48
-4
@@ -528,6 +528,7 @@ type WaitOutcome =
528
readonly type: "ended";
529
readonly runId: RunId | null;
530
readonly status: OrchestratorMcpThreadStatus;
531
+ readonly output?: Schema.Json;
532
}
533
| { readonly type: "needs_input" };
534
@@ -598,7 +599,12 @@ export const waitForRun = Effect.fn("cli.thread.waitForRun")(function* (
599
OrchestratorMcpThreadWaitResult,
600
);
601
const ended = (waited: OrchestratorMcpThreadWaitResult) =>
601
- ({ type: "ended", runId: waited.runId, status: waited.status }) satisfies WaitOutcome;
602
+ ({
603
+ type: "ended",
604
+ runId: waited.runId,
605
+ status: waited.status,
606
+ ...(waited.output === undefined ? {} : { output: waited.output }),
607
+ }) satisfies WaitOutcome;
608
const ownRun = Effect.gen(function* () {
609
while (true) {
610
const waited = yield* waitSlice(WAIT_SLICE_MS);
@@ -641,7 +647,13 @@ export const waitForRun = Effect.fn("cli.thread.waitForRun")(function* (
647
if (after.sent) return outcome;
648
if (!waited.timedOut) {
649
if (result !== undefined && after.later.some((run) => run.runId === result.runId)) {
644
- return { type: "ended", runId: result.runId, status: result.status } satisfies WaitOutcome;
650
+ // A run that work woke was not asked for the result; the run before it holds it.
651
+ return {
652
+ type: "ended",
653
+ runId: result.runId,
654
+ status: result.status,
655
+ ...(outcome.output === undefined ? {} : { output: outcome.output }),
656
+ } satisfies WaitOutcome;
657
}
658
if (!workOutlivedRun) return outcome;
659
if (after.later.some((run) => !TERMINAL_RUN_STATUSES.has(run.status))) continue;
@@ -684,7 +696,15 @@ const finishRun = Effect.fn("cli.thread.finishRun")(function* (
696
? null
697
: yield* runResultText(tools, input.threadId, runId, "error");
698
if (input.json) {
687
- yield* printJson({ threadId: input.threadId, runId, status, reply, error });
699
+ const output = outcome.type === "ended" ? outcome.output : undefined;
700
+ yield* printJson({
701
+ threadId: input.threadId,
702
+ runId,
703
+ status,
704
+ reply,
705
+ error,
706
+ ...(output === undefined ? {} : { output }),
707
+ });
708
} else if (reply !== null) {
709
yield* Console.log(reply);
710
}
@@ -778,6 +798,25 @@ const waitFlag = Flag.Boolean("wait").pipe(
798
),
799
Flag.withDefault(false),
800
);
801
+const outputSchemaFlag = Flag.String("output-schema").pipe(
802
+ Flag.withDescription(
803
+ "File holding a JSON Schema. The agent must return data matching it; --wait --json prints it as `output`.",
804
+ ),
805
+ Flag.optional,
806
+);
807
+const decodeOutputSchema = Schema.decodeUnknownEffect(
808
+ Schema.fromJsonString(Schema.Record(Schema.String, Schema.Json)),
809
+);
810
+const readOutputSchema = Effect.fn("cli.thread.readOutputSchema")(function* (
811
+ path: Option.Option<string>,
812
+) {
813
+ if (Option.isNone(path)) return {};
814
+ const fileSystem = yield* FileSystem.FileSystem;
815
+ const usage = () =>
816
+ new ThreadUsageError({ detail: `${path.value} does not hold a JSON Schema object.` });
817
+ const text = yield* fileSystem.readFileString(path.value).pipe(Effect.mapError(usage));
818
+ return { outputSchema: yield* decodeOutputSchema(text).pipe(Effect.mapError(usage)) };
819
+});
820
const messageArgument = Argument.String("message").pipe(
821
Argument.withDescription("Message for the agent, or - to read it from stdin."),
822
);
@@ -860,6 +899,7 @@ const threadStartCommand = Command.make("start", {
899
Flag.withDescription("Branch name for the new worktree."),
900
Flag.optional,
901
),
902
+ outputSchema: outputSchemaFlag,
903
wait: waitFlag,
904
json: jsonFlag,
905
}).pipe(
@@ -867,6 +907,7 @@ const threadStartCommand = Command.make("start", {
907
Command.withHandler((flags) =>
908
Effect.gen(function* () {
909
const message = yield* readMessageArgument(flags.message);
910
+ const output = yield* readOutputSchema(flags.outputSchema);
911
const workspaceStrategy = yield* launchWorkspaceStrategy(flags);
912
const modelSelection = yield* launchModelSelection(flags);
913
const title = yield* decodeTitle(
@@ -882,6 +923,7 @@ const threadStartCommand = Command.make("start", {
923
projectId: project.id,
924
title,
925
message,
926
+ ...output,
927
...(workspaceStrategy === undefined ? {} : { workspaceStrategy }),
928
...(modelSelection === undefined ? {} : { modelSelection }),
929
},
@@ -907,6 +949,7 @@ const threadSendCommand = Command.make("send", {
949
...projectLocationFlags,
950
thread: threadArgument,
951
message: messageArgument,
952
+ outputSchema: outputSchemaFlag,
953
wait: waitFlag,
954
json: jsonFlag,
955
}).pipe(
@@ -917,6 +960,7 @@ const threadSendCommand = Command.make("send", {
960
Effect.gen(function* () {
961
const threadId = yield* decodeThreadId(flags.thread);
962
const message = yield* readMessageArgument(flags.message);
963
+ const output = yield* readOutputSchema(flags.outputSchema);
964
yield* withThreadTools(
965
flags,
966
Effect.fn("cli.thread.send")(function* (tools) {
@@ -924,7 +968,7 @@ const threadSendCommand = Command.make("send", {
968
const followWakes = flags.wait ? yield* threadIsIdle(tools, threadId) : false;
969
const sent = yield* tools.call(
970
"t3_thread_send",
927
- { threadId, message, mode: "queue" },
971
+ { threadId, message, mode: "queue", ...output },
972
OrchestratorMcpThreadSendResult,
973
);
974
if (flags.wait) {
apps/server/src/mcp/OrchestratorMcpService.ts
+5
@@ -261,6 +261,8 @@ export function threadManagementFailure(error: unknown): OrchestratorMcpFailure
261
"thread_not_sendable",
262
`${error.message} Send with mode: "auto" or "queue" to start a new turn there.`,
263
);
264
+ case "ThreadManagementRunOutputRejectedError":
265
+ return failure("invalid_request", error.message);
266
case "ThreadManagementThreadNotInterruptibleError":
267
return failure("thread_not_interruptible", error.message);
268
case "ThreadManagementProjectionLoadError":
@@ -3656,6 +3658,7 @@ const make = Effect.gen(function* () {
3658
attachments: [],
3659
mode,
3660
...(input.freshContext ? { freshContext: true } : {}),
3661
+ ...(input.outputSchema === undefined ? {} : { outputSchema: input.outputSchema }),
3662
createdBy: "agent",
3663
creationSource: "mcp",
3664
})
@@ -3691,6 +3694,7 @@ const make = Effect.gen(function* () {
3694
Math.max(1, input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS),
3695
),
3696
...(input.untilDelegatedWorkSettled === true ? { untilDelegatedWorkSettled: true } : {}),
3697
+ ...(input.untilOutput === true ? { untilOutput: true } : {}),
3698
})
3699
.pipe(Effect.mapError(threadManagementFailure));
3700
const status = result.run === null ? "idle" : runOutcome(result.run);
@@ -3727,6 +3731,7 @@ const make = Effect.gen(function* () {
3731
: {
3732
resultRun: { runId: result.resultRun.id, status: runOutcome(result.resultRun) },
3733
}),
3734
+ ...(result.run?.output === undefined ? {} : { output: result.run.output.value }),
3735
} satisfies OrchestratorMcpThreadWaitResult;
3736
}),
3737
interruptThread: Effect.fn("OrchestratorMcpService.interruptThread")(function* (scope, input) {
apps/server/src/mcp/toolkits/project/handlers.ts
+14
@@ -16,6 +16,7 @@ import * as FileSystem from "effect/FileSystem";
16
import * as Option from "effect/Option";
17
import * as Schema from "effect/Schema";
18
import { OrchestratorRuntimeModeAboveCeilingError } from "../../../orchestration-v2/Orchestrator.ts";
19
+import { outputRequestProblem } from "../../../orchestration-v2/runOutput.ts";
20
import * as ThreadLaunch from "../../../orchestration-v2/ThreadLaunchService.ts";
21
import * as ThreadMessageIntake from "../../../orchestration-v2/ThreadMessageIntake.ts";
22
import * as Claims from "../../../orchestration-v2/AttachmentClaims.ts";
@@ -224,6 +225,18 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
225
const threadId = ThreadId.make(commandId);
226
const messageId = MessageId.make(commandId);
227
const attachments = input.attachments ?? [];
228
+ const schemaProblem =
229
+ input.outputSchema === undefined
230
+ ? null
231
+ : outputRequestProblem(input.outputSchema, {
232
+ text: input.message ?? "",
233
+ attachments: input.attachments,
234
+ });
235
+ if (schemaProblem !== null || (input.outputSchema !== undefined && !input.message))
236
+ return yield* new OrchestratorMcpFailure({
237
+ code: "invalid_request",
238
+ message: schemaProblem ?? "outputSchema needs a message that asks for the result.",
239
+ });
240
if (attachments.some((attachment) => !Claims.attachmentIsPendingUpload(attachment)))
241
return yield* new OrchestratorMcpFailure({
242
code: "invalid_request",
@@ -427,6 +440,7 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
440
...(caller === undefined ? {} : { senderThreadId: caller.id }),
441
text: input.message ?? "",
442
attachments,
443
+ ...(input.outputSchema === undefined ? {} : { outputSchema: input.outputSchema }),
444
},
445
}),
446
createdBy: "agent",
apps/server/src/mcp/toolkits/project/tools.ts
+5
@@ -156,6 +156,11 @@ const ThreadLaunchTool = Tool.make("t3_thread_launch", {
156
}),
157
),
158
attachments: Schema.optional(Schema.Array(McpAttachmentInput).check(Schema.isMaxLength(8))),
159
+ outputSchema: Schema.optional(
160
+ Schema.Record(Schema.String, Schema.Json).annotate({
161
+ description: "As in `t3_thread_send`. Needs `message`.",
162
+ }),
163
+ ),
164
clientRequestId: Schema.optional(OrchestratorMcpClientRequestId),
165
/** Set by a linked environment launching its agent's delegated task here; ignored otherwise. */
166
delegatedFrom: Schema.optional(OrchestrationV2DelegatedFrom),
apps/server/src/mcp/toolkits/thread/handlers.ts
+26
@@ -283,6 +283,32 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, {
283
}),
284
),
285
),
286
+ t3_submit_output: McpToolAccess.actsAsCaller((input) =>
287
+ Effect.gen(function* () {
288
+ const { scope, threads } = yield* readCaller();
289
+ if (scope.thread === undefined) return yield* unavailable();
290
+ return yield* threads
291
+ .submitRunOutput({
292
+ threadId: scope.thread.threadId,
293
+ commandId: yield* newCommandId(),
294
+ json: input.json,
295
+ })
296
+ .pipe(
297
+ Effect.mapError((error) =>
298
+ error._tag === "ThreadManagementRunOutputRejectedError"
299
+ ? new OrchestratorMcpFailure({
300
+ code: "invalid_request",
301
+ // The agent wrote the value, so it is told what in it did not fit.
302
+ message:
303
+ error.cause instanceof Error
304
+ ? `${error.message}\n${error.cause.message.slice(0, 2000)}`
305
+ : error.message,
306
+ })
307
+ : unavailable(),
308
+ ),
309
+ );
310
+ }),
311
+ ),
312
t3_queue: McpToolAccess.either(
313
(input) => input.action === "list" || input.action === "read",
314
McpToolAccess.reads((input) =>
apps/server/src/mcp/toolkits/thread/tools.ts
+15
-1
@@ -23,7 +23,7 @@ import {
23
} from "@t3tools/contracts";
24
import * as SecureRandom from "effect/crypto/SecureRandom";
25
import * as Schema from "effect/Schema";
26
-import { Tool, Toolkit } from "effect/ai";
26
+import { McpSchema, Tool, Toolkit } from "effect/ai";
27
28
import * as ThreadSearch from "../../../orchestration-v2/ThreadSearch.ts";
29
import * as ScheduledTaskService from "../../../scheduledTasks/ScheduledTaskService.ts";
@@ -241,6 +241,19 @@ const ScheduledTaskRunTool = Tool.make("run_scheduled_task_now", {
241
.annotate(Tool.Destructive, true)
242
.annotate(Tool.OpenWorld, true);
243
244
+const SubmitOutputTool = Tool.make("t3_submit_output", {
245
+ ...commandTool,
246
+ description:
247
+ "Return this turn's result as data, when the message asked for one. `json`: JSON text matching the schema it gave. A rejection says what did not fit; fix it and call again.",
248
+ // Stored on the run, which every client of the thread holds.
249
+ parameters: Schema.Struct({ json: Schema.String.check(Schema.isMaxLength(200000)) }),
250
+ success: Schema.Struct({ runId: RunId }),
251
+})
252
+ // It writes only the caller's own run, so a read-only or plan-mode agent can still answer.
253
+ .annotate(Tool.Readonly, true)
254
+ .annotate(Tool.Destructive, false)
255
+ .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromOutsideClients);
256
+
257
export const ThreadToolkit = Toolkit.make(
258
ScheduledTaskRunTool,
259
ThreadSearchTool,
@@ -249,4 +262,5 @@ export const ThreadToolkit = Toolkit.make(
262
ThreadOrganizeTool,
263
PendingRequestTool,
264
QueueTool,
265
+ SubmitOutputTool,
266
);
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+1
@@ -2537,6 +2537,7 @@ export const CLAUDE_READ_ONLY_T3_MCP_ALLOWED_TOOLS: ReadonlyArray<string> = [
2537
"mcp__t3-code__html_preview",
2538
"mcp__t3-code__html_render",
2539
"mcp__t3-code__send_to_user",
2540
+ "mcp__t3-code__t3_submit_output",
2541
];
2542
2543
// request_secret can wait an hour; exceed Claude's default 60 s timeout.
apps/server/src/orchestration-v2/Orchestrator.ts
+105
-1
@@ -89,6 +89,7 @@ import { modelSwitchSince } from "./modelSwitch.ts";
89
import { contextBoundaryOrdinal, isScheduledFreshRun } from "./contextBoundary.ts";
90
import { isPlaceholderThreadTitle } from "./placeholderThreadTitle.ts";
91
import { combinePullRequestWatchWakes, type PullRequestWatchWake } from "./pullRequestWatch.ts";
92
+import { outputRequestProblem } from "./runOutput.ts";
93
import { recordThreadOpen } from "@t3tools/shared/paletteSearch";
94
import {
95
backgroundWorkHoldsCompletion,
@@ -675,6 +676,7 @@ function commandThreadId(command: OrchestrationV2ServerCommand): ThreadId {
676
case "prepared-run.retry":
677
case "subagent.stop":
678
case "run.interrupt":
679
+ case "run.output.submit":
680
case "queued-message.promote-to-steer":
681
case "queued-run.start":
682
case "queue.resume":
@@ -7472,8 +7474,31 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
7474
dispatchMode = { type: "start_immediately" };
7475
}
7476
const freshContext = command.freshContext === true;
7477
+ // A result is asked of one whole turn, so a send that declares one never joins a running turn.
7478
+ // A run that continues one cut short still owes that run's result.
7479
+ const continuedRunId =
7480
+ command.restartContinuationOfRunId ??
7481
+ command.usageLimitContinuationOfRunId ??
7482
+ command.manualContinuationOfRunId;
7483
+ const outputSchema =
7484
+ command.outputSchema ??
7485
+ (continuedRunId === undefined
7486
+ ? undefined
7487
+ : projection.runs.find((run) => run.id === continuedRunId)?.outputSchema);
7488
+ const schemaProblem =
7489
+ command.outputSchema === undefined
7490
+ ? null
7491
+ : outputRequestProblem(command.outputSchema, command);
7492
+ if (schemaProblem !== null) {
7493
+ return yield* new OrchestratorDispatchError({
7494
+ commandId: command.commandId,
7495
+ commandType: command.type,
7496
+ cause: schemaProblem,
7497
+ });
7498
+ }
7499
+ const output = outputSchema === undefined ? {} : { outputSchema };
7500
if (
7476
- freshContext &&
7501
+ (freshContext || command.outputSchema !== undefined) &&
7502
(dispatchMode.type === "steer_active" || dispatchMode.type === "restart_active")
7503
) {
7504
dispatchMode = { type: "queue_after_active" };
@@ -8057,6 +8082,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
8082
: { usageLimitContinuationOfRunId: command.usageLimitContinuationOfRunId }),
8083
...(continuedTaskId === undefined ? {} : { delegatedTaskId: continuedTaskId }),
8084
...(freshContext ? { freshContext: true } : {}),
8085
+ ...output,
8086
};
8087
const attempt: OrchestrationV2RunAttempt = {
8088
id: attemptId,
@@ -8481,6 +8507,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
8507
...(continuedTaskId === undefined ? {} : { delegatedTaskId: continuedTaskId }),
8508
...wakeWorkStartedAt(projection, command),
8509
...(freshContext ? { freshContext: true } : {}),
8510
+ ...output,
8511
};
8512
const attempt: OrchestrationV2RunAttempt = {
8513
id: attemptId,
@@ -9294,6 +9321,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
9321
: { usageLimitContinuationOfRunId: command.usageLimitContinuationOfRunId }),
9322
...(continuedTaskId === undefined ? {} : { delegatedTaskId: continuedTaskId }),
9323
...wakeWorkStartedAt(projection, command),
9324
+ ...output,
9325
};
9326
const attempt: OrchestrationV2RunAttempt = {
9327
id: attemptId,
@@ -11808,6 +11836,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
11836
cause: "A message that starts a fresh session can't steer the current turn.",
11837
});
11838
}
11839
+ // Steering joins a turn that was not asked for this message's result, so it would be lost.
11840
+ if (queuedRun.outputSchema !== undefined) {
11841
+ return yield* new OrchestratorDispatchError({
11842
+ commandId: command.commandId,
11843
+ commandType: command.type,
11844
+ cause: "A message that asks for a result can't steer the current turn.",
11845
+ });
11846
+ }
11847
if (goalCommand !== null) {
11848
yield* ensureGoalCommandSupported(command, queuedMessage, modelSelection.instanceId);
11849
const goal = projection.providerThreads.find(
@@ -12088,6 +12124,57 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
12124
}
12125
});
12126
12127
+ const dispatchRunOutputSubmit = Effect.fn("Orchestrator.dispatchRunOutputSubmit")(function* (
12128
+ command: Extract<OrchestrationV2InternalCommand, { readonly type: "run.output.submit" }>,
12129
+ events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
12130
+ ) {
12131
+ const projection = yield* projectionStore
12132
+ .getThreadRecords(command.threadId, ["runs"])
12133
+ .pipe(mapDispatchError(command));
12134
+ const run = projection.runs.find((candidate) => candidate.id === command.runId);
12135
+ if (run?.outputSchema === undefined) {
12136
+ return yield* new OrchestratorDispatchError({
12137
+ commandId: command.commandId,
12138
+ commandType: command.type,
12139
+ cause: `Run ${command.runId} was not asked for a result.`,
12140
+ });
12141
+ }
12142
+ // The service picks the active run, but the run can end before this command is its turn. A
12143
+ // turn that completed without its result still owes it, and a later turn may give it.
12144
+ const owes = run.status === "completed" && run.output === undefined;
12145
+ if (!isActiveRun(run) && !owes) {
12146
+ return yield* new OrchestratorDispatchError({
12147
+ commandId: command.commandId,
12148
+ commandType: command.type,
12149
+ cause: `Run ${command.runId} is ${run.status} and takes no result.`,
12150
+ });
12151
+ }
12152
+ // A stopped run stays active until its provider settles; what it submits then is not kept.
12153
+ if (yield* stopReachedRun(command, command.threadId, run.id)) {
12154
+ return yield* new OrchestratorDispatchError({
12155
+ commandId: command.commandId,
12156
+ commandType: command.type,
12157
+ cause: `Run ${command.runId} was stopped and takes no result.`,
12158
+ });
12159
+ }
12160
+ const now = yield* DateTime.now;
12161
+ yield* emit(
12162
+ events,
12163
+ command,
12164
+ )({
12165
+ type: "run.output-submitted",
12166
+ threadId: command.threadId,
12167
+ runId: run.id,
12168
+ ...(run.rootNodeId === null ? {} : { nodeId: run.rootNodeId }),
12169
+ providerInstanceId: run.providerInstanceId,
12170
+ occurredAt: now,
12171
+ payload: {
12172
+ runId: run.id,
12173
+ output: { value: command.value, submittedAt: DateTime.formatIso(now) },
12174
+ },
12175
+ });
12176
+ });
12177
+
12178
const dispatchQueuedRunEdit = Effect.fn("Orchestrator.dispatchQueuedRunEdit")(function* (
12179
command: Extract<OrchestrationV2Command, { readonly type: "queued-run.edit" }>,
12180
events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
@@ -12145,6 +12232,20 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
12232
{ text: command.text, attachments: command.attachments ?? queuedMessage.attachments },
12233
queuedRunModelSelection(projection, queuedRun).instanceId,
12234
);
12235
+ const editProblem =
12236
+ queuedRun.outputSchema === undefined
12237
+ ? null
12238
+ : outputRequestProblem(queuedRun.outputSchema, {
12239
+ text: command.text,
12240
+ attachments: command.attachments ?? queuedMessage.attachments,
12241
+ });
12242
+ if (editProblem !== null) {
12243
+ return yield* new OrchestratorDispatchError({
12244
+ commandId: command.commandId,
12245
+ commandType: command.type,
12246
+ cause: editProblem,
12247
+ });
12248
+ }
12249
const queuedTurnItem = projection.turnItems.find(
12250
(candidate) => candidate.type === "user_message" && candidate.messageId === queuedMessage.id,
12251
);
@@ -15799,6 +15900,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
15900
case "queued-run.edit":
15901
yield* dispatchQueuedRunEdit(command, events, effects);
15902
break;
15903
+ case "run.output.submit":
15904
+ yield* dispatchRunOutputSubmit(command, events);
15905
+ break;
15906
case "checkpoint.rollback":
15907
yield* dispatchCheckpointRollback(command, events, effects);
15908
break;
apps/server/src/orchestration-v2/ProjectionStore.test.ts
+21
-1
@@ -8044,6 +8044,19 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
8044
payload: task,
8045
});
8046
8047
+ const output = { value: { verdict: "merge" }, submittedAt: "2026-11-11T00:00:00.000Z" };
8048
+ yield* projectionStore.apply({
8049
+ id: EventId.make("event:projection-delegated-completion:output"),
8050
+ type: "run.output-submitted",
8051
+ threadId,
8052
+ runId,
8053
+ nodeId: rootNodeId,
8054
+ providerInstanceId,
8055
+ occurredAt: now,
8056
+ payload: { runId, output },
8057
+ });
8058
+
8059
+ // Lifecycle writers hold the run as it was when the turn started.
8060
const { delegatedCompletion: _delegatedCompletion, ...staleRun } = run;
8061
const { completionDelivery: _completionDelivery, ...staleTask } = task;
8062
yield* projectionStore.apply({
@@ -8054,7 +8067,13 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
8067
nodeId: rootNodeId,
8068
providerInstanceId,
8069
occurredAt: later,
8057
- payload: { ...staleRun, status: "interrupted", completedAt: later },
8070
+ payload: {
8071
+ ...staleRun,
8072
+ // An earlier submission, read before the latest one landed.
8073
+ output: { value: { verdict: "fix-first" }, submittedAt: "2026-11-10T00:00:00.000Z" },
8074
+ status: "interrupted",
8075
+ completedAt: later,
8076
+ },
8077
});
8078
yield* projectionStore.apply({
8079
id: EventId.make("event:projection-delegated-completion:stale-task"),
@@ -8075,6 +8094,7 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
8094
8095
const projection = yield* projectionStore.getThreadProjection(threadId);
8096
assert.deepEqual(projection.runs[0]?.delegatedCompletion, run.delegatedCompletion);
8097
+ assert.deepEqual(projection.runs[0]?.output, output);
8098
assert.deepEqual(projection.subagents[0]?.completionDelivery, task.completionDelivery);
8099
assert.deepEqual(
8100
(yield* projectionStore.getThreadRecords(threadId, ["subagents"], {
apps/server/src/orchestration-v2/ProjectionStore.ts
+39
-3
@@ -980,6 +980,8 @@ function preserveRunRecordedFields(
980
current.restartCancelledBackgroundWork !== undefined
981
? { restartCancelledBackgroundWork: current.restartCancelledBackgroundWork }
982
: {}),
983
+ // Only a submission sets the output; a lifecycle write carries it as it was when read.
984
+ ...(current.output !== undefined ? { output: current.output } : {}),
985
};
986
}
987
@@ -1104,6 +1106,13 @@ export function applyToProjection(
1106
: run,
1107
),
1108
};
1109
+ case "run.output-submitted":
1110
+ return {
1111
+ ...base,
1112
+ runs: base.runs.map((run) =>
1113
+ run.id === event.payload.runId ? { ...run, output: event.payload.output } : run,
1114
+ ),
1115
+ };
1116
case "run-attempt.created":
1117
case "run-attempt.updated":
1118
return withLocalVisibleTurnItems({
@@ -1339,6 +1348,9 @@ const encodeRunPayload = Schema.encodeEffect(Schema.fromJsonString(Orchestration
1348
const encodeRestartCancelledBackgroundWork = Schema.encodeEffect(
1349
Schema.fromJsonString(OrchestrationV2RunJsonSchema.fields.restartCancelledBackgroundWork),
1350
);
1351
+const encodeRunOutput = Schema.encodeEffect(
1352
+ Schema.fromJsonString(OrchestrationV2RunJsonSchema.fields.output),
1353
+);
1354
const encodeRunAttemptPayload = Schema.encodeEffect(
1355
Schema.fromJsonString(OrchestrationV2RunAttemptJsonSchema),
1356
);
@@ -2384,6 +2396,18 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
2396
ELSE ${payload}
2397
END
2398
`;
2399
+ // Only a submission sets the output; a lifecycle write carries it as it was when read.
2400
+ const keepRecordedRunOutput = (payload: Statement.Fragment) => sql`
2401
+ CASE
2402
+ WHEN json_type(orchestration_v2_projection_runs.payload_json, '$.output') IS NOT NULL
2403
+ THEN json_set(
2404
+ ${payload},
2405
+ '$.output',
2406
+ json_extract(orchestration_v2_projection_runs.payload_json, '$.output')
2407
+ )
2408
+ ELSE ${payload}
2409
+ END
2410
+ `;
2411
2412
type TimelineIndexItem = Pick<
2413
OrchestrationV2TurnItem,
@@ -2578,9 +2602,11 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
2602
status = excluded.status,
2603
requested_at = excluded.requested_at,
2604
completed_at = excluded.completed_at,
2581
- payload_json = ${keepRecordedRunField(
2582
- keepRecordedRunField(sql`excluded.payload_json`, "$.delegatedCompletion"),
2583
- "$.restartCancelledBackgroundWork",
2605
+ payload_json = ${keepRecordedRunOutput(
2606
+ keepRecordedRunField(
2607
+ keepRecordedRunField(sql`excluded.payload_json`, "$.delegatedCompletion"),
2608
+ "$.restartCancelledBackgroundWork",
2609
+ ),
2610
)}
2611
`;
2612
break;
@@ -2601,6 +2627,16 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
2627
`;
2628
break;
2629
}
2630
+ case "run.output-submitted": {
2631
+ // Only this field changes, so a concurrent lifecycle write is never regressed.
2632
+ const outputJson = yield* encodeRunOutput(event.payload.output);
2633
+ yield* sql`
2634
+ UPDATE orchestration_v2_projection_runs
2635
+ SET payload_json = json_set(payload_json, '$.output', json(${outputJson}))
2636
+ WHERE run_id = ${event.payload.runId} AND thread_id = ${event.threadId}
2637
+ `;
2638
+ break;
2639
+ }
2640
case "run-attempt.created":
2641
case "run-attempt.updated": {
2642
const payloadJson = yield* encodeRunAttemptPayload(event.payload);
apps/server/src/orchestration-v2/ProviderTurnStartService.ts
+7
-1
@@ -59,6 +59,7 @@ import {
59
latestNativeContextUsage,
60
} from "@t3tools/provider-core/server/handoffBudget";
61
import { deliverContextHandoffs, withInlineContext } from "./ContextHandoffDelivery.ts";
62
+import { isProviderCommand, outputInstructions } from "./runOutput.ts";
63
import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
64
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
65
import * as ProjectionStore from "./ProjectionStore.ts";
@@ -986,7 +987,7 @@ export const layer: Layer.Layer<
987
});
988
let effectiveHandoffs = handoffs;
989
let resumeFellBack = false;
989
- const userText = withMessageSenderNote(
990
+ const messageText = withMessageSenderNote(
991
providerMessage,
992
projectComposerContextForProvider({
993
text: providerMessage.text,
@@ -999,6 +1000,11 @@ export const layer: Layer.Layer<
1000
session.driver === "claudeAgent" ||
1001
session.providerSession.capabilities.turns.supportsNativeGoals === true;
1002
const goalCommand = goalDriver && parseGoalCommand(providerMessage) !== null;
1003
+ // Part of the user text, so every way a turn starts carries it, after the user's own words.
1004
+ const userText =
1005
+ run.outputSchema === undefined || goalCommand || isProviderCommand(providerMessage)
1006
+ ? messageText
1007
+ : `${messageText}\n\n${outputInstructions(run.outputSchema)}`;
1008
// The provider turn marks cancellation work delivered; restart continuations use their own text or resume natively.
1009
const noteContinuation = isRestartNoteContinuation(
1010
run,
apps/server/src/orchestration-v2/ThreadLaunchService.test.ts
+104
@@ -627,6 +627,110 @@ it.effect("retains automation and sender attribution while a message waits in th
627
}).pipe(Effect.provide(harness.layer));
628
});
629
630
+it.effect("a run asked for a result stores what its agent submits once it fits the schema", () => {
631
+ const harness = makeHarness({ runSetup: () => Effect.never });
632
+ const outputSchema = {
633
+ type: "object",
634
+ properties: { verdict: { enum: ["merge", "fix-first"] } },
635
+ required: ["verdict"],
636
+ };
637
+ return Effect.gen(function* () {
638
+ const launches = yield* ThreadLaunch.ThreadLaunchService;
639
+ const threads = yield* ThreadManagement.ThreadManagementService;
640
+ const input = launchInput({
641
+ command: "command:output:launch",
642
+ thread: "thread:output",
643
+ message: "Review it",
644
+ workspace: { type: "worktree", baseRef: "main" },
645
+ });
646
+ const launched = yield* launches.launch({
647
+ ...input,
648
+ initialMessage: { ...input.initialMessage!, outputSchema },
649
+ });
650
+ const submit = (command: string, json: string) =>
651
+ threads.submitRunOutput({
652
+ threadId: launched.threadId,
653
+ commandId: CommandId.make(command),
654
+ json,
655
+ });
656
+
657
+ const rejected = yield* submit("command:output:bad", '{"verdict":"maybe"}').pipe(Effect.flip);
658
+ assert.equal(rejected._tag, "ThreadManagementRunOutputRejectedError");
659
+ // What did not fit is kept as the cause, for the agent that wrote it and nobody's logs.
660
+ assert.equal(rejected.message, "The result does not match the schema.");
661
+ assert.include(
662
+ String((rejected as { cause?: { message?: string } }).cause?.message),
663
+ "verdict",
664
+ );
665
+ const unparsed = yield* submit("command:output:text", "merge").pipe(Effect.flip);
666
+ assert.include(unparsed.message, "not valid JSON");
667
+
668
+ const accepted = yield* submit("command:output:good", '{"verdict":"merge","note":"kept"}');
669
+ const stored = (yield* threads.getThreadProjection(launched.threadId)).runs.find(
670
+ (run) => run.id === accepted.runId,
671
+ );
672
+ assert.deepStrictEqual(stored?.outputSchema, outputSchema);
673
+ // Kept as submitted, including what the schema does not name.
674
+ assert.deepStrictEqual(stored?.output?.value, { verdict: "merge", note: "kept" });
675
+
676
+ // Asking for a result never joins the running turn, and a plain turn has nothing to submit to.
677
+ const next = yield* threads.sendToThread({
678
+ projectId,
679
+ commandId: CommandId.make("command:output:next"),
680
+ threadId: launched.threadId,
681
+ messageId: MessageId.make("message:output:next"),
682
+ text: "Review it again",
683
+ attachments: [],
684
+ mode: "steer",
685
+ outputSchema,
686
+ createdBy: "agent",
687
+ creationSource: "mcp",
688
+ });
689
+ assert.equal(next.delivery, "queued");
690
+ assert.deepStrictEqual(next.run.outputSchema, outputSchema);
691
+ assert.isUndefined(next.run.output);
692
+ const unusable = yield* threads
693
+ .sendToThread({
694
+ projectId,
695
+ commandId: CommandId.make("command:output:unusable"),
696
+ threadId: launched.threadId,
697
+ messageId: MessageId.make("message:output:unusable"),
698
+ text: "Review it again",
699
+ attachments: [],
700
+ mode: "queue",
701
+ outputSchema: { $ref: "#/$defs/Missing" },
702
+ createdBy: "agent",
703
+ creationSource: "mcp",
704
+ })
705
+ .pipe(Effect.result);
706
+ assert.isTrue(Result.isFailure(unusable));
707
+ }).pipe(Effect.provide(harness.layer));
708
+});
709
+
710
+it.effect("a run that was not asked for a result rejects a submission", () => {
711
+ const harness = makeHarness({ runSetup: () => Effect.never });
712
+ return Effect.gen(function* () {
713
+ const launches = yield* ThreadLaunch.ThreadLaunchService;
714
+ const threads = yield* ThreadManagement.ThreadManagementService;
715
+ const launched = yield* launches.launch(
716
+ launchInput({
717
+ command: "command:no-output:launch",
718
+ thread: "thread:no-output",
719
+ message: "Just talk",
720
+ workspace: { type: "worktree", baseRef: "main" },
721
+ }),
722
+ );
723
+ const rejected = yield* threads
724
+ .submitRunOutput({
725
+ threadId: launched.threadId,
726
+ commandId: CommandId.make("command:no-output:submit"),
727
+ json: "{}",
728
+ })
729
+ .pipe(Effect.flip);
730
+ assert.include(rejected.message, "not asked for a result");
731
+ }).pipe(Effect.provide(harness.layer));
732
+});
733
+
734
it.effect("provisions independent launches concurrently instead of behind a global semaphore", () =>
735
Effect.gen(function* () {
736
const setupCount = yield* Ref.make(0);
apps/server/src/orchestration-v2/ThreadLaunchService.ts
+6
@@ -86,6 +86,8 @@ export interface ThreadLaunchInitialMessage {
86
readonly text: string;
87
readonly attachments: ReadonlyArray<ChatAttachment>;
88
readonly context?: import("@t3tools/contracts").OrchestrationMessageContext | undefined;
89
+ /** Ask the first run for a result as data matching this JSON Schema. */
90
+ readonly outputSchema?: Readonly<Record<string, Schema.Json>> | undefined;
91
}
92
93
export interface ThreadLaunchInput {
@@ -1356,6 +1358,9 @@ const make = Effect.gen(function* () {
1358
: { senderThreadId: input.initialMessage.senderThreadId }),
1359
attachments: input.initialMessage.attachments,
1360
...(input.initialMessage.context ? { context: input.initialMessage.context } : {}),
1361
+ ...(input.initialMessage.outputSchema === undefined
1362
+ ? {}
1363
+ : { outputSchema: input.initialMessage.outputSchema }),
1364
...(input.generateTitle === true ? { titleSeed: input.title } : {}),
1365
};
1366
const claimDispatch =
@@ -1597,6 +1602,7 @@ const make = Effect.gen(function* () {
1602
text: message.text,
1603
attachments: message.attachments,
1604
...(message.context ? { context: message.context } : {}),
1605
+ ...(run.outputSchema === undefined ? {} : { outputSchema: run.outputSchema }),
1606
},
1607
}),
1608
},
apps/server/src/orchestration-v2/ThreadManagementService.ts
+88
-3
@@ -55,6 +55,7 @@ import * as Fiber from "effect/Fiber";
55
import * as Layer from "effect/Layer";
56
import * as Option from "effect/Option";
57
import * as Ref from "effect/Ref";
58
+import * as Result from "effect/Result";
59
import * as Schema from "effect/Schema";
60
import * as Semaphore from "effect/Semaphore";
61
import * as Stream from "effect/Stream";
@@ -72,6 +73,7 @@ import { cancelledBeforeStart } from "./RestartBackgroundNote.ts";
73
import * as LegacyV1ThreadImporter from "./legacy/LegacyV1ThreadImporter.ts";
74
import * as ServerSettings from "../serverSettings.ts";
75
import { ThreadWorktreeRestore } from "../workspace/restoreMissingWorktree.ts";
76
+import { checkOutput, outputRequestProblem } from "./runOutput.ts";
77
78
export type ThreadManagementSendMode = "auto" | "queue" | "steer" | "restart";
79
@@ -160,6 +162,8 @@ export interface ThreadManagementSendInput {
162
readonly mode: ThreadManagementSendMode;
163
/** Start a new provider session; the orchestrator queues it instead of steering. */
164
readonly freshContext?: boolean;
165
+ /** Ask the run for a result as data matching this JSON Schema; it is queued, never steered. */
166
+ readonly outputSchema?: Readonly<Record<string, Schema.Json>>;
167
readonly createdBy: OrchestrationV2Actor;
168
readonly creationSource: OrchestrationV2CreationSource;
169
}
@@ -187,6 +191,11 @@ export interface ThreadManagementWaitInput {
191
* completion delivery will wake it again, as a delegated task's result does.
192
*/
193
readonly untilDelegatedWorkSettled?: boolean;
194
+ /**
195
+ * Also wait until the run has the result it was asked for. A turn may end without one while
196
+ * its agent waits to be woken, and submit it from a later turn.
197
+ */
198
+ readonly untilOutput?: boolean;
199
}
200
201
export interface ThreadManagementWaitResult {
@@ -273,6 +282,20 @@ export class ThreadManagementNoSteerableRunError extends Schema.TaggedError<Thre
282
}
283
}
284
285
+export class ThreadManagementRunOutputRejectedError extends Schema.TaggedError<ThreadManagementRunOutputRejectedError>()(
286
+ "ThreadManagementRunOutputRejectedError",
287
+ {
288
+ threadId: ThreadId,
289
+ /** One of a few fixed sentences. What a submission got wrong is in `cause`. */
290
+ problem: Schema.String,
291
+ cause: Schema.optional(Schema.Defect()),
292
+ },
293
+) {
294
+ override get message(): string {
295
+ return this.problem;
296
+ }
297
+}
298
+
299
export class ThreadManagementThreadNotInterruptibleError extends Schema.TaggedError<ThreadManagementThreadNotInterruptibleError>()(
300
"ThreadManagementThreadNotInterruptibleError",
301
{
@@ -376,6 +399,7 @@ export const ThreadManagementError = Schema.Union([
399
ThreadManagementRunNotFoundError,
400
ThreadManagementThreadArchivedError,
401
ThreadManagementNoSteerableRunError,
402
+ ThreadManagementRunOutputRejectedError,
403
ThreadManagementThreadNotInterruptibleError,
404
ThreadManagementProjectionLoadError,
405
ThreadManagementProjectThreadsListError,
@@ -463,6 +487,12 @@ export interface ThreadManagementServiceShape {
487
readonly sendToThread: (
488
input: ThreadManagementSendInput,
489
) => Effect.Effect<ThreadManagementSendResult, ThreadManagementFailure>;
490
+ /** Stores what the thread's running turn returns, once it fits the schema that turn declared. */
491
+ readonly submitRunOutput: (input: {
492
+ readonly threadId: ThreadId;
493
+ readonly commandId: CommandId;
494
+ readonly json: string;
495
+ }) => Effect.Effect<{ readonly runId: RunId }, ThreadManagementFailure>;
496
readonly assertProviderInstanceEnabled: (input: {
497
readonly projectId: ProjectId;
498
readonly commandId: CommandId;
@@ -875,10 +905,19 @@ const make = Effect.gen(function* () {
905
threadId: input.threadId,
906
});
907
}
908
+ const schemaProblem =
909
+ input.outputSchema === undefined ? null : outputRequestProblem(input.outputSchema, input);
910
+ if (schemaProblem !== null) {
911
+ return yield* new ThreadManagementRunOutputRejectedError({
912
+ threadId: input.threadId,
913
+ problem: schemaProblem,
914
+ });
915
+ }
916
const steerableRun = latestSteerableRun(target);
879
- // A fresh send never joins a running turn, so it needs none to steer or restart.
917
+ // A fresh send, or one that asks for a result, never joins a running turn.
918
const mode =
881
- input.freshContext && (input.mode === "steer" || input.mode === "restart")
919
+ (input.freshContext || input.outputSchema !== undefined) &&
920
+ (input.mode === "steer" || input.mode === "restart")
921
? "queue"
922
: input.mode;
923
const explicitSteer = mode === "steer" || mode === "restart";
@@ -938,6 +977,7 @@ const make = Effect.gen(function* () {
977
attachments: input.attachments,
978
...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
979
...(input.freshContext ? { freshContext: true } : {}),
980
+ ...(input.outputSchema === undefined ? {} : { outputSchema: input.outputSchema }),
981
dispatchMode,
982
...(mode === "auto" ? { deliveryIntent: "auto" } : {}),
983
createdBy: input.createdBy,
@@ -991,6 +1031,47 @@ const make = Effect.gen(function* () {
1031
return { dispatch: dispatched, projection, message, run, turnItem, delivery };
1032
});
1033
1034
+ const submitRunOutput: ThreadManagementServiceShape["submitRunOutput"] = Effect.fn(
1035
+ "ThreadManagementService.submitRunOutput",
1036
+ )(function* (input) {
1037
+ const records = yield* orchestrator.getThreadRecords(input.threadId, ["runs"]);
1038
+ const active = latestActiveRun(records);
1039
+ // A turn that ended without its result still owes it: the agent may have ended it to wait
1040
+ // for something, and answer from the turn that woke it.
1041
+ // Only an ended turn can owe one; a queued or running turn asked for one answers for itself.
1042
+ const owed = records.runs
1043
+ .filter(
1044
+ (candidate) =>
1045
+ candidate.outputSchema !== undefined &&
1046
+ candidate.output === undefined &&
1047
+ candidate.status === "completed",
1048
+ )
1049
+ .toSorted((left, right) => right.ordinal - left.ordinal)[0];
1050
+ const run = active?.outputSchema !== undefined ? active : owed;
1051
+ if (active === undefined || run?.outputSchema === undefined) {
1052
+ return yield* new ThreadManagementRunOutputRejectedError({
1053
+ threadId: input.threadId,
1054
+ problem: "This turn was not asked for a result. Reply in your message instead.",
1055
+ });
1056
+ }
1057
+ const checked = yield* checkOutput(run.outputSchema, input.json);
1058
+ if (Result.isFailure(checked)) {
1059
+ return yield* new ThreadManagementRunOutputRejectedError({
1060
+ threadId: input.threadId,
1061
+ problem: checked.failure.problem,
1062
+ ...(checked.failure.cause === undefined ? {} : { cause: checked.failure.cause }),
1063
+ });
1064
+ }
1065
+ yield* dispatch({
1066
+ type: "run.output.submit",
1067
+ commandId: input.commandId,
1068
+ threadId: input.threadId,
1069
+ runId: run.id,
1070
+ value: checked.success,
1071
+ });
1072
+ return { runId: run.id };
1073
+ });
1074
+
1075
const waitForThread: ThreadManagementServiceShape["waitForThread"] = Effect.fn(
1076
"ThreadManagementService.waitForThread",
1077
)(function* (input) {
@@ -1033,7 +1114,9 @@ const make = Effect.gen(function* () {
1114
const run = latestRestartContinuation(runs, current);
1115
const pending =
1116
isTerminalRunStatus(run.status) && (yield* orchestrator.restartContinuationPending(run));
1036
- return { run, pending, settled: isTerminalRunStatus(run.status) && !pending };
1117
+ const owesOutput =
1118
+ input.untilOutput === true && run.status === "completed" && run.output === undefined;
1119
+ return { run, pending, settled: isTerminalRunStatus(run.status) && !pending && !owesOutput };
1120
});
1121
const untilDelegatedWorkSettled = input.untilDelegatedWorkSettled === true;
1122
const delegatedWorkResult = Effect.gen(function* () {
@@ -1083,6 +1166,7 @@ const make = Effect.gen(function* () {
1166
[
1167
"run.updated",
1168
"thread.deleted",
1169
+ ...(input.untilOutput === true ? (["run.output-submitted"] as const) : []),
1170
// What delegated work reads besides runs: tasks and their
1171
// deliveries, and a provider thread's background tasks.
1172
...(untilDelegatedWorkSettled
@@ -1778,6 +1862,7 @@ const make = Effect.gen(function* () {
1862
getThreadLinkMetadata: orchestrator.getThreadLinkMetadata,
1863
listProjectThreads,
1864
sendToThread,
1865
+ submitRunOutput,
1866
assertProviderInstanceEnabled,
1867
isProviderInstanceEnabledForProject,
1868
hasReceipt,
apps/server/src/orchestration-v2/runOutput.test.ts
new
+25
@@ -0,0 +1,25 @@
1
+import { assert, it } from "@effect/vitest";
2
+import * as Effect from "effect/Effect";
3
+import * as Result from "effect/Result";
4
+
5
+import { checkOutput, outputRequestProblem } from "./runOutput.ts";
6
+
7
+const open = { type: "object", properties: { verdict: { type: "string" } }, required: ["verdict"] };
8
+const closed = { ...open, additionalProperties: false };
9
+
10
+it.effect("a closed schema turns down a key it does not name, and an open one keeps it", () =>
11
+ Effect.gen(function* () {
12
+ const extra = '{"verdict":"merge","note":"kept"}';
13
+ assert.deepStrictEqual(yield* checkOutput(open, extra), Result.succeed(JSON.parse(extra)));
14
+ const rejected = yield* checkOutput(closed, extra);
15
+ assert.isTrue(Result.isFailure(rejected));
16
+ assert.isTrue(Result.isSuccess(yield* checkOutput(closed, '{"verdict":"merge"}')));
17
+ }),
18
+);
19
+
20
+it("a command its provider runs itself cannot be asked for a result", () => {
21
+ for (const text of ["/compact", "/goal Review the changes"]) {
22
+ assert.include(outputRequestProblem(open, { text }) ?? "", "command");
23
+ }
24
+ assert.isNull(outputRequestProblem(open, { text: "Review the changes" }));
25
+});
apps/server/src/orchestration-v2/runOutput.ts
new
+93
@@ -0,0 +1,93 @@
1
+import { parseGoalCommand } from "@t3tools/contracts";
2
+import * as Effect from "effect/Effect";
3
+import * as JsonSchema from "effect/JsonSchema";
4
+import * as Result from "effect/Result";
5
+import * as Schema from "effect/Schema";
6
+import * as SchemaRepresentation from "effect/SchemaRepresentation";
7
+
8
+type OutputSchema = Readonly<Record<string, Schema.Json>>;
9
+
10
+// A schema built from JSON Schema needs no services, which its `Schema.Top` type cannot say.
11
+const compile = (schema: OutputSchema) =>
12
+ Result.try(
13
+ () =>
14
+ SchemaRepresentation.fromJsonSchemaDocument(
15
+ JsonSchema.fromSchemaDraft2020_12(schema),
16
+ ) as Schema.Codec<unknown>,
17
+ );
18
+
19
+// The schema travels with the run to every client, and into the prompt of every turn that owes it.
20
+const MAX_SCHEMA_CHARS = 32_000;
21
+
22
+/** Why a declared output schema cannot be used, or null when it can. */
23
+const outputSchemaProblem = (schema: OutputSchema): string | null =>
24
+ JSON.stringify(schema).length > MAX_SCHEMA_CHARS
25
+ ? `The output schema is larger than ${MAX_SCHEMA_CHARS} characters.`
26
+ : Result.isFailure(compile(schema))
27
+ ? "The output schema is not a usable JSON Schema."
28
+ : null;
29
+
30
+/** Whether a message is a command its provider runs itself, which takes no appended instructions. */
31
+export const isProviderCommand = (message: {
32
+ readonly text: string;
33
+ readonly attachments?: ReadonlyArray<unknown> | undefined;
34
+}): boolean =>
35
+ (message.attachments?.length ?? 0) === 0 &&
36
+ (["/compact", "/logout"].includes(message.text.trim().toLowerCase()) ||
37
+ parseGoalCommand(message) !== null);
38
+
39
+/** Why a message cannot be asked for a result under this schema, or null when it can. */
40
+export const outputRequestProblem = (
41
+ schema: OutputSchema,
42
+ message: { readonly text: string; readonly attachments?: ReadonlyArray<unknown> | undefined },
43
+): string | null =>
44
+ isProviderCommand(message)
45
+ ? "A command cannot be asked for a result. Ask for it in a message."
46
+ : outputSchemaProblem(schema);
47
+
48
+/** Appended to the turn's prompt: the agent learns the shape and how to hand the result back. */
49
+export const outputInstructions = (schema: OutputSchema): string =>
50
+ [
51
+ "A program reads the result of this turn, not a person.",
52
+ "When the work is done, call the `t3_submit_output` tool once with `json` set to JSON text matching this JSON Schema:",
53
+ JSON.stringify(schema),
54
+ "If you could not finish, still submit, with the fields that say so. A rejected submission names what did not fit: correct it and submit again.",
55
+ ].join("\n");
56
+
57
+/** Why a submission was turned down. What did not fit is in `cause`, never in the problem. */
58
+export interface OutputRejection {
59
+ readonly problem: string;
60
+ readonly cause?: unknown;
61
+}
62
+
63
+/**
64
+ * Checks what an agent submitted against the schema its run declared. The value is kept as
65
+ * submitted. A schema that closes its object turns down keys it does not name; an open one keeps
66
+ * them.
67
+ */
68
+export const checkOutput = Effect.fn("runOutput.checkOutput")(function* (
69
+ schema: OutputSchema,
70
+ json: string,
71
+) {
72
+ const parsed = Result.try(() => JSON.parse(json) as Schema.Json);
73
+ if (Result.isFailure(parsed)) {
74
+ return Result.fail<OutputRejection>({ problem: "`json` is not valid JSON text." });
75
+ }
76
+ const compiled = compile(schema);
77
+ if (Result.isFailure(compiled)) {
78
+ return Result.fail<OutputRejection>({
79
+ problem: "The output schema is not a usable JSON Schema.",
80
+ });
81
+ }
82
+ const outputSchema = compiled.success;
83
+ const decoded = yield* Schema.decodeEffect(outputSchema)(parsed.success, {
84
+ errors: "all",
85
+ onExcessProperty: "error",
86
+ }).pipe(Effect.result);
87
+ return Result.isFailure(decoded)
88
+ ? Result.fail<OutputRejection>({
89
+ problem: "The result does not match the schema.",
90
+ cause: decoded.failure,
91
+ })
92
+ : Result.succeed(parsed.success);
93
+});
apps/server/src/orchestration-v2/runtimeLayer.test.ts
+241
@@ -11658,6 +11658,247 @@ it.layer(layerSharedApplicationDataPlaneTest)("pending provider interruption", (
11658
);
11659
});
11660
11661
+it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => {
11662
+ it.effect("takes a result a completed turn still owes from the turn after it", () =>
11663
+ Effect.gen(function* () {
11664
+ const projects = yield* ProjectService.ProjectService;
11665
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
11666
+ const eventSink = yield* EventSink.EventSinkV2;
11667
+ const threadManagement = yield* ThreadManagementService.ThreadManagementService;
11668
+ const projectId = ProjectId.make("runtime-layer-owed-output-project");
11669
+ const threadId = ThreadId.make("runtime-layer-owed-output-thread");
11670
+ yield* projects.create({
11671
+ commandId: CommandId.make("runtime-layer-owed-output-project-create"),
11672
+ projectId,
11673
+ title: "Owed output project",
11674
+ workspaceRoot: "/tmp/runtime-layer-owed-output-project",
11675
+ });
11676
+ yield* orchestrator.dispatch({
11677
+ type: "thread.create",
11678
+ createdBy: "user",
11679
+ creationSource: "web",
11680
+ commandId: CommandId.make("runtime-layer-owed-output-create"),
11681
+ threadId,
11682
+ projectId,
11683
+ title: "Owed output",
11684
+ modelSelection,
11685
+ runtimeMode: "full-access",
11686
+ interactionMode: "default",
11687
+ branch: null,
11688
+ worktreePath: null,
11689
+ });
11690
+ const send = (key: string, outputSchema?: { readonly type: "object" }) =>
11691
+ orchestrator.dispatch({
11692
+ type: "message.dispatch",
11693
+ createdBy: "user",
11694
+ creationSource: "web",
11695
+ commandId: CommandId.make(`runtime-layer-owed-output-${key}`),
11696
+ threadId,
11697
+ messageId: MessageId.make(`runtime-layer-owed-output-${key}`),
11698
+ text: key,
11699
+ attachments: [],
11700
+ modelSelection,
11701
+ ...(outputSchema === undefined ? {} : { outputSchema }),
11702
+ dispatchMode: { type: "start_immediately" },
11703
+ });
11704
+ yield* send("asked", { type: "object" });
11705
+ const asked = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!;
11706
+ // The agent ended its turn to wait for something, without the result.
11707
+ yield* eventSink.write({
11708
+ events: [
11709
+ {
11710
+ id: EventId.make(`${threadId}-asked-completed`),
11711
+ type: "run.updated",
11712
+ threadId,
11713
+ runId: asked.id,
11714
+ occurredAt: asked.requestedAt,
11715
+ payload: { ...asked, status: "completed", completedAt: asked.requestedAt },
11716
+ },
11717
+ ],
11718
+ });
11719
+ yield* send("woken");
11720
+
11721
+ const accepted = yield* threadManagement.submitRunOutput({
11722
+ threadId,
11723
+ commandId: CommandId.make("runtime-layer-owed-output-submit"),
11724
+ json: '{"head":"abc"}',
11725
+ });
11726
+ assert.equal(accepted.runId, asked.id);
11727
+ const after = yield* orchestrator.getThreadProjection(threadId);
11728
+ assert.deepEqual(after.runs.find((run) => run.id === asked.id)?.output?.value, {
11729
+ head: "abc",
11730
+ });
11731
+ }),
11732
+ );
11733
+
11734
+ it.effect("turns down a provider command asked for a result", () =>
11735
+ Effect.gen(function* () {
11736
+ const projects = yield* ProjectService.ProjectService;
11737
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
11738
+ const projectId = ProjectId.make("runtime-layer-command-output-project");
11739
+ const threadId = ThreadId.make("runtime-layer-command-output-thread");
11740
+ yield* projects.create({
11741
+ commandId: CommandId.make("runtime-layer-command-output-project-create"),
11742
+ projectId,
11743
+ title: "Command output project",
11744
+ workspaceRoot: "/tmp/runtime-layer-command-output-project",
11745
+ });
11746
+ yield* orchestrator.dispatch({
11747
+ type: "thread.create",
11748
+ createdBy: "user",
11749
+ creationSource: "web",
11750
+ commandId: CommandId.make("runtime-layer-command-output-create"),
11751
+ threadId,
11752
+ projectId,
11753
+ title: "Command output",
11754
+ modelSelection,
11755
+ runtimeMode: "full-access",
11756
+ interactionMode: "default",
11757
+ branch: null,
11758
+ worktreePath: null,
11759
+ });
11760
+ const rejected = yield* orchestrator
11761
+ .dispatch({
11762
+ type: "message.dispatch",
11763
+ createdBy: "user",
11764
+ creationSource: "web",
11765
+ commandId: CommandId.make("runtime-layer-command-output-message"),
11766
+ threadId,
11767
+ messageId: MessageId.make("runtime-layer-command-output-message"),
11768
+ text: "/goal Review the changes",
11769
+ attachments: [],
11770
+ modelSelection,
11771
+ outputSchema: { type: "object" },
11772
+ dispatchMode: { type: "start_immediately" },
11773
+ })
11774
+ .pipe(Effect.flip);
11775
+ assert.include(String(rejected.cause), "cannot be asked for a result");
11776
+ assert.deepEqual((yield* orchestrator.getThreadProjection(threadId)).runs, []);
11777
+
11778
+ // Nor can a queued request for a result be edited into one.
11779
+ for (const [key, text, dispatchMode] of [
11780
+ ["active", "Start", { type: "start_immediately" }],
11781
+ ["queued", "Return a verdict.", { type: "queue_after_active" }],
11782
+ ] as const) {
11783
+ yield* orchestrator.dispatch({
11784
+ type: "message.dispatch",
11785
+ createdBy: "user",
11786
+ creationSource: "web",
11787
+ commandId: CommandId.make(`runtime-layer-command-output-${key}`),
11788
+ threadId,
11789
+ messageId: MessageId.make(`runtime-layer-command-output-${key}`),
11790
+ text,
11791
+ attachments: [],
11792
+ modelSelection,
11793
+ ...(key === "queued" ? { outputSchema: { type: "object" } } : {}),
11794
+ dispatchMode,
11795
+ });
11796
+ }
11797
+ const queued = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
11798
+ (run) => run.status === "queued",
11799
+ )!;
11800
+ const edit = (key: string, text: string) =>
11801
+ orchestrator.dispatch({
11802
+ type: "queued-run.edit",
11803
+ commandId: CommandId.make(`runtime-layer-command-output-edit-${key}`),
11804
+ threadId,
11805
+ runId: queued.id,
11806
+ text,
11807
+ });
11808
+ const refused = yield* edit("goal", "/goal Review the changes").pipe(Effect.flip);
11809
+ assert.include(String(refused.cause), "cannot be asked for a result");
11810
+ yield* edit("prompt", "Return a verdict, briefly.");
11811
+ }),
11812
+ );
11813
+
11814
+ it.effect("turns down a result submitted after a stop was requested", () =>
11815
+ Effect.gen(function* () {
11816
+ const projects = yield* ProjectService.ProjectService;
11817
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
11818
+ const eventSink = yield* EventSink.EventSinkV2;
11819
+ const threadManagement = yield* ThreadManagementService.ThreadManagementService;
11820
+ const projectId = ProjectId.make("runtime-layer-stopped-output-project");
11821
+ const threadId = ThreadId.make("runtime-layer-stopped-output-thread");
11822
+ yield* projects.create({
11823
+ commandId: CommandId.make("runtime-layer-stopped-output-project-create"),
11824
+ projectId,
11825
+ title: "Stopped output project",
11826
+ workspaceRoot: "/tmp/runtime-layer-stopped-output-project",
11827
+ });
11828
+ yield* orchestrator.dispatch({
11829
+ type: "thread.create",
11830
+ createdBy: "user",
11831
+ creationSource: "web",
11832
+ commandId: CommandId.make("runtime-layer-stopped-output-create"),
11833
+ threadId,
11834
+ projectId,
11835
+ title: "Stopped output",
11836
+ modelSelection,
11837
+ runtimeMode: "full-access",
11838
+ interactionMode: "default",
11839
+ branch: null,
11840
+ worktreePath: null,
11841
+ });
11842
+ yield* orchestrator.dispatch({
11843
+ type: "message.dispatch",
11844
+ createdBy: "user",
11845
+ creationSource: "web",
11846
+ commandId: CommandId.make("runtime-layer-stopped-output-message"),
11847
+ threadId,
11848
+ messageId: MessageId.make("runtime-layer-stopped-output-message"),
11849
+ text: "Return a verdict.",
11850
+ attachments: [],
11851
+ modelSelection,
11852
+ outputSchema: { type: "object" },
11853
+ dispatchMode: { type: "start_immediately" },
11854
+ });
11855
+ const run = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!;
11856
+ // The stop is asked for while the provider has not settled it, so the run is still active.
11857
+ const at = run.requestedAt;
11858
+ yield* eventSink.write({
11859
+ events: [
11860
+ {
11861
+ id: EventId.make(`${threadId}-interrupt-request`),
11862
+ type: "turn-item.updated",
11863
+ threadId,
11864
+ runId: run.id,
11865
+ occurredAt: at,
11866
+ payload: {
11867
+ id: TurnItemId.make(`${threadId}-interrupt-request`),
11868
+ type: "run_interrupt_request",
11869
+ threadId,
11870
+ runId: run.id,
11871
+ nodeId: run.rootNodeId,
11872
+ providerThreadId: null,
11873
+ providerTurnId: null,
11874
+ nativeItemRef: null,
11875
+ parentItemId: null,
11876
+ ordinal: 90,
11877
+ status: "completed",
11878
+ title: "Interrupt requested",
11879
+ startedAt: at,
11880
+ completedAt: at,
11881
+ updatedAt: at,
11882
+ message: "Stopped by user",
11883
+ },
11884
+ },
11885
+ ],
11886
+ });
11887
+
11888
+ const rejected = yield* threadManagement
11889
+ .submitRunOutput({
11890
+ threadId,
11891
+ commandId: CommandId.make("runtime-layer-stopped-output-submit"),
11892
+ json: "{}",
11893
+ })
11894
+ .pipe(Effect.flip);
11895
+ assert.include(String((rejected as { cause?: unknown }).cause), "was stopped");
11896
+ const after = yield* orchestrator.getThreadProjection(threadId);
11897
+ assert.isUndefined(after.runs[0]?.output);
11898
+ }),
11899
+ );
11900
+});
11901
+
11902
it.layer(layerTest)("snooze queued runs", (it) => {
11903
it.effect.each(["notification", "delegated-completion", "user", "limited-user"] as const)(
11904
"only user messages block snooze with a queued %s run, unless a usage limit holds them",
apps/server/src/provider/agentContextBudget.json
+1
-1
@@ -1,5 +1,5 @@
1
{
2
"claudeSystemAppendBytes": 6245,
3
"codexAdditionalContextBytes": 7639,
4
- "mcpToolListJsonBytes": 57696
4
+ "mcpToolListJsonBytes": 58406
5
}
apps/server/src/relay/AgentAwarenessRelay.test.ts
+1
@@ -250,6 +250,7 @@ const makeTestRelay = Effect.fnUntraced(function* (
250
getProjectThreadRecords: () => Effect.die("unused project record read"),
251
listProjectThreads: unused,
252
sendToThread: unused,
253
+ submitRunOutput: unused,
254
assertProviderInstanceEnabled: unused,
255
isProviderInstanceEnabledForProject: unused,
256
hasReceipt: unused,
apps/server/src/relay/AgentAwarenessRelay.ts
+1
@@ -124,6 +124,7 @@ function shouldPublishAgentAwarenessEvent(
124
case "thread.runtime-mode-updated":
125
case "thread.interaction-mode-updated":
126
case "run.background-work-cancelled":
127
+ case "run.output-submitted":
128
case "run-attempt.created":
129
case "run-attempt.updated":
130
case "node.updated":
docs/orchestration-v2/orchestrator-mcp-server.md
+19
-1
@@ -454,12 +454,30 @@ The target runtime and interaction modes may not be broader than the caller's.
454
Stable command and message IDs are derived from `clientRequestId` for
455
idempotent retries.
456
457
+`outputSchema` (also on `t3_thread_launch`) asks the run for a result as data.
458
+The run stores the schema, the turn's prompt ends with how to hand the result
459
+back, and the agent calls `t3_submit_output`. The server checks the value
460
+against the schema before storing it, so the caller never parses a reply. A send
461
+that asks for a result is queued instead of steered: the result belongs to one
462
+whole turn. A turn can end without submitting; the caller sees a finished run
463
+with no `output`.
464
+
465
+### `t3_submit_output`
466
+
467
+Stores the calling thread's result on its running turn, once it fits the schema
468
+that turn was sent with. A turn that was asked for nothing answers for the
469
+newest turn that was asked and has not answered yet, which is how an agent that
470
+ended its turn to wait gives its result after it is woken. A rejection names what did not fit, so the agent can
471
+correct it and call again; a later accepted submission replaces an earlier one.
472
+
473
### `t3_thread_wait`
474
475
Waits for a selected run to become `completed`, `failed`, `cancelled`,
476
`interrupted`, or `rolled_back`. Without `runId`, it pins the latest run at call
477
time; an idle thread returns immediately. A timeout reports the latest durable
462
-status and does not cancel work.
478
+status and does not cancel work. `output` carries what the run submitted
479
+against its `outputSchema`; with `untilOutput`, a completed run that has not
480
+submitted yet is waited on until it has.
481
482
### `t3_thread_interrupt`
483
packages/client-runtime/src/state/orchestrationV2Projection.ts
+16
-4
@@ -333,11 +333,16 @@ export function applyOrchestrationV2ProjectionEvent(
333
};
334
case "run.created":
335
case "run.updated": {
336
- const next = { ...base, runs: upsertEntity(base.runs, event.payload) };
336
+ // Lifecycle updates carry the run as it was when the turn started. What the run returned
337
+ // is written by its own event, and an update without it must not take it away.
338
+ const known = base.runs.find((run) => run.id === event.payload.id);
339
+ const run =
340
+ event.payload.output === undefined && known?.output !== undefined
341
+ ? { ...event.payload, output: known.output }
342
+ : event.payload;
343
+ const next = { ...base, runs: upsertEntity(base.runs, run) };
344
const visible = { ...next, visibleTurnItems: activeVisibleTurnItems(next) };
338
- const wasQueued = base.runs.some(
339
- (run) => run.id === event.payload.id && run.status === "queued",
340
- );
345
+ const wasQueued = known?.status === "queued";
346
return wasQueued && event.payload.status !== "queued"
347
? { ...visible, visibleTurnItems: restoreQueuedUserItems(visible, event.payload.id) }
348
: visible;
@@ -354,6 +359,13 @@ export function applyOrchestrationV2ProjectionEvent(
359
: run,
360
),
361
};
362
+ case "run.output-submitted":
363
+ return {
364
+ ...base,
365
+ runs: base.runs.map((run) =>
366
+ run.id === event.payload.runId ? { ...run, output: event.payload.output } : run,
367
+ ),
368
+ };
369
case "run-attempt.created":
370
case "run-attempt.updated": {
371
const next = { ...base, attempts: upsertEntity(base.attempts, event.payload) };
packages/contracts/src/orchestrationV2.ts
+42
@@ -765,6 +765,14 @@ export type OrchestrationV2ThreadLaunchWorkspaceStrategy =
765
766
export const ORCHESTRATION_V2_WORKSPACE_PREPARATION_FAILURE_CODE = "workspace_preparation_failed";
767
768
+/** What a run returned as data: a value the server accepted against the run's `outputSchema`. */
769
+export const OrchestrationV2RunOutput = Schema.Struct({
770
+ value: Schema.Json,
771
+ // A string, not a DateTime: the run's JSON form only converts its own top-level dates.
772
+ submittedAt: IsoDateTime,
773
+});
774
+export type OrchestrationV2RunOutput = typeof OrchestrationV2RunOutput.Type;
775
+
776
export const OrchestrationV2Run = Schema.Struct({
777
id: RunId,
778
threadId: ThreadId,
@@ -802,9 +810,22 @@ export const OrchestrationV2Run = Schema.Struct({
810
workspacePreparation: Schema.optional(OrchestrationV2ThreadLaunchWorkspaceStrategy),
811
/** Starts a new provider conversation; earlier runs stay visible but never reach the provider. */
812
freshContext: Schema.optional(Schema.Boolean),
813
+ /** The JSON Schema of the result this run was asked to return as data. */
814
+ outputSchema: Schema.optional(Schema.Record(Schema.String, Schema.Json)),
815
+ /**
816
+ * Its own field, written by its own event: lifecycle writers hold a copy of the run from when
817
+ * the turn started, and their updates must not put an unanswered run back.
818
+ */
819
+ output: Schema.optional(OrchestrationV2RunOutput),
820
});
821
export type OrchestrationV2Run = typeof OrchestrationV2Run.Type;
822
823
+export const OrchestrationV2RunOutputSubmitted = Schema.Struct({
824
+ runId: RunId,
825
+ output: OrchestrationV2RunOutput,
826
+});
827
+export type OrchestrationV2RunOutputSubmitted = typeof OrchestrationV2RunOutputSubmitted.Type;
828
+
829
export function orchestrationV2RunWorkStartedAt(
830
run: Pick<OrchestrationV2Run, "workStartedAt" | "startedAt" | "requestedAt">,
831
): OrchestrationV2Run["requestedAt"] {
@@ -2094,6 +2115,11 @@ export const OrchestrationV2DomainEvent = Schema.Union([
2115
type: Schema.Literal("run.background-work-cancelled"),
2116
payload: OrchestrationV2RunBackgroundWorkCancelled,
2117
}),
2118
+ Schema.Struct({
2119
+ ...OrchestrationV2EventBase.fields,
2120
+ type: Schema.Literal("run.output-submitted"),
2121
+ payload: OrchestrationV2RunOutputSubmitted,
2122
+ }),
2123
Schema.Struct({
2124
...OrchestrationV2EventBase.fields,
2125
type: Schema.Literal("run-attempt.created"),
@@ -3041,6 +3067,11 @@ export const OrchestrationV2DomainEventJson = Schema.Union([
3067
type: Schema.Literal("run.background-work-cancelled"),
3068
payload: OrchestrationV2RunBackgroundWorkCancelled,
3069
}),
3070
+ Schema.Struct({
3071
+ ...OrchestrationV2JsonEventBaseFields,
3072
+ type: Schema.Literal("run.output-submitted"),
3073
+ payload: OrchestrationV2RunOutputSubmitted,
3074
+ }),
3075
Schema.Struct({
3076
...OrchestrationV2JsonEventBaseFields,
3077
type: Schema.Literal("run-attempt.created"),
@@ -3185,6 +3216,7 @@ export const OrchestrationV2Command = Schema.Union([
3216
titleSeed: Schema.optional(TrimmedNonEmptyString),
3217
scheduledTaskId: Schema.optional(ScheduledTaskId),
3218
senderThreadId: Schema.optional(ThreadId),
3219
+ outputSchema: Schema.optional(Schema.Record(Schema.String, Schema.Json)),
3220
workspaceStrategy: Schema.optional(OrchestrationV2ThreadLaunchWorkspaceStrategy),
3221
}),
3222
),
@@ -3440,6 +3472,8 @@ export const OrchestrationV2Command = Schema.Union([
3472
idleCompaction: Schema.optional(OrchestrationV2IdleCompaction),
3473
/** Start a new provider session without the thread's earlier context. Never steers. */
3474
freshContext: Schema.optional(Schema.Boolean),
3475
+ /** Asks the run for a result as data matching this JSON Schema. Never steers. */
3476
+ outputSchema: Schema.optional(Schema.Record(Schema.String, Schema.Json)),
3477
commandId: CommandId,
3478
threadId: ThreadId,
3479
messageId: MessageId,
@@ -3664,6 +3698,14 @@ export type OrchestrationV2Command = typeof OrchestrationV2Command.Type;
3698
3699
// Excluded from dispatchCommand so only the server can send these.
3700
const OrchestrationV2InternalCommand = Schema.Union([
3701
+ // The server issues this after checking the value against the run's declared schema.
3702
+ Schema.Struct({
3703
+ type: Schema.Literal("run.output.submit"),
3704
+ commandId: CommandId,
3705
+ threadId: ThreadId,
3706
+ runId: RunId,
3707
+ value: Schema.Json,
3708
+ }),
3709
// Guest share commands the server issues after checking T3 Connect and the guest token.
3710
Schema.Struct({
3711
type: Schema.Literal("thread.guest-share.open"),
packages/contracts/src/orchestratorMcp.ts
+14
@@ -561,6 +561,12 @@ export const OrchestratorMcpThreadSendInput = Schema.Struct({
561
"Start a new provider session without the thread's earlier context, like /clear. Never steers.",
562
}),
563
),
564
+ outputSchema: Schema.optional(
565
+ Schema.Record(Schema.String, Schema.Json).annotate({
566
+ description:
567
+ "JSON Schema for a result the turn must return as data, read back as `output` from `t3_thread_wait`. Never steers.",
568
+ }),
569
+ ),
570
clientRequestId: Schema.optional(OrchestratorMcpClientRequestId),
571
});
572
export type OrchestratorMcpThreadSendInput = typeof OrchestratorMcpThreadSendInput.Type;
@@ -587,6 +593,12 @@ export const OrchestratorMcpThreadWaitInput = Schema.Struct({
593
"Also wait for its delegated and background tasks and their completions to settle. `resultRun` then names the run with its final answer.",
594
}),
595
),
596
+ untilOutput: Schema.optional(
597
+ Schema.Boolean.annotate({
598
+ description:
599
+ "Also wait for the `output` the run was asked for, which a later turn may submit.",
600
+ }),
601
+ ),
602
});
603
export type OrchestratorMcpThreadWaitInput = typeof OrchestratorMcpThreadWaitInput.Type;
604
@@ -598,6 +610,8 @@ export const OrchestratorMcpThreadWaitResult = Schema.Struct({
610
next: Schema.optional(OrchestratorMcpRunningTaskNext),
611
/** With untilDelegatedWorkSettled, once settled: the run whose reply is the thread's result. */
612
resultRun: Schema.optional(Schema.Struct({ runId: RunId, status: OrchestrationV2RunStatus })),
613
+ /** What the run returned against the `outputSchema` it was sent with. Absent until submitted. */
614
+ output: Schema.optional(Schema.Json),
615
});
616
export type OrchestratorMcpThreadWaitResult = typeof OrchestratorMcpThreadWaitResult.Type;
617
packages/shared/src/t3McpToolPresentation.ts
+1
@@ -359,6 +359,7 @@ const T3_MCP_TOOLS: Readonly<Record<string, T3McpToolDefinition>> = {
359
["Handle", "Handling", "Handled", "pending questions"],
360
"question-respond",
361
),
362
+ t3_submit_output: tool(["Submit", "Submitting", "Submitted", "the result"], "thread-send"),
363
t3_queue_list: tool(["List", "Listing", "Listed", "queued messages"], "queue-list"),
364
t3_queue_read: tool(["Read", "Reading", "Read", "a queued message"], "queue-read"),
365
t3_queue_edit: tool(["Edit", "Editing", "Edited", "a queued message"], "queue-edit"),