Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

fix(assistant): send Anthropic's thinking back only where the conversation before it is unchanged

Maurice758612679755
diff --git a/server/src/db/json-columns.ts b/server/src/db/json-columns.ts
index b5a8355c5..1a4a59fe0 100644
--- a/server/src/db/json-columns.ts
+++ b/server/src/db/json-columns.ts
@@ -387,10 +387,12 @@ const aiProviderStateSchema = z.discriminatedUnion('adapter', [
adapter: z.literal('openai-responses'),
items: z.array(z.record(z.string(), z.unknown())),
}),
- // Anthropic's content blocks of an answer that searched the web or thought, replayed as they came.
+ // Anthropic's content blocks of an answer that searched the web or thought, replayed as they came, and the
+ // fingerprint of what its request sent before it, which its thinking blocks are bound to.
z.object({
adapter: z.literal('anthropic-messages'),
blocks: z.array(z.record(z.string(), z.unknown())),
+ sentBefore: z.string().optional(),
}),
// Gemini's thought signature per tool call id, which its Chat Completions endpoint wants back with the call.
z.object({
diff --git a/server/src/nest/ai-connections/providers/anthropic-messages.client.ts b/server/src/nest/ai-connections/providers/anthropic-messages.client.ts
index 2aa2cbcd0..7426b81ed 100644
--- a/server/src/nest/ai-connections/providers/anthropic-messages.client.ts
+++ b/server/src/nest/ai-connections/providers/anthropic-messages.client.ts
@@ -23,6 +23,8 @@ import {
} from './provider-http';
import { readSseEvents } from './sse-lines';
+import { createHash, type Hash } from 'node:crypto';
+
export const ANTHROPIC_VERSION = '2023-06-01';
/**
* The answer cap of one step, which Anthropic requires to be set: the most
@@ -40,18 +42,50 @@ function imageBlock(image: AiImage): ContentBlock {
return { type: 'image', source: { type: 'base64', media_type: image.mimeType, data: image.data } };
}
+/**
+ * What a thinking block is bound to: Anthropic checks its signature against
+ * everything the request sends before it (the system blocks, the tools, the
+ * earlier turns) and refuses the whole request when any of it changed since
+ * the block was written. The history does change: a tool group loaded later
+ * in the turn, an earlier answer cut short once a new question follows, a
+ * held change applied since, a trip card that moved on. The fingerprint of
+ * what was sent before a step is kept with its record (AnthropicTurn), and
+ * its thinking goes back only while the request still sends the same before
+ * it (#3094).
+ */
+export class SentBefore {
+ private readonly hash: Hash;
+
+ constructor(head: unknown) {
+ this.hash = createHash('sha256').update(JSON.stringify(head));
+ }
+
+ add(role: AnthropicMessage['role'], blocks: readonly ContentBlock[]): void {
+ for (const block of blocks) this.hash.update(`${role}\n${JSON.stringify(block)}\n`);
+ }
+
+ fingerprint(): string {
+ return this.hash.copy().digest('base64url');
+ }
+}
+
/**
* The provider-neutral history as Messages API turns: a tool result is a
* `tool_result` block of a user turn, and turns of the same role that follow
* each other merge into one, since the API wants them alternating. An image
* of a tool result goes inside that `tool_result`, after its text, where the
* model reads it as what the tool produced; a user's images go before their
- * words.
+ * words. A recorded answer keeps its thinking only where `sent` still holds
+ * what was sent before it; without a record of that it goes back without.
*/
-export function toAnthropicMessages(messages: AiChatMessage[]): AnthropicMessage[] {
+export function toAnthropicMessages(
+ messages: AiChatMessage[],
+ sent: SentBefore = new SentBefore(null),
+): AnthropicMessage[] {
const out: AnthropicMessage[] = [];
const push = (role: AnthropicMessage['role'], blocks: ContentBlock[]) => {
if (blocks.length === 0) return;
+ sent.add(role, blocks);
const last = out.at(-1);
if (last?.role === role) last.content.push(...blocks);
else out.push({ role, content: blocks });
@@ -60,7 +94,11 @@ export function toAnthropicMessages(messages: AiChatMessage[]): AnthropicMessage
if (message.role === 'user') {
push('user', [...(message.images ?? []).map(imageBlock), { type: 'text', text: message.text }]);
} else if (message.role === 'assistant' && message.providerState?.adapter === 'anthropic-messages') {
- push('assistant', message.providerState.blocks.filter((block) => !isBlankText(block)).map(replayed));
+ const bound = message.providerState.sentBefore === sent.fingerprint();
+ const blocks = message.providerState.blocks.filter(
+ (block) => !isBlankText(block) && (bound || !isThinking(block)),
+ );
+ push('assistant', blocks.map(replayed));
} else if (message.role === 'assistant') {
push('assistant', [
...(message.text.trim() ? [{ type: 'text', text: message.text }] : []),
@@ -159,15 +197,8 @@ export class AnthropicMessagesClient implements AiChatClient {
const system = [request.system, request.context]
.filter((text): text is string => !!text)
.map((text) => ({ type: 'text', text, cache_control: CACHED }));
- const messages = toAnthropicMessages(request.messages);
- markHistoryForCache(messages, MAX_CACHE_BREAKPOINTS - system.length);
- const body = {
- model: this.model,
- max_tokens: MAX_TOKENS,
- stream: true,
- system,
- messages,
- ...(request.tools.length > 0 || request.webSearch
+ const tools =
+ request.tools.length > 0 || request.webSearch
? {
tools: [
...request.tools.map((tool) => ({
@@ -180,8 +211,12 @@ export class AnthropicMessagesClient implements AiChatClient {
// `none` is allowed with extended thinking, unlike forcing a tool.
...(request.toolChoice === 'none' ? { tool_choice: { type: 'none' } } : {}),
}
- : {}),
- };
+ : {};
+ const sent = new SentBefore({ model: this.model, system, ...tools });
+ const messages = toAnthropicMessages(request.messages, sent);
+ const sentBefore = sent.fingerprint();
+ markHistoryForCache(messages, MAX_CACHE_BREAKPOINTS - system.length);
+ const body = { model: this.model, max_tokens: MAX_TOKENS, stream: true, system, messages, ...tools };
const events = await openProviderStream(
this.fetcher,
this.kind,
@@ -199,7 +234,7 @@ export class AnthropicMessagesClient implements AiChatClient {
signal,
);
- const turn = new AnthropicTurn();
+ const turn = new AnthropicTurn(sentBefore);
for await (const sse of readSseEvents(events)) {
const event = parseEventData(sse.data);
if (!event) continue;
@@ -242,6 +277,9 @@ class AnthropicTurn {
private readonly cited = new Set<string>();
private searched = false;
+ /** `sentBefore`: the fingerprint of what the request sent before this answer, kept with its record. */
+ constructor(private readonly sentBefore: string) {}
+
*apply(event: Record<string, unknown>): Generator<AiChatEvent> {
const index = asCount(event.index);
switch (event.type) {
@@ -321,7 +359,7 @@ class AnthropicTurn {
const blocks = [...this.blocks.entries()].sort(([a], [b]) => a - b).map(([, open]) => open.block);
const thought = blocks.some(isThinking);
if (!this.searched && !thought) return null;
- return { adapter: 'anthropic-messages', blocks };
+ return { adapter: 'anthropic-messages', blocks, sentBefore: this.sentBefore };
}
}
diff --git a/server/src/nest/ai-connections/providers/provider-http.ts b/server/src/nest/ai-connections/providers/provider-http.ts
index 188e8dfc3..38902eb7a 100644
--- a/server/src/nest/ai-connections/providers/provider-http.ts
+++ b/server/src/nest/ai-connections/providers/provider-http.ts
@@ -70,10 +70,15 @@ export async function refusalOf(kind: AiConnectionKind, res: Response): Promise<
return failure;
}
-/** The field an error body names as refused (OpenAI's `param`, such as `input[12]`), when it is a bare path. */
+/**
+ * The field an error body names as refused, when it is a bare path: OpenAI's
+ * `param` (`input[12]`), or the path Anthropic's message starts with
+ * (`messages.1.content.0: ...`), of which nothing after the path is kept.
+ */
function refusedParamOf(body: unknown): string | undefined {
- const param = asRecord(asRecord(body).error).param;
- return typeof param === 'string' && /^[\w.[\]-]{1,80}$/.test(param) ? param : undefined;
+ const error = asRecord(asRecord(body).error);
+ const param = typeof error.param === 'string' ? error.param : /^([\w.]{1,80}): /.exec(asText(error.message))?.[1];
+ return param !== undefined && /^[\w.[\]-]{1,80}$/.test(param) ? param : undefined;
}
/** One SSE data payload as a JSON object; null for anything else (a `[DONE]`, a keepalive). */
diff --git a/server/tests/unit/nest/ai-connections/provider-adapters.test.ts b/server/tests/unit/nest/ai-connections/provider-adapters.test.ts
index f0d2f9103..0bcb7fb25 100644
--- a/server/tests/unit/nest/ai-connections/provider-adapters.test.ts
+++ b/server/tests/unit/nest/ai-connections/provider-adapters.test.ts
@@ -4,10 +4,15 @@
* neutral events, and how a refusal becomes an AiProviderError. No socket is
* opened: every adapter is handed a fetch that answers from the fixtures.
*/
-import type { AiChatEvent, AiChatRequest } from '../../../../src/nest/ai-connections/ai-chat-client.interface';
+import type {
+ AiChatEvent,
+ AiChatRequest,
+ AiProviderState,
+} from '../../../../src/nest/ai-connections/ai-chat-client.interface';
import {
AnthropicMessagesClient,
markHistoryForCache,
+ SentBefore,
toAnthropicMessages,
} from '../../../../src/nest/ai-connections/providers/anthropic-messages.client';
import { OpenAiChatClient, toChatMessages } from '../../../../src/nest/ai-connections/providers/openai-chat.client';
@@ -185,6 +190,26 @@ describe('provider errors', () => {
'[ai] chatgpt refused the request: HTTP 400 (invalid_request_error)',
]);
});
+ it('PERR-005: Anthropic names the refused field at the start of its message; the log keeps that path alone (#3094)', async () => {
+ const refused = (message: unknown) =>
+ failure(
+ new AnthropicMessagesClient(
+ 'm',
+ 'k',
+ fetchAnswering(jsonResponse(400, { type: 'error', error: { type: 'invalid_request_error', message } }))
+ .fetcher,
+ ).stream(REQUEST, signal()),
+ );
+ logWarn.mockClear();
+ await refused('messages.1.content.0: Invalid `signature` in `thinking` block. Dinner in Rome at 20:00.');
+ await refused('Dinner in Rome: at 20:00');
+ await refused(42);
+ expect(logWarn.mock.calls.map(([line]) => line)).toEqual([
+ '[ai] anthropic refused the request: HTTP 400 (invalid_request_error) at messages.1.content.0',
+ '[ai] anthropic refused the request: HTTP 400 (invalid_request_error)',
+ '[ai] anthropic refused the request: HTTP 400 (invalid_request_error)',
+ ]);
+ });
});
describe('toProviderSchema', () => {
@@ -353,6 +378,13 @@ describe('AnthropicMessagesClient', () => {
expect((err as Error).name).toBe('AbortError');
});
+ /** The fingerprint a history of this one question leaves, as toAnthropicMessages takes it without a request. */
+ const after = (question: string): string => {
+ const sent = new SentBefore(null);
+ toAnthropicMessages([{ role: 'user', text: question }], sent);
+ return sent.fingerprint();
+ };
+
it('ANTH-008: an answer that thought is replayed with its thinking blocks as they came, never marked for the cache (#2789)', async () => {
const thinking = { type: 'thinking', thinking: '', signature: 'sig-a1b2' };
const call = { type: 'tool_use', id: 'toolu_02', name: 'list_accommodations', input: {} };
@@ -381,7 +413,7 @@ describe('AnthropicMessagesClient', () => {
expect(events.filter((e) => e.type === 'text-delta')).toEqual([]);
expect(events).toContainEqual({
type: 'provider-state',
- state: { adapter: 'anthropic-messages', blocks: [thinking, call] },
+ state: { adapter: 'anthropic-messages', blocks: [thinking, call], sentBefore: expect.any(String) },
});
const next = toAnthropicMessages([
@@ -390,7 +422,11 @@ describe('AnthropicMessagesClient', () => {
role: 'assistant',
text: '',
toolCalls: [{ id: 'toolu_02', name: 'list_accommodations', args: {} }],
- providerState: { adapter: 'anthropic-messages', blocks: [thinking, call] },
+ providerState: {
+ adapter: 'anthropic-messages',
+ blocks: [thinking, call],
+ sentBefore: after('Where are we staying?'),
+ },
},
{ role: 'tool', toolCallId: 'toolu_02', name: 'list_accommodations', output: '[]' },
{ role: 'user', text: 'And in Kyoto?' },
@@ -406,7 +442,7 @@ describe('AnthropicMessagesClient', () => {
role: 'assistant',
text: '',
toolCalls: [],
- providerState: { adapter: 'anthropic-messages', blocks: [thinking] },
+ providerState: { adapter: 'anthropic-messages', blocks: [thinking], sentBefore: after('Hi') },
},
{ role: 'user', text: 'Still there?' },
]);
@@ -415,7 +451,11 @@ describe('AnthropicMessagesClient', () => {
expect(ended[0]?.content[0]?.cache_control).toEqual({ type: 'ephemeral' });
// The request is marked, the stored answer is not: a mark left on it would go out on every later step.
- const stored = { adapter: 'anthropic-messages' as const, blocks: [{ ...thinking }, { ...call }] };
+ const stored = {
+ adapter: 'anthropic-messages' as const,
+ blocks: [{ ...thinking }, { ...call }],
+ sentBefore: after('Hi'),
+ };
const marked = toAnthropicMessages([
{ role: 'user', text: 'Hi' },
{ role: 'assistant', text: '', toolCalls: [], providerState: stored },
@@ -425,6 +465,79 @@ describe('AnthropicMessagesClient', () => {
expect(marked[1]?.content[1]?.cache_control).toEqual({ type: 'ephemeral' });
expect(stored.blocks[1]).not.toHaveProperty('cache_control');
});
+ it('ANTH-010: thinking goes back only while the request sends what it was written after, else without it (#3094)', async () => {
+ const thought = [
+ { type: 'message_start', message: { usage: { input_tokens: 5, output_tokens: 1 } } },
+ { type: 'content_block_start', index: 0, content_block: { type: 'thinking', thinking: '', signature: '' } },
+ { type: 'content_block_delta', index: 0, delta: { type: 'thinking_delta', thinking: 'Look it up.' } },
+ { type: 'content_block_delta', index: 0, delta: { type: 'signature_delta', signature: 'sig-c3' } },
+ { type: 'content_block_stop', index: 0 },
+ {
+ type: 'content_block_start',
+ index: 1,
+ content_block: { type: 'tool_use', id: 'toolu_09', name: 'create_place' },
+ },
+ {
+ type: 'content_block_delta',
+ index: 1,
+ delta: { type: 'input_json_delta', partial_json: '{"name":"Ryoan-ji"}' },
+ },
+ { type: 'content_block_stop', index: 1 },
+ { type: 'message_delta', delta: { stop_reason: 'tool_use' }, usage: { output_tokens: 30 } },
+ { type: 'message_stop' },
+ ];
+ const first = await run(
+ new AnthropicMessagesClient('claude-sonnet-5-5', 'k', fetchAnswering(streamResponse(thought)).fetcher).stream(
+ REQUEST,
+ signal(),
+ ),
+ );
+ const recorded = first.find((e) => e.type === 'provider-state');
+ if (recorded?.type !== 'provider-state' || recorded.state.adapter !== 'anthropic-messages')
+ throw new Error('no record');
+ const record = recorded.state;
+ const followUp = (request: AiChatRequest, state: AiProviderState = record): AiChatRequest => ({
+ ...request,
+ messages: [
+ ...request.messages,
+ {
+ role: 'assistant',
+ text: '',
+ toolCalls: [{ id: 'toolu_09', name: 'create_place', args: {} }],
+ providerState: state,
+ },
+ { role: 'tool', toolCallId: 'toolu_09', name: 'create_place', output: '{"id":8}' },
+ { role: 'user', text: 'And Ginkaku-ji?' },
+ ],
+ });
+ const sentTypes = async (request: AiChatRequest, model = 'claude-sonnet-5-5') => {
+ const http = fetchAnswering(streamResponse(STREAM));
+ await run(new AnthropicMessagesClient(model, 'k', http.fetcher).stream(request, signal()));
+ const body = JSON.parse(String(http.calls[0]?.init.body)) as {
+ messages: Array<{ content: Array<{ type: string }> }>;
+ };
+ return body.messages.flatMap((message) => message.content.map((block) => block.type));
+ };
+ const [question, answer, result, thanks] = REQUEST.messages;
+ if (result?.role !== 'tool' || !question || !answer || !thanks) throw new Error('fixture');
+
+ // Everything before the answer as it was: its thinking goes back with its call.
+ expect(await sentTypes(followUp(REQUEST))).toContain('thinking');
+ // A tool group loaded since, the trip card moved on, an earlier answer cut short, another model, a record
+ // kept before the fingerprint: the provider would refuse the block and the request with it, so it stays out.
+ const changed: Array<[AiChatRequest, string?]> = [
+ [followUp({ ...REQUEST, tools: [...REQUEST.tools, { ...TOOL, name: 'list_bookings' }] })],
+ [followUp({ ...REQUEST, context: 'Trip: Japan, 3 days, 1 place' })],
+ [followUp({ ...REQUEST, messages: [question, answer, { ...result, output: '{"id":7,"more":1}' }, thanks] })],
+ [followUp(REQUEST), 'claude-opus-5-5'],
+ [followUp(REQUEST, { adapter: 'anthropic-messages', blocks: record.blocks })],
+ ];
+ for (const [request, model] of changed) {
+ const types = await sentTypes(request, model);
+ expect(types).not.toContain('thinking');
+ expect(types).toContain('tool_use');
+ }
+ });
});
describe('OpenAiChatClient', () => {
@@ -1128,6 +1241,7 @@ describe('web search through the provider', () => {
RESULT,
{ type: 'text', text: 'Eat at A.' },
],
+ sentBefore: expect.any(String),
},
},
{ type: 'finish', reason: 'stop' },