Skip to content

Commit 1db2682

Browse files
committed
fix(acp): prevent assistant message fragmentation on background tool updates & filter leaked harness telemetry
Fixes #13133 - Only close active assistant segments on new tool calls (isNew: previous === undefined) instead of on every in-flight tool progress or completion event. - Prevent duplicate `assistant:assistant:` message IDs in ProviderRuntimeIngestion. - Add streaming filter to strip echoed <SYSTEM_MESSAGE> blocks and harness preambles from Antigravity session chunks. - Add negative constraint to buildRuntimeInstructions preventing models from quoting harness telemetry.
1 parent d7819c1 commit 1db2682

7 files changed

Lines changed: 211 additions & 44 deletions

File tree

‎apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,8 @@ import * as ThreadPlanProgress from "../ThreadPlanProgress.ts";
6161
import {
6262
ProviderRuntimeIngestionLive,
6363
splitBufferedAssistantText,
64+
canonicalAssistantMessageId,
65+
assistantSegmentMessageId,
6466
} from "./ProviderRuntimeIngestion.ts";
6567
import { DEFAULT_THREAD_TITLE } from "../threadTitles.ts";
6668
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
@@ -5175,3 +5177,20 @@ describe("splitBufferedAssistantText", () => {
51755177
});
51765178
});
51775179
});
5180+
5181+
describe("assistant message id canonicalization and segmentation", () => {
5182+
it("avoids double-prefixing assistant message IDs", () => {
5183+
expect(canonicalAssistantMessageId("item-123")).toBe("assistant:item-123");
5184+
expect(canonicalAssistantMessageId("assistant:item-123")).toBe("assistant:item-123");
5185+
});
5186+
5187+
it("normalizes segments without nesting the prefix", () => {
5188+
expect(assistantSegmentMessageId("item-123", 0)).toBe("assistant:item-123");
5189+
expect(assistantSegmentMessageId("assistant:item-123", 0)).toBe("assistant:item-123");
5190+
expect(assistantSegmentMessageId("item-123", 1)).toBe("assistant:item-123:segment:1");
5191+
expect(assistantSegmentMessageId("assistant:item-123", 1)).toBe("assistant:item-123:segment:1");
5192+
expect(assistantSegmentMessageId("reasoning:thought-1", 1, "reasoning")).toBe(
5193+
"reasoning:thought-1:segment:1",
5194+
);
5195+
});
5196+
});

‎apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts‎

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -297,14 +297,19 @@ function messageStreamRoleOf(messageId: MessageId): MessageStreamRole {
297297
return messageId.startsWith(REASONING_MESSAGE_ID_PREFIX) ? "reasoning" : "assistant";
298298
}
299299

