refactor: dedupe string readers

This commit is contained in:
Peter Steinberger
2026-04-07 04:38:40 +01:00
parent 2f115bc645
commit 8c7dd66a7b
15 changed files with 51 additions and 103 deletions

View File

@@ -9,6 +9,7 @@ import type {
ChannelMessageToolDiscovery,
} from "openclaw/plugin-sdk/channel-contract";
import type { DiscordActionConfig } from "openclaw/plugin-sdk/config-runtime";
import { extractToolSend } from "openclaw/plugin-sdk/tool-send";
import {
createDiscordActionGate,
listEnabledDiscordAccounts,
@@ -169,8 +170,7 @@ export const discordMessageActions: ChannelMessageActionAdapter = {
extractToolSend: ({ args }) => {
const action = typeof args.action === "string" ? args.action.trim() : "";
if (action === "sendMessage") {
const to = typeof args.to === "string" ? args.to : undefined;
return to ? { to } : null;
return extractToolSend(args, "sendMessage");
}
if (action === "threadReply") {
const channelId = typeof args.channelId === "string" ? args.channelId.trim() : "";

View File

@@ -1,4 +1,5 @@
import { Type } from "@sinclair/typebox";
import { extractToolSend } from "openclaw/plugin-sdk/tool-send";
import { requiresExplicitMatrixDefaultAccount } from "./account-selection.js";
import { resolveDefaultMatrixAccountId, resolveMatrixAccount } from "./matrix/accounts.js";
import {
@@ -133,15 +134,7 @@ export const matrixMessageActions: ChannelMessageActionAdapter = {
},
supportsAction: ({ action }) => MATRIX_PLUGIN_HANDLED_ACTIONS.has(action),
extractToolSend: ({ args }): ChannelToolSend | null => {
const action = typeof args.action === "string" ? args.action.trim() : "";
if (action !== "sendMessage") {
return null;
}
const to = typeof args.to === "string" ? args.to : undefined;
if (!to) {
return null;
}
return { to };
return extractToolSend(args, "sendMessage");
},
handleAction: async (ctx: ChannelMessageActionContext) => {
const { handleMatrixAction } = await import("./tool-actions.runtime.js");

View File

@@ -1,5 +1,6 @@
import { Type } from "@sinclair/typebox";
import { jsonResult, readStringParam } from "openclaw/plugin-sdk/core";
import { extractToolSend } from "openclaw/plugin-sdk/tool-send";
import { resolveQaChannelAccount } from "./accounts.js";
import {
createQaBusThread,
@@ -60,8 +61,7 @@ export const qaChannelMessageActions: ChannelMessageActionAdapter = {
extractToolSend: ({ args }: { args: Record<string, unknown> }) => {
const action = typeof args.action === "string" ? args.action.trim() : "";
if (action === "sendMessage") {
const to = typeof args.to === "string" ? args.to : undefined;
return to ? { to } : null;
return extractToolSend(args, "sendMessage");
}
if (action === "threadReply") {
const channelId = typeof args.channelId === "string" ? args.channelId.trim() : "";

View File

@@ -1,7 +1,7 @@
import { createActionGate } from "openclaw/plugin-sdk/channel-actions";
import type { ChannelMessageActionName } from "openclaw/plugin-sdk/channel-contract";
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-runtime";
import type { ChannelToolSend } from "openclaw/plugin-sdk/tool-send";
import { extractToolSend, type ChannelToolSend } from "openclaw/plugin-sdk/tool-send";
import { listEnabledSlackAccounts, resolveSlackAccount } from "./accounts.js";
export function listSlackMessageActions(
@@ -54,14 +54,5 @@ export function listSlackMessageActions(
}
export function extractSlackToolSend(args: Record<string, unknown>): ChannelToolSend | null {
const action = typeof args.action === "string" ? args.action.trim() : "";
if (action !== "sendMessage") {
return null;
}
const to = typeof args.to === "string" ? args.to : undefined;
if (!to) {
return null;
}
const accountId = typeof args.accountId === "string" ? args.accountId.trim() : undefined;
return { to, accountId };
return extractToolSend(args, "sendMessage");
}

View File

@@ -11,6 +11,7 @@ import type {
ChannelMessageToolSchemaContribution,
} from "openclaw/plugin-sdk/channel-contract";
import type { TelegramActionConfig } from "openclaw/plugin-sdk/config-runtime";
import { readStringValue } from "openclaw/plugin-sdk/text-runtime";
import { extractToolSend } from "openclaw/plugin-sdk/tool-send";
import {
createTelegramActionGate,
@@ -176,7 +177,7 @@ export const telegramMessageActions: ChannelMessageActionAdapter = {
action: "topic-create",
args: {
...rest,
name: typeof threadName === "string" ? threadName : undefined,
name: readStringValue(threadName),
},
};
},

View File

@@ -1,33 +1 @@
import { formatErrorMessage } from "../../../../src/infra/errors.js";
type BatchOutputErrorLike = {
error?: { message?: string };
response?: {
body?:
| string
| {
error?: { message?: string };
};
};
};
function getResponseErrorMessage(line: BatchOutputErrorLike | undefined): string | undefined {
const body = line?.response?.body;
if (typeof body === "string") {
return body || undefined;
}
if (!body || typeof body !== "object") {
return undefined;
}
return typeof body.error?.message === "string" ? body.error.message : undefined;
}
export function extractBatchErrorMessage(lines: BatchOutputErrorLike[]): string | undefined {
const first = lines.find((line) => line.error?.message || getResponseErrorMessage(line));
return first?.error?.message ?? getResponseErrorMessage(first);
}
export function formatUnavailableBatchError(err: unknown): string | undefined {
const message = formatErrorMessage(err);
return message ? `error file unavailable: ${message}` : undefined;
}
export * from "../../../../src/memory-host-sdk/host/batch-error-utils.js";

View File

@@ -11,6 +11,7 @@ import {
resolveOpenClawManifestOs,
resolveOpenClawManifestRequires,
} from "../../shared/frontmatter.js";
import { readStringValue } from "../../shared/string-coerce.js";
import type { Skill } from "./skill-contract.js";
import type {
OpenClawSkillMetadata,
@@ -195,10 +196,10 @@ export function resolveOpenClawMetadata(
const osRaw = resolveOpenClawManifestOs(metadataObj);
return {
always: typeof metadataObj.always === "boolean" ? metadataObj.always : undefined,
emoji: typeof metadataObj.emoji === "string" ? metadataObj.emoji : undefined,
homepage: typeof metadataObj.homepage === "string" ? metadataObj.homepage : undefined,
skillKey: typeof metadataObj.skillKey === "string" ? metadataObj.skillKey : undefined,
primaryEnv: typeof metadataObj.primaryEnv === "string" ? metadataObj.primaryEnv : undefined,
emoji: readStringValue(metadataObj.emoji),
homepage: readStringValue(metadataObj.homepage),
skillKey: readStringValue(metadataObj.skillKey),
primaryEnv: readStringValue(metadataObj.primaryEnv),
os: osRaw.length > 0 ? osRaw : undefined,
requires: requires,
install: install.length > 0 ? install : undefined,

View File

@@ -16,6 +16,7 @@ import { buildOutboundSessionContext } from "../../infra/outbound/session-contex
import { maybeResolveIdLikeTarget } from "../../infra/outbound/target-resolver.js";
import { resolveOutboundTarget } from "../../infra/outbound/targets.js";
import { normalizePollInput } from "../../polls.js";
import { readStringValue } from "../../shared/string-coerce.js";
import {
ErrorCodes,
errorShape,
@@ -60,8 +61,7 @@ async function resolveRequestedChannel(params: {
error: ReturnType<typeof errorShape>;
}
> {
const channelInput =
typeof params.requestChannel === "string" ? params.requestChannel : undefined;
const channelInput = readStringValue(params.requestChannel);
const normalizedChannel = channelInput ? normalizeChannelId(channelInput) : null;
if (channelInput && !normalizedChannel) {
const normalizedInput = channelInput.trim().toLowerCase();

View File

@@ -7,6 +7,7 @@ import { getLastHeartbeatEvent } from "../../infra/heartbeat-events.js";
import { setHeartbeatsEnabled } from "../../infra/heartbeat-runner.js";
import { enqueueSystemEvent, isSystemEventContextChanged } from "../../infra/system-events.js";
import { listSystemPresence, updateSystemPresence } from "../../infra/system-presence.js";
import { readStringValue } from "../../shared/string-coerce.js";
import { ErrorCodes, errorShape } from "../protocol/index.js";
import { broadcastPresenceSnapshot } from "../server/presence-events.js";
import type { GatewayRequestHandlers } from "./types.js";
@@ -53,21 +54,20 @@ export const systemHandlers: GatewayRequestHandlers = {
return;
}
const sessionKey = resolveMainSessionKeyFromConfig();
const deviceId = typeof params.deviceId === "string" ? params.deviceId : undefined;
const instanceId = typeof params.instanceId === "string" ? params.instanceId : undefined;
const host = typeof params.host === "string" ? params.host : undefined;
const ip = typeof params.ip === "string" ? params.ip : undefined;
const mode = typeof params.mode === "string" ? params.mode : undefined;
const version = typeof params.version === "string" ? params.version : undefined;
const platform = typeof params.platform === "string" ? params.platform : undefined;
const deviceFamily = typeof params.deviceFamily === "string" ? params.deviceFamily : undefined;
const modelIdentifier =
typeof params.modelIdentifier === "string" ? params.modelIdentifier : undefined;
const deviceId = readStringValue(params.deviceId);
const instanceId = readStringValue(params.instanceId);
const host = readStringValue(params.host);
const ip = readStringValue(params.ip);
const mode = readStringValue(params.mode);
const version = readStringValue(params.version);
const platform = readStringValue(params.platform);
const deviceFamily = readStringValue(params.deviceFamily);
const modelIdentifier = readStringValue(params.modelIdentifier);
const lastInputSeconds =
typeof params.lastInputSeconds === "number" && Number.isFinite(params.lastInputSeconds)
? params.lastInputSeconds
: undefined;
const reason = typeof params.reason === "string" ? params.reason : undefined;
const reason = readStringValue(params.reason);
const roles =
Array.isArray(params.roles) && params.roles.every((t) => typeof t === "string")
? params.roles

View File

@@ -1,5 +1,6 @@
import { randomUUID } from "node:crypto";
import { defaultRuntime } from "../../runtime.js";
import { readStringValue } from "../../shared/string-coerce.js";
import { WizardSession } from "../../wizard/session.js";
import {
ErrorCodes,
@@ -46,7 +47,7 @@ export const wizardHandlers: GatewayRequestHandlers = {
const sessionId = randomUUID();
const opts = {
mode: params.mode,
workspace: typeof params.workspace === "string" ? params.workspace : undefined,
workspace: readStringValue(params.workspace),
};
const session = new WizardSession((prompter) =>
context.wizardRunner(opts, defaultRuntime, prompter),

View File

@@ -10,6 +10,7 @@ import {
resolveOpenClawManifestOs,
resolveOpenClawManifestRequires,
} from "../shared/frontmatter.js";
import { readStringValue } from "../shared/string-coerce.js";
import type {
OpenClawHookMetadata,
HookEntry,
@@ -57,10 +58,10 @@ export function resolveOpenClawMetadata(
const eventsRaw = normalizeStringList(metadataObj.events);
return {
always: typeof metadataObj.always === "boolean" ? metadataObj.always : undefined,
emoji: typeof metadataObj.emoji === "string" ? metadataObj.emoji : undefined,
homepage: typeof metadataObj.homepage === "string" ? metadataObj.homepage : undefined,
hookKey: typeof metadataObj.hookKey === "string" ? metadataObj.hookKey : undefined,
export: typeof metadataObj.export === "string" ? metadataObj.export : undefined,
emoji: readStringValue(metadataObj.emoji),
homepage: readStringValue(metadataObj.homepage),
hookKey: readStringValue(metadataObj.hookKey),
export: readStringValue(metadataObj.export),
os: osRaw.length > 0 ? osRaw : undefined,
events: eventsRaw.length > 0 ? eventsRaw : [],
requires: requires,

View File

@@ -1,4 +1,5 @@
import type { ChannelOutboundAdapter } from "../channels/plugins/types.js";
import { readStringValue } from "../shared/string-coerce.js";
export type { MediaPayload, MediaPayloadInput } from "../channels/plugins/media-payload.js";
export { buildMediaPayload } from "../channels/plugins/media-payload.js";
@@ -31,14 +32,14 @@ type SendPayloadAdapter = Pick<
export function normalizeOutboundReplyPayload(
payload: Record<string, unknown>,
): OutboundReplyPayload {
const text = typeof payload.text === "string" ? payload.text : undefined;
const text = readStringValue(payload.text);
const mediaUrls = Array.isArray(payload.mediaUrls)
? payload.mediaUrls.filter(
(entry): entry is string => typeof entry === "string" && entry.length > 0,
)
: undefined;
const mediaUrl = typeof payload.mediaUrl === "string" ? payload.mediaUrl : undefined;
const replyToId = typeof payload.replyToId === "string" ? payload.replyToId : undefined;
const mediaUrl = readStringValue(payload.mediaUrl);
const replyToId = readStringValue(payload.replyToId);
return {
text,
mediaUrls,

View File

@@ -1,3 +1,5 @@
import { readStringValue } from "../shared/string-coerce.js";
export type { ChannelToolSend } from "../channels/plugins/types.js";
/** Extract the canonical send target fields from tool arguments when the action matches. */
@@ -5,21 +7,19 @@ export function extractToolSend(
args: Record<string, unknown>,
expectedAction = "sendMessage",
): { to: string; accountId?: string; threadId?: string } | null {
const action = typeof args.action === "string" ? args.action.trim() : "";
const action = readStringValue(args.action)?.trim() ?? "";
if (action !== expectedAction) {
return null;
}
const to = typeof args.to === "string" ? args.to : undefined;
const to = readStringValue(args.to);
if (!to) {
return null;
}
const accountId = typeof args.accountId === "string" ? args.accountId.trim() : undefined;
const accountId = readStringValue(args.accountId)?.trim();
const threadIdRaw =
typeof args.threadId === "string"
? args.threadId.trim()
: typeof args.threadId === "number"
? String(args.threadId)
: "";
typeof args.threadId === "number"
? String(args.threadId)
: (readStringValue(args.threadId)?.trim() ?? "");
const threadId = threadIdRaw.length > 0 ? threadIdRaw : undefined;
return { to, accountId, threadId };
}

View File

@@ -24,6 +24,7 @@ import type { OpenClawConfig, ConfigFileSnapshot } from "../config/config.js";
import { collectIncludePathsRecursive } from "../config/includes-scan.js";
import { resolveOAuthDir } from "../config/paths.js";
import type { AgentToolsConfig } from "../config/types.tools.js";
import { readInstalledPackageVersion } from "../infra/package-update-utils.js";
import { normalizePluginsConfig } from "../plugins/config-state.js";
import { normalizeAgentId } from "../routing/session-key.js";
import {
@@ -330,16 +331,6 @@ function isPinnedRegistrySpec(spec: string): boolean {
return /^v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(version);
}
async function readInstalledPackageVersion(dir: string): Promise<string | undefined> {
try {
const raw = await fs.readFile(path.join(dir, "package.json"), "utf-8");
const parsed = JSON.parse(raw) as { version?: unknown };
return typeof parsed.version === "string" ? parsed.version : undefined;
} catch {
return undefined;
}
}
function buildCodeSafetySummaryCacheKey(params: {
dirPath: string;
includeFiles?: string[];

View File

@@ -1,6 +1,7 @@
import JSON5 from "json5";
import { LEGACY_MANIFEST_KEYS, MANIFEST_KEY } from "../compat/legacy-names.js";
import { parseBooleanValue } from "../utils/boolean.js";
import { readStringValue } from "./string-coerce.js";
import { normalizeCsvOrLooseStringList } from "./string-normalization.js";
export function normalizeStringList(input: unknown): string[] {
@@ -11,8 +12,7 @@ export function getFrontmatterString(
frontmatter: Record<string, unknown>,
key: string,
): string | undefined {
const raw = frontmatter[key];
return typeof raw === "string" ? raw : undefined;
return readStringValue(frontmatter[key]);
}
export function parseFrontmatterBool(value: string | undefined, fallback: boolean): boolean {