diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 878e4bc6b1726..f5019ca95f8b8 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -177,7 +177,11 @@ import { readClaudeSettingsEnv, } from "../../provider/Drivers/ClaudeSkills.ts"; // t4 fork: questionsAsMessages, declineSafetyChecks. -import { QUESTION_POSTED_NOTE, t4QuestionsAsMessages } from "../../t4/questionsAsMessages.ts"; +import { + QUESTION_POSTED_NOTE, + T4_CLAUDE_SEND_TO_USER_INSTRUCTIONS, + t4QuestionsAsMessages, +} from "../../t4/questionsAsMessages.ts"; import { awaitsOnItsOwn } from "../../t4/autoAwait.ts"; import { claudeAutoCompactWindowFor, compactAtTokensFor } from "../../t4/threadCompaction.ts"; import { @@ -2451,7 +2455,10 @@ export function makeClaudeQueryOptions(input: { ? "" : T3_CODE_ORCHESTRATION_INSTRUCTIONS + CLAUDE_BACKGROUND_WAIT_INSTRUCTIONS + - CLAUDE_SEND_TO_USER_INSTRUCTIONS + + // t4 fork: a question's brief goes in the final reply (AI-154). + (t4QuestionsAsMessages() + ? T4_CLAUDE_SEND_TO_USER_INSTRUCTIONS + : CLAUDE_SEND_TO_USER_INSTRUCTIONS) + (deviceInstructions ? `\n${T3_CODE_DEVICE_TOOL_INSTRUCTIONS_WITH_TOOL_SEARCH}\n` : "")), diff --git a/apps/server/src/t4/T4Http.ts b/apps/server/src/t4/T4Http.ts index ba4d4a2804c6b..306ef64a0f377 100644 --- a/apps/server/src/t4/T4Http.ts +++ b/apps/server/src/t4/T4Http.ts @@ -16,6 +16,7 @@ import { ThreadId, TurnItemId, } from "@t3tools/contracts"; +import { sentMessageFromToolItem } from "@t3tools/shared/toolOutput"; import * as Clock from "effect/Clock"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as DateTime from "effect/DateTime"; @@ -55,6 +56,7 @@ import { resumePace, takeResumeSlot, } from "./limitResumePace.ts"; +import { questionBrief, type QuestionMessage } from "./questionBrief.ts"; import { isSettled, shortId } from "./T4Threads.ts"; type Shell = OrchestrationV2ThreadShell; @@ -761,19 +763,57 @@ export const layer = Layer.mergeAll( Effect.map((r) => r.messages), Effect.orElseSucceed(() => []), ); - const said = messages.filter((m) => m.role !== "system" && m.text.trim().length > 0); + // AI-154: what the agent posted with `send_to_user` is a tool call, not a + // message; the user saw it in the thread, so the window shows it too. + const sentItems = + runIds.length === 0 + ? [] + : yield* threads + .getProjectThreadRecords({ projectId: thread.projectId, threadId }, ["turnItems"], { + turnItemTypes: ["dynamic_tool"], + turnItemRunIds: runIds, + }) + .pipe( + Effect.map((r) => r.turnItems), + Effect.orElseSucceed(() => []), + ); + const sent = sentItems.flatMap((candidate) => { + if (candidate.type !== "dynamic_tool" || candidate.status !== "completed") return []; + const text = sentMessageFromToolItem(candidate); + if (text === undefined || text.trim().length === 0) return []; + const at = candidate.completedAt ?? candidate.startedAt ?? candidate.updatedAt; + return [ + { + role: "assistant", + text, + createdAt: DateTime.toEpochMillis(at), + runId: candidate.runId, + sent: true, + }, + ]; + }); + const said = [ + ...messages + .filter((m) => m.role !== "system" && m.text.trim().length > 0) + .map((m) => ({ + role: m.role as string, + text: m.text, + createdAt: DateTime.toEpochMillis(m.createdAt), + runId: m.runId, + })), + ...sent, + ].toSorted((a, b) => a.createdAt - b.createdAt); // AI-116: the brief is kept apart, so later messages (handoffs, the agent's - // replies) never push it out of the window. Claude asks first and writes the - // brief right after (message-mode questions); Codex writes it before asking. - const askedAt = DateTime.toEpochMillis(open.createdAt); - const ownRun = said.filter((m) => m.role === "assistant" && m.runId === item.runId); - const brief = - ownRun.find((m) => DateTime.toEpochMillis(m.createdAt) >= askedAt) ?? - ownRun.filter((m) => DateTime.toEpochMillis(m.createdAt) < askedAt).at(-1); - const shown = (m: (typeof said)[number]) => ({ + // replies) never push it out of the window. + const brief = questionBrief({ + said, + askedAt: DateTime.toEpochMillis(open.createdAt), + askedRunId: item.runId, + }); + const shown = (m: QuestionMessage<(typeof said)[number]["runId"]>) => ({ role: m.role, text: m.text, - createdAt: DateTime.formatIso(m.createdAt), + createdAt: DateTime.formatIso(DateTime.makeUnsafe(m.createdAt)), runId: m.runId, }); return json({ @@ -790,7 +830,13 @@ export const layer = Layer.mergeAll( multiSelect: q.multiSelect === true, options: q.options.map((o) => ({ label: o.label, description: o.description })), })), - brief: brief === undefined ? null : shown(brief), + brief: + brief === undefined + ? null + : { + ...shown(brief), + ...(brief.parts === undefined ? {} : { parts: brief.parts.map(shown) }), + }, messages: said.slice(-12).map(shown), }); }), diff --git a/apps/server/src/t4/questionBrief.test.ts b/apps/server/src/t4/questionBrief.test.ts new file mode 100644 index 0000000000000..387c368e3a3f6 --- /dev/null +++ b/apps/server/src/t4/questionBrief.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it } from "@effect/vitest"; + +import { questionBrief, type QuestionMessage } from "./questionBrief.ts"; + +const msg = ( + createdAt: number, + text: string, + extra: Partial = {}, +): QuestionMessage => ({ role: "assistant", text, createdAt, runId: "run-1", ...extra }); + +describe("t4 question brief", () => { + it("is Claude's reply after asking", () => { + const said = [msg(10, "Reading the code."), msg(30, "The plan: ...")]; + expect(questionBrief({ said, askedAt: 20, askedRunId: "run-1" })?.text).toBe("The plan: ..."); + }); + + it("is Codex's last message before asking", () => { + const said = [msg(10, "Reading the code."), msg(15, "The plan: ...")]; + expect(questionBrief({ said, askedAt: 20, askedRunId: "run-1" })?.text).toBe("The plan: ..."); + }); + + it("leads with what the agent sent with send_to_user before asking (USA-3219)", () => { + const said = [ + msg(5, "Mapping where action items are listed."), + msg(12, "**USA-3219 plan** ...", { sent: true }), + msg(30, "The plan for USA-3219 is in the message above, and the approval card is open."), + msg(40, "From the user", { role: "user", runId: "run-2" }), + ]; + const brief = questionBrief({ said, askedAt: 13, askedRunId: "run-1" }); + expect(brief?.text).toBe( + "**USA-3219 plan** ...\n\nThe plan for USA-3219 is in the message above, and the approval card is open.", + ); + expect(brief?.createdAt).toBe(30); + expect(brief?.parts?.map((p) => p.createdAt)).toEqual([12, 30]); + }); + + it("is the sent message alone when the turn wrote nothing else", () => { + const said = [msg(12, "The plan", { sent: true })]; + const brief = questionBrief({ said, askedAt: 13, askedRunId: "run-1" }); + expect(brief?.text).toBe("The plan"); + expect(brief?.parts).toBeUndefined(); + }); + + it("leaves out other runs' messages", () => { + const said = [ + msg(5, "Earlier turn's draft", { sent: true, runId: "run-0" }), + msg(30, "The plan"), + ]; + const brief = questionBrief({ said, askedAt: 20, askedRunId: "run-1" }); + expect(brief?.text).toBe("The plan"); + }); + + it("is undefined when the asking turn wrote nothing", () => { + expect(questionBrief({ said: [], askedAt: 20, askedRunId: "run-1" })).toBeUndefined(); + }); +}); diff --git a/apps/server/src/t4/questionBrief.ts b/apps/server/src/t4/questionBrief.ts new file mode 100644 index 0000000000000..28c9d33696b3b --- /dev/null +++ b/apps/server/src/t4/questionBrief.ts @@ -0,0 +1,46 @@ +/** + * t4 fork (AI-116, AI-154): an open question's brief. Claude writes it right after asking, Codex + * before. `send_to_user` text is a tool call, passed in marked `sent`: USA-3219 sent its plan that + * way and the card showed only "The plan ... is in the message above". + */ +export interface QuestionMessage { + readonly role: string; + readonly text: string; + readonly createdAt: number; + readonly runId: RunId | null; + /** Posted with `send_to_user`. */ + readonly sent?: boolean; +} + +export interface QuestionBrief extends QuestionMessage { + /** The messages joined into the brief, in order, when there are several. */ + readonly parts?: ReadonlyArray>; +} + +export const questionBrief = (input: { + readonly said: ReadonlyArray>; + readonly askedAt: number; + readonly askedRunId: RunId | null; +}): QuestionBrief | undefined => { + const ownRun = input.said + .filter((m) => m.role === "assistant" && m.runId === input.askedRunId) + .toSorted((a, b) => a.createdAt - b.createdAt); + const pick = (candidates: ReadonlyArray>) => + candidates.find((m) => m.createdAt >= input.askedAt) ?? + candidates.filter((m) => m.createdAt < input.askedAt).at(-1); + const main = pick(ownRun.filter((m) => m.sent !== true)) ?? pick(ownRun); + if (main === undefined) return undefined; + // What the agent sent the user before asking belongs to the brief too. + const sent = ownRun.filter( + (m) => m.sent === true && m !== main && m.createdAt <= Math.max(input.askedAt, main.createdAt), + ); + if (sent.length === 0) return main; + const parts = [...sent, main].toSorted((a, b) => a.createdAt - b.createdAt); + return { + role: "assistant", + text: parts.map((m) => m.text.trim()).join("\n\n"), + createdAt: main.createdAt, + runId: main.runId, + parts, + }; +}; diff --git a/apps/server/src/t4/questionsAsMessages.ts b/apps/server/src/t4/questionsAsMessages.ts index ff9b27a6ddb31..e99f174236ef4 100644 --- a/apps/server/src/t4/questionsAsMessages.ts +++ b/apps/server/src/t4/questionsAsMessages.ts @@ -14,3 +14,13 @@ export const QUESTION_POSTED_NOTE = "write before a tool call can reach them only as a short summary. It replaces any earlier " + "question of yours still open, so it must hold every decision still open. Don't ask it " + "again in this turn unless it left one out."; + +/** + * Upstream names a question's subject as a use of send_to_user; with message-mode questions the + * brief belongs in the final reply, where the dashboard's card reads it (AI-154). + */ +export const T4_CLAUDE_SEND_TO_USER_INSTRUCTIONS = ` +### Text the user must read mid-turn + +Text you write before a tool call may reach the user only as a one-line summary. When the user must read something in full before your turn ends, such as a draft or a code block, send it with \`send_to_user\`. What a question you ask refers to is not that: ask it, then end the turn with it all as your final reply. Put everything else in your final reply. +`;