UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

290 lines (289 loc) • 13 kB
import { m as readNonBlankString } from "./string-coerce-CCIiB4H7.mjs"; import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { f as normalizeStringEntries } from "./string-normalization-DLmfYZXI.mjs"; import { a as parseConcreteConfigPathWithProvenance, r as parseConcreteConfigPath, s as toDotPath } from "./dot-path-BJ4tyWKJ.mjs"; import { d as isValidFileSecretRefId, f as isValidSecretProviderAlias, l as isValidEnvSecretRefId, o as formatExecSecretRefIdValidationMessage, u as isValidExecSecretRefId } from "./ref-contract-b8L-9DrQ.mjs"; import { a as coerceSecretRef } from "./types.secrets-BmNLLnHp.mjs"; import { o as getAsyncWorkSignal } from "./async-work-scope-BXagjUap.mjs"; import { r as decodeUtf8Input } from "./utf8-input-BHczGT8v.mjs"; import { _ as SecretProviderSchema } from "./zod-schema.core-BWFCYYML.mjs"; import { s as resolveConfigSecretTargetByPath } from "./target-registry-query-le6rMGHo.mjs"; import "./target-registry-C0PdHjLu.mjs"; import { n as visitConfigValueTree } from "./value-tree-Deh4eoFD.mjs"; import { n as formatConfigSetPath, s as parseConfigSetValue, u as validatePathSegments } from "./config-cli-path-rYPQt5Be.mjs"; import { t as readByteStreamWithLimit } from "./read-byte-stream-with-limit-BjmaH2Xs.mjs"; import { t as parseOptionalPositiveInteger } from "./parse-positive-integer-DrSNo4LV.mjs"; import { a as resolveConfigSetMode, i as readConfigMutationFileSync, n as parseConfigMutationJson5, t as parseBatchSource } from "./config-set-input-Da30AAoz.mjs"; import { addAbortSignal } from "node:stream"; //#region src/cli/config-cli-input.ts const CONFIG_PATCH_STDIN_MAX_BYTES = 1048576; function modeError(e) { return /* @__PURE__ */ new Error(`config set mode error: ${e}`); } function configPatchModeError(e) { return /* @__PURE__ */ new Error(`config patch mode error: ${e}`); } function parseSecretRefSource(e, t) { const n = e.trim(); if (n === "env" || n === "file" || n === "exec" || n === "store") return n; throw new Error(`${t} must be one of: env, file, exec, store.`); } function parseSecretRefBuilder(e) { const t = e.provider.trim(); if (!t) throw new Error(`${e.fieldPrefix}.provider is required.`); if (!isValidSecretProviderAlias(t)) throw new Error(`${e.fieldPrefix}.provider must match /^[a-z][a-z0-9_-]{0,63}$/ (example: "default").`); const n = parseSecretRefSource(e.source, `${e.fieldPrefix}.source`); const r = e.id.trim(); if (!r) throw new Error(`${e.fieldPrefix}.id is required.`); if ((n === "env" || n === "store") && !isValidEnvSecretRefId(r)) throw new Error(`${e.fieldPrefix}.id must match /^[A-Z][A-Z0-9_]{0,127}$/ for ${n} refs.`); if (n === "file" && !isValidFileSecretRefId(r)) throw new Error(`${e.fieldPrefix}.id must be an absolute JSON pointer (or "value" for singleValue mode).`); if (n === "exec" && !isValidExecSecretRefId(r)) throw new Error(formatExecSecretRefIdValidationMessage()); return { source: n, provider: t, id: r }; } function parseProviderPositiveInteger(e, t) { if (e !== void 0 && !e.trim()) throw new Error(`${t} must not be empty.`); return parseOptionalPositiveInteger(e, t, "."); } function parseProviderEnvEntries(e) { if (!e || e.length === 0) return; const t = {}; for (const n of e) { const e = n.indexOf("="); if (e <= 0) throw new Error("--provider-env expects KEY=*** entries."); const r = n.slice(0, e).trim(); if (!r) throw new Error("--provider-env key must not be empty."); t[r] = n.slice(e + 1); } return Object.keys(t).length > 0 ? t : void 0; } function validateProviderAliasPath(e) { if (e.length !== 3 || e[0] !== "secrets" || e[1] !== "providers") throw new Error("Provider builder mode requires path \"secrets.providers.<alias>\" (example: secrets.providers.vault)."); const t = e[2] ?? ""; if (!isValidSecretProviderAlias(t)) throw new Error(`Provider alias "${t}" must match /^[a-z][a-z0-9_-]{0,63}$/ (example: "default").`); } function parseSecretRefFromUnknown(e, t) { if (!isRecord(e)) throw new Error(`${t} must be an object with source/provider/id.`); if (typeof e.provider !== "string" || typeof e.source !== "string" || typeof e.id !== "string") throw new Error(`${t} must include string fields: source, provider, id.`); return parseSecretRefBuilder({ provider: e.provider, source: e.source, id: e.id, fieldPrefix: t }); } function buildAssignmentOperation(e) { const t = resolveConfigSecretTargetByPath(e.requestedPath, e.pathTokens); const n = coerceSecretRef(e.value); return { inputMode: e.inputMode, requestedPath: e.requestedPath, ...e.pathTokens ? { pathTokens: e.pathTokens } : {}, ...e.quotedNumericSegments ? { quotedNumericSegments: e.quotedNumericSegments } : {}, setPath: n && t?.entry.secretShape === "sibling_ref" && t.refPathSegments ? t.refPathSegments : e.requestedPath, value: e.value, ...e.validatedRef && t ? { schemaValidated: true } : {} }; } function buildConfigSetOperations(e) { const t = Boolean(e.opts.strictJson || e.opts.json); const n = resolveConfigSetMode(e.opts); if (e.opts.allowExec && !e.opts.dryRun) throw modeError("--allow-exec requires --dry-run."); if (e.opts.merge && e.opts.replace) throw modeError("choose either --merge or --replace, not both."); const r = parseBatchSource(e.opts); if (r) { if (e.path !== void 0 || e.value !== void 0) throw modeError("batch mode does not accept <path> or <value> arguments."); return r.map((e, t) => { const { tokens: n, quotedNumericSegments: r } = parseConcreteConfigPathWithProvenance(e.path); const i = n.map(String); if (e.ref === void 0 && e.provider !== void 0) { validateProviderAliasPath(i); const a = SecretProviderSchema.safeParse(e.provider); if (!a.success) { const e = a.error.issues[0]; throw new Error(`batch[${t}].provider invalid at ${e?.path?.join(".") ?? "<provider>"}: ${e?.message ?? ""}`); } return { inputMode: "json", requestedPath: i, pathTokens: n, quotedNumericSegments: r, setPath: i, value: a.data, schemaValidated: true }; } return buildAssignmentOperation({ requestedPath: i, pathTokens: n, quotedNumericSegments: r, value: e.ref === void 0 ? e.value : parseSecretRefFromUnknown(e.ref, `batch[${t}].ref`), inputMode: "json", validatedRef: e.ref !== void 0 }); }); } const i = typeof e.path === "string" && e.path.trim() ? parseConcreteConfigPathWithProvenance(e.path) : void 0; if (!i) throw modeError(n === "ref_builder" ? "ref builder mode requires <path>." : n === "provider_builder" ? "provider builder mode requires <path>." : "value/json mode requires <path> when batch mode is not used."); const a = { requestedPath: i.tokens.map(String), pathTokens: i.tokens, quotedNumericSegments: i.quotedNumericSegments }; if (n === "provider_builder") { if (e.value !== void 0) throw modeError("provider builder mode does not accept <value>."); const t = e.opts; const n = t.providerSource?.trim(); if (!n) throw new Error("--provider-source is required in provider builder mode."); const r = parseSecretRefSource(n, "--provider-source"); const i = parseProviderPositiveInteger(t.providerTimeoutMs, "--provider-timeout-ms"); const o = parseProviderPositiveInteger(t.providerMaxBytes, "--provider-max-bytes"); const s = parseProviderPositiveInteger(t.providerNoOutputTimeoutMs, "--provider-no-output-timeout-ms"); const c = parseProviderPositiveInteger(t.providerMaxOutputBytes, "--provider-max-output-bytes"); const l = parseProviderEnvEntries(t.providerEnv); let u; if (r === "env") { const e = normalizeStringEntries(t.providerAllowlist); for (const t of e) if (!isValidEnvSecretRefId(t)) throw new Error(`--provider-allowlist entry "${t}" must match /^[A-Z][A-Z0-9_]{0,127}$/.`); u = { source: "env", ...e.length > 0 ? { allowlist: e } : {} }; } else if (r === "file") { const e = t.providerPath?.trim(); if (!e) throw new Error("--provider-path is required when --provider-source file is used."); const n = t.providerMode?.trim(); if (n && n !== "singleValue" && n !== "json") throw new Error("--provider-mode must be one of: singleValue, json."); const r = n === "singleValue" || n === "json" ? n : void 0; u = { source: "file", path: e, ...r ? { mode: r } : {}, ...i !== void 0 ? { timeoutMs: i } : {}, ...o !== void 0 ? { maxBytes: o } : {} }; } else if (r === "store") u = { source: "store" }; else { const e = t.providerCommand?.trim(); if (!e) throw new Error("--provider-command is required when --provider-source exec is used."); u = { source: "exec", command: e, ...t.providerArg?.length ? { args: t.providerArg } : {}, ...i !== void 0 ? { timeoutMs: i } : {}, ...s !== void 0 ? { noOutputTimeoutMs: s } : {}, ...c !== void 0 ? { maxOutputBytes: c } : {}, ...t.providerJsonOnly ? { jsonOnly: true } : {}, ...l ? { env: l } : {}, ...t.providerPassEnv?.length ? { passEnv: normalizeStringEntries(t.providerPassEnv) } : {}, ...t.providerTrustedDir?.length ? { trustedDirs: normalizeStringEntries(t.providerTrustedDir) } : {} }; } const d = SecretProviderSchema.safeParse(u); if (!d.success) { const e = d.error.issues[0]; throw new Error(`Provider builder config invalid at ${e?.path?.join(".") ?? "<provider>"}: ${e?.message ?? "Invalid provider config."}`); } const f = d.data; validateProviderAliasPath(a.requestedPath); return [{ inputMode: "builder", ...a, setPath: a.requestedPath, value: f, schemaValidated: true }]; } let o; if (n === "ref_builder") { if (e.value !== void 0) throw modeError("ref builder mode does not accept <value>."); if (!e.opts.refProvider || !e.opts.refSource || !e.opts.refId) throw modeError("ref builder mode requires --ref-provider <alias>, --ref-source <env|file|exec|store>, and --ref-id <id>."); o = parseSecretRefBuilder({ provider: e.opts.refProvider, source: e.opts.refSource, id: e.opts.refId, fieldPrefix: "ref" }); } else { if (e.value === void 0) throw modeError("value/json mode requires <value>."); o = parseConfigSetValue(e.value, t); } return [buildAssignmentOperation({ ...a, value: o, inputMode: n === "ref_builder" ? "builder" : n === "json" ? "json" : "value", validatedRef: n === "ref_builder" })]; } async function readStdinText() { if (process.stdin.isTTY) throw configPatchModeError("--stdin refuses to read from an interactive terminal; pipe input or use --file <path>."); const e = getAsyncWorkSignal(); e?.throwIfAborted(); const t = e ? addAbortSignal(e, process.stdin) : process.stdin; const n = await readByteStreamWithLimit(t, { maxBytes: CONFIG_PATCH_STDIN_MAX_BYTES, onOverflow: ({ maxBytes: e }) => configPatchModeError(`--stdin input exceeds ${e} bytes; use --file <path> for larger patches.`) }); e?.throwIfAborted(); return decodeUtf8Input(n, "--stdin"); } function buildUnsetOperation(e, t) { return { inputMode: "unset", requestedPath: e, ...t ? { pathTokens: t } : {}, setPath: e, value: void 0, mutation: "delete" }; } async function readConfigPatchOperations(e) { const t = readNonBlankString(e.file); const n = Boolean(e.stdin); if (Boolean(t) === n) throw configPatchModeError("provide exactly one of --file <path> or --stdin."); const r = n ? "--stdin" : "--file"; const i = t ? readConfigMutationFileSync(t, "--file") : await readStdinText(); const a = parseConfigMutationJson5(i, `${r} as JSON5`); const o = (e.replacePath ?? []).map(parseConcreteConfigPath); if (!isRecord(a)) throw configPatchModeError("input must be a JSON5 object patch."); const s = []; const pathKey = (e) => JSON.stringify(e); const c = new Set(o.map(pathKey)); const l = new Set(o.map((e) => e.length)); const u = /* @__PURE__ */ new Set(); visitConfigValueTree(a, (e, t) => { const n = t.at(-1); if (n === void 0) return true; validatePathSegments([n]); const r = l.has(t.length) ? pathKey(t) : void 0; const i = r !== void 0 && c.has(r); if (i) u.add(r); const a = isRecord(e) ? coerceSecretRef(e) : null; const o = !i && isRecord(e) && !a; if (o && Object.keys(e).length > 0) return true; if (e === null) s.push({ ...buildUnsetOperation([...t]), inputMode: "json" }); else { const n = buildAssignmentOperation({ requestedPath: [...t], value: a ? parseSecretRefFromUnknown(e, `patch.${toDotPath(t)}`) : e, inputMode: "json", validatedRef: Boolean(a) }); if (i || o) n.mutation = i ? "replace" : "merge"; s.push(n); } return false; }); const d = o.find((e) => !u.has(pathKey(e))); if (d) throw configPatchModeError(`--replace-path ${formatConfigSetPath(d)} did not match any value in the input patch.`); if (s.length === 0) throw configPatchModeError("input patch did not contain any config updates."); return s; } //#endregion export { buildConfigSetOperations, buildUnsetOperation, configPatchModeError, readConfigPatchOperations };