Skip to content

Commit 4153451

Browse files
authored
perf(agent): trace local startup stages (#117653)
1 parent 825a794 commit 4153451

6 files changed

Lines changed: 169 additions & 66 deletions

File tree

‎src/agents/agent-command.ts‎

Lines changed: 61 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ import { AGENT_LANE_SUBAGENT } from "./lanes.js";
5656
import type { MainSessionRecoveryPendingTarget } from "./main-session-recovery-store.js";
5757
import type { AgentRunSessionTarget } from "./run-session-target.js";
5858
import { createAgentRunRestartAbortError } from "./run-termination.js";
59+
import { measureAgentStartup } from "./startup-timing.js";
5960

6061
const log = createSubsystemLogger("agents/agent-command");
6162

@@ -386,53 +387,63 @@ async function agentCommandInternal(
386387
});
387388
}
388389

389-
const embeddedSessionState = await prepareEmbeddedSessionState({
390-
cfg,
391-
opts,
392-
sessionEntry,
393-
sessionStore,
394-
sessionKey,
395-
sessionId,
396-
storePath,
397-
sessionAgentId,
398-
lifecycleGeneration,
399-
runId,
400-
workspaceDir,
401-
isNewSession,
402-
isSubagentLaneTurn,
403-
suppressVisibleSessionEffects,
404-
thinkOnce,
405-
thinkOverride,
406-
persistedThinking,
407-
verboseOverride,
408-
persistedVerbose,
409-
verboseDefault: agentCfg?.verboseDefault as VerboseLevel | undefined,
410-
sessionStateActor,
411-
});
390+
const embeddedSessionState = await measureAgentStartup(
391+
"session-state",
392+
() =>
393+
prepareEmbeddedSessionState({
394+
cfg,
395+
opts,
396+
sessionEntry,
397+
sessionStore,
398+
sessionKey,
399+
sessionId,
400+
storePath,
401+
sessionAgentId,
402+
lifecycleGeneration,
403+
runId,
404+
workspaceDir,
405+
isNewSession,
406+
isSubagentLaneTurn,
407+
suppressVisibleSessionEffects,
408+
thinkOnce,
409+
thinkOverride,
410+
persistedThinking,
411+
verboseOverride,
412+
persistedVerbose,
413+
verboseDefault: agentCfg?.verboseDefault as VerboseLevel | undefined,
414+
sessionStateActor,
415+
}),
416+
{ config: cfg },
417+
);
412418
sessionEntry = embeddedSessionState.sessionEntry;
413419
const { requestedThinkLevel, runContext } = embeddedSessionState;
414420