300-
function assistantSegmentMessageId(
300+
export function canonicalAssistantMessageId(rawId: string): MessageId {
301+
return MessageId.make(rawId.startsWith("assistant:") ? rawId : `assistant:${rawId}`);
302+
}
303+
304+
export function assistantSegmentMessageId(
301305
baseKey: string,
302306
segmentIndex: number,
303307
role: MessageStreamRole = "assistant",
304308
): MessageId {
305309
const prefix = role === "reasoning" ? REASONING_MESSAGE_ID_PREFIX : "assistant:";
310+
const normalizedBaseKey = baseKey.startsWith(prefix) ? baseKey.slice(prefix.length) : baseKey;
306311
return MessageId.make(
307-
segmentIndex === 0 ? `${prefix}${baseKey}` : `${prefix}${baseKey}:segment:${segmentIndex}`,
312+
segmentIndex === 0 ? `${prefix}${normalizedBaseKey}` : `${prefix}${normalizedBaseKey}:segment:${segmentIndex}`,
308313
);
309314
}
310315

@@ -2228,8 +2233,8 @@ const make = Effect.gen(function* () {
22282233
const assistantCompletion =
22292234
event.type === "item.completed" && event.payload.itemType === "assistant_message"
22302235
? {
2231-
messageId: MessageId.make(
2232-
`assistant:${event.itemId ?? event.turnId ?? event.eventId}`,
2236+
messageId: canonicalAssistantMessageId(
2237+
String(event.itemId ?? event.turnId ?? event.eventId),
22332238
),
22342239
fallbackText: event.payload.detail,
22352240
}
@@ -2625,8 +2630,8 @@ const make = Effect.gen(function* () {
26252630
checkpointRef: CheckpointRef.make(`provider-diff:${event.eventId}`),
26262631
status: "missing",
26272632
files: [],
2628-
assistantMessageId: MessageId.make(
2629-
`assistant:${event.itemId ?? event.turnId ?? event.eventId}`,
2633+
assistantMessageId: canonicalAssistantMessageId(
2634+
String(event.itemId ?? event.turnId ?? event.eventId),
26302635
),
26312636
checkpointTurnCount: maxCheckpointTurnCount(checkpointContext.checkpoints) + 1,
26322637
createdAt: now,

‎apps/server/src/provider/RuntimeInstructions.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
const SYSTEM_TELEMETRY_INSTRUCTIONS = `<system_messages>
2+
Internal harness notifications, background task updates, and messages enclosed in <SYSTEM_MESSAGE> are strictly for contextual awareness. Never repeat, quote, or echo <SYSTEM_MESSAGE> tags, background task logs, or internal harness status lines to the user.
3+
</system_messages>`;
4+
15
const PULL_REQUEST_LINKING_INSTRUCTIONS = `<pull_request_linking>
26
When the t3-code MCP server exposes link_pull_request, you must use it to register every pull request you create or work on for this thread. Call link_pull_request with the full PR URL immediately after creating a PR or starting work on an existing PR. For a stack, call it for every layer, not just the current branch or the top PR. This applies when creating or updating PRs through gh, gh stack, another CLI, or the host API: those operations do not register the PRs with this thread. Linking an already-linked PR is safe. Before finishing PR work, call list_thread_pull_requests and link any PR from your work that is missing. Do not link unrelated PRs mentioned only as background. If a linking call fails, report that failure instead of claiming the PR is linked.
37
</pull_request_linking>`;
@@ -13,7 +17,7 @@ export function buildRuntimeInstructions(runtime: {
1317
const effort = toSingleLine(runtime.reasoningEffort ?? "");
1418
const modelInfo = model && model !== "auto" && model !== "default" ? `, as ${model}` : "";
1519
const effortInfo = effort ? ` with ${effort} reasoning effort` : "";
16-
return `<runtime_info>In case you're asked: you are running in T3 Code through the ${harness} harness${modelInfo}${effortInfo}. No need to mention this otherwise. You can embed images and videos in your response using Markdown with absolute file paths.</runtime_info>\n\n${PULL_REQUEST_LINKING_INSTRUCTIONS}`;
20+
return `<runtime_info>In case you're asked: you are running in T3 Code through the ${harness} harness${modelInfo}${effortInfo}. No need to mention this otherwise. You can embed images and videos in your response using Markdown with absolute file paths.</runtime_info>\n\n${PULL_REQUEST_LINKING_INSTRUCTIONS}\n\n${SYSTEM_TELEMETRY_INSTRUCTIONS}`;
1721
}
1822

1923
function toSingleLine(value: string): string {

‎apps/server/src/provider/acp/AcpSessionRuntime.ts‎

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1202,11 +1202,7 @@ const handleSessionUpdate = ({
12021202
}
12031203
for (const event of parsed.events) {
12041204
if (event._tag === "ToolCallUpdated") {
1205-
yield* closeActiveAssistantSegment({
1206-
queue,
1207-
assistantSegmentRef,
1208-
});
1209-
const { merged, decision } = yield* Ref.modify(toolCallsRef, (current) => {
1205+
const { merged, decision, isNew } = yield* Ref.modify(toolCallsRef, (current) => {
12101206
const tracked = current.get(event.toolCall.toolCallId);
12111207
const previous = tracked?.state;
12121208
const nextToolCall = mergeToolCallState(previous, event.toolCall);
@@ -1228,8 +1224,14 @@ const handleSessionUpdate = ({
12281224
skippedSinceEmit: decision.skippedSinceEmit,
12291225
});
12301226
}
1231-
return [{ merged: nextToolCall, decision }, next] as const;
1227+
return [{ merged: nextToolCall, decision, isNew: previous === undefined }, next] as const;
12321228
});
1229+
if (isNew) {
1230+
yield* closeActiveAssistantSegment({
1231+
queue,
1232+
assistantSegmentRef,
1233+
});
1234+
}
12331235
if (!decision.emit) {
12341236
continue;
12351237
}
@@ -1241,6 +1243,9 @@ const handleSessionUpdate = ({
12411243
continue;
12421244
}
12431245
if (event._tag === "ContentDelta") {
1246+
if (event.text.length === 0) {
1247+
continue;
1248+
}
12441249
if (event.text.trim().length === 0) {
12451250
const assistantSegmentState = yield* Ref.get(assistantSegmentRef);
12461251
if (!assistantSegmentState.activeItemId) {

‎apps/server/src/provider/acp/AntigravityAcpSupport.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ import {
2323
makeAntigravityStdoutTransform,
2424
} from "../antigravityAuthSupport.ts";
2525
import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
26-
import { normalizeAntigravitySessionUpdate } from "./AntigravityProtocol.ts";
26+
import { makeAntigravitySessionUpdateTransformer } from "./AntigravityProtocol.ts";
2727

2828
export interface AntigravityAcpRuntimeInput extends Omit<
2929
AcpSessionRuntime.AcpSessionRuntimeOptions,
@@ -78,7 +78,7 @@ export const makeAntigravityAcpRuntime = Effect.fn("makeAntigravityAcpRuntime")(
7878
onStderr: makeAntigravityStderrHandler(
7979
input.onAuthorizationUrl ? { onAuthorizationUrl: input.onAuthorizationUrl } : {},
8080
),
81-
transformSessionUpdate: normalizeAntigravitySessionUpdate,
81+
transformSessionUpdate: makeAntigravitySessionUpdateTransformer(),
8282
}).pipe(
8383
Layer.provide(
8484
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, input.childProcessSpawner),

‎apps/server/src/provider/acp/AntigravityProtocol.test.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ import {
1111
classifyAntigravitySubagentToolCall,
1212
isAntigravityUserInputRequest,
1313
makeAntigravityUserInputResponse,
14+
createAntigravityMessageFilter,
15+
makeAntigravitySessionUpdateTransformer,
1416
normalizeAntigravitySessionUpdate,
1517
normalizeAntigravityToolCall,
1618
sanitizeAntigravityToolPayload,
@@ -482,4 +484,33 @@ describe("Antigravity tool results", () => {
482484
);
483485
expect(isAntigravityOpenCommand(completed)).toBe(false);
484486
});
487+
488+
it("sanitizes echoed SYSTEM_MESSAGE telemetry blocks from agent message chunks", () => {
489+
const transformer = makeAntigravitySessionUpdateTransformer();
490+
const leaked =
491+
"The following is a <SYSTEM_MESSAGE> not actually sent by the user. It is provided by the system as important information to pay attention to.\n\n<SYSTEM_MESSAGE>\n[Message] timestamp=2026-09-22T20:00:23Z sender=task-1 content=Task finished\n</SYSTEM_MESSAGE>Here is the real answer.";
492+
493+
const notification = {
494+
sessionId: "session-1",
495+
update: {
496+
sessionUpdate: "agent_message_chunk" as const,
497+
content: { type: "text" as const, text: leaked },
498+
},
499+
};
500+
501+
const normalized = transformer(notification);
502+
expect((normalized.update as any).content.text).toBe("Here is the real answer.");
503+
});
504+
505+
it("sanitizes streamed SYSTEM_MESSAGE blocks across chunk boundaries", () => {
506+
const filter = createAntigravityMessageFilter();
507+
expect(filter("Before ")).toBe("Before ");
508+
expect(
509+
filter(
510+
"The following is a <SYSTEM_MESSAGE> not actually sent by the user.\n\n<SYSTEM_MESSAGE>\n[Message] part 1",
511+
),
512+
).toBe("");
513+
expect(filter("\npart 2\nOutput: [mobile] OK\n")).toBe("");
514+
expect(filter("</SYSTEM_MESSAGE> After")).toBe(" After");
515+
});
485516
});

‎apps/server/src/provider/acp/AntigravityProtocol.ts‎

Lines changed: 132 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -234,39 +234,142 @@ export function sanitizeAntigravityToolPayload(payload: unknown): unknown {
234234
return sanitizeToolValue(payload, { nodes: 512, text: 64_000 }, 0);
235235
}
236236

237-
/** The runtime uses this before it retains tool state or dispatches raw callbacks. */
238-
export function normalizeAntigravitySessionUpdate(
237+
/**
238+
* Stateful streaming filter that discards internal Antigravity harness system messages
239+
* (e.g. `<SYSTEM_MESSAGE>...</SYSTEM_MESSAGE>` and the system preamble) that the model
240+
* may mistakenly echo back into its assistant message or thought stream.
241+
*/
242+
export function createAntigravityMessageFilter(): (text: string) => string {
243+
let inSystemMessage = false;
244+
245+
return (text: string): string => {
246+
let result = "";
247+
let cursor = 0;
248+
249+
while (cursor < text.length) {
250+
if (inSystemMessage) {
251+
const closeTagIndex = text.indexOf("</SYSTEM_MESSAGE>", cursor);
252+
if (closeTagIndex === -1) {
253+
// Entire remainder of text is inside <SYSTEM_MESSAGE>
254+
break;
255+
}
256+
cursor = closeTagIndex + "</SYSTEM_MESSAGE>".length;
257+
inSystemMessage = false;
258+
continue;
259+
}
260+
261+
const preambleText = "The following is a <SYSTEM_MESSAGE> not actually sent by the user";
262+
const preambleIndex = text.indexOf(preambleText, cursor);
263+
const openTagIndex = text.indexOf("<SYSTEM_MESSAGE>", cursor);
264+
265+
let nextIndex = -1;
266+
let isPreamble = false;
267+
268+
if (preambleIndex !== -1 && openTagIndex !== -1) {
269+
if (preambleIndex < openTagIndex) {
270+
nextIndex = preambleIndex;
271+
isPreamble = true;
272+
} else {
273+
nextIndex = openTagIndex;
274+
}
275+
} else if (preambleIndex !== -1) {
276+
nextIndex = preambleIndex;
277+
isPreamble = true;
278+
} else if (openTagIndex !== -1) {
279+
nextIndex = openTagIndex;
280+
}
281+
282+
if (nextIndex === -1) {
283+
result += text.slice(cursor);
284+
break;
285+
}
286+
287+
result += text.slice(cursor, nextIndex);
288+
289+
if (isPreamble) {
290+
const afterPreamble = text.indexOf("<SYSTEM_MESSAGE>", nextIndex);
291+
if (afterPreamble !== -1) {
292+
cursor = afterPreamble + "<SYSTEM_MESSAGE>".length;
293+
inSystemMessage = true;
294+
} else {
295+
const nextNewline = text.indexOf("\n", nextIndex);
296+
if (nextNewline !== -1) {
297+
cursor = nextNewline + 1;
298+
} else {
299+
cursor = text.length;
300+
}
301+
}
302+
} else {
303+
cursor = nextIndex + "<SYSTEM_MESSAGE>".length;
304+
inSystemMessage = true;
305+
}
306+
}
307+
308+
return result;
309+
};
310+
}
311+
312+
export function makeAntigravitySessionUpdateTransformer(): (
239313
notification: EffectAcpSchema.SessionNotification,
240-
): EffectAcpSchema.SessionNotification {
241-
const update = notification.update;
242-
if (update.sessionUpdate !== "tool_call" && update.sessionUpdate !== "tool_call_update") {
243-
return notification;
244-
}
245-
const contentBudget = { nodes: 512, text: 32_000 };
246-
const content = update.content?.flatMap((entry) => {
247-
const decoded = Option.getOrUndefined(
248-
decodeToolCallContent(sanitizeToolValue(entry, contentBudget, 0)),
249-
);
250-
return decoded === undefined ? [] : [decoded];
251-
});
252-
const meta = sanitizeAntigravityToolPayload(update._meta);
253-
return {
254-
...notification,
255-
update: {
256-
...update,
257-
...(typeof update.title === "string" ? { title: boundText(update.title) } : {}),
258-
...(update.rawInput !== undefined
259-
? { rawInput: sanitizeAntigravityToolPayload(update.rawInput) }
260-
: {}),
261-
...(update.rawOutput !== undefined
262-
? { rawOutput: sanitizeAntigravityToolPayload(update.rawOutput) }
263-
: {}),
264-
...(update.content !== undefined ? { content: content ?? [] } : {}),
265-
...(update._meta !== undefined ? { _meta: Predicate.isObject(meta) ? meta : null } : {}),
266-
},
314+
) => EffectAcpSchema.SessionNotification {
315+
const filterMessage = createAntigravityMessageFilter();
316+
const filterThought = createAntigravityMessageFilter();
317+
318+
return (notification: EffectAcpSchema.SessionNotification): EffectAcpSchema.SessionNotification => {
319+
const update = notification.update;
320+
if (update.sessionUpdate === "agent_message_chunk" || update.sessionUpdate === "agent_thought_chunk") {
321+
if (update.content.type === "text") {
322+
const filter = update.sessionUpdate === "agent_message_chunk" ? filterMessage : filterThought;
323+
const filtered = filter(update.content.text);
324+
if (filtered !== update.content.text) {
325+
return {
326+
...notification,
327+
update: {
328+
...update,
329+
content: {
330+
...update.content,
331+
text: filtered,
332+
},
333+
},
334+
};
335+
}
336+
}
337+
return notification;
338+
}
339+
if (update.sessionUpdate !== "tool_call" && update.sessionUpdate !== "tool_call_update") {
340+
return notification;
341+
}
342+
const contentBudget = { nodes: 512, text: 32_000 };
343+
const content = update.content?.flatMap((entry) => {
344+
const decoded = Option.getOrUndefined(
345+
decodeToolCallContent(sanitizeToolValue(entry, contentBudget, 0)),
346+
);
347+
return decoded === undefined ? [] : [decoded];
348+
});
349+
const meta = sanitizeAntigravityToolPayload(update._meta);
350+
return {
351+
...notification,
352+
update: {
353+
...update,
354+
...(typeof update.title === "string" ? { title: boundText(update.title) } : {}),
355+
...(update.rawInput !== undefined
356+
? { rawInput: sanitizeAntigravityToolPayload(update.rawInput) }
357+
: {}),
358+
...(update.rawOutput !== undefined
359+
? { rawOutput: sanitizeAntigravityToolPayload(update.rawOutput) }
360+
: {}),
361+
...(update.content !== undefined ? { content: content ?? [] } : {}),
362+
...(update._meta !== undefined ? { _meta: Predicate.isObject(meta) ? meta : null } : {}),
363+
},
364+
};
267365
};
268366
}
269367

368+
/** The runtime uses this before it retains tool state or dispatches raw callbacks. */
369+
export const normalizeAntigravitySessionUpdate: (
370+
notification: EffectAcpSchema.SessionNotification,
371+
) => EffectAcpSchema.SessionNotification = makeAntigravitySessionUpdateTransformer();
372+
270373
function localImagePath(imagePath: string | undefined): string | undefined {
271374
if (!imagePath || imagePath.length > TOOL_TEXT_LIMIT) {
272375
return undefined;

0 commit comments

Comments
 (0)