Skip to content

Commit 1cb67e3

Browse files
committed
perf(agents): avoid repeated turn and tool preparation
1 parent a6d94f2 commit 1cb67e3

4 files changed

Lines changed: 58 additions & 37 deletions

File tree

‎config/assertion-safety-baseline.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1798,7 +1798,7 @@ src/agents/embedded-agent-runner/run/attempt-client-tools.ts 2
17981798
src/agents/embedded-agent-runner/run/attempt-context-summary.ts 2
17991799
src/agents/embedded-agent-runner/run/attempt-execution-phase.ts 1
18001800
src/agents/embedded-agent-runner/run/attempt-finalize.ts 3
1801-
src/agents/embedded-agent-runner/run/attempt-history.ts 19
1801+
src/agents/embedded-agent-runner/run/attempt-history.ts 17
18021802
src/agents/embedded-agent-runner/run/attempt-llm-boundary.ts 19
18031803
src/agents/embedded-agent-runner/run/attempt-normalization.ts 1
18041804
src/agents/embedded-agent-runner/run/attempt-prompt-build.ts 2

‎src/agents/agent-tools.schema.ts‎

Lines changed: 8 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -48,19 +48,6 @@ function schemaHasRequiredParams(schema: Record<string, unknown>): boolean {
4848
return false;
4949
}
5050

51-
function addEmptyObjectArgumentPreparation(tool: AnyAgentTool, parameters: unknown): AnyAgentTool {
52-
if (!isObjectSchemaWithNoRequiredParams(parameters)) {
53-
return tool;
54-
}
55-
return {
56-
...tool,
57-
prepareArguments: (args: unknown) => {
58-
const prepared = tool.prepareArguments ? tool.prepareArguments(args) : args;
59-
return prepared === null || prepared === undefined ? {} : prepared;
60-
},
61-
};
62-
}
63-
6451
/** Normalize a tool's parameter schema for the selected provider/model. */
6552
export function normalizeToolParameters(
6653
tool: AnyAgentTool,
@@ -74,9 +61,12 @@ export function normalizeToolParameters(
7461
return tool;
7562
}
7663
const parameters = normalizeToolParameterSchema(schema, options);
77-
return copyAgentToolMetadata(tool, {
78-
...tool,
79-
...addEmptyObjectArgumentPreparation(tool, parameters),
80-
parameters,
81-
});
64+
const normalized = { ...tool, parameters };
65+
if (isObjectSchemaWithNoRequiredParams(parameters)) {
66+
normalized.prepareArguments = (args: unknown) => {
67+
const prepared = tool.prepareArguments ? tool.prepareArguments(args) : args;
68+
return prepared === null || prepared === undefined ? {} : prepared;
69+
};
70+
}
71+
return copyAgentToolMetadata(tool, normalized);
8272
}

‎src/agents/embedded-agent-runner/run/attempt-history.ts‎