415-
const modelSelection = await resolveEmbeddedModelSelection({
416-
cfg,
417-
opts,
418-
sessionEntry,
419-
sessionStore,
420-
sessionKey,
421-
sessionId,
422-
storePath,
423-
sessionAgentId,
424-
workspaceDir,
425-
pluginsEnabled,
426-
manifestMetadataSnapshot,
427-
modelManifestContext,
428-
configuredThinkingCatalog,
429-
requestedThinkLevel,
430-
thinkOverride,
431-
thinkOnce,
432-
isSubagentLane,
433-
suppressVisibleSessionEffects,
434-
runContext,
435-
});
421+
const modelSelection = await measureAgentStartup(
422+
"model-selection",
423+
() =>
424+
resolveEmbeddedModelSelection({
425+
cfg,
426+
opts,
427+
sessionEntry,
428+
sessionStore,
429+
sessionKey,
430+
sessionId,
431+
storePath,
432+
sessionAgentId,
433+
workspaceDir,
434+
pluginsEnabled,
435+
manifestMetadataSnapshot,
436+
modelManifestContext,
437+
configuredThinkingCatalog,
438+
requestedThinkLevel,
439+
thinkOverride,
440+
thinkOnce,
441+
isSubagentLane,
442+
suppressVisibleSessionEffects,
443+
runContext,
444+
}),
445+
{ config: cfg },
446+
);
436447
sessionEntry = modelSelection.sessionEntry;
437448
const embeddedAttempt = await runEmbeddedAgentAttempt({
438449
prepared,
@@ -546,7 +557,9 @@ export async function agentCommand(
546557
runtime: RuntimeEnv = defaultRuntime,
547558
deps?: CliDeps,
548559
) {
549-
const resolvedDeps = await resolveAgentCommandDeps(deps);
560+
const resolvedDeps = await measureAgentStartup("command-dependencies", () =>
561+
resolveAgentCommandDeps(deps),
562+
);
550563
const lifecycleGeneration =
551564
opts.lifecycleGeneration ?? captureAgentRunLifecycleGeneration(opts.runId ?? "");
552565
return await withAgentRunLifecycleGeneration(lifecycleGeneration, () =>
@@ -570,7 +583,9 @@ export async function agentCommand(
570583
allowModelOverride: opts.allowModelOverride ?? true,
571584
},
572585
prepare: async (preparedOpts) =>
573-
await prepareAgentCommandExecution(preparedOpts, runtime),
586+
await measureAgentStartup("command-prepare", () =>
587+
prepareAgentCommandExecution(preparedOpts, runtime),
588+
),
574589
run: async (prepared) =>
575590
await agentCommandInternal(prepared, prepared.opts, runtime, resolvedDeps),
576591
}),

‎src/agents/agent-runtime-config.ts‎

Lines changed: 32 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import type { PluginMetadataSnapshot } from "../plugins/plugin-metadata-snapshot
1313
import type { RuntimeEnv } from "../runtime.js";
1414
import { discoverConfigSecretTargetsByIds } from "../secrets/target-registry.js";
1515
import { listAgentEntries } from "./agent-scope.js";
16+
import { measureAgentStartup } from "./startup-timing.js";
1617

1718
/** Loads runtime/source config and resolves command SecretRefs when the agent path needs them. */
1819
export async function resolveAgentRuntimeConfig(
@@ -36,19 +37,23 @@ export async function resolveAgentRuntimeConfig(
3637
channel: channelSecretScope?.channel,
3738
});
3839
let pluginMetadataSnapshot: PluginMetadataSnapshot | undefined;
39-
const sourceConfig = await (async () => {
40-
try {
41-
const { snapshot, writeOptions } = await readConfigFileSnapshotForWrite();
42-
if (snapshot.valid) {
43-
pluginMetadataSnapshot = writeOptions.basePluginMetadataSnapshot;
44-
return snapshot.resolved;
40+
const sourceConfig = await measureAgentStartup(
41+
"config-source",
42+
async () => {
43+
try {
44+
const { snapshot, writeOptions } = await readConfigFileSnapshotForWrite();
45+
if (snapshot.valid) {
46+
pluginMetadataSnapshot = writeOptions.basePluginMetadataSnapshot;
47+
return snapshot.resolved;
48+
}
49+
} catch {
50+
// Fall back to runtime-loaded config when source snapshot is unavailable.
4551
}
46-
} catch {
47-
// Fall back to runtime-loaded config when source snapshot is unavailable.
48-
}
49-
pluginMetadataSnapshot = resolvePluginMetadataSnapshot({ config: loadedRaw });
50-
return loadedRaw;
51-
})();
52+
pluginMetadataSnapshot = resolvePluginMetadataSnapshot({ config: loadedRaw });
53+
return loadedRaw;
54+
},
55+
{ config: loadedRaw },
56+
);
5257
const cfg = hasRuntimeSecretRefs
5358
? await (async () => {
5459
const runtimeSecretTargets = resolveAgentRuntimeSecretTargets({
@@ -74,17 +79,26 @@ export async function resolveAgentRuntimeConfig(
7479
).resolvedConfig;
7580
})()
7681
: loadedRaw;
77-
const secretsRuntime = await import("../secrets/runtime.js");
82+
const secretsRuntime = await measureAgentStartup(
83+
"secrets-runtime-import",
84+
() => import("../secrets/runtime.js"),
85+
{ config: cfg },
86+
);
7887
if (secretsRuntime.getActiveSecretsRuntimeSnapshot()) {
7988
setRuntimeConfigSnapshot(cfg, sourceConfig);
8089
} else {
8190
// Standalone local agent commands have no Gateway-owned snapshot. Materialize
8291
// auth-profile refs too; resolving only config refs leaves selected credentials unusable.
83-
const snapshot = await secretsRuntime.prepareSecretsRuntimeSnapshot({
84-
config: sourceConfig,
85-
assignmentConfig: cfg,
86-
includeConfigRefs: false,
87-
});
92+
const snapshot = await measureAgentStartup(
93+
"secrets-snapshot",
94+
() =>
95+
secretsRuntime.prepareSecretsRuntimeSnapshot({
96+
config: sourceConfig,
97+
assignmentConfig: cfg,
98+
includeConfigRefs: false,
99+
}),
100+
{ config: cfg },
101+
);
88102
secretsRuntime.activateSecretsRuntimeSnapshot(snapshot);
89103
}
90104
return {

‎src/agents/command/run-embedded-attempt.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ import {
3838
resolveAgentRunErrorLifecycleFields,
3939
} from "../run-termination.js";
4040
import { resolveSessionRuntimeOverrideForProvider } from "../session-runtime-compat.js";
41+
import { measureAgentStartup } from "../startup-timing.js";
4142
import {
4243
hasResolvedThinkingCatalogEntry,
4344
normalizeThinkingCatalogProviders,
@@ -195,7 +196,11 @@ export async function runEmbeddedAgentAttempt(params: {
195196
abortSignal: params.opts.abortSignal,
196197
state: attemptLifecycleState,
197198
});
198-
const attemptExecutionRuntime = await loadAttemptExecutionRuntime();
199+
const attemptExecutionRuntime = await measureAgentStartup(
200+
"attempt-runtime-import",
201+
() => loadAttemptExecutionRuntime(),
202+
{ config: cfg },
203+
);
199204
const messageChannel = resolveMessageChannel(
200205
runContext.messageChannel,
201206
params.opts.replyChannel ?? params.opts.channel,

‎src/agents/startup-timing.test.ts‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import { mkdtemp, readFile, rm } from "node:fs/promises";
2+
import { tmpdir } from "node:os";
3+
import { join } from "node:path";
4+
import { afterEach, describe, expect, it } from "vitest";
5+
import { measureAgentStartup } from "./startup-timing.js";
6+
7+
const tempDirs: string[] = [];
8+
9+
afterEach(async () => {
10+
await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
11+
});
12+
13+
describe("measureAgentStartup", () => {
14+
it("records the startup stage without changing the result", async () => {
15+
const dir = await mkdtemp(join(tmpdir(), "openclaw-agent-startup-"));
16+
tempDirs.push(dir);
17+
const path = join(dir, "timeline.jsonl");
18+
const env = {
19+
OPENCLAW_DIAGNOSTICS: "timeline",
20+
OPENCLAW_DIAGNOSTICS_TIMELINE_PATH: path,
21+
} as NodeJS.ProcessEnv;
22+
23+
await expect(measureAgentStartup("command-import", async () => "ready", { env })).resolves.toBe(
24+
"ready",
25+
);
26+
27+
const events = (await readFile(path, "utf8"))
28+
.trim()
29+
.split("\n")
30+
.map((line) => JSON.parse(line) as Record<string, unknown>);
31+
expect(events).toHaveLength(2);
32+
expect(events[0]).toMatchObject({
33+
type: "span.start",
34+
name: "agent.startup",
35+
phase: "agent.startup",
36+
attributes: { stage: "command-import" },
37+
});
38+
expect(events[1]).toMatchObject({
39+
type: "span.end",
40+
name: "agent.startup",
41+
phase: "agent.startup",
42+
attributes: { stage: "command-import" },
43+
});
44+
});
45+
});

‎src/agents/startup-timing.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import type { OpenClawConfig } from "../config/types.openclaw.js";
2+
import { measureDiagnosticsTimelineSpan } from "../infra/diagnostics-timeline.js";
3+
4+
type AgentStartupTimingOptions = {
5+
config?: OpenClawConfig;
6+
env?: NodeJS.ProcessEnv;
7+
};
8+
9+
/** Measures local agent startup work before the canonical provider-preparation spans begin. */
10+
export function measureAgentStartup<T>(
11+
stage: string,
12+
run: () => Promise<T> | T,
13+
options: AgentStartupTimingOptions = {},
14+
): Promise<T> {
15+
return measureDiagnosticsTimelineSpan("agent.startup", run, {
16+
config: options.config,
17+
env: options.env,
18+
phase: "agent.startup",
19+
attributes: { stage },
20+
});
21+
}

‎src/commands/agent-via-gateway.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
GATEWAY_CLIENT_NAMES,
99
} from "../../packages/gateway-protocol/src/client-info.js";
1010
import { listAgentIds, resolveDefaultAgentId } from "../agents/agent-scope-config.js";
11+
import { measureAgentStartup } from "../agents/startup-timing.js";
1112
import { formatCliCommand } from "../cli/command-format.js";
1213
import type { CliDeps } from "../cli/deps.types.js";
1314
import { withProgress } from "../cli/progress.js";
@@ -917,7 +918,9 @@ export async function agentCliCommand(
917918
const signalBridge = createAgentCliSignalBridge(resolveAgentCliProcessLike(deps));
918919
try {
919920
if (dispatchOpts.local === true) {
920-
const agentCommand = await embeddedAgentCommandLoader.load();
921+
const agentCommand = await measureAgentStartup("command-import", () =>
922+
embeddedAgentCommandLoader.load(),
923+
);
921924
const result = await agentCommand(
922925
{
923926
...gatewayDispatchOpts,

0 commit comments

Comments
 (0)