diff --git a/apps/server/src/mcp/toolkits/message/handlers.ts b/apps/server/src/mcp/toolkits/message/handlers.ts index defe3609f08ca..68699ca959a05 100644 --- a/apps/server/src/mcp/toolkits/message/handlers.ts +++ b/apps/server/src/mcp/toolkits/message/handlers.ts @@ -10,6 +10,12 @@ const handlers = { message: "Shown to the user. Don't repeat it.", }), ), + silent_ack: McpToolAccess.actsAsCaller(() => + Effect.succeed({ + acknowledged: true as const, + message: "Acknowledged silently; kept folded.", + }), + ), } satisfies McpToolAccess.Handlers; export const layer = McpToolAccess.toLayer(MessageToolkit, handlers); diff --git a/apps/server/src/mcp/toolkits/message/tools.ts b/apps/server/src/mcp/toolkits/message/tools.ts index 418a252eb9ead..a38075fbd6504 100644 --- a/apps/server/src/mcp/toolkits/message/tools.ts +++ b/apps/server/src/mcp/toolkits/message/tools.ts @@ -1,5 +1,9 @@ import { OrchestratorMcpFailure } from "@t3tools/contracts"; -import { SEND_TO_USER_MAX_LENGTH, SEND_TO_USER_TOOL_NAME } from "@t3tools/shared/toolOutput"; +import { + SEND_TO_USER_MAX_LENGTH, + SEND_TO_USER_TOOL_NAME, + SILENT_ACK_TOOL_NAME, +} from "@t3tools/shared/toolOutput"; import * as Schema from "effect/Schema"; import { McpSchema, Tool, Toolkit } from "effect/ai"; @@ -37,4 +41,32 @@ const SendToUserTool = Tool.make(SEND_TO_USER_TOOL_NAME, { // Claude Code defers MCP tools behind ToolSearch; Anthropic says to declare this from the first request. .annotate(Tool.Meta, { "anthropic/alwaysLoad": true }); -export const MessageToolkit = Toolkit.make(SendToUserTool); +const SilentAckTool = Tool.make(SILENT_ACK_TOOL_NAME, { + description: + "Acknowledge an agent or automation wake with nothing to deliver to the user or another agent. Keeps this turn folded out of the user's timeline.", + parameters: Schema.Struct({ + reason: Schema.optional( + Schema.String.check(Schema.isMaxLength(256)).annotate({ + description: "Optional brief note for the folded audit log.", + }), + ), + }), + success: Schema.Struct({ + acknowledged: Schema.Literal(true), + message: Schema.String, + }), + failure: OrchestratorMcpFailure, + failureMode: "return", + dependencies: [ + McpInvocationContext.McpInvocationContext, + ThreadManagementService.ThreadManagementService, + ], +}) + .annotate(Tool.Title, "Acknowledge silently") + .annotate(Tool.Readonly, true) + .annotate(Tool.Destructive, false) + .annotate(Tool.Idempotent, true) + .annotate(Tool.OpenWorld, false) + .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromOutsideClients); + +export const MessageToolkit = Toolkit.make(SendToUserTool, SilentAckTool); diff --git a/apps/server/src/orchestration-v2/AgentOutputGate.test.ts b/apps/server/src/orchestration-v2/AgentOutputGate.test.ts new file mode 100644 index 0000000000000..93e2cc2a6a5f9 --- /dev/null +++ b/apps/server/src/orchestration-v2/AgentOutputGate.test.ts @@ -0,0 +1,373 @@ +import { assert, describe, it } from "@effect/vitest"; +import { + EventId, + MessageId, + ProjectId, + ProviderInstanceId, + RunId, + ThreadId, + TurnItemId, + type OrchestrationV2AppThread, + type OrchestrationV2ConversationMessage, + type OrchestrationV2DomainEvent, + type OrchestrationV2Run, + type OrchestrationV2ServerCommand, + type OrchestrationV2TurnItem, +} from "@t3tools/contracts"; +import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Ref from "effect/Ref"; +import * as Stream from "effect/Stream"; + +import { + evaluateAgentOutputGate, + isExplicitChannelToolName, + OUTPUT_GATE_BOUNCE_PROMPT, + outputGateBounceCommandId, + outputGateBounceMessageId, +} from "./AgentOutputGate.ts"; +import * as AgentOutputGateReactor from "./AgentOutputGateReactor.ts"; +import * as EventSink from "./EventSink.ts"; +import * as Orchestrator from "./Orchestrator.ts"; +import * as ProjectionStore from "./ProjectionStore.ts"; + +const now = DateTime.makeUnsafe("2026-11-26T00:00:00.000Z"); +const threadId = ThreadId.make("thread:output-gate"); +const runId = RunId.make("run:output-gate-1"); +const bounceRunId = RunId.make("run:output-gate-2"); +const userMsgId = MessageId.make("msg:user-1"); +const agentMsgId = MessageId.make("msg:agent-1"); + +const baseThread = ( + overrides: Partial< + Pick< + OrchestrationV2AppThread, + "deletedAt" | "archivedAt" | "lineage" | "replacedByThreadId" | "settledOverride" + > + > = {}, +): Pick< + OrchestrationV2AppThread, + "deletedAt" | "archivedAt" | "lineage" | "replacedByThreadId" | "settledOverride" +> => ({ + deletedAt: null, + archivedAt: null, + replacedByThreadId: null, + settledOverride: null, + lineage: { + rootThreadId: threadId, + parentThreadId: null, + relationshipToParent: null, + }, + ...overrides, +}); + +const baseRun = ( + overrides: Partial> = {}, +): Pick => ({ + id: runId, + status: "completed", + userMessageId: agentMsgId, + ...overrides, +}); + +const assistantItem = ( + id: string, + text: string, + targetRunId: RunId = runId, +): Extract => ({ + type: "assistant_message", + id: TurnItemId.make(id), + threadId, + runId: targetRunId, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 1, + status: "completed", + title: null, + startedAt: now, + completedAt: now, + updatedAt: now, + messageId: MessageId.make(`m:${id}`), + text, + streaming: false, +}); + +const toolItem = ( + id: string, + toolName: string, + status: OrchestrationV2TurnItem["status"] = "completed", + targetRunId: RunId = runId, +): Extract => ({ + type: "dynamic_tool", + id: TurnItemId.make(id), + threadId, + runId: targetRunId, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 0, + status, + title: null, + startedAt: now, + completedAt: now, + updatedAt: now, + toolName, + input: {}, + output: {}, +}); + +const userMessage = ( + createdBy: "user" | "agent", + extra: Partial = {}, +): Pick< + OrchestrationV2ConversationMessage, + | "createdBy" + | "creationSource" + | "notification" + | "scheduledTaskId" + | "senderThreadId" + | "linkedSender" +> => ({ + createdBy, + creationSource: createdBy === "user" ? "web" : "mcp", + ...extra, +}); + +describe("AgentOutputGate policy", () => { + it("recognizes explicit channel tools across raw and provider-prefixed names", () => { + assert.isTrue(isExplicitChannelToolName("send_to_user")); + assert.isTrue(isExplicitChannelToolName("mcp__t3-code__send_to_user")); + assert.isTrue(isExplicitChannelToolName("silent_ack")); + assert.isTrue(isExplicitChannelToolName("mcp__t3-code__silent_ack")); + assert.isTrue(isExplicitChannelToolName("mcp_t3-code_silent_ack")); + assert.isTrue(isExplicitChannelToolName("t3-code.silent_ack")); + assert.isTrue(isExplicitChannelToolName("t3-code-thread123_silent_ack")); + assert.isTrue(isExplicitChannelToolName("t3_thread_send")); + assert.isTrue(isExplicitChannelToolName("mcp__t3-code__t3_thread_send")); + assert.isTrue(isExplicitChannelToolName("ask_agent")); + assert.isTrue(isExplicitChannelToolName("mcp__t3-code__ask_agent")); + assert.isTrue(isExplicitChannelToolName("mcp_t3-code_ask_agent")); + assert.isTrue(isExplicitChannelToolName("t3-code.ask_agent")); + assert.isTrue(isExplicitChannelToolName("t3-code-thread123_ask_agent")); + assert.isFalse(isExplicitChannelToolName("t3_thread_read")); + assert.isFalse(isExplicitChannelToolName(null)); + }); + + it("never gates or bounces origin='user' turns", () => { + const decision = evaluateAgentOutputGate({ + thread: baseThread(), + run: baseRun({ userMessageId: userMsgId }), + userMessage: userMessage("user"), + turnItems: [assistantItem("a1", "Here is my reply to the founder.")], + }); + assert.deepEqual(decision, { action: "allow", reason: "user_origin" }); + }); + + it("never gates sideChat (ask_agent) or subagent threads", () => { + const side = evaluateAgentOutputGate({ + thread: baseThread({ + lineage: { + rootThreadId: threadId, + parentThreadId: ThreadId.make("thread:parent"), + relationshipToParent: "fork", + sideChat: true, + }, + }), + run: baseRun(), + userMessage: userMessage("agent"), + turnItems: [assistantItem("a1", "Direct answer for ask_agent.")], + }); + assert.deepEqual(side, { action: "allow", reason: "side_chat" }); + + const subagent = evaluateAgentOutputGate({ + thread: baseThread({ + lineage: { + rootThreadId: threadId, + parentThreadId: ThreadId.make("thread:parent"), + relationshipToParent: "subagent", + }, + }), + run: baseRun(), + userMessage: userMessage("agent"), + turnItems: [assistantItem("a1", "Child task summary.")], + }); + assert.deepEqual(subagent, { action: "allow", reason: "subagent_thread" }); + }); + + it("allows agent-originated turns that already used an explicit channel tool", () => { + for (const toolName of [ + "mcp__t3-code__send_to_user", + "mcp__t3-code__t3_thread_send", + "mcp__t3-code__ask_agent", + "mcp__t3-code__silent_ack", + ]) { + const decision = evaluateAgentOutputGate({ + thread: baseThread(), + run: baseRun(), + userMessage: userMessage("agent"), + turnItems: [toolItem("t1", toolName), assistantItem("a1", "Done.")], + }); + assert.deepEqual(decision, { action: "allow", reason: "explicit_channel" }); + } + }); + + it("bounces once on unrouted plain text in an agent-originated wake", () => { + const decision = evaluateAgentOutputGate({ + thread: baseThread(), + run: baseRun(), + userMessage: userMessage("agent"), + turnItems: [assistantItem("a1", "I think Kameron should pick option B.")], + }); + assert.deepEqual(decision, { action: "bounce", prompt: OUTPUT_GATE_BOUNCE_PROMPT }); + }); + + it("does not treat an error-returning channel tool call as a valid delivery (F2)", () => { + const failedChannelCall: Extract = { + ...toolItem("t-err", "mcp__t3-code__t3_thread_send"), + output: { isError: true, content: [{ type: "text", text: "thread_not_found" }] }, + }; + const decision = evaluateAgentOutputGate({ + thread: baseThread(), + run: baseRun(), + userMessage: userMessage("agent"), + turnItems: [failedChannelCall, assistantItem("a1", "Could not send, here is the update.")], + }); + assert.deepEqual(decision, { action: "bounce", prompt: OUTPUT_GATE_BOUNCE_PROMPT }); + }); + + it("fails open to agent_fold on settled threads (F4) or when a newer run is active (F3)", () => { + const settled = evaluateAgentOutputGate({ + thread: baseThread({ settledOverride: "settled" }), + run: baseRun(), + userMessage: userMessage("agent"), + turnItems: [assistantItem("a1", "Done.")], + }); + assert.deepEqual(settled, { action: "fail_open_fold", reason: "thread_settled" }); + + const superseded = evaluateAgentOutputGate({ + thread: baseThread(), + run: baseRun(), + userMessage: userMessage("agent"), + turnItems: [assistantItem("a1", "Done.")], + hasNewerOrActiveRun: true, + }); + assert.deepEqual(superseded, { action: "fail_open_fold", reason: "superseded_by_newer_run" }); + }); + + it("fails open into agent_fold on a bounce run that still ends unrouted (never loops >1)", () => { + const decision = evaluateAgentOutputGate({ + thread: baseThread(), + run: baseRun({ id: bounceRunId, userMessageId: outputGateBounceMessageId(runId) }), + userMessage: userMessage("agent"), + turnItems: [assistantItem("a2", "Still plain text.", bounceRunId)], + }); + assert.deepEqual(decision, { action: "fail_open_fold", reason: "bounce_exhausted" }); + }); +}); + +describe("AgentOutputGateReactor", () => { + it.effect( + "dispatches 1 bounce on unrouted agent wake and fails open to agent_fold on second pass", + () => + Effect.gen(function* () { + const dispatched = yield* Ref.make>([]); + const writtenEvents = yield* Ref.make>([]); + let nextEventSeq = 1; + + const makeRecords = (targetRunId: RunId) => { + const isBounce = targetRunId === bounceRunId; + const msgId = isBounce ? outputGateBounceMessageId(runId) : agentMsgId; + return { + thread: { + ...baseThread(), + id: threadId, + projectId: ProjectId.make("project:gate"), + providerInstanceId: ProviderInstanceId.make("claudeAgent"), + }, + runs: [ + { + ...baseRun({ id: targetRunId, userMessageId: msgId }), + providerInstanceId: ProviderInstanceId.make("claudeAgent"), + }, + ], + messages: [ + { + id: msgId, + threadId, + runId: targetRunId, + role: "user", + text: isBounce ? OUTPUT_GATE_BOUNCE_PROMPT : "Agent wake", + ...userMessage("agent"), + }, + ], + turnItems: [assistantItem(isBounce ? "a2" : "a1", "Unrouted plain text", targetRunId)], + }; + }; + + const layer = Layer.mergeAll( + Layer.mock(Orchestrator.OrchestratorV2)({ + streamDomainEvents: Stream.empty, + dispatch: (command) => + Ref.update(dispatched, (list) => [...list, command]).pipe( + Effect.as({ sequence: 1, storedEvents: [] } as never), + ), + }), + Layer.mock(ProjectionStore.ProjectionStoreV2)({ + getThreadShell: () => + Effect.succeed({ + activeRunId: null, + latestRunId: runId, + } as never), + getThreadRecords: (_id, _fields, filter) => + Effect.succeed(makeRecords(filter?.runIds?.[0] ?? runId) as never), + getMessagesById: () => Effect.succeed(new Map()), + }), + Layer.mock(EventSink.EventSinkV2)({ + write: ({ events }) => + Ref.update(writtenEvents, (list) => [...list, ...events]).pipe( + Effect.as([] as never), + ), + }), + Layer.mock(IdAllocator.IdAllocatorV2)({ + allocate: { + event: () => Effect.sync(() => EventId.make(`evt:${nextEventSeq++}`)), + } as never, + derive: {} as never, + }), + ); + + yield* Effect.gen(function* () { + const reactor = yield* AgentOutputGateReactor.make; + // Pass 1: unrouted agent wake -> dispatches exactly 1 bounce. + yield* reactor.evaluateCompletedRun({ threadId, runId }); + const cmdsAfterFirst = yield* Ref.get(dispatched); + assert.equal(cmdsAfterFirst.length, 1); + assert.equal(cmdsAfterFirst[0]!.type, "message.dispatch"); + if (cmdsAfterFirst[0]!.type === "message.dispatch") { + assert.equal(cmdsAfterFirst[0]!.commandId, outputGateBounceCommandId(runId)); + assert.equal(cmdsAfterFirst[0]!.messageId, outputGateBounceMessageId(runId)); + assert.equal(cmdsAfterFirst[0]!.createdBy, "agent"); + } + + // Pass 2: bounce run still ends with plain text -> fails open into agent_fold, 0 new bounces. + yield* reactor.evaluateCompletedRun({ threadId, runId: bounceRunId }); + const cmdsAfterSecond = yield* Ref.get(dispatched); + assert.equal(cmdsAfterSecond.length, 1); + + const written = yield* Ref.get(writtenEvents); + assert.equal(written.length, 1); + assert.equal(written[0]!.type, "turn-item.updated"); + if (written[0]!.type === "turn-item.updated") { + assert.equal(written[0]!.payload.timelineVisibility, "agent_fold"); + } + }).pipe(Effect.provide(layer)); + }), + ); +}); diff --git a/apps/server/src/orchestration-v2/AgentOutputGate.ts b/apps/server/src/orchestration-v2/AgentOutputGate.ts new file mode 100644 index 0000000000000..b83c2904b25e2 --- /dev/null +++ b/apps/server/src/orchestration-v2/AgentOutputGate.ts @@ -0,0 +1,180 @@ +import { + CommandId, + MessageId, + type OrchestrationV2AppThread, + type OrchestrationV2ConversationMessage, + type OrchestrationV2Run, + type OrchestrationV2TurnItem, + type RunId, +} from "@t3tools/contracts"; +import { resolveT3McpToolId } from "@t3tools/shared/t3McpToolPresentation"; +import { + compactDynamicToolOutput, + SEND_TO_USER_TOOL_NAME, + SILENT_ACK_TOOL_NAME, +} from "@t3tools/shared/toolOutput"; + +const OUTPUT_GATE_BOUNCE_MESSAGE_PREFIX = "message:output-gate-bounce:"; + +export const OUTPUT_GATE_BOUNCE_PROMPT = + "Triggered by an agent/automation wake, not the user — plain assistant text stays folded and is not delivered. Route your response now: call `send_to_user` if it is for the founder, `t3_thread_send` or `ask_agent` if it is for another agent, or `silent_ack` if nothing needs delivery."; + +const EXPLICIT_CHANNEL_TOOL_IDS: ReadonlySet = new Set([ + SEND_TO_USER_TOOL_NAME, + SILENT_ACK_TOOL_NAME, + "t3_thread_send", + "t3_thread_send_attachments", + "ask_agent", +]); + +export function outputGateBounceCommandId(runId: RunId): CommandId { + return CommandId.make(`server:output-gate-bounce:${runId}`); +} + +export function outputGateBounceMessageId(runId: RunId): MessageId { + return MessageId.make(`${OUTPUT_GATE_BOUNCE_MESSAGE_PREFIX}${runId}`); +} + +export function isOutputGateBounceMessageId(messageId: MessageId | null | undefined): boolean { + return typeof messageId === "string" && messageId.startsWith(OUTPUT_GATE_BOUNCE_MESSAGE_PREFIX); +} + +/** Recognizes explicit user/agent channel sinks across raw and provider-prefixed MCP tool names. */ +export function isExplicitChannelToolName(toolName: string | null | undefined): boolean { + if (typeof toolName !== "string" || toolName.length === 0) return false; + if (EXPLICIT_CHANNEL_TOOL_IDS.has(toolName)) return true; + const resolved = resolveT3McpToolId(toolName); + if (resolved !== null && EXPLICIT_CHANNEL_TOOL_IDS.has(resolved)) return true; + for (const id of EXPLICIT_CHANNEL_TOOL_IDS) { + if (toolName.endsWith(`__${id}`)) return true; + } + return false; +} + +/** + * Only async agent/automation-originated turns are eligible for the turn-end output gate. + * Human user turns (`createdBy === "user"` with no agent/automation wake metadata) are never gated. + */ +export function isAgentOriginatedWake( + message: + | Pick< + OrchestrationV2ConversationMessage, + | "createdBy" + | "creationSource" + | "notification" + | "scheduledTaskId" + | "senderThreadId" + | "linkedSender" + > + | undefined, +): boolean { + if (message === undefined) return false; + if (message.createdBy === "agent") return true; + if (message.createdBy === "user") return false; + return ( + message.notification !== undefined || + message.scheduledTaskId !== undefined || + message.senderThreadId !== undefined || + message.linkedSender !== undefined + ); +} + +export type AgentOutputGateDecision = + | { + readonly action: "allow"; + readonly reason: + | "not_completed" + | "thread_inactive" + | "side_chat" + | "subagent_thread" + | "user_origin" + | "explicit_channel" + | "no_plain_text"; + } + | { readonly action: "bounce"; readonly prompt: string } + | { + readonly action: "fail_open_fold"; + readonly reason: "bounce_exhausted" | "thread_settled" | "superseded_by_newer_run"; + }; + +export function evaluateAgentOutputGate(input: { + readonly thread: Pick< + OrchestrationV2AppThread, + "deletedAt" | "archivedAt" | "lineage" | "replacedByThreadId" | "settledOverride" + >; + readonly run: Pick; + readonly userMessage: + | Pick< + OrchestrationV2ConversationMessage, + | "createdBy" + | "creationSource" + | "notification" + | "scheduledTaskId" + | "senderThreadId" + | "linkedSender" + > + | undefined; + readonly turnItems: ReadonlyArray; + readonly assistantMessages?: ReadonlyArray< + Pick + >; + /** True when another run is already active or queued after this completed run. */ + readonly hasNewerOrActiveRun?: boolean; +}): AgentOutputGateDecision { + if (input.run.status !== "completed") { + return { action: "allow", reason: "not_completed" }; + } + if ( + input.thread.deletedAt !== null || + input.thread.archivedAt !== null || + input.thread.replacedByThreadId != null + ) { + return { action: "allow", reason: "thread_inactive" }; + } + if (input.thread.lineage.sideChat === true) { + return { action: "allow", reason: "side_chat" }; + } + if (input.thread.lineage.relationshipToParent === "subagent") { + return { action: "allow", reason: "subagent_thread" }; + } + if (!isAgentOriginatedWake(input.userMessage)) { + return { action: "allow", reason: "user_origin" }; + } + + const runItems = input.turnItems.filter((item) => item.runId === input.run.id); + const usedExplicitChannel = runItems.some( + (item) => + item.type === "dynamic_tool" && + item.status === "completed" && + isExplicitChannelToolName(item.toolName) && + compactDynamicToolOutput(item.output)?.isError !== true, + ); + if (usedExplicitChannel) { + return { action: "allow", reason: "explicit_channel" }; + } + + const hasPlainTextItem = runItems.some( + (item) => item.type === "assistant_message" && item.text.trim().length > 0, + ); + const hasPlainTextMessage = (input.assistantMessages ?? []).some( + (message) => + message.role === "assistant" && + message.runId === input.run.id && + message.text.trim().length > 0, + ); + if (!hasPlainTextItem && !hasPlainTextMessage) { + return { action: "allow", reason: "no_plain_text" }; + } + + if (input.thread.settledOverride === "settled") { + return { action: "fail_open_fold", reason: "thread_settled" }; + } + if (input.hasNewerOrActiveRun === true) { + return { action: "fail_open_fold", reason: "superseded_by_newer_run" }; + } + if (isOutputGateBounceMessageId(input.run.userMessageId)) { + return { action: "fail_open_fold", reason: "bounce_exhausted" }; + } + + return { action: "bounce", prompt: OUTPUT_GATE_BOUNCE_PROMPT }; +} diff --git a/apps/server/src/orchestration-v2/AgentOutputGateReactor.ts b/apps/server/src/orchestration-v2/AgentOutputGateReactor.ts new file mode 100644 index 0000000000000..034b9f6197c41 --- /dev/null +++ b/apps/server/src/orchestration-v2/AgentOutputGateReactor.ts @@ -0,0 +1,193 @@ +import { + type OrchestrationV2DomainEvent, + type OrchestrationV2Run, + type OrchestrationV2TurnItem, + type RunId, + type ThreadId, +} from "@t3tools/contracts"; +import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import * as Cause from "effect/Cause"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Queue from "effect/Queue"; +import * as Stream from "effect/Stream"; + +import { forkParked } from "../serverActivation.ts"; +import { + evaluateAgentOutputGate, + outputGateBounceCommandId, + outputGateBounceMessageId, +} from "./AgentOutputGate.ts"; +import * as EventSink from "./EventSink.ts"; +import * as Orchestrator from "./Orchestrator.ts"; +import * as ProjectionStore from "./ProjectionStore.ts"; + +interface CompletedRunSignal { + readonly threadId: ThreadId; + readonly runId: RunId; +} + +/** + * Enforces a 1-bounce fail-open turn-end output gate on async `origin: "agent"` wakes. + * - Never gates `origin: "user"` turns, side chats, or subagent threads. + * - Allows turns that already invoked an explicit channel tool (`send_to_user`, `t3_thread_send`, + * `ask_agent`, `silent_ack`) or emitted no plain assistant text. + * - Issues at most 1 bounce on an unrouted plain-text turn; if the bounce still ends unrouted, + * fails open by stamping the output `timelineVisibility: "agent_fold"` without dropping text or + * bumping founder unread/attention. + */ +export const make = Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const eventSink = yield* EventSink.EventSinkV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const ids = yield* IdAllocator.IdAllocatorV2; + // Unbounded queue decouples stream callbacks from orchestrator dispatches (avoids transaction deadlock). + const queue = yield* Queue.unbounded(); + + const stampAgentFold = Effect.fn("AgentOutputGateReactor.stampAgentFold")(function* ( + threadId: ThreadId, + run: OrchestrationV2Run, + turnItems: ReadonlyArray< + Extract + >, + ) { + const unstamped = turnItems.filter((item) => item.timelineVisibility === undefined); + if (unstamped.length === 0) return; + const now = yield* DateTime.now; + const events = yield* Effect.forEach(unstamped, (item) => + Effect.gen(function* () { + return { + id: yield* ids.allocate.event({ threadId }), + type: "turn-item.updated" as const, + threadId, + runId: run.id, + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: { + ...item, + timelineVisibility: "agent_fold" as const, + updatedAt: now, + }, + }; + }), + ); + yield* eventSink.write({ events }); + }); + + const evaluateCompletedRun = Effect.fn("AgentOutputGateReactor.evaluateCompletedRun")(function* ( + signal: CompletedRunSignal, + ) { + const records = yield* projections.getThreadRecords( + signal.threadId, + ["runs", "messages", "turnItems"], + { + runIds: [signal.runId], + turnItemRunId: signal.runId, + }, + ); + const run = records.runs.find((candidate) => candidate.id === signal.runId); + if (run === undefined) return; + + const userMessage = + run.userMessageId === null + ? undefined + : (records.messages.find((message) => message.id === run.userMessageId) ?? + (yield* projections.getMessagesById(signal.threadId, [run.userMessageId])).get( + run.userMessageId, + )); + + const shell = yield* projections.getThreadShell(signal.threadId); + const hasNewerOrActiveRun = + shell !== null && + (shell.activeRunId !== null || + (shell.latestRunId !== null && shell.latestRunId !== signal.runId)); + + const decision = evaluateAgentOutputGate({ + thread: records.thread, + run, + userMessage, + turnItems: records.turnItems, + assistantMessages: records.messages, + hasNewerOrActiveRun, + }); + + if (decision.action === "allow") return; + + if (decision.action === "bounce") { + yield* orchestrator + .dispatch({ + type: "message.dispatch", + commandId: outputGateBounceCommandId(run.id), + threadId: signal.threadId, + messageId: outputGateBounceMessageId(run.id), + text: decision.prompt, + // Use `monitor` (not `system`) so Orchestrator never classifies this bounce as a + // delegationReminder and never promotes it to `steer_active` into a racing newer turn. + notification: { + source: { kind: "monitor" }, + outcome: "updated", + summary: "Output routing reminder", + }, + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "server", + }) + .pipe( + Effect.catchCause((cause) => + Effect.logWarning("agent output gate bounce failed; failing open", { + threadId: signal.threadId, + runId: run.id, + cause: Cause.pretty(cause), + }), + ), + ); + return; + } + + const assistantItems = records.turnItems.filter( + (item): item is Extract => + item.type === "assistant_message" && item.runId === run.id, + ); + yield* stampAgentFold(signal.threadId, run, assistantItems).pipe( + Effect.catchCause((cause) => + Effect.logWarning("agent output gate fail-open fold stamp failed", { + threadId: signal.threadId, + runId: run.id, + cause: Cause.pretty(cause), + }), + ), + ); + }); + + const onEvent = (event: OrchestrationV2DomainEvent) => + event.type === "run.updated" && event.payload.status === "completed" + ? Queue.offer(queue, { threadId: event.threadId, runId: event.payload.id }).pipe( + Effect.asVoid, + ) + : Effect.void; + + const processQueued = Queue.take(queue).pipe( + Effect.flatMap((signal) => + evaluateCompletedRun(signal).pipe( + Effect.catchCauseIf( + (cause) => !Cause.hasInterruptsOnly(cause), + (cause) => + Effect.logWarning("agent output gate worker failed; failing open", { + threadId: signal.threadId, + runId: signal.runId, + cause: Cause.pretty(cause), + }), + ), + ), + ), + Effect.forever, + ); + + const start = Effect.fn("AgentOutputGateReactor.start")(function* () { + yield* forkParked(orchestrator.streamDomainEvents.pipe(Stream.runForEach(onEvent))); + yield* forkParked(processQueued); + }); + + return { start, evaluateCompletedRun }; +}); diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 73047ba340de1..67009a34b2a2d 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 6245, "codexAdditionalContextBytes": 7639, - "mcpToolListJsonBytes": 75321 + "mcpToolListJsonBytes": 75656 } diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index ad8656d21e57b..bd536b1cc8fa1 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -247,6 +247,7 @@ import * as ThreadSettlementService from "./orchestration-v2/ThreadSettlementSer import * as CompactionLoopGuard from "./orchestration-v2/CompactionLoopGuard.ts"; import * as IdleCompactionService from "./orchestration-v2/IdleCompactionService.ts"; import * as SessionSpendGuardReactor from "./orchestration-v2/SessionSpendGuardReactor.ts"; +import * as AgentOutputGateReactor from "./orchestration-v2/AgentOutputGateReactor.ts"; import * as DelegationNudgeReactor from "./orchestration-v2/DelegationNudgeReactor.ts"; import * as ThreadPullRequestService from "./orchestration-v2/ThreadPullRequestService.ts"; import * as ThreadIssueService from "./orchestration-v2/ThreadIssueService.ts"; @@ -727,6 +728,14 @@ const layerDelegationNudgeWorker = Layer.effectDiscard( ), ); +const layerAgentOutputGateWorker = Layer.effectDiscard( + AgentOutputGateReactor.make.pipe(Effect.flatMap((service) => service.start())), +).pipe( + Layer.provide( + Layer.mergeAll(ProjectionStoreV2.layer, RuntimeLayer.layerEventSink, IdAllocator.layer), + ), +); + const layerCompactionLoopGuard = Layer.effectDiscard( CompactionLoopGuard.make.pipe(Effect.flatMap((service) => service.start())), ).pipe(Layer.provide(ProjectionStoreV2.layer)); @@ -789,6 +798,7 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll( layerIdleCompactionWorker, layerSessionSpendGuardWorker, layerDelegationNudgeWorker, + layerAgentOutputGateWorker, layerCompactionLoopGuard, StorageCleanup.layer.pipe(Layer.provide(ProjectionStoreV2.layer)), DatabaseStorage.layer.pipe( diff --git a/packages/client-runtime/src/seenMarker.test.ts b/packages/client-runtime/src/seenMarker.test.ts index e9e2a09a121f8..628663842ab9a 100644 --- a/packages/client-runtime/src/seenMarker.test.ts +++ b/packages/client-runtime/src/seenMarker.test.ts @@ -286,4 +286,31 @@ describe("agent messages stamped for the user's timeline", () => { count: 2, }); }); + + it("never counts a human user's own message as unseen even if stamped user_timeline", () => { + const founderStamped = MessageId.make("message-founder-stamped"); + const agentStamped = MessageId.make("message-agent-stamped"); + const thread = [ + { id: userId, role: "user", createdBy: "user" }, + { + id: founderStamped, + role: "user", + createdBy: "user", + timelineVisibility: "user_timeline" as const, + }, + { + id: agentStamped, + role: "user", + createdBy: "agent", + timelineVisibility: "user_timeline" as const, + }, + ]; + expect(resolveUnseenDivider({ messages: thread, lastSeenMessageId: userId })).toEqual({ + afterMessageId: userId, + count: 1, + }); + expect( + catchUpOffer({ messages: thread.slice(0, 2), lastSeenMessageId: userId, seenAt }), + ).toBeNull(); + }); }); diff --git a/packages/client-runtime/src/seenMarker.ts b/packages/client-runtime/src/seenMarker.ts index dd9835ac94e4a..5c0ae35009089 100644 --- a/packages/client-runtime/src/seenMarker.ts +++ b/packages/client-runtime/src/seenMarker.ts @@ -59,20 +59,21 @@ export interface SeenMessage { id: MessageId; role: string; streaming?: boolean; - /** An explicit `user_timeline` stamp makes a message new to the reader whoever wrote it. */ + /** Who created the message (`"user"` vs `"agent"`). Human user messages are never unseen. */ + createdBy?: string | undefined; + /** An explicit `user_timeline` stamp makes an agent/non-user message new to the reader. */ timelineVisibility?: OrchestrationV2TimelineVisibility | undefined; } /** * Whether a message counts as new for "catch me up" and the new-messages line. A model reply - * always does. Anything else does only when the server stamped it for the user's own timeline, - * such as an agent-sent message, so a person's own sends never count. + * always does. Anything else does only when it is not a human founder's own message and the server + * stamped it for the user's own timeline, such as an agent-sent message. */ function isUnseenCandidate(message: SeenMessage): boolean { - return ( - message.streaming !== true && - (message.role === "assistant" || message.timelineVisibility === "user_timeline") - ); + if (message.streaming === true) return false; + if (message.role === "assistant") return true; + return message.timelineVisibility === "user_timeline" && message.createdBy !== "user"; } interface SeenEntry { diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 08989fe9400a9..ef2d88bf6f5bb 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -1765,6 +1765,8 @@ export const OrchestrationV2ConversationMessage = Schema.Struct({ /** A human side note. It is stored and shown, and never sent to the provider. */ humanNote: Schema.optional(Schema.Literal(true)), seenMarker: Schema.optional(ThreadSeenMarkerSummary), + /** Absent on messages stored before the stamp existed; clients then fall back on the run's origin. */ + timelineVisibility: Schema.optional(OrchestrationV2TimelineVisibility), /** * The message is the script a provider-native workflow run executes, not prose. Clients show * the workflow's opening instead and keep the script behind a disclosure. diff --git a/packages/shared/src/t3McpToolPresentation.ts b/packages/shared/src/t3McpToolPresentation.ts index 95669152227f8..610cb2587cbf1 100644 --- a/packages/shared/src/t3McpToolPresentation.ts +++ b/packages/shared/src/t3McpToolPresentation.ts @@ -250,6 +250,7 @@ const T3_MCP_TOOLS: Readonly> = { t3_thread_list: tool(["List", "Listing", "Listed", "T3 threads"], "thread-list"), t3_thread_read: tool(["Read", "Reading", "Read", "a T3 thread"], "thread-read"), t3_thread_send: tool(["Send", "Sending", "Sent", "to a T3 thread"], "thread-send"), + ask_agent: tool(["Ask", "Asking", "Asked", "an agent"], "thread-send"), t3_thread_wait: tool(["Wait", "Waiting", "Waited", "for a T3 thread"], "thread-wait"), t3_workflow_stop: tool( ["Stop", "Stopping", "Requested a stop for", "a workflow"], @@ -460,6 +461,7 @@ const T3_MCP_TOOLS: Readonly> = { html_preview: tool(["Preview", "Previewing", "Previewed", "an HTML page"], "html-preview"), html_render: tool(["Render", "Rendering", "Rendered", "an HTML page"], "html-render"), send_to_user: tool(["Send", "Sending", "Sent", "a message"], "send-to-user"), + silent_ack: tool(["Acknowledge", "Acknowledging", "Acknowledged", "silently"], "send-to-user"), show_file: tool(["Show", "Showing", "Showed", "a file"], "show-file"), }; diff --git a/packages/shared/src/toolOutput.ts b/packages/shared/src/toolOutput.ts index 65b80c7dd470c..a1740dc4ab83e 100644 --- a/packages/shared/src/toolOutput.ts +++ b/packages/shared/src/toolOutput.ts @@ -19,6 +19,7 @@ import { import { resolveT3McpToolId } from "./t3McpToolPresentation.ts"; export const SEND_TO_USER_TOOL_NAME = "send_to_user"; +export const SILENT_ACK_TOOL_NAME = "silent_ack"; // 4,000 UTF-16 units stay inside MAX_PARSED_BYTES even as 3-byte characters. export const SEND_TO_USER_MAX_LENGTH = 4_000;