mirror of
https://github.com/openclaw/openclaw.git
synced 2026-07-17 09:11:39 +00:00
* fix(core): make indexed access explicit in auto-reply, infra, and config Part 1/3 of the src NUIA phase-3b burn-down (#104600): iteration and destructuring over index reads, boundary guards on parsed input, and named invariants. Config path walkers bind the path head once; SQLite migration key handling is hoisted without query-shape changes. * fix(core): make indexed access explicit in cli, gateway, commands, security, shared Part 2/3: argv/token selection restructured, gateway event/attachment invariants named, security parsers stay fail-closed (invariant violations throw), edit-distance matrices access checked entries. * fix(core): make indexed access explicit across remaining src surfaces Part 3/3: channels, plugins, process, cron, plugin-sdk, media, logging, tui, hooks, daemon, and small directories. Latent bug fixed: a tailnet resolver could leak undefined through a string|null contract and now fails with a descriptive local error. * fix(core): keep optional boundaries optional after per-commit review Review findings: expectDefined misused where absence is a legitimate state. CLI --profile/route-args missing next tokens take their existing miss paths; help normalization compares --help against the last positional again; first-time plugin install spreads absent cfg.plugins; denylist scan iterates manifest dependency entries instead of throwing on omitted sections; tailnet resolver returns a guaranteed string at the source instead of a caller-side undefined throw. * refactor(core): closed-key provider labels and honest optional passthroughs PROVIDER_LABELS becomes a satisfies-typed closed record (static reads provably defined; dynamic lookups go through providerUsageLabel with honest string|undefined). Status-scan overview passes its optional params through unchanged instead of asserting them. * fix(channels): make getChatChannelMeta honestly optional The original signature claimed ChatChannelMeta while leaking undefined on bundled channel id metadata drift; three of four callers already handled absence. The return type now says so, and the one assuming caller falls back to the raw channel label. * fix(core): index-safety for post-rebase main drift Covers the sqlite-sessions flip and auth-source-plan code that landed mid-phase, plus the channel-validation test consuming the now honestly optional getChatChannelMeta. * refactor(channels): split chat-meta accessors along the SDK contract getChatChannelMeta keeps its shipped plugin-SDK signature (defined for bundled ids, fail-loud on impossible misses); new findChatChannelMeta carries the drift-tolerant optional contract for core auto-enable and formatting paths. * fix(qa-channel): own channel metadata instead of a guaranteed-undefined catalog lookup qa-channel spread getChatChannelMeta over an id that is never in the bundled catalog, shipping an empty setup meta by accident; the fail-loud SDK accessor exposed it. The channel now declares its metadata once. * fix(gateway): heartbeat projection lookahead is optional at the transcript tail expectDefined wrapped messages[i + 1] whose absence on the final message is the normal case; the adjacent ternary already handled it. Restores the plain optional read with an explicit guard in the pair condition. * fix(plugin-sdk): channel plugin factory tolerates non-bundled channel ids again createChannelPluginBase spreads bundled catalog meta for ANY channel id, where absence is the normal case for external plugins; the resolver is honestly optional again while the exported bundled-id accessor keeps the fail-loud contract. * fix(core): spreads of optional config sections stay optional Fresh-setup and first-install paths (crestodian setup inference, hook installs, agent config base, target agent models) legitimately lack the section being rebuilt; spreading undefined is the shipped {} semantics. Removes the remaining gratuitous assertion wraps found by tree audit.
111 lines
3.6 KiB
TypeScript
111 lines
3.6 KiB
TypeScript
// Root --profile/--dev parsing and environment projection for profile-specific state.
|
|
import os from "node:os";
|
|
import path from "node:path";
|
|
import {
|
|
normalizeLowercaseStringOrEmpty,
|
|
normalizeOptionalString,
|
|
} from "@openclaw/normalization-core/string-coerce";
|
|
import { resolveRequiredHomeDir } from "../infra/home-dir.js";
|
|
import { resolveCliArgvInvocation } from "./argv-invocation.js";
|
|
import { isValidProfileName } from "./profile-utils.js";
|
|
import { scanCliRootOptions } from "./root-option-scan.js";
|
|
import { takeCliRootOptionValue } from "./root-option-value.js";
|
|
|
|
type CliProfileParseResult =
|
|
| { ok: true; profile: string | null; argv: string[] }
|
|
| { ok: false; error: string };
|
|
|
|
export function parseCliProfileArgs(argv: string[]): CliProfileParseResult {
|
|
// Root profile flags are stripped before Commander sees argv, except command-local cases.
|
|
let profile: string | null = null;
|
|
let sawDev = false;
|
|
|
|
const scanned = scanCliRootOptions(argv, ({ arg, args, index, out }) => {
|
|
if (arg === "--dev") {
|
|
if (resolveCliArgvInvocation(out).primary === "gateway") {
|
|
out.push(arg);
|
|
return { kind: "handled" };
|
|
}
|
|
if (profile && profile !== "dev") {
|
|
return { kind: "error", error: "Cannot combine --dev with --profile" };
|
|
}
|
|
sawDev = true;
|
|
profile = "dev";
|
|
return { kind: "handled" };
|
|
}
|
|
|
|
if (arg === "--profile" || arg.startsWith("--profile=")) {
|
|
const next = args[index + 1];
|
|
const { value, consumedNext } = takeCliRootOptionValue(arg, next);
|
|
const [primary, secondary] = resolveCliArgvInvocation(out).commandPath;
|
|
if (primary === "qa" && secondary === "matrix") {
|
|
out.push(arg);
|
|
if (consumedNext && next !== undefined) {
|
|
out.push(next);
|
|
}
|
|
return { kind: "handled", consumedNext };
|
|
}
|
|
if (sawDev) {
|
|
return { kind: "error", error: "Cannot combine --dev with --profile" };
|
|
}
|
|
if (!value) {
|
|
return { kind: "error", error: "--profile requires a value" };
|
|
}
|
|
if (!isValidProfileName(value)) {
|
|
return {
|
|
kind: "error",
|
|
error: 'Invalid --profile (use letters, numbers, "_", "-" only)',
|
|
};
|
|
}
|
|
profile = value;
|
|
return { kind: "handled", consumedNext };
|
|
}
|
|
return { kind: "pass" };
|
|
});
|
|
|
|
if (!scanned.ok) {
|
|
return scanned;
|
|
}
|
|
|
|
return { ok: true, profile, argv: scanned.argv };
|
|
}
|
|
|
|
function resolveProfileStateDir(
|
|
profile: string,
|
|
env: Record<string, string | undefined>,
|
|
homedir: () => string,
|
|
): string {
|
|
const suffix = normalizeLowercaseStringOrEmpty(profile) === "default" ? "" : `-${profile}`;
|
|
return path.join(resolveRequiredHomeDir(env as NodeJS.ProcessEnv, homedir), `.openclaw${suffix}`);
|
|
}
|
|
|
|
export function applyCliProfileEnv(params: {
|
|
profile: string;
|
|
env?: Record<string, string | undefined>;
|
|
homedir?: () => string;
|
|
}) {
|
|
const env = params.env ?? (process.env as Record<string, string | undefined>);
|
|
const homedir = params.homedir ?? os.homedir;
|
|
const profile = params.profile.trim();
|
|
if (!profile) {
|
|
return;
|
|
}
|
|
|
|
// Convenience only: fill defaults, never override explicit env values.
|
|
env.OPENCLAW_PROFILE = profile;
|
|
|
|
const existingStateDir = normalizeOptionalString(env.OPENCLAW_STATE_DIR);
|
|
const stateDir = existingStateDir || resolveProfileStateDir(profile, env, homedir);
|
|
if (!existingStateDir) {
|
|
env.OPENCLAW_STATE_DIR = stateDir;
|
|
}
|
|
|
|
if (!normalizeOptionalString(env.OPENCLAW_CONFIG_PATH)) {
|
|
env.OPENCLAW_CONFIG_PATH = path.join(stateDir, "openclaw.json");
|
|
}
|
|
|
|
if (profile === "dev" && !env.OPENCLAW_GATEWAY_PORT?.trim()) {
|
|
env.OPENCLAW_GATEWAY_PORT = "19001";
|
|
}
|
|
}
|