GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat(server): a thread turn can return a typed result (#38874) · pingdotgg/t3code@2770bf3

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • apps/server/src
    • cli
      • thread.ts
    • mcp
      • OrchestratorMcpService.ts
      • toolkits
        • project
          • handlers.ts
          • tools.ts
        • thread
          • handlers.ts
          • tools.ts
    • orchestration-v2
      • Adapters
        • ClaudeAdapterV2.ts
      • Orchestrator.ts
      • ProjectionStore.test.ts
      • ProjectionStore.ts
      • ProviderTurnStartService.ts
      • ThreadLaunchService.test.ts
      • ThreadLaunchService.ts
      • ThreadManagementService.ts
      • runOutput.test.ts
      • runOutput.ts
      • runtimeLayer.test.ts
    • provider
      • agentContextBudget.json
    • relay
      • AgentAwarenessRelay.test.ts
      • AgentAwarenessRelay.ts
  • docs/orchestration-v2
    • orchestrator-mcp-server.md
  • packages
    • client-runtime/src/state
      • orchestrationV2Projection.ts
    • contracts/src
      • orchestrationV2.ts
      • orchestratorMcp.ts
    • shared/src
      • t3McpToolPresentation.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎apps/server/src/cli/thread.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/cli/thread.ts
+48-4Lines changed: 48 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -528,6 +528,7 @@ type WaitOutcome =
528528
readonly type: "ended";
529529
readonly runId: RunId | null;
530530
readonly status: OrchestratorMcpThreadStatus;
531+
readonly output?: Schema.Json;
531532
}
532533
| { readonly type: "needs_input" };
533534