Lines changed: 43 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -105,39 +105,68 @@ export function resolveUserTranscriptMessages(
105105
messages: AgentMessage[],
106106
contexts: readonly UserTranscriptContext[] | undefined,
107107
override: CurrentUserTimestampMatch | undefined,
108-
): Array<AgentMessage | undefined> {
108+
): Array<AgentMessage | undefined> | undefined {
109+
if (!contexts?.length) {
110+
return undefined;
111+
}
109112
const resolved = Array.from(
110113
{ length: messages.length },
111114
() => undefined as AgentMessage | undefined,
112115
);
113-
if (!contexts?.length) {
114-
return resolved;
115-
}
116-
const activeUserMessageIndex = findActiveUserMessageIndex(messages);
117116
const unusedContexts = new Set(contexts);
117+
const byRuntimeMessage = new Map<AgentMessage, UserTranscriptContext[]>();
118+
for (const context of unusedContexts) {
119+
const bucket = byRuntimeMessage.get(context.runtimeMessage);
120+
if (bucket) {
121+
bucket.push(context);
122+
} else {
123+
byRuntimeMessage.set(context.runtimeMessage, [context]);
124+
}
125+
}
118126
// Reserve object-identity matches before structural fallback so duplicate
119127
// timestamp/text turns cannot consume a later message's exact pairing.
120128
for (const [index, message] of messages.entries()) {
121129
if (message.role !== "user") {
122130
continue;
123131
}
124-
const context = [...unusedContexts].find((candidate) => candidate.runtimeMessage === message);
132+
const context = byRuntimeMessage.get(message)?.shift();
125133
if (!context) {
126134
continue;
127135
}
128136
resolved[index] = context.transcriptMessage;
129137
unusedContexts.delete(context);
130138
}
139+
if (unusedContexts.size === 0) {
140+
return resolved;
141+
}
142+
const byTimestamp = new Map<number, UserTranscriptContext[]>();
143+
for (const context of unusedContexts) {
144+
const timestamp = context.runtimeMessage.timestamp;
145+
if (typeof timestamp !== "number" || !Number.isFinite(timestamp)) {
146+
continue;
147+
}
148+
const bucket = byTimestamp.get(timestamp);
149+
if (bucket) {
150+
bucket.push(context);
151+
} else {
152+
byTimestamp.set(timestamp, [context]);
153+
}
154+
}
155+
const activeUserMessageIndex = findActiveUserMessageIndex(messages);
131156
for (const [index, message] of messages.entries()) {
132157
if (message.role !== "user" || resolved[index]) {
133158
continue;
134159
}
135-
const context = [...unusedContexts].find((candidate) =>
136-
userMessageMatchesTranscriptContext(
137-
message,
138-
candidate,
139-
index === activeUserMessageIndex ? override : undefined,
140-
),
160+
const timestamp = message.timestamp;
161+
const candidates = typeof timestamp === "number" ? byTimestamp.get(timestamp) : undefined;
162+
const context = candidates?.find(
163+
(candidate) =>
164+
unusedContexts.has(candidate) &&
165+
userMessageMatchesTranscriptContext(
166+
message,
167+
candidate,
168+
index === activeUserMessageIndex ? override : undefined,
169+
),
141170
);
142171
if (!context) {
143172
continue;
@@ -156,8 +185,8 @@ function userMessageMatchesTranscriptContext(
156185
if (message === context.runtimeMessage) {
157186
return true;
158187
}
159-
const messageTimestamp = (message as { timestamp?: unknown }).timestamp;
160-
const runtimeTimestamp = (context.runtimeMessage as { timestamp?: unknown }).timestamp;
188+
const messageTimestamp = message.timestamp;
189+
const runtimeTimestamp = context.runtimeMessage.timestamp;
161190
if (
162191
typeof messageTimestamp !== "number" ||
163192
!Number.isFinite(messageTimestamp) ||

‎src/agents/embedded-agent-runner/run/attempt-llm-boundary.ts‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -468,9 +468,7 @@ function stripHistoricalInboundMetadataFromUserMessages(
468468
return message;
469469
}
470470
const content = (message as { content?: unknown }).content;
471-
const injectMediaText = hasPersistedMedia(message) && !hasNonBlankUserText(content);
472-
// #111204: restore marked path lines here, never in UI-visible transcript storage.
473-
const mediaOnlyText = buildLateMediaAttachedProjection(message).text ?? MEDIA_ONLY_USER_TEXT;
471+
const injectMediaText = !hasNonBlankUserText(content) && hasPersistedMedia(message);
474472
const isActive = index === activeUserMessageIndex;
475473
const override = options?.currentUserTimestampOverride;
476474
const runtimeTimestamp = (message as { timestamp?: unknown }).timestamp;
@@ -495,7 +493,11 @@ function stripHistoricalInboundMetadataFromUserMessages(
495493
// keeps such messages byte-stable across current↔historical (the envelope is
496494
// present in both forms) and avoids double-stamping.
497495
const transformText = (raw: string): string => {
498-
const sourceText = injectMediaText && !raw.trim() ? mediaOnlyText : raw;
496+
// Restore late-media paths only for blank media turns, never into transcript storage.
497+
const sourceText =
498+
injectMediaText && !raw.trim()
499+
? (buildLateMediaAttachedProjection(message).text ?? MEDIA_ONLY_USER_TEXT)
500+
: raw;
499501
const { body, envelope } = splitLeadingTimestampEnvelope(sourceText);
500502
if (envelope || sourceText.includes(BOUNDARY_CRON_TIME_MARKER)) {
501503
if (isActive) {

0 commit comments

Comments
 (0)