Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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`
: "")),
Expand Down
68 changes: 57 additions & 11 deletions apps/server/src/t4/T4Http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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({
Expand All @@ -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),
});
}),
Expand Down
56 changes: 56 additions & 0 deletions apps/server/src/t4/questionBrief.test.ts
Original file line number Diff line number Diff line change
@@ -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> = {},
): 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();
});
});
46 changes: 46 additions & 0 deletions apps/server/src/t4/questionBrief.ts
Original file line number Diff line number Diff line change
@@ -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<RunId = string> {
readonly role: string;
readonly text: string;
readonly createdAt: number;
readonly runId: RunId | null;
/** Posted with `send_to_user`. */
readonly sent?: boolean;
}

export interface QuestionBrief<RunId = string> extends QuestionMessage<RunId> {
/** The messages joined into the brief, in order, when there are several. */
readonly parts?: ReadonlyArray<QuestionMessage<RunId>>;
}

export const questionBrief = <RunId>(input: {
readonly said: ReadonlyArray<QuestionMessage<RunId>>;
readonly askedAt: number;
readonly askedRunId: RunId | null;
}): QuestionBrief<RunId> | 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<QuestionMessage<RunId>>) =>
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,
};
};
10 changes: 10 additions & 0 deletions apps/server/src/t4/questionsAsMessages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
`;
Loading