@@ -598,7 +599,12 @@ export const waitForRun = Effect.fn("cli.thread.waitForRun")(function* (
598599
OrchestratorMcpThreadWaitResult,
599600
);
600601
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;
602608
const ownRun = Effect.gen(function* () {
603609
while (true) {
604610
const waited = yield* waitSlice(WAIT_SLICE_MS);
@@ -641,7 +647,13 @@ export const waitForRun = Effect.fn("cli.thread.waitForRun")(function* (
641647
if (after.sent) return outcome;
642648
if (!waited.timedOut) {
643649
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;
645657
}
646658
if (!workOutlivedRun) return outcome;
647659
if (after.later.some((run) => !TERMINAL_RUN_STATUSES.has(run.status))) continue;
@@ -684,7 +696,15 @@ const finishRun = Effect.fn("cli.thread.finishRun")(function* (
684696
? null
685697
: yield* runResultText(tools, input.threadId, runId, "error");
686698
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+
});
688708
} else if (reply !== null) {
689709
yield* Console.log(reply);
690710
}
@@ -778,6 +798,25 @@ const waitFlag = Flag.Boolean("wait").pipe(
778798
),
779799
Flag.withDefault(false),
780800
);
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+
});
781820
const messageArgument = Argument.String("message").pipe(
782821
Argument.withDescription("Message for the agent, or - to read it from stdin."),
783822
);
@@ -860,13 +899,15 @@ const threadStartCommand = Command.make("start", {
860899
Flag.withDescription("Branch name for the new worktree."),
861900
Flag.optional,
862901
),
902+
outputSchema: outputSchemaFlag,
863903
wait: waitFlag,
864904
json: jsonFlag,
865905
}).pipe(
866906
Command.withDescription("Start a thread in a project and print its id."),
867907
Command.withHandler((flags) =>
868908
Effect.gen(function* () {
869909
const message = yield* readMessageArgument(flags.message);
910+
const output = yield* readOutputSchema(flags.outputSchema);
870911
const workspaceStrategy = yield* launchWorkspaceStrategy(flags);
871912
const modelSelection = yield* launchModelSelection(flags);
872913
const title = yield* decodeTitle(
@@ -882,6 +923,7 @@ const threadStartCommand = Command.make("start", {
882923
projectId: project.id,
883924
title,
884925
message,
926+
...output,
885927
...(workspaceStrategy === undefined ? {} : { workspaceStrategy }),
886928
...(modelSelection === undefined ? {} : { modelSelection }),
887929
},
@@ -907,6 +949,7 @@ const threadSendCommand = Command.make("send", {
907949
...projectLocationFlags,
908950
thread: threadArgument,
909951
message: messageArgument,
952+
outputSchema: outputSchemaFlag,
910953
wait: waitFlag,
911954
json: jsonFlag,
912955
}).pipe(
@@ -917,14 +960,15 @@ const threadSendCommand = Command.make("send", {
917960
Effect.gen(function* () {
918961
const threadId = yield* decodeThreadId(flags.thread);
919962
const message = yield* readMessageArgument(flags.message);
963+
const output = yield* readOutputSchema(flags.outputSchema);
920964
yield* withThreadTools(
921965
flags,
922966
Effect.fn("cli.thread.send")(function* (tools) {
923967
// Work already running when this is sent is not this message's to wait for.
924968
const followWakes = flags.wait ? yield* threadIsIdle(tools, threadId) : false;
925969
const sent = yield* tools.call(
926970
"t3_thread_send",
927-
{ threadId, message, mode: "queue" },
971+
{ threadId, message, mode: "queue", ...output },
928972
OrchestratorMcpThreadSendResult,
929973
);
930974
if (flags.wait) {
Collapse file

‎apps/server/src/mcp/OrchestratorMcpService.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/mcp/OrchestratorMcpService.ts
+5Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,8 @@ export function threadManagementFailure(error: unknown): OrchestratorMcpFailure
261261
"thread_not_sendable",
262262
`${error.message} Send with mode: "auto" or "queue" to start a new turn there.`,
263263
);
264+
case "ThreadManagementRunOutputRejectedError":
265+
return failure("invalid_request", error.message);
264266
case "ThreadManagementThreadNotInterruptibleError":
265267
return failure("thread_not_interruptible", error.message);
266268
case "ThreadManagementProjectionLoadError":
@@ -3656,6 +3658,7 @@ const make = Effect.gen(function* () {
36563658
attachments: [],
36573659
mode,
36583660
...(input.freshContext ? { freshContext: true } : {}),
3661+
...(input.outputSchema === undefined ? {} : { outputSchema: input.outputSchema }),
36593662
createdBy: "agent",
36603663
creationSource: "mcp",
36613664
})
@@ -3691,6 +3694,7 @@ const make = Effect.gen(function* () {
36913694
Math.max(1, input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS),
36923695
),
36933696
...(input.untilDelegatedWorkSettled === true ? { untilDelegatedWorkSettled: true } : {}),
3697+
...(input.untilOutput === true ? { untilOutput: true } : {}),
36943698
})
36953699
.pipe(Effect.mapError(threadManagementFailure));
36963700
const status = result.run === null ? "idle" : runOutcome(result.run);
@@ -3727,6 +3731,7 @@ const make = Effect.gen(function* () {
37273731
: {
37283732
resultRun: { runId: result.resultRun.id, status: runOutcome(result.resultRun) },
37293733
}),
3734+
...(result.run?.output === undefined ? {} : { output: result.run.output.value }),
37303735
} satisfies OrchestratorMcpThreadWaitResult;
37313736
}),
37323737
interruptThread: Effect.fn("OrchestratorMcpService.interruptThread")(function* (scope, input) {
Collapse file

‎apps/server/src/mcp/toolkits/project/handlers.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/mcp/toolkits/project/handlers.ts
+14Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import * as FileSystem from "effect/FileSystem";
1616
import * as Option from "effect/Option";
1717
import * as Schema from "effect/Schema";
1818
import { OrchestratorRuntimeModeAboveCeilingError } from "../../../orchestration-v2/Orchestrator.ts";
19+
import { outputRequestProblem } from "../../../orchestration-v2/runOutput.ts";
1920
import * as ThreadLaunch from "../../../orchestration-v2/ThreadLaunchService.ts";
2021
import * as ThreadMessageIntake from "../../../orchestration-v2/ThreadMessageIntake.ts";
2122
import * as Claims from "../../../orchestration-v2/AttachmentClaims.ts";
@@ -224,6 +225,18 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
224225
const threadId = ThreadId.make(commandId);
225226
const messageId = MessageId.make(commandId);
226227
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+
});
227240
if (attachments.some((attachment) => !Claims.attachmentIsPendingUpload(attachment)))
228241
return yield* new OrchestratorMcpFailure({
229242
code: "invalid_request",
@@ -427,6 +440,7 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
427440
...(caller === undefined ? {} : { senderThreadId: caller.id }),
428441
text: input.message ?? "",
429442
attachments,
443+
...(input.outputSchema === undefined ? {} : { outputSchema: input.outputSchema }),
430444
},
431445
}),
432446
createdBy: "agent",
Collapse file

‎apps/server/src/mcp/toolkits/project/tools.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/mcp/toolkits/project/tools.ts
+5Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,11 @@ const ThreadLaunchTool = Tool.make("t3_thread_launch", {
156156
}),
157157
),
158158
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+
),
159164
clientRequestId: Schema.optional(OrchestratorMcpClientRequestId),
160165
/** Set by a linked environment launching its agent's delegated task here; ignored otherwise. */
161166
delegatedFrom: Schema.optional(OrchestrationV2DelegatedFrom),
Collapse file

‎apps/server/src/mcp/toolkits/thread/handlers.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/mcp/toolkits/thread/handlers.ts
+26Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -283,6 +283,32 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, {
283283
}),
284284
),
285285
),
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+
),
286312
t3_queue: McpToolAccess.either(
287313
(input) => input.action === "list" || input.action === "read",
288314
McpToolAccess.reads((input) =>
Collapse file

‎apps/server/src/mcp/toolkits/thread/tools.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/mcp/toolkits/thread/tools.ts
+15-1Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ import {
2323
} from "@t3tools/contracts";
2424
import * as SecureRandom from "effect/crypto/SecureRandom";
2525
import * as Schema from "effect/Schema";
26-
import { Tool, Toolkit } from "effect/ai";
26+
import { McpSchema, Tool, Toolkit } from "effect/ai";
2727

2828
import * as ThreadSearch from "../../../orchestration-v2/ThreadSearch.ts";
2929
import * as ScheduledTaskService from "../../../scheduledTasks/ScheduledTaskService.ts";
@@ -241,6 +241,19 @@ const ScheduledTaskRunTool = Tool.make("run_scheduled_task_now", {
241241
.annotate(Tool.Destructive, true)
242242
.annotate(Tool.OpenWorld, true);
243243

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+
244257
export const ThreadToolkit = Toolkit.make(
245258
ScheduledTaskRunTool,
246259
ThreadSearchTool,
@@ -249,4 +262,5 @@ export const ThreadToolkit = Toolkit.make(
249262
ThreadOrganizeTool,
250263
PendingRequestTool,
251264
QueueTool,
265+
SubmitOutputTool,
252266
);
Collapse file

‎apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+1Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2537,6 +2537,7 @@ export const CLAUDE_READ_ONLY_T3_MCP_ALLOWED_TOOLS: ReadonlyArray<string> = [
25372537
"mcp__t3-code__html_preview",
25382538
"mcp__t3-code__html_render",
25392539
"mcp__t3-code__send_to_user",
2540+
"mcp__t3-code__t3_submit_output",
25402541
];
25412542

25422543
// request_secret can wait an hour; exceed Claude's default 60 s timeout.

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.