Skip to content

Commit b4a0fc5

Browse files
authored
perf(agents): reduce repeated turn setup latency (#105220)
* perf(agents): reuse prepared auth route models * chore: leave release notes to release automation
1 parent 9bdb2a5 commit b4a0fc5

2 files changed

Lines changed: 42 additions & 7 deletions

File tree

‎src/agents/embedded-agent-runner/run.overflow-compaction.test.ts‎

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1922,6 +1922,7 @@ describe("runEmbeddedAgent overflow compaction trigger routing", () => {
19221922
}
19231923

19241924
expect(mockedGetApiKeyForModel).toHaveBeenCalledTimes(1);
1925+
expect(mockedResolveModelAsync).toHaveBeenCalledTimes(1);
19251926
expect(mockedBuildAgentRuntimePlan).toHaveBeenCalledTimes(1);
19261927
expect(authStorage.setRuntimeApiKey).toHaveBeenCalledTimes(1);
19271928
const pluginParams = expectMockCallFields(pluginRunAttempt, {
@@ -2840,11 +2841,6 @@ describe("runEmbeddedAgent overflow compaction trigger routing", () => {
28402841
baseUrl: "https://api.openai.com/v1",
28412842
authStorage,
28422843
});
2843-
queueOpenAIResolvedModel({
2844-
api: "openai-responses",
2845-
baseUrl: "https://api.openai.com/v1",
2846-
authStorage,
2847-
});
28482844
queueOpenAIResolvedModel({
28492845
api: "openai-chatgpt-responses",
28502846
baseUrl: "https://chatgpt.com/backend-api/codex",
@@ -2906,6 +2902,7 @@ describe("runEmbeddedAgent overflow compaction trigger routing", () => {
29062902
}
29072903

29082904
expect(mockedGetApiKeyForModel).toHaveBeenCalledOnce();
2905+
expect(mockedResolveModelAsync).toHaveBeenCalledTimes(3);
29092906
expect(pluginRunAttempt).toHaveBeenCalledTimes(2);
29102907
const firstAttempt = mockCallArg(pluginRunAttempt) as EmbeddedRunAttemptParams;
29112908
const secondAttempt = mockCallArg(pluginRunAttempt, 1) as EmbeddedRunAttemptParams;

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

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1495,6 +1495,7 @@ async function runEmbeddedAgentInternal(
14951495
agentHarness = selectHarnessForModel(effectiveModel);
14961496
pluginHarnessOwnsTransport = agentHarness.id !== "openclaw";
14971497

1498+
const authStages = log.isEnabled("trace") ? createEmbeddedRunStageTracker() : undefined;
14981499
const usesOpenAIAuthRouting = provider === OPENAI_PROVIDER_ID;
14991500
const openClawNativeCodexResponsesNeedsAuthBootstrap =
15001501
!pluginHarnessOwnsTransport &&
@@ -1532,6 +1533,7 @@ async function runEmbeddedAgentInternal(
15321533
params.authProfileIdSource === "user" ? params.authProfileId : undefined,
15331534
});
15341535
}
1536+
authStages?.mark("scope");
15351537
const attemptAuthProfileStore = usesOpenAIAuthRouting
15361538
? ensureAuthProfileStore(agentDir, {
15371539
externalCliProviderIds: [OPENAI_PROVIDER_ID],
@@ -1550,6 +1552,7 @@ async function runEmbeddedAgentInternal(
15501552
ensureAuthProfileStoreWithoutExternalProfiles(agentDir, {
15511553
allowKeychainPrompt: false,
15521554
}));
1555+
authStages?.mark("store");
15531556
const requestedProfileId = params.authProfileId?.trim() || undefined;
15541557
const lockedProfileId =
15551558
params.authProfileIdSource === "user" ? requestedProfileId : undefined;
@@ -1586,20 +1589,29 @@ async function runEmbeddedAgentInternal(
15861589
}),
15871590
});
15881591

1589-
const materializeAuthPlan = async (plan: AgentRuntimeAuthPlan) => {
1592+
const materializedRouteModels = new WeakMap<
1593+
AgentRuntimeAuthPlan,
1594+
Promise<typeof runtimeModel>
1595+
>();
1596+
const materializeAuthPlanUncached = async (plan: AgentRuntimeAuthPlan) => {
15901597
// Native harness sessions own their model tuple. Route preparation may
15911598
// attest auth/transport, but must not rediscover or replace that model.
15921599
if (nativeModelOwned) {
15931600
return runtimeModel;
15941601
}
1602+
const requiresCredentialScopedResolve = Boolean(
1603+
plan.modelRoute && (plan.forwardedAuthProfileId || params.authProfileId),
1604+
);
15951605
return (
15961606
(await materializePreparedRuntimeModel({
15971607
plan,
15981608
provider,
15991609
modelId,
16001610
config: params.config,
16011611
model: runtimeModel,
1602-
forceResolve: Boolean(plan.modelRoute),
1612+
// Unscoped direct auth cannot change credential-scoped metadata.
1613+
// Reuse an already matching tuple; route mismatches still resolve.
1614+
forceResolve: requiresCredentialScopedResolve,
16031615
resolveModel: ({ config, authProfileId, authProfileMode }) =>
16041616
resolveModelAsync(provider, modelId, agentDir, config, {
16051617
authStorage,
@@ -1614,10 +1626,25 @@ async function runEmbeddedAgentInternal(
16141626
})) ?? runtimeModel
16151627
);
16161628
};
1629+
const materializeAuthPlan = (plan: AgentRuntimeAuthPlan) => {
1630+
if (!plan.modelRoute) {
1631+
return materializeAuthPlanUncached(plan);
1632+
}
1633+
const cached = materializedRouteModels.get(plan);
1634+
if (cached) {
1635+
return cached;
1636+
}
1637+
// Prepared plans are immutable within one run. Carry their exact model
1638+
// tuple into auth initialization instead of repeating provider discovery.
1639+
const materialized = materializeAuthPlanUncached(plan);
1640+
materializedRouteModels.set(plan, materialized);
1641+
return materialized;
1642+
};
16171643
let resolvedAuthPreparation = createAuthPreparation();
16181644
let preparedAuthAttempts = resolvedAuthPreparation.attempts;
16191645
let activePreparedAuthPlan = resolvedAuthPreparation.plan;
16201646
applyResolvedRuntimeModel(await materializeAuthPlan(activePreparedAuthPlan));
1647+
authStages?.mark("prepare-plan");
16211648

16221649
const finalizedHarness = selectHarnessForPreparedAttempts(
16231650
effectiveModel,
@@ -1640,6 +1667,7 @@ async function runEmbeddedAgentInternal(
16401667
);
16411668
}
16421669
}
1670+
authStages?.mark("harness");
16431671
// A selected plugin harness owns context pressure with its native transcript,
16441672
// even if it cannot expose manual compaction. Generic recovery is OpenClaw-only.
16451673
const genericCompactionRecoveryAllowed = !pluginHarnessOwnsTransport;
@@ -1851,6 +1879,7 @@ async function runEmbeddedAgentInternal(
18511879
},
18521880
log,
18531881
});
1882+
authStages?.mark("controller");
18541883
const advancePluginHarnessAuthAttempt = async (): Promise<boolean> => {
18551884
if (!pluginHarnessOwnsTransport || lockedProfileId) {
18561885
return false;
@@ -1951,6 +1980,15 @@ async function runEmbeddedAgentInternal(
19511980
lastProfileId = forwardedPluginHarnessProfileId;
19521981
}
19531982
}
1983+
authStages?.mark("initialize");
1984+
if (authStages) {
1985+
log.trace(
1986+
formatEmbeddedRunStageSummary(
1987+
`[trace:embedded-run] auth stages: runId=${params.runId} sessionId=${params.sessionId} phase=auth`,
1988+
authStages.snapshot(),
1989+
),
1990+
);
1991+
}
19541992
startupStages.mark("auth");
19551993
notifyExecutionPhase("auth", { provider, model: modelId });
19561994
const resolveRunAttemptAuthProfileStore = (): AuthProfileStore => {

0 commit comments

Comments
 (0)