Skip to content

Commit 526372e

Browse files
authored
fix(gateway): use runtime config for secret-backed talk
* fix(gateway): use runtime config for secret-backed talk * test(gateway): relax talk config rpc timeout * refactor(gateway): clarify talk config resolution
1 parent 75deb12 commit 526372e

9 files changed

Lines changed: 215 additions & 166 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ Docs: https://docs.openclaw.ai
7272
- Backup: skip installed plugin `extensions/*/node_modules` dependency trees while keeping plugin manifests and source files in archives, so local backups avoid rebuildable npm payload bloat. Fixes #64144. Thanks @BrilliantWang.
7373
- Cron/models: fail isolated cron runs closed when an explicit `payload.model` is not allowed or cannot be resolved, so scheduled jobs do not silently fall back to an unrelated agent default or paid route before configured provider proxies such as LiteLLM can run. Fixes #73146. Thanks @oneandrewwang.
7474
- Memory/QMD: back off repeated chat-turn QMD open failures while still letting memory status and CLI probes recheck immediately, so a broken sidecar dependency cannot trigger active-memory or cron retry storms. Fixes #73188 and #73176. Thanks @leonlushgit and @w3i-William.
75-
- Talk Mode: keep `talk.config` callable when `messages.tts.providers.<id>` stores SecretRef-backed `apiKey` or `token` values, so Talk overlays can discover the configured speech provider without falling back to local speech. Fixes #73109. (#73111) Thanks @omarshahine.
75+
- Talk Mode: resolve `messages.tts.providers.<id>.apiKey` through the active runtime snapshot for `talk.config`, so Talk overlays can discover SecretRef-backed speech providers without falling back to local speech. Fixes #73109. (#73111) Thanks @omarshahine.
7676
- Memory/Ollama: resolve `memorySearch.provider` custom provider ids through their configured `models.providers.<id>.api` owner, so multi-GPU Ollama setups can dedicate embeddings to providers such as `ollama-5080` without losing the Ollama adapter or local auth semantics. Fixes #73150. Thanks @oneandrewwang.
7777
- CLI/memory: skip eager context-window warmup for `openclaw memory` commands so memory search does not race unrelated model metadata discovery. Fixes #73123. Thanks @oalansilva and @neeravmakwana.
7878
- CLI/Telegram: route Telegram `message send` and poll actions through the running Gateway when available, so packaged installs use the staged `grammy` runtime deps and CLI sends return instead of hanging after the Telegram channel is active. Fixes #73140. Thanks @oalansilva.

‎docs/plugins/sdk-runtime.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,8 @@ subpaths directly instead of mocking the broad compatibility barrel.
5252

5353
Internal OpenClaw runtime code has the same direction: load config once at the CLI, gateway, or process boundary, then pass that value through. Successful mutation writes refresh the process runtime snapshot and advance its internal revision; long-lived caches should key off the runtime-owned cache key instead of serializing config locally. Long-lived runtime modules have a zero-tolerance scanner for ambient `loadConfig()` calls; use a passed `cfg`, a request `context.getRuntimeConfig()`, or `getRuntimeConfig()` at an explicit process boundary.
5454

55+
Provider and channel execution paths must use the active runtime config snapshot, not a file snapshot returned for config readback or editing. File snapshots preserve source values such as SecretRef markers for UI and writes; provider callbacks need the resolved runtime view. When a helper may be called with either the active source snapshot or the active runtime snapshot, route through `selectApplicableRuntimeConfig()` before reading credentials.
56+
5557
## Runtime namespaces
5658

5759
<AccordionGroup>

‎extensions/speech-core/src/tts.ts‎

Lines changed: 8 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import {
2727
import {
2828
getRuntimeConfigSnapshot,
2929
getRuntimeConfigSourceSnapshot,
30+
selectApplicableRuntimeConfig,
3031
} from "openclaw/plugin-sdk/runtime-config-snapshot";
3132
import { isVerbose, logVerbose } from "openclaw/plugin-sdk/runtime-env";
3233
import { resolvePreferredOpenClawTmpDir } from "openclaw/plugin-sdk/sandbox";
@@ -235,41 +236,14 @@ function _resolveRegistryDefaultSpeechProviderId(cfg?: OpenClawConfig): TtsProvi
235236
return sortSpeechProvidersForAutoSelection(cfg)[0]?.id ?? "";
236237
}
237238

238-
function stableConfigStringify(value: unknown): string {
239-
if (value === null || typeof value !== "object") {
240-
return JSON.stringify(value) ?? "null";
241-
}
242-
if (Array.isArray(value)) {
243-
return `[${value.map((entry) => stableConfigStringify(entry)).join(",")}]`;
244-
}
245-
const record = value as Record<string, unknown>;
246-
return `{${Object.keys(record)
247-
.toSorted()
248-
.map((key) => `${JSON.stringify(key)}:${stableConfigStringify(record[key])}`)
249-
.join(",")}}`;
250-
}
251-
252-
function configSnapshotsMatch(left: OpenClawConfig, right: OpenClawConfig): boolean {
253-
if (left === right) {
254-
return true;
255-
}
256-
try {
257-
return stableConfigStringify(left) === stableConfigStringify(right);
258-
} catch {
259-
return false;
260-
}
261-
}
262-
263239
function resolveTtsRuntimeConfig(cfg: OpenClawConfig): OpenClawConfig {
264-
const runtimeConfig = getRuntimeConfigSnapshot();
265-
if (!runtimeConfig || cfg === runtimeConfig) {
266-
return cfg;
267-
}
268-
const sourceConfig = getRuntimeConfigSourceSnapshot();
269-
if (!sourceConfig || configSnapshotsMatch(cfg, sourceConfig)) {
270-
return runtimeConfig;
271-
}
272-
return cfg;
240+
return (
241+
selectApplicableRuntimeConfig({
242+
inputConfig: cfg,
243+
runtimeConfig: getRuntimeConfigSnapshot(),
244+
runtimeSourceConfig: getRuntimeConfigSourceSnapshot(),
245+
}) ?? cfg
246+
);
273247
}
274248

275249
function asProviderConfig(value: unknown): SpeechProviderConfig {

‎src/gateway/server-methods/channels.start.test.ts‎

Lines changed: 75 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,14 @@ import type { GatewayRequestHandlerOptions } from "./types.js";
44

55
const mocks = vi.hoisted(() => ({
66
getRuntimeConfig: vi.fn(() => ({})),
7+
readConfigFileSnapshot: vi.fn(),
78
applyPluginAutoEnable: vi.fn(),
89
getChannelPlugin: vi.fn(),
910
}));
1011

1112
vi.mock("../../config/config.js", () => ({
1213
getRuntimeConfig: mocks.getRuntimeConfig,
13-
readConfigFileSnapshot: vi.fn(),
14+
readConfigFileSnapshot: mocks.readConfigFileSnapshot,
1415
}));
1516

1617
vi.mock("../../config/plugin-auto-enable.js", () => ({
@@ -38,6 +39,7 @@ function createOptions(
3839
context: {
3940
getRuntimeConfig: mocks.getRuntimeConfig,
4041
startChannel: vi.fn(),
42+
stopChannel: vi.fn(),
4143
getRuntimeSnapshot: vi.fn(
4244
(): ChannelRuntimeSnapshot => ({
4345
channels: {
@@ -175,3 +177,75 @@ describe("channelsHandlers channels.start", () => {
175177
);
176178
});
177179
});
180+
181+
describe("channelsHandlers channels.logout", () => {
182+
beforeEach(() => {
183+
vi.clearAllMocks();
184+
mocks.readConfigFileSnapshot.mockResolvedValue({
185+
valid: true,
186+
config: {
187+
channels: {
188+
whatsapp: {
189+
token: { source: "env", provider: "default", id: "WHATSAPP_TOKEN" },
190+
},
191+
},
192+
},
193+
});
194+
});
195+
196+
it("passes the active runtime config to channel plugins", async () => {
197+
const runtimeConfig = {
198+
channels: {
199+
whatsapp: {
200+
token: "runtime-token",
201+
},
202+
},
203+
};
204+
const stopChannel = vi.fn();
205+
const markChannelLoggedOut = vi.fn();
206+
const logoutAccount = vi.fn(async ({ cfg }: { cfg: typeof runtimeConfig }) => {
207+
expect(cfg.channels.whatsapp.token).toBe("runtime-token");
208+
return { cleared: true, envToken: false, loggedOut: true };
209+
});
210+
const respond = vi.fn();
211+
mocks.getRuntimeConfig.mockReturnValue(runtimeConfig);
212+
mocks.getChannelPlugin.mockReturnValue({
213+
id: "whatsapp",
214+
gateway: { logoutAccount },
215+
config: {
216+
defaultAccountId: () => "default-account",
217+
listAccountIds: () => ["default-account"],
218+
resolveAccount: () => ({}),
219+
},
220+
});
221+
222+
await channelsHandlers["channels.logout"](
223+
createOptions(
224+
{ channel: "whatsapp" },
225+
{
226+
respond,
227+
context: {
228+
getRuntimeConfig: mocks.getRuntimeConfig,
229+
stopChannel,
230+
markChannelLoggedOut,
231+
} as unknown as GatewayRequestHandlerOptions["context"],
232+
},
233+
),
234+
);
235+
236+
expect(stopChannel).toHaveBeenCalledWith("whatsapp", "default-account");
237+
expect(markChannelLoggedOut).toHaveBeenCalledWith("whatsapp", true, "default-account");
238+
expect(logoutAccount).toHaveBeenCalledTimes(1);
239+
expect(respond).toHaveBeenCalledWith(
240+
true,
241+
{
242+
channel: "whatsapp",
243+
accountId: "default-account",
244+
cleared: true,
245+
envToken: false,
246+
loggedOut: true,
247+
},
248+
undefined,
249+
);
250+
});
251+
});

‎src/gateway/server-methods/channels.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -437,7 +437,7 @@ export const channelsHandlers: GatewayRequestHandlers = {
437437
const payload = await logoutChannelAccount({
438438
channelId,
439439
accountId,
440-
cfg: snapshot.config ?? {},
440+
cfg: context.getRuntimeConfig(),
441441
context,
442442
plugin,
443443
});

‎src/gateway/server-methods/talk.test.ts‎

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { beforeEach, describe, expect, it, vi } from "vitest";
22
import type { OpenClawConfig } from "../../config/config.js";
3+
import { normalizeResolvedSecretInputString } from "../../config/types.secrets.js";
34
import { talkHandlers } from "./talk.js";
45

56
const mocks = vi.hoisted(() => ({
@@ -132,6 +133,111 @@ describe("talk.speak handler", () => {
132133
});
133134
});
134135

136+
describe("talk.config handler", () => {
137+
beforeEach(() => {
138+
vi.clearAllMocks();
139+
});
140+
141+
it("passes runtime-resolved messages.tts provider secrets to strict provider resolvers", async () => {
142+
const sourceConfig = {
143+
talk: {
144+
provider: "acme",
145+
providers: {
146+
acme: {
147+
voiceId: "voice-from-talk-config",
148+
},
149+
},
150+
},
151+
messages: {
152+
tts: {
153+
provider: "acme",
154+
timeoutMs: 12_345,
155+
providers: {
156+
acme: {
157+
apiKey: { source: "env", provider: "default", id: "ACME_SPEECH_API_KEY" },
158+
},
159+
},
160+
},
161+
},
162+
} as OpenClawConfig;
163+
const runtimeConfig = {
164+
...sourceConfig,
165+
messages: {
166+
tts: {
167+
provider: "acme",
168+
timeoutMs: 54_321,
169+
providers: {
170+
acme: {
171+
apiKey: "env-acme-key",
172+
},
173+
},
174+
},
175+
},
176+
} as OpenClawConfig;
177+
178+
mocks.readConfigFileSnapshot.mockResolvedValue({
179+
path: "/tmp/openclaw.json",
180+
hash: "test-hash",
181+
valid: true,
182+
config: sourceConfig,
183+
});
184+
mocks.getSpeechProvider.mockReturnValue({
185+
id: "acme",
186+
label: "Acme Strict Speech",
187+
resolveTalkConfig: ({
188+
baseTtsConfig,
189+
talkProviderConfig,
190+
timeoutMs,
191+
}: {
192+
baseTtsConfig: Record<string, unknown>;
193+
talkProviderConfig: Record<string, unknown>;
194+
timeoutMs: number;
195+
}) => {
196+
const providers = (baseTtsConfig.providers ?? {}) as Record<string, unknown>;
197+
const providerConfig = (providers.acme ?? {}) as Record<string, unknown>;
198+
const apiKey = normalizeResolvedSecretInputString({
199+
value: providerConfig.apiKey,
200+
path: "messages.tts.providers.acme.apiKey",
201+
});
202+
expect(apiKey).toBe("env-acme-key");
203+
expect(timeoutMs).toBe(54_321);
204+
return {
205+
...talkProviderConfig,
206+
...(apiKey === undefined ? {} : { apiKey }),
207+
};
208+
},
209+
});
210+
211+
const respond = vi.fn();
212+
await talkHandlers["talk.config"]({
213+
req: { type: "req", id: "1", method: "talk.config" },
214+
params: {},
215+
client: { connect: { scopes: ["operator.read"] } } as never,
216+
isWebchatConnect: () => false,
217+
respond: respond as never,
218+
context: { getRuntimeConfig: () => runtimeConfig } as never,
219+
});
220+
221+
expect(respond).toHaveBeenCalledWith(
222+
true,
223+
{
224+
config: {
225+
talk: expect.objectContaining({
226+
provider: "acme",
227+
resolved: {
228+
provider: "acme",
229+
config: expect.objectContaining({
230+
apiKey: "__OPENCLAW_REDACTED__",
231+
}),
232+
},
233+
}),
234+
},
235+
},
236+
undefined,
237+
);
238+
});
239+
});
240+
135241
describe("talk.realtime.session handler", () => {
136242
beforeEach(() => {
137243
vi.clearAllMocks();

‎src/gateway/server-methods/talk.ts‎

Lines changed: 19 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -362,6 +362,10 @@ function resolveTalkResponseFromConfig(params: {
362362
const runtimeBaseTts = asRecord(params.runtimeConfig.messages?.tts) ?? {};
363363
const sourceProviderConfig = sourceResolved?.config ?? {};
364364
const runtimeProviderConfig = runtimeResolved?.config ?? {};
365+
const selectedBaseTts =
366+
Object.keys(runtimeBaseTts).length > 0
367+
? runtimeBaseTts
368+
: stripUnresolvedSecretApiKeysFromBaseTtsProviders(sourceBaseTts);
365369
// Prefer runtime-resolved provider config (already-substituted secrets) and
366370
// fall back to source. Strip any apiKey that is still a SecretRef wrapper —
367371
// provider plugins (ElevenLabs/OpenAI) call strict secret helpers that throw
@@ -371,22 +375,12 @@ function resolveTalkResponseFromConfig(params: {
371375
const providerInputConfig = stripUnresolvedSecretApiKey(
372376
Object.keys(runtimeProviderConfig).length > 0 ? runtimeProviderConfig : sourceProviderConfig,
373377
);
374-
// The same SecretRef-wrapper hazard exists on `messages.tts.providers.*`:
375-
// strict speech resolvers normalize base TTS secrets before merging talk config.
376-
const baseTtsConfig = stripUnresolvedSecretInputsFromBaseTtsProviders(
377-
Object.keys(sourceBaseTts).length > 0 ? sourceBaseTts : runtimeBaseTts,
378-
);
379378
const resolvedConfig =
380379
speechProvider?.resolveTalkConfig?.({
381380
cfg: params.runtimeConfig,
382-
baseTtsConfig,
381+
baseTtsConfig: selectedBaseTts,
383382
talkProviderConfig: providerInputConfig,
384-
timeoutMs:
385-
typeof sourceBaseTts.timeoutMs === "number"
386-
? sourceBaseTts.timeoutMs
387-
: typeof runtimeBaseTts.timeoutMs === "number"
388-
? runtimeBaseTts.timeoutMs
389-
: 30_000,
383+
timeoutMs: typeof selectedBaseTts.timeoutMs === "number" ? selectedBaseTts.timeoutMs : 30_000,
390384
}) ?? providerInputConfig;
391385
const responseConfig =
392386
sourceProviderConfig.apiKey === undefined
@@ -404,31 +398,10 @@ function resolveTalkResponseFromConfig(params: {
404398
}
405399

406400
function stripUnresolvedSecretApiKey(config: TalkProviderConfig): TalkProviderConfig {
407-
if (config.apiKey === undefined || typeof config.apiKey === "string") {
408-
return config;
409-
}
410-
const { apiKey: _omit, ...rest } = config;
411-
return rest;
401+
return stripUnresolvedSecretApiKeyFromRecord(config) as TalkProviderConfig;
412402
}
413403

414-
const BASE_TTS_PROVIDER_SECRET_INPUT_KEYS = ["apiKey", "token"] as const;
415-
416-
function stripUnresolvedSecretInputsFromProviderConfig(
417-
config: Record<string, unknown>,
418-
): Record<string, unknown> {
419-
let next: Record<string, unknown> | undefined;
420-
for (const key of BASE_TTS_PROVIDER_SECRET_INPUT_KEYS) {
421-
const value = config[key];
422-
if (value === undefined || typeof value === "string") {
423-
continue;
424-
}
425-
next ??= { ...config };
426-
delete next[key];
427-
}
428-
return next ?? config;
429-
}
430-
431-
function stripUnresolvedSecretInputsFromBaseTtsProviders(
404+
function stripUnresolvedSecretApiKeysFromBaseTtsProviders(
432405
base: Record<string, unknown>,
433406
): Record<string, unknown> {
434407
const providers = asRecord(base.providers);
@@ -448,7 +421,7 @@ function stripUnresolvedSecretInputsFromBaseTtsProviders(
448421
cleaned[providerId] = providerConfig;
449422
continue;
450423
}
451-
const next = stripUnresolvedSecretInputsFromProviderConfig(cfg);
424+
const next = stripUnresolvedSecretApiKeyFromRecord(cfg);
452425
if (next !== cfg) {
453426
mutated = true;
454427
}
@@ -460,6 +433,16 @@ function stripUnresolvedSecretInputsFromBaseTtsProviders(
460433
return { ...base, providers: cleaned };
461434
}
462435

436+
function stripUnresolvedSecretApiKeyFromRecord(
437+
config: Record<string, unknown>,
438+
): Record<string, unknown> {
439+
if (config.apiKey === undefined || typeof config.apiKey === "string") {
440+
return config;
441+
}
442+
const { apiKey: _omit, ...rest } = config;
443+
return rest;
444+
}
445+
463446
export const talkHandlers: GatewayRequestHandlers = {
464447
"talk.config": async ({ params, respond, client, context }) => {
465448
if (!validateTalkConfigParams(params)) {

0 commit comments

Comments
 (0)