diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts index 10cc4b10b7130..df80f2ded5836 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts @@ -379,7 +379,7 @@ it.effect( }), ); -it.effect("steers a running turn with the thread's MCP app model context", () => +it.effect("steers a running turn with its sender and the thread's MCP app model context", () => Effect.gen(function* () { const now = yield* DateTime.now; 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", () => id: MessageId.make("message:steer-app-context"), text: "What did the app report?", attachments: [], - createdBy: "user", - creationSource: "web", + createdBy: "agent", + creationSource: "mcp", + senderThreadId: ThreadId.make("thread:steer-sender"), } as unknown as NonNullable< ProjectionStore.ProjectionProviderControlContext["message"] >, @@ -454,6 +455,10 @@ it.effect("steers a running turn with the thread's MCP app model context", () => }).pipe(Effect.provide(layerControl)); assert.equal(steered.length, 1); + assert.equal( + steered[0]!.message.text, + '[T3 Code: the agent in T3 thread "thread:steer-sender" sent this message, not the user.]\n\nWhat did the app report?', + ); assert.deepEqual("appContext" in steered[0]! ? steered[0].appContext : undefined, [ { key: "mcp_app_turn-item_call-1", text: "Pressed: blue" }, ]); diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.ts index 25df164788e76..088b4d386d177 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnControlService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.ts @@ -8,6 +8,7 @@ import { ProviderTurnId, RunAttemptId, ThreadId, + withMessageSenderNote, } from "@t3tools/contracts"; import type * as DateTime from "effect/DateTime"; import * as Context from "effect/Context"; @@ -463,10 +464,13 @@ export const layer: Layer.Layer< ...(appContext.length === 0 ? {} : { appContext }), message: { messageId: message.id, - text: projectComposerContextForProvider({ - text: message.text, - records: message.context?.records ?? [], - }), + text: withMessageSenderNote( + message, + projectComposerContextForProvider({ + text: message.text, + records: message.context?.records ?? [], + }), + ), attachments: message.attachments, createdBy: message.createdBy, creationSource: message.creationSource, diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 3a9313ac45475..f21062a50fabb 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -5,6 +5,7 @@ import { CommandId, PROVIDER_SEND_TURN_MAX_INPUT_CHARS, latestProviderTurnForAttempt, + withMessageSenderNote, type OrchestrationV2DomainEvent, type OrchestrationV2ContextHandoff, type OrchestrationV2ExecutionNode, @@ -970,10 +971,13 @@ export const layer: Layer.Layer< }); let effectiveHandoffs = handoffs; let resumeFellBack = false; - const userText = projectComposerContextForProvider({ - text: providerMessage.text, - records: providerMessage.context?.records ?? [], - }); + const userText = withMessageSenderNote( + providerMessage, + projectComposerContextForProvider({ + text: providerMessage.text, + records: providerMessage.context?.records ?? [], + }), + ); // Native goal commands go verbatim; handoff history waits a turn. const goalDriver = session.driver === "codex" || diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index ca794563234d7..ebe5e7215bcbd 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -2427,7 +2427,9 @@ it.effect("steers a promoted scheduled delivery with the thread's current select yield* worker.drain(); const projection = yield* orchestrator.getThreadProjection(threadId); - assert.deepEqual(steered, ["scheduled"]); + assert.deepEqual(steered, [ + '[T3 Code: scheduled task "task:scheduled" sent this prompt, not the user typing in this chat.]\n\nscheduled', + ]); assert.deepEqual(projection.thread.modelSelection, composerSelection); }).pipe(Effect.provide(layer)); }), @@ -3180,7 +3182,16 @@ it.effect("starts a restart that stops the running turn ahead of an older held q const { queue, started: startedTexts } = yield* read(threadId); assert.deepEqual( { queue, started: startedTexts }, - { queue: ["queued"], started: ["first", "second", "do this instead"] }, + { + queue: ["queued"], + started: [ + "first", + ...["second", "do this instead"].map( + (text) => + `[T3 Code: this message came through T3 Code's tools, not from the user typing in this chat.]\n\n${text}`, + ), + ], + }, ); }).pipe(Effect.provide(layer)); }), @@ -3300,7 +3311,9 @@ it.effect("replays an accepted steer after its target turn completes", () => .pipe(Effect.flip); assert.equal(fresh._tag, "ThreadManagementNoSteerableRunError"); yield* worker.drain(); - assert.deepEqual(steered, [input.text]); + assert.deepEqual(steered, [ + `[T3 Code: this message came through T3 Code's tools, not from the user typing in this chat.]\n\n${input.text}`, + ]); assert.lengthOf(started, 1); }).pipe( Effect.provide( diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/delegated_task_status/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/delegated_task_status/codex_transcript.ndjson index 95427ba136636..e40c278285055 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/delegated_task_status/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/delegated_task_status/codex_transcript.ndjson @@ -21,7 +21,7 @@ {"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"}}} {"type":"expect_outbound","label":"config/read","frame":{"id":8,"method":"config/read","params":{"cwd":"","includeLayers":false}}} {"type":"emit_inbound","label":"config/read","frame":{"id":8,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"child.original.turn/start","frame":{"id":9,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","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"}}}}} +{"type":"expect_outbound","label":"child.original.turn/start","frame":{"id":9,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","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"}}}}} {"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":[]}}}} {"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}}}} {"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 @@ {"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}}}} {"type":"expect_outbound","label":"config/read","frame":{"id":10,"method":"config/read","params":{"cwd":"","includeLayers":false}}} {"type":"emit_inbound","label":"config/read","frame":{"id":10,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"child.running.turn/start","frame":{"id":11,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","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"}}}}} +{"type":"expect_outbound","label":"child.running.turn/start","frame":{"id":11,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","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"}}}}} {"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}}}} {"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":[]}}}} {"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 @@ {"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}}}} {"type":"expect_outbound","label":"config/read","frame":{"id":13,"method":"config/read","params":{"cwd":"","includeLayers":false}}} {"type":"emit_inbound","label":"config/read","frame":{"id":13,"result":{"config":{},"origins":{}}}} -{"type":"expect_outbound","label":"child.queued.turn/start","frame":{"id":14,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","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"}}}}} +{"type":"expect_outbound","label":"child.queued.turn/start","frame":{"id":14,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","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"}}}}} {"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}}}} {"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":[]}}}} {"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}}}} diff --git a/packages/contracts/src/orchestrationV2.test.ts b/packages/contracts/src/orchestrationV2.test.ts index 76f78f536d7c5..bacf812ab8057 100644 --- a/packages/contracts/src/orchestrationV2.test.ts +++ b/packages/contracts/src/orchestrationV2.test.ts @@ -2,7 +2,14 @@ import { describe, expect, it } from "@effect/vitest"; import * as DateTime from "effect/DateTime"; import * as Schema from "effect/Schema"; -import { NodeId, RunAttemptId, TrimmedNonEmptyString } from "./index.ts"; +import { + EnvironmentId, + NodeId, + RunAttemptId, + ScheduledTaskId, + ThreadId, + TrimmedNonEmptyString, +} from "./index.ts"; import { latestProviderTurnForAttempt, OrchestrationV2CheckpointFileSummary, @@ -16,6 +23,7 @@ import { OrchestrationV2ThreadHistoryPage, OrchestrationV2TurnItem, OrchestrationV2TurnItemJson, + withMessageSenderNote, } from "./orchestrationV2.ts"; const now = DateTime.makeUnsafe("2026-04-20T00:00:00.000Z"); @@ -650,3 +658,49 @@ describe("latestProviderTurnForAttempt", () => { expect(latestProviderTurnForAttempt(turns, null)).toBeUndefined(); }); }); + +describe("withMessageSenderNote", () => { + const thread = { + createdBy: "agent", + creationSource: "mcp", + senderThreadId: ThreadId.make("t"), + } as const; + it.each([ + [thread, "Hi", '[T3 Code: the agent in T3 thread "t" sent this message, not the user.]\n\nHi'], + [thread, "", '[T3 Code: the agent in T3 thread "t" sent this message, not the user.]'], + [thread, " /git/review staged", " /git/review staged"], + [thread, "$deploy ship it", "$deploy ship it"], + [ + thread, + "$25 left", + '[T3 Code: the agent in T3 thread "t" sent this message, not the user.]\n\n$25 left', + ], + [ + { + createdBy: "agent", + creationSource: "mcp", + linkedSender: { + environmentId: EnvironmentId.make("e"), + threadId: ThreadId.make("r"), + title: "x", + }, + }, + "Hi", + '[T3 Code: the agent in T3 thread "r" on linked environment "e" sent this message, not the user.]\n\nHi', + ], + [ + { createdBy: "user", creationSource: "web", scheduledTaskId: ScheduledTaskId.make("s") }, + "Hi", + '[T3 Code: scheduled task "s" sent this prompt, not the user typing in this chat.]\n\nHi', + ], + [ + { createdBy: "agent", creationSource: "mcp" }, + "Hi", + "[T3 Code: this message came through T3 Code's tools, not from the user typing in this chat.]\n\nHi", + ], + [{ createdBy: "user", creationSource: "web" }, "Hi", "Hi"], + [{ createdBy: "agent", creationSource: "server" }, "Hi", "Hi"], + ] as const)("labels %j's message %j for the provider", (message, text, expected) => { + expect(withMessageSenderNote(message, text)).toBe(expected); + }); +}); diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index f59ac95c5cffb..b5fd428d6b4cc 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -602,6 +602,38 @@ export function isCompactionCommandMessage(message: CompactionMessageFields): bo ); } +const LEADING_COMMAND = /^\s*(?:\/|\p{Sc}[a-zA-Z0-9:_-]*[a-zA-Z])/u; + +/** + * Who sent a message, in a line the model reads before its text, or the text unchanged when a + * person typed it. Providers parse slash commands and skill mentions such as `$deploy` from the + * start of a prompt, so those stay as sent. + */ +export function withMessageSenderNote( + message: { + readonly createdBy: OrchestrationV2Actor; + readonly creationSource: OrchestrationV2CreationSource; + readonly scheduledTaskId?: ScheduledTaskId | undefined; + readonly senderThreadId?: ThreadId | undefined; + readonly linkedSender?: OrchestrationV2LinkedSender | undefined; + }, + text: string, +): string { + const agent = message.createdBy === "agent"; + const note = + agent && message.linkedSender !== undefined + ? `[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.]` + : agent && message.senderThreadId !== undefined + ? `[T3 Code: the agent in T3 thread ${JSON.stringify(message.senderThreadId)} sent this message, not the user.]` + : message.scheduledTaskId !== undefined + ? `[T3 Code: scheduled task ${JSON.stringify(message.scheduledTaskId)} sent this prompt, not the user typing in this chat.]` + : agent && message.creationSource === "mcp" + ? "[T3 Code: this message came through T3 Code's tools, not from the user typing in this chat.]" + : undefined; + if (note === undefined || LEADING_COMMAND.test(text)) return text; + return text === "" ? note : `${note}\n\n${text}`; +} + export type OrchestrationV2GoalCommand = | { readonly type: "show" } | { readonly type: "clear" } diff --git a/packages/provider-core/src/server/handoffBudget.ts b/packages/provider-core/src/server/handoffBudget.ts index 18bd5fb1fd284..ddf9b692c337c 100644 --- a/packages/provider-core/src/server/handoffBudget.ts +++ b/packages/provider-core/src/server/handoffBudget.ts @@ -8,6 +8,7 @@ import type { OrchestrationV2ProviderThread, OrchestrationV2TurnItem, } from "@t3tools/contracts"; +import { withMessageSenderNote } from "@t3tools/contracts"; import * as Config from "effect/Config"; @@ -137,6 +138,8 @@ export function historicalMessage( let text: string; switch (item.type) { case "user_message": + text = withMessageSenderNote(item, item.text); + break; case "assistant_message": text = item.text; break;