Skip to content

Commit fde87f4

Browse files
committed
perf(cli): defer shell env for gateway dispatch
1 parent 823c38a commit fde87f4

5 files changed

Lines changed: 257 additions & 29 deletions

File tree

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

Lines changed: 77 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,16 @@ import type { agentCommand as AgentCommand } from "./agent.js";
1111

1212
const loadConfig = vi.hoisted(() => vi.fn());
1313
const callGateway = vi.hoisted(() => vi.fn());
14+
const isGatewayCredentialsRequiredError = vi.hoisted(() =>
15+
vi.fn(
16+
(value: unknown) => value instanceof Error && value.name === "GatewayCredentialsRequiredError",
17+
),
18+
);
19+
const isGatewayExplicitAuthRequiredError = vi.hoisted(() =>
20+
vi.fn(
21+
(value: unknown) => value instanceof Error && value.name === "GatewayExplicitAuthRequiredError",
22+
),
23+
);
1424
const isGatewayTransportError = vi.hoisted(() =>
1525
vi.fn((value: unknown) => {
1626
if (!(value instanceof Error) || value.name !== "GatewayTransportError") {
@@ -210,6 +220,8 @@ function createGatewayNormalCloseError() {
210220
vi.mock("../config/io.js", () => ({ getRuntimeConfig: loadConfig, loadConfig }));
211221
vi.mock("../gateway/call.js", () => ({
212222
callGateway,
223+
isGatewayCredentialsRequiredError,
224+
isGatewayExplicitAuthRequiredError,
213225
isGatewayTransportError,
214226
randomIdempotencyKey: () => "idem-1",
215227
}));
@@ -332,12 +344,74 @@ describe("agentCliCommand", () => {
332344
expect(params.sessionId).toBeUndefined();
333345
expect(params.to).toBeUndefined();
334346
expect(request.config).toBe(loadConfig.mock.results[0]?.value);
335-
expect(loadConfig).toHaveBeenCalledWith({ skipPluginValidation: true, pin: false });
347+
expect(loadConfig).toHaveBeenCalledWith({
348+
skipPluginValidation: true,
349+
pin: false,
350+
skipShellEnvFallback: true,
351+
});
336352
expect(agentCommand).not.toHaveBeenCalled();
337353
expect(loadAgentSessionModuleMock).not.toHaveBeenCalled();
338354
});
339355
});
340356

357+
it("retries gateway dispatch with shell env fallback only when credentials need it", async () => {
358+
await withTempStore(async ({ store }) => {
359+
const fastConfig = {
360+
agents: { defaults: { timeoutSeconds: 600 } },
361+
session: { store, mainKey: "main" },
362+
};
363+
const shellEnvConfig = {
364+
...fastConfig,
365+
gateway: { auth: { mode: "token" as const } },
366+
};
367+
loadConfig.mockReset();
368+
loadConfig.mockReturnValueOnce(fastConfig);
369+
loadConfig.mockReturnValueOnce(shellEnvConfig);
370+
const authError = new Error("gateway agent requires credentials");
371+
authError.name = "GatewayCredentialsRequiredError";
372+
callGateway.mockRejectedValueOnce(authError);
373+
mockGatewaySuccessReply();
374+
375+
await agentCliCommand({ message: "hi", sessionKey: "agent:main:incident-42" }, runtime);
376+
377+
expect(loadConfig.mock.calls).toEqual([
378+
[{ skipPluginValidation: true, pin: false, skipShellEnvFallback: true }],
379+
[{ skipPluginValidation: true, pin: false, skipShellEnvFallback: false }],
380+
]);
381+
expect(callGateway).toHaveBeenCalledTimes(2);
382+
expect(requireRecord(callGateway.mock.calls[0]?.[0], "first gateway request").config).toBe(
383+
fastConfig,
384+
);
385+
expect(requireRecord(callGateway.mock.calls[1]?.[0], "second gateway request").config).toBe(
386+
shellEnvConfig,
387+
);
388+
});
389+
});
390+
391+
it("retries gateway dispatch with shell env fallback for env URL auth", async () => {
392+
await withTempStore(async ({ store }) => {
393+
const fastConfig = {
394+
agents: { defaults: { timeoutSeconds: 600 } },
395+
session: { store, mainKey: "main" },
396+
};
397+
loadConfig.mockReset();
398+
loadConfig.mockReturnValueOnce(fastConfig);
399+
loadConfig.mockReturnValueOnce(fastConfig);
400+
const authError = new Error("gateway url override requires explicit credentials");
401+
authError.name = "GatewayExplicitAuthRequiredError";
402+
callGateway.mockRejectedValueOnce(authError);
403+
mockGatewaySuccessReply();
404+
405+
await agentCliCommand({ message: "hi", sessionKey: "agent:main:incident-42" }, runtime);
406+
407+
expect(loadConfig.mock.calls).toEqual([
408+
[{ skipPluginValidation: true, pin: false, skipShellEnvFallback: true }],
409+
[{ skipPluginValidation: true, pin: false, skipShellEnvFallback: false }],
410+
]);
411+
expect(callGateway).toHaveBeenCalledTimes(2);
412+
});
413+
});
414+
341415
it("scopes legacy explicit session keys to the requested agent", async () => {
342416
await withTempStore(
343417
async () => {
@@ -1486,8 +1560,8 @@ describe("agentCliCommand", () => {
14861560
expect(fallbackOpts.sessionId).toMatch(/^gateway-fallback-/);
14871561
expect(fallbackOpts.sessionKey).toBe(`agent:ops:explicit:${fallbackOpts.sessionId}`);
14881562
expect(loadConfig.mock.calls).toEqual([
1489-
[{ skipPluginValidation: true, pin: false }],
1490-
[{ skipPluginValidation: true, pin: false }],
1563+
[{ skipPluginValidation: true, pin: false, skipShellEnvFallback: true }],
1564+
[{ skipPluginValidation: true, pin: false, skipShellEnvFallback: true }],
14911565
]);
14921566
},
14931567
{ agents: { list: [{ id: "ops", default: true }, { id: "main" }] } },

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

Lines changed: 56 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,13 @@ import { getRuntimeConfig } from "../config/io.js";
1313
import type { OpenClawConfig } from "../config/types.openclaw.js";
1414
import {
1515
callGateway,
16+
isGatewayCredentialsRequiredError,
17+
isGatewayExplicitAuthRequiredError,
1618
isGatewayTransportError,
1719
randomIdempotencyKey,
1820
type GatewayRequestFunction,
1921
} from "../gateway/call.js";
22+
import { isGatewaySecretRefUnavailableError } from "../gateway/credentials.js";
2023
import { ADMIN_SCOPE } from "../gateway/operator-scopes.js";
2124
import { parseStrictNonNegativeInteger } from "../infra/parse-finite-number.js";
2225
import { routeLogsToStderr } from "../logging/console.js";
@@ -175,10 +178,14 @@ function resolveGatewayAgentTimeoutMs(timeoutSeconds: number): number {
175178
return resolveTimerTimeoutMs((timeoutSeconds + 30) * 1000, 10_000, 10_000);
176179
}
177180

178-
function getGatewayDispatchConfig(): OpenClawConfig {
181+
function getGatewayDispatchConfig(options?: { skipShellEnvFallback?: boolean }): OpenClawConfig {
179182
// Scoped gateway turns need core agent/session/gateway fields only. The
180183
// running gateway owns plugin validation and plugin metadata freshness.
181-
return getRuntimeConfig({ skipPluginValidation: true, pin: false });
184+
return getRuntimeConfig({
185+
skipPluginValidation: true,
186+
pin: false,
187+
skipShellEnvFallback: options?.skipShellEnvFallback ?? true,
188+
});
182189
}
183190

184191
async function formatPayloadForLog(payload: {
@@ -218,6 +225,14 @@ function isSessionResetCommand(message: string): boolean {
218225
return /^\/(?:new|reset)(?:\s|$)/i.test(message.trim());
219226
}
220227

228+
function shouldRetryGatewayDispatchWithShellEnvFallback(err: unknown): boolean {
229+
return (
230+
isGatewayCredentialsRequiredError(err) ||
231+
isGatewayExplicitAuthRequiredError(err) ||
232+
isGatewaySecretRefUnavailableError(err)
233+
);
234+
}
235+
221236
function isGatewayAgentEmbeddedFallbackError(err: unknown): boolean {
222237
return isGatewayTransportError(err);
223238
}
@@ -600,7 +615,7 @@ async function agentViaGatewayCommand(
600615
);
601616
}
602617

603-
const cfg = getGatewayDispatchConfig();
618+
let cfg = getGatewayDispatchConfig();
604619
const agentIdRaw = opts.agent?.trim();
605620
const agentId = agentIdRaw ? normalizeAgentId(agentIdRaw) : undefined;
606621
if (agentId) {
@@ -646,9 +661,9 @@ async function agentViaGatewayCommand(
646661
let acceptedGatewayRun = false;
647662
let activeConnectionAbortAttempted = false;
648663
let activeConnectionAbortSucceeded = false;
649-
let response: GatewayAgentResponse;
650-
try {
651-
response = await withProgress(
664+
let response: GatewayAgentResponse | undefined;
665+
const dispatchGatewayAgentCall = async (activeCfg: OpenClawConfig) =>
666+
await withProgress(
652667
{
653668
label: "Waiting for agent reply…",
654669
indeterminate: true,
@@ -678,7 +693,7 @@ async function agentViaGatewayCommand(
678693
},
679694
expectFinal: true,
680695
timeoutMs: gatewayTimeoutMs,
681-
config: cfg,
696+
config: activeCfg,
682697
signal: signalBridge.signal,
683698
onAccepted: (payload) => {
684699
acceptedGatewayRun = true;
@@ -699,22 +714,41 @@ async function agentViaGatewayCommand(
699714
...gatewayIdentity,
700715
}),
701716
);
702-
} catch (err) {
703-
if (
704-
isAbortError(err) &&
705-
!activeConnectionAbortSucceeded &&
706-
(acceptedGatewayRun || activeConnectionAbortAttempted)
707-
) {
708-
await abortAcceptedGatewayAgentRunWithGatewayCall({
709-
runId: acceptedRunId,
710-
sessionKey: acceptedSessionKey,
711-
signal: signalBridge.getReceivedSignal(),
712-
runtime,
713-
gatewayIdentity,
714-
config: cfg,
715-
});
717+
718+
let retriedWithShellEnvFallback = false;
719+
for (;;) {
720+
try {
721+
response = await dispatchGatewayAgentCall(cfg);
722+
break;
723+
} catch (err) {
724+
if (
725+
!retriedWithShellEnvFallback &&
726+
!acceptedGatewayRun &&
727+
shouldRetryGatewayDispatchWithShellEnvFallback(err)
728+
) {
729+
retriedWithShellEnvFallback = true;
730+
cfg = getGatewayDispatchConfig({ skipShellEnvFallback: false });
731+
continue;
732+
}
733+
if (
734+
isAbortError(err) &&
735+
!activeConnectionAbortSucceeded &&
736+
(acceptedGatewayRun || activeConnectionAbortAttempted)
737+
) {
738+
await abortAcceptedGatewayAgentRunWithGatewayCall({
739+
runId: acceptedRunId,
740+
sessionKey: acceptedSessionKey,
741+
signal: signalBridge.getReceivedSignal(),
742+
runtime,
743+
gatewayIdentity,
744+
config: cfg,
745+
});
746+
}
747+
throw err;
716748
}
717-
throw err;
749+
}
750+
if (!response) {
751+
throw new Error("gateway agent call did not return a response");
718752
}
719753

720754
if (opts.json) {
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
import fs from "node:fs/promises";
2+
import os from "node:os";
3+
import path from "node:path";
4+
import { beforeEach, describe, expect, it, vi } from "vitest";
5+
import { createConfigIO } from "./io.js";
6+
7+
const shellEnvMocks = vi.hoisted(() => ({
8+
loadShellEnvFallback: vi.fn(),
9+
resolveShellEnvFallbackTimeoutMs: vi.fn(() => 15_000),
10+
shouldDeferShellEnvFallback: vi.fn(() => false),
11+
shouldEnableShellEnvFallback: vi.fn(() => false),
12+
}));
13+
14+
vi.mock("../infra/shell-env.js", async (importOriginal) => ({
15+
...(await importOriginal<typeof import("../infra/shell-env.js")>()),
16+
loadShellEnvFallback: shellEnvMocks.loadShellEnvFallback,
17+
resolveShellEnvFallbackTimeoutMs: shellEnvMocks.resolveShellEnvFallbackTimeoutMs,
18+
shouldDeferShellEnvFallback: shellEnvMocks.shouldDeferShellEnvFallback,
19+
shouldEnableShellEnvFallback: shellEnvMocks.shouldEnableShellEnvFallback,
20+
}));
21+
22+
async function withConfig(run: (params: { home: string; configPath: string }) => Promise<void>) {
23+
const home = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-shell-env-"));
24+
try {
25+
const configPath = path.join(home, ".openclaw", "openclaw.json");
26+
await fs.mkdir(path.dirname(configPath), { recursive: true });
27+
await fs.writeFile(
28+
configPath,
29+
JSON.stringify({ env: { shellEnv: { enabled: true } } }, null, 2),
30+
);
31+
await run({ home, configPath });
32+
} finally {
33+
await fs.rm(home, { recursive: true, force: true });
34+
}
35+
}
36+
37+
describe("config io shell env fallback", () => {
38+
beforeEach(() => {
39+
vi.clearAllMocks();
40+
shellEnvMocks.resolveShellEnvFallbackTimeoutMs.mockReturnValue(15_000);
41+
shellEnvMocks.shouldDeferShellEnvFallback.mockReturnValue(false);
42+
shellEnvMocks.shouldEnableShellEnvFallback.mockReturnValue(false);
43+
});
44+
45+
it("can defer shell env fallback during config load", async () => {
46+
await withConfig(async ({ home, configPath }) => {
47+
const env = {} as NodeJS.ProcessEnv;
48+
const logger = { error: vi.fn(), warn: vi.fn() };
49+
const baseOptions = {
50+
configPath,
51+
env,
52+
homedir: () => home,
53+
logger,
54+
observe: false,
55+
};
56+
57+
createConfigIO(baseOptions).loadConfig();
58+
expect(shellEnvMocks.loadShellEnvFallback).toHaveBeenCalledTimes(1);
59+
60+
shellEnvMocks.loadShellEnvFallback.mockClear();
61+
createConfigIO({
62+
...baseOptions,
63+
shellEnvFallback: "defer",
64+
}).loadConfig();
65+
expect(shellEnvMocks.loadShellEnvFallback).not.toHaveBeenCalled();
66+
});
67+
});
68+
69+
it("honors deferred shell env fallback when the config file is missing", async () => {
70+
await withConfig(async ({ home, configPath }) => {
71+
await fs.rm(configPath);
72+
shellEnvMocks.shouldEnableShellEnvFallback.mockReturnValue(true);
73+
const env = {} as NodeJS.ProcessEnv;
74+
const logger = { error: vi.fn(), warn: vi.fn() };
75+
const baseOptions = {
76+
configPath,
77+
env,
78+
homedir: () => home,
79+
logger,
80+
observe: false,
81+
};
82+
83+
createConfigIO({
84+
...baseOptions,
85+
shellEnvFallback: "defer",
86+
}).loadConfig();
87+
expect(shellEnvMocks.loadShellEnvFallback).not.toHaveBeenCalled();
88+
89+
createConfigIO(baseOptions).loadConfig();
90+
expect(shellEnvMocks.loadShellEnvFallback).toHaveBeenCalledTimes(1);
91+
});
92+
});
93+
});

‎src/config/io.ts‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1355,6 +1355,7 @@ export function createConfigIO(
13551355
overrides: ConfigIoDeps & {
13561356
pluginValidation?: "full" | "skip";
13571357
preservedLegacyRootKeys?: readonly string[];
1358+
shellEnvFallback?: "load" | "defer";
13581359
} = {},
13591360
) {
13601361
const deps = normalizeDeps(overrides);
@@ -1377,7 +1378,11 @@ export function createConfigIO(
13771378
applyConfigEnvVars(cfg, deps.env);
13781379

13791380
const enabled = shouldEnableShellEnvFallback(deps.env) || cfg.env?.shellEnv?.enabled === true;
1380-
if (enabled && !shouldDeferShellEnvFallback(deps.env)) {
1381+
if (
1382+
enabled &&
1383+
overrides.shellEnvFallback !== "defer" &&
1384+
!shouldDeferShellEnvFallback(deps.env)
1385+
) {
13811386
loadShellEnvFallback({
13821387
enabled: true,
13831388
env: deps.env,
@@ -1649,7 +1654,11 @@ export function createConfigIO(
16491654
try {
16501655
maybeLoadDotEnvForConfig(deps.env);
16511656
if (!deps.fs.existsSync(configPath)) {
1652-
if (shouldEnableShellEnvFallback(deps.env) && !shouldDeferShellEnvFallback(deps.env)) {
1657+
if (
1658+
overrides.shellEnvFallback !== "defer" &&
1659+
shouldEnableShellEnvFallback(deps.env) &&
1660+
!shouldDeferShellEnvFallback(deps.env)
1661+
) {
16531662
loadShellEnvFallback({
16541663
enabled: true,
16551664
env: deps.env,
@@ -2567,9 +2576,13 @@ export function projectConfigOntoRuntimeSourceSnapshot(config: OpenClawConfig):
25672576
export function loadConfig(options?: {
25682577
skipPluginValidation?: boolean;
25692578
pin?: boolean;
2579+
skipShellEnvFallback?: boolean;
25702580
}): OpenClawConfig {
25712581
const loadFresh = () =>
2572-
createConfigIO(options?.skipPluginValidation ? { pluginValidation: "skip" } : {}).loadConfig();
2582+
createConfigIO({
2583+
...(options?.skipPluginValidation ? { pluginValidation: "skip" as const } : {}),
2584+
...(options?.skipShellEnvFallback ? { shellEnvFallback: "defer" as const } : {}),
2585+
}).loadConfig();
25732586
if (options?.pin === false) {
25742587
return loadFresh();
25752588
}
@@ -2582,6 +2595,7 @@ export function loadConfig(options?: {
25822595
export function getRuntimeConfig(options?: {
25832596
skipPluginValidation?: boolean;
25842597
pin?: boolean;
2598+
skipShellEnvFallback?: boolean;
25852599
}): OpenClawConfig {
25862600
return loadConfig(options);
25872601
}

0 commit comments

Comments
 (0)