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

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

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

Synced Nov 21, 06:00 UTC

fix(server): agents can tell another agent's message from the user's (#39306)

Co-authored-by: Julius Marminge <julius0216@outlook.com>

Bilal Bakr committed Nov 20, 2026 at 00:33 UTC b0b2c4f952d3a12a886e915ad8ffe7e82ebc1fb4
8 files changed +133 -18
apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts
+8 -3
@@ -379,7 +379,7 @@ it.effect(
379 }),
380 );
381
382 -it.effect("steers a running turn with the thread's MCP app model context", () =>
382 +it.effect("steers a running turn with its sender and the thread's MCP app model context", () =>
383 Effect.gen(function* () {
384 const now = yield* DateTime.now;
385 const threadId = ThreadId.make("thread:steer-app-context");
@@ -413,8 +413,9 @@ it.effect("steers a running turn with the thread's MCP app model context", () =>
413 id: MessageId.make("message:steer-app-context"),
414 text: "What did the app report?",
415 attachments: [],
416 - createdBy: "user",
417 - creationSource: "web",
416 + createdBy: "agent",
417 + creationSource: "mcp",
418 + senderThreadId: ThreadId.make("thread:steer-sender"),
419 } as unknown as NonNullable<
420 ProjectionStore.ProjectionProviderControlContext["message"]
421 >,
@@ -454,6 +455,10 @@ it.effect("steers a running turn with the thread's MCP app model context", () =>
455 }).pipe(Effect.provide(layerControl));
456
457 assert.equal(steered.length, 1);
458 + assert.equal(
459 + steered[0]!.message.text,
460 + '[T3 Code: the agent in T3 thread "thread:steer-sender" sent this message, not the user.]\n\nWhat did the app report?',
461 + );
462 assert.deepEqual("appContext" in steered[0]! ? steered[0].appContext : undefined, [
463 { key: "mcp_app_turn-item_call-1", text: "Pressed: blue" },
464 ]);
apps/server/src/orchestration-v2/ProviderTurnControlService.ts
+8 -4
@@ -8,6 +8,7 @@ import {
8 ProviderTurnId,
9 RunAttemptId,
10 ThreadId,
11 + withMessageSenderNote,
12 } from "@t3tools/contracts";
13 import type * as DateTime from "effect/DateTime";
14 import * as Context from "effect/Context";
@@ -463,10 +464,13 @@ export const layer: Layer.Layer<
464 ...(appContext.length === 0 ? {} : { appContext }),
465 message: {
466 messageId: message.id,
466 - text: projectComposerContextForProvider({
467 - text: message.text,
468 - records: message.context?.records ?? [],
469 - }),
467 + text: withMessageSenderNote(
468 + message,
469 + projectComposerContextForProvider({
470 + text: message.text,
471 + records: message.context?.records ?? [],
472 + }),
473 + ),
474 attachments: message.attachments,
475 createdBy: message.createdBy,
476 creationSource: message.creationSource,
apps/server/src/orchestration-v2/ProviderTurnStartService.ts
+8 -4
@@ -5,6 +5,7 @@ import {
5 CommandId,
6 PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
7 latestProviderTurnForAttempt,
8 + withMessageSenderNote,
9 type OrchestrationV2DomainEvent,
10 type OrchestrationV2ContextHandoff,
11 type OrchestrationV2ExecutionNode,
@@ -985,10 +986,13 @@ export const layer: Layer.Layer<
986 });
987 let effectiveHandoffs = handoffs;
988 let resumeFellBack = false;
988 - const userText = projectComposerContextForProvider({
989 - text: providerMessage.text,
990 - records: providerMessage.context?.records ?? [],
991 - });
989 + const userText = withMessageSenderNote(
990 + providerMessage,
991 + projectComposerContextForProvider({
992 + text: providerMessage.text,
993 + records: providerMessage.context?.records ?? [],
994 + }),
995 + );
996 // Native goal commands go verbatim; handoff history waits a turn.
997 const goalDriver =
998 session.driver === "codex" ||
apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts
+16 -3
@@ -2427,7 +2427,9 @@ it.effect("steers a promoted scheduled delivery with the thread's current select
2427 yield* worker.drain();
2428
2429 const projection = yield* orchestrator.getThreadProjection(threadId);
2430 - assert.deepEqual(steered, ["scheduled"]);
2430 + assert.deepEqual(steered, [
2431 + '[T3 Code: scheduled task "task:scheduled" sent this prompt, not the user typing in this chat.]\n\nscheduled',
2432 + ]);
2433 assert.deepEqual(projection.thread.modelSelection, composerSelection);
2434 }).pipe(Effect.provide(layer));
2435 }),
@@ -3180,7 +3182,16 @@ it.effect("starts a restart that stops the running turn ahead of an older held q
3182 const { queue, started: startedTexts } = yield* read(threadId);
3183 assert.deepEqual(
3184 { queue, started: startedTexts },
3183 - { queue: ["queued"], started: ["first", "second", "do this instead"] },
3185 + {
3186 + queue: ["queued"],
3187 + started: [
3188 + "first",
3189 + ...["second", "do this instead"].map(
3190 + (text) =>
3191 + `[T3 Code: this message came through T3 Code's tools, not from the user typing in this chat.]\n\n${text}`,
3192 + ),
3193 + ],
3194 + },
3195 );
3196 }).pipe(Effect.provide(layer));
3197 }),
@@ -3300,7 +3311,9 @@ it.effect("replays an accepted steer after its target turn completes", () =>
3311 .pipe(Effect.flip);
3312 assert.equal(fresh._tag, "ThreadManagementNoSteerableRunError");
3313 yield* worker.drain();
3303 - assert.deepEqual(steered, [input.text]);
3314 + assert.deepEqual(steered, [
3315 + `[T3 Code: this message came through T3 Code's tools, not from the user typing in this chat.]\n\n${input.text}`,
3316 + ]);
3317 assert.lengthOf(started, 1);
3318 }).pipe(
3319 Effect.provide(
apps/server/src/orchestration-v2/testkit/fixtures/delegated_task_status/codex_transcript.ndjson
+3 -3
@@ -21,7 +21,7 @@
21 {"type":"emit_inbound","label":"thread/name/updated","frame":{"method":"thread/name/updated","params":{"threadId":"019f1000-0000-7000-8000-000000000003","threadName":"Replay fixture: delegated_task_status"}}}
22 {"type":"expect_outbound","label":"config/read","frame":{"id":8,"method":"config/read","params":{"cwd":"<workspace>","includeLayers":false}}}
23 {"type":"emit_inbound","label":"config/read","frame":{"id":8,"result":{"config":{},"origins":{}}}}
24 -{"type":"expect_outbound","label":"child.original.turn/start","frame":{"id":9,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"<workspace>","input":[{"text":"Inspect the delegated API boundary and return the result.","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019f1000-0000-7000-8000-000000000003","approvalsReviewer":"user","summary":"auto","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.4"}}}}}
24 +{"type":"expect_outbound","label":"child.original.turn/start","frame":{"id":9,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"<workspace>","input":[{"text":"[T3 Code: the agent in T3 thread \"thread:mcp-orchestrator-parent\" sent this message, not the user.]\n\nInspect the delegated API boundary and return the result.","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019f1000-0000-7000-8000-000000000003","approvalsReviewer":"user","summary":"auto","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.4"}}}}}
25 {"type":"emit_inbound","label":"child.thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"019f1000-0000-7000-8000-000000000003","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776739468,"updatedAt":1776739468,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/delegated-task-status-child.jsonl","cwd":"/home/replay-user/t3code","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]}}}}
26 {"type":"emit_inbound","label":"child.original.turn/start","frame":{"id":9,"result":{"turn":{"id":"019f1000-0000-7000-8000-000000000004","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}}
27 {"type":"emit_inbound","label":"child.original.thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019f1000-0000-7000-8000-000000000003","status":{"type":"active","activeFlags":[]}}}}
@@ -33,7 +33,7 @@
33 {"type":"emit_inbound","label":"child.original.turn/completed","frame":{"method":"turn/completed","params":{"threadId":"019f1000-0000-7000-8000-000000000003","turn":{"id":"019f1000-0000-7000-8000-000000000004","items":[],"status":"completed","error":null,"startedAt":1776739468,"completedAt":1776739469,"durationMs":1000}}}}
34 {"type":"expect_outbound","label":"config/read","frame":{"id":10,"method":"config/read","params":{"cwd":"<workspace>","includeLayers":false}}}
35 {"type":"emit_inbound","label":"config/read","frame":{"id":10,"result":{"config":{},"origins":{}}}}
36 -{"type":"expect_outbound","label":"child.running.turn/start","frame":{"id":11,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"<workspace>","input":[{"text":"Remain active until the parent cancels this delegated task.","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019f1000-0000-7000-8000-000000000003","approvalsReviewer":"user","summary":"auto","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.4"}}}}}
36 +{"type":"expect_outbound","label":"child.running.turn/start","frame":{"id":11,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"<workspace>","input":[{"text":"[T3 Code: the agent in T3 thread \"thread:mcp-orchestrator-parent\" sent this message, not the user.]\n\nRemain active until the parent cancels this delegated task.","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019f1000-0000-7000-8000-000000000003","approvalsReviewer":"user","summary":"auto","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.4"}}}}}
37 {"type":"emit_inbound","label":"child.running.turn/start","frame":{"id":11,"result":{"turn":{"id":"019f1000-0000-7000-8000-000000000005","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}}
38 {"type":"emit_inbound","label":"child.running.thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019f1000-0000-7000-8000-000000000003","status":{"type":"active","activeFlags":[]}}}}
39 {"type":"emit_inbound","label":"child.running.turn/started","frame":{"method":"turn/started","params":{"threadId":"019f1000-0000-7000-8000-000000000003","turn":{"id":"019f1000-0000-7000-8000-000000000005","items":[],"status":"inProgress","error":null,"startedAt":1776739470,"completedAt":null,"durationMs":null}}}}
@@ -43,7 +43,7 @@
43 {"type":"emit_inbound","label":"child.running.turn/completed","frame":{"method":"turn/completed","params":{"threadId":"019f1000-0000-7000-8000-000000000003","turn":{"id":"019f1000-0000-7000-8000-000000000005","items":[],"status":"interrupted","error":null,"startedAt":1776739470,"completedAt":1776739471,"durationMs":1000}}}}
44 {"type":"expect_outbound","label":"config/read","frame":{"id":13,"method":"config/read","params":{"cwd":"<workspace>","includeLayers":false}}}
45 {"type":"emit_inbound","label":"config/read","frame":{"id":13,"result":{"config":{},"origins":{}}}}
46 -{"type":"expect_outbound","label":"child.queued.turn/start","frame":{"id":14,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"<workspace>","input":[{"text":"Complete the queued follow-up and return the final result.","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019f1000-0000-7000-8000-000000000003","approvalsReviewer":"user","summary":"auto","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.4"}}}}}
46 +{"type":"expect_outbound","label":"child.queued.turn/start","frame":{"id":14,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"<workspace>","input":[{"text":"[T3 Code: the agent in T3 thread \"thread:mcp-orchestrator-parent\" sent this message, not the user.]\n\nComplete the queued follow-up and return the final result.","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019f1000-0000-7000-8000-000000000003","approvalsReviewer":"user","summary":"auto","collaborationMode":{"mode":"default","settings":{"model":"gpt-5.4"}}}}}
47 {"type":"emit_inbound","label":"child.queued.turn/start","frame":{"id":14,"result":{"turn":{"id":"019f1000-0000-7000-8000-000000000006","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}}
48 {"type":"emit_inbound","label":"child.queued.thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019f1000-0000-7000-8000-000000000003","status":{"type":"active","activeFlags":[]}}}}
49 {"type":"emit_inbound","label":"child.queued.turn/started","frame":{"method":"turn/started","params":{"threadId":"019f1000-0000-7000-8000-000000000003","turn":{"id":"019f1000-0000-7000-8000-000000000006","items":[],"status":"inProgress","error":null,"startedAt":1776739472,"completedAt":null,"durationMs":null}}}}
packages/contracts/src/orchestrationV2.test.ts
+55 -1
@@ -2,7 +2,14 @@ import { describe, expect, it } from "@effect/vitest";
2 import * as DateTime from "effect/DateTime";
3 import * as Schema from "effect/Schema";
4
5 -import { NodeId, RunAttemptId, TrimmedNonEmptyString } from "./index.ts";
5 +import {
6 + EnvironmentId,
7 + NodeId,
8 + RunAttemptId,
9 + ScheduledTaskId,
10 + ThreadId,
11 + TrimmedNonEmptyString,
12 +} from "./index.ts";
13 import {
14 latestProviderTurnForAttempt,
15 OrchestrationV2CheckpointFileSummary,
@@ -16,6 +23,7 @@ import {
23 OrchestrationV2ThreadHistoryPage,
24 OrchestrationV2TurnItem,
25 OrchestrationV2TurnItemJson,
26 + withMessageSenderNote,
27 } from "./orchestrationV2.ts";
28
29 const now = DateTime.makeUnsafe("2026-04-20T00:00:00.000Z");
@@ -650,3 +658,49 @@ describe("latestProviderTurnForAttempt", () => {
658 expect(latestProviderTurnForAttempt(turns, null)).toBeUndefined();
659 });
660 });
661 +
662 +describe("withMessageSenderNote", () => {
663 + const thread = {
664 + createdBy: "agent",
665 + creationSource: "mcp",
666 + senderThreadId: ThreadId.make("t"),
667 + } as const;
668 + it.each([
669 + [thread, "Hi", '[T3 Code: the agent in T3 thread "t" sent this message, not the user.]\n\nHi'],
670 + [thread, "", '[T3 Code: the agent in T3 thread "t" sent this message, not the user.]'],
671 + [thread, " /git/review staged", " /git/review staged"],
672 + [thread, "$deploy ship it", "$deploy ship it"],
673 + [
674 + thread,
675 + "$25 left",
676 + '[T3 Code: the agent in T3 thread "t" sent this message, not the user.]\n\n$25 left',
677 + ],
678 + [
679 + {
680 + createdBy: "agent",
681 + creationSource: "mcp",
682 + linkedSender: {
683 + environmentId: EnvironmentId.make("e"),
684 + threadId: ThreadId.make("r"),
685 + title: "x",
686 + },
687 + },
688 + "Hi",
689 + '[T3 Code: the agent in T3 thread "r" on linked environment "e" sent this message, not the user.]\n\nHi',
690 + ],
691 + [
692 + { createdBy: "user", creationSource: "web", scheduledTaskId: ScheduledTaskId.make("s") },
693 + "Hi",
694 + '[T3 Code: scheduled task "s" sent this prompt, not the user typing in this chat.]\n\nHi',
695 + ],
696 + [
697 + { createdBy: "agent", creationSource: "mcp" },
698 + "Hi",
699 + "[T3 Code: this message came through T3 Code's tools, not from the user typing in this chat.]\n\nHi",
700 + ],
701 + [{ createdBy: "user", creationSource: "web" }, "Hi", "Hi"],
702 + [{ createdBy: "agent", creationSource: "server" }, "Hi", "Hi"],
703 + ] as const)("labels %j's message %j for the provider", (message, text, expected) => {
704 + expect(withMessageSenderNote(message, text)).toBe(expected);
705 + });
706 +});
packages/contracts/src/orchestrationV2.ts
+32
@@ -602,6 +602,38 @@ export function isCompactionCommandMessage(message: CompactionMessageFields): bo
602 );
603 }
604
605 +const LEADING_COMMAND = /^\s*(?:\/|\p{Sc}[a-zA-Z0-9:_-]*[a-zA-Z])/u;
606 +
607 +/**
608 + * Who sent a message, in a line the model reads before its text, or the text unchanged when a
609 + * person typed it. Providers parse slash commands and skill mentions such as `$deploy` from the
610 + * start of a prompt, so those stay as sent.
611 + */
612 +export function withMessageSenderNote(
613 + message: {
614 + readonly createdBy: OrchestrationV2Actor;
615 + readonly creationSource: OrchestrationV2CreationSource;
616 + readonly scheduledTaskId?: ScheduledTaskId | undefined;
617 + readonly senderThreadId?: ThreadId | undefined;
618 + readonly linkedSender?: OrchestrationV2LinkedSender | undefined;
619 + },
620 + text: string,
621 +): string {
622 + const agent = message.createdBy === "agent";
623 + const note =
624 + agent && message.linkedSender !== undefined
625 + ? `[T3 Code: the agent in T3 thread ${JSON.stringify(message.linkedSender.threadId)} on linked environment ${JSON.stringify(message.linkedSender.environmentId)} sent this message, not the user.]`
626 + : agent && message.senderThreadId !== undefined
627 + ? `[T3 Code: the agent in T3 thread ${JSON.stringify(message.senderThreadId)} sent this message, not the user.]`
628 + : message.scheduledTaskId !== undefined
629 + ? `[T3 Code: scheduled task ${JSON.stringify(message.scheduledTaskId)} sent this prompt, not the user typing in this chat.]`
630 + : agent && message.creationSource === "mcp"
631 + ? "[T3 Code: this message came through T3 Code's tools, not from the user typing in this chat.]"
632 + : undefined;
633 + if (note === undefined || LEADING_COMMAND.test(text)) return text;
634 + return text === "" ? note : `${note}\n\n${text}`;
635 +}
636 +
637 export type OrchestrationV2GoalCommand =
638 | { readonly type: "show" }
639 | { readonly type: "clear" }
packages/provider-core/src/server/handoffBudget.ts
+3
@@ -8,6 +8,7 @@ import type {
8 OrchestrationV2ProviderThread,
9 OrchestrationV2TurnItem,
10 } from "@t3tools/contracts";
11 +import { withMessageSenderNote } from "@t3tools/contracts";
12
13 import * as Config from "effect/Config";
14
@@ -137,6 +138,8 @@ export function historicalMessage(
138 let text: string;
139 switch (item.type) {
140 case "user_message":
141 + text = withMessageSenderNote(item, item.text);
142 + break;
143 case "assistant_message":
144 text = item.text;
145 break;