UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

890 lines (889 loc) • 36.4 kB
import { a as asOptionalRecord, l as isRecord, p as readStringField } from "./record-coerce-CVPuDqcc.mjs"; import "./src-H3RMXyFL.mjs"; import { t as expectDefined } from "./expect-DDakjvvQ.mjs"; import { t as isBlockedObjectKey } from "./prototype-keys-CLGi5xDj.mjs"; import { t as parseConfigPathArrayIndex } from "./path-array-index-qP-D1DoI.mjs"; import { o as readObjectPath, t as appendConfigPathSegment } from "./dot-path-BJ4tyWKJ.mjs"; import { i as resolveConfigEnvVars, n as containsEnvVarReference } from "./env-substitution-CgVeOqUd.mjs"; import "./utils-C8YECn2Q.mjs"; import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs"; import "./session-key-CqAyZeVk.mjs"; import { n as listAgentEntries, r as listAgentEntriesWithSource, s as readAgentRosterProperty, t as hasAgentRosterProperty } from "./agent-roster-t1ooUdXp.mjs"; import { E as toAgentEntriesRecord } from "./agent-scope-config-DmXgFGKP.mjs"; import { o as createConfigRuntimeEnvBase } from "./config-env-vars-ByeGN-9N.mjs"; import { d as hasUnresolvedConfigPath, f as hasUnresolvedConfigPathInSubtree, g as setConfigResolutionFacts, l as getConfigResolutionFacts } from "./resolution-facts-xaIKuREs.mjs"; import { n as createMergePatch } from "./merge-patch-D-7aajuy.mjs"; import { t as coerceConfig, u as resolveConfigForRead } from "./io.read-helpers-qAcqsRC0.mjs"; import { n as normalizeAgentModelMapForConfig, r as normalizeAgentModelRefForConfig } from "./model-input-DrM4DWHG.mjs"; import { n as projectLegacyAgentRosterEntries, t as parseLegacyAgentRoster } from "./legacy.roster-BcYJITMZ.mjs"; import { t as projectRuntimeChangesOntoSource } from "./source-value-projection-Dw6wBBVW.mjs"; import { t as isSecretRefShape } from "./redact-snapshot.secret-ref-DsdaGkng.mjs"; import { n as configIncludeOwnsAgentRosterValues } from "./agent-roster-provenance-DiT1dDed.mjs"; import { r as restoreEnvVarRefsFromResolved, t as resolveWriteEnvSnapshotForPath } from "./env-preserve-D_8K8swo.mjs"; import { n as createConfigIncludeOwnershipError } from "./io.write-errors-CuPAqPbq.mjs"; import { isDeepStrictEqual } from "node:util"; //#region src/config/io.write-values.ts /** Keep reference identity for persistence separate from values used by physical owners. */ function prepareProjectedConfigWriteValues(e, t) { const { snapshot: n } = e; const r = n.sourceConfigBeforeMigrations ?? n.sourceConfig; const i = n.authoredConfig ?? n.parsed; const a = resolveWriteEnvSnapshotForPath({ actualConfigPath: n.path, expectedConfigPath: e.writeOptions?.expectedConfigPath, envSnapshotForRestore: e.writeOptions?.envSnapshotForRestore }); const o = a ? resolveConfigEnvVars(i, a, { onMissing: () => {} }) : r; const restore = (e, n, a = r) => { const o = readAgentRosterProperty(e)?.kind === "entries"; const project = (e) => o ? t({ rootAuthoredConfig: e, sourceConfigBeforeMigrations: a }) : e; return coerceConfig(restoreEnvVarRefsFromResolved(e, project(i), project(a), n)); }; const s = restore(e.nextConfig, e.explicitSetPaths, o); const c = resolveConfigForRead(s, createConfigRuntimeEnvBase(r, e.env), e.lowerPrecedenceEnv); const l = coerceConfig(c.resolvedConfigRaw); setConfigResolutionFacts(l, c.resolutionFacts); return { authoredConfig: s, resolutionEnv: c.envSnapshotForRestore, explicitSetValueSource: e.explicitSetValueSource ? restore(e.explicitSetValueSource, e.explicitSetPaths, o) : s, resolvedConfig: l, authoredSourceConfig: restore(n.sourceConfig), authoredRuntimeConfig: restore(n.runtimeConfig) }; } //#endregion //#region src/config/io.write-prepare.ts const getPathValue = (e, t) => readObjectPath(e, t, "bounded"); function prepareConfigWriteValues(e) { return prepareProjectedConfigWriteValues(e, projectAuthoredAgentRosterForWrite); } const AGENT_ROSTER_PATHS = [["agents", "entries"], ["agents", "list"]]; var DuplicateAgentRosterIdError = class extends Error { constructor(e) { super(`Config write cannot canonicalize duplicate normalized agent id "${e}".`); this.name = "DuplicateAgentRosterIdError"; } }; function assertUniqueNormalizedLegacyRosterIds(e, t = (e) => e.id) { const n = /* @__PURE__ */ new Set(); for (const [r, i] of e.entries()) { if (!isRecord(i)) continue; const e = t(i, r); if (typeof e !== "string") continue; const a = normalizeAgentId(e); if (n.has(a)) throw new DuplicateAgentRosterIdError(a); n.add(a); } } function hasOwnValidIncludeDirective(e) { if (!isRecord(e) || !Object.hasOwn(e, "$include")) return false; const t = e.$include; return typeof t === "string" || Array.isArray(t) && t.every((e) => typeof e === "string"); } function collectConfigPaths(e, t, n, r) { if (r?.(t)) return []; if (n(e)) return [t]; if (!Array.isArray(e) && !isRecord(e)) return []; return Object.entries(e).flatMap(([e, i]) => collectConfigPaths(i, [...t, e], n, r)); } function collectIncludeOwnedPaths(e, t = []) { return collectConfigPaths(e, t, hasOwnValidIncludeDirective); } function collectMutableSiblingPathsAtInclude(e, t) { const n = getPathValue(e, t); if (!hasOwnValidIncludeDirective(n)) return []; return Object.keys(n).flatMap((e) => e === "$include" || isBlockedObjectKey(e) ? [] : [[...t, e]]); } function isMutableSiblingPathAtInclude(e, t, n) { return collectMutableSiblingPathsAtInclude(e, t).some((t) => { if (!pathStartsWith(n, t)) return false; return !collectIncludeOwnedPaths(getPathValue(e, t), t).some((e) => pathStartsWith(n, e) || pathStartsWith(e, n)); }); } function findContainingArrayPath(e, t) { let n = e; const r = []; for (const e of t) { if (Array.isArray(n)) return r; if (!isRecord(n)) return; n = n[e]; r.push(e); } } function hasChangedEquivalentArraySibling(e, t, n) { if (!Array.isArray(e) || !Array.isArray(t) || n >= e.length) return false; return e.some((r, i) => i !== n && isDeepStrictEqual(r, e[n]) && !isDeepStrictEqual(t[i], r)); } function hasNewEquivalentArraySibling(e, t, n) { if (!Array.isArray(e) || !Array.isArray(t) || n >= e.length) return false; const r = e[n]; if (!isDeepStrictEqual(t[n], r)) return false; return t.some((t, i) => i !== n && isDeepStrictEqual(t, r) && !isDeepStrictEqual(e[i], r)); } function setPathValue(e, t, n, r = false) { if (t.length === 0) return n; const i = expectDefined(t[0], "config path head"); const a = t.slice(1); const o = parseConfigPathArrayIndex(i); if (Array.isArray(e) || r && !isRecord(e) && o !== void 0) { if (o === void 0 || !r && Array.isArray(e) && o >= e.length) return e; const t = Array.isArray(e) ? [...e] : []; t[o] = setPathValue(t[o], a, n, r); return t; } if (!r && !isRecord(e)) return e; const s = isRecord(e) ? e : {}; return { ...s, [i]: setPathValue(s[i], a, n, r) }; } function pathStartsWith(e, t) { return t.length <= e.length && t.every((t, n) => e[n] === t); } function pathOverlapsAny(e, t) { return Boolean(t?.some((t) => pathStartsWith(e, t) || pathStartsWith(t, e))); } function findOverlappingIncludeOwnedPath(e, t) { return collectIncludeOwnedPaths(e).find((n) => { if (!(pathStartsWith(t, n) || pathStartsWith(n, t))) return false; return !isMutableSiblingPathAtInclude(e, n, t); }); } function deletePathValue(e, t) { if (t.length === 0) return e; const n = expectDefined(t[0], "config path head"); const r = t.slice(1); if (Array.isArray(e)) { const t = parseConfigPathArrayIndex(n); if (t === void 0 || t >= e.length || r.length === 0) return e; const i = [...e]; i[t] = deletePathValue(e[t], r); return i; } if (!isRecord(e) || !Object.hasOwn(e, n)) return e; const i = { ...e }; if (r.length === 0) { delete i[n]; return i; } i[n] = deletePathValue(e[n], r); return i; } function normalizeTouchedAgentModelMapEntries(e) { const t = /* @__PURE__ */ new Map(); const addKey = (e, n) => { const r = e.join("\0"); const i = t.get(r) ?? { path: e, canonicalKeys: /* @__PURE__ */ new Set() }; i.canonicalKeys.add(normalizeAgentModelRefForConfig(n)); t.set(r, i); }; const n = getPathValue(e.patch, [ "agents", "defaults", "models" ]); if (isRecord(n)) for (const e of Object.keys(n)) addKey([ "agents", "defaults", "models" ], e); const r = getPathValue(e.patch, ["agents", "entries"]); if (isRecord(r)) { for (const [e, t] of Object.entries(r)) if (isRecord(t) && isRecord(t.models)) for (const n of Object.keys(t.models)) addKey([ "agents", "entries", e, "models" ], n); } const i = [[ "agents", "defaults", "models" ]]; const a = getPathValue(e.explicitSetValueSource, ["agents", "entries"]); if (isRecord(a)) for (const e of Object.keys(a)) i.push([ "agents", "entries", e, "models" ]); for (const t of i) for (const n of e.touchedPaths ?? []) { if (pathStartsWith(n, t) && n.length > t.length) { const e = n[t.length]; if (e) addKey(t, e); continue; } if (!pathStartsWith(n, t) && !pathStartsWith(t, n)) continue; const r = getPathValue(e.explicitSetValueSource, t); if (!isRecord(r)) continue; for (const e of Object.keys(r)) addKey(t, e); } let o = e.projectedSource; for (const { path: e, canonicalKeys: n } of t.values()) { const t = getPathValue(o, e); if (!isRecord(t)) continue; const r = []; const i = []; let a = false; for (const [e, o] of Object.entries(t)) { const t = normalizeAgentModelRefForConfig(e); if (!n.has(t)) { i.push([e, o]); continue; } r.push([e, o]); a ||= t !== e; } if (a) { const t = normalizeAgentModelMapForConfig(Object.fromEntries(r)); o = setPathValue(o, e, Object.fromEntries([...i, ...Object.entries(t)])); } } return o; } function preserveSourceValueAtPath(e) { if (pathOverlapsAny(e.path, e.unsetPaths)) return e.persistedCandidate; if (findOverlappingIncludeOwnedPath(e.rootAuthoredConfig, e.path)) return e.persistedCandidate; if (getPathValue(e.nextConfig, e.path) !== void 0) return e.persistedCandidate; const t = e.sourceValue ?? getPathValue(e.sourceConfig, e.path); if (t === void 0 || getPathValue(e.persistedCandidate, e.path) !== void 0) return e.persistedCandidate; return setPathValue(e.persistedCandidate, e.path, t, true); } function preserveAuthoredAgentParams(e) { const t = getPathValue(e.sourceConfig, ["agents", "defaults"]); if (!isRecord(t)) return e.persistedCandidate; let n = e.persistedCandidate; if (Object.hasOwn(t, "params")) n = preserveSourceValueAtPath({ ...e, persistedCandidate: n, path: [ "agents", "defaults", "params" ], sourceValue: t.params }); const r = t.models; if (!isRecord(r)) return n; const i = getPathValue(e.nextConfig, [ "agents", "defaults", "models" ]); for (const [t, a] of Object.entries(r)) { if (!isRecord(a) || !Object.hasOwn(a, "params")) continue; const r = [ "agents", "defaults", "models", normalizeAgentModelRefForConfig(t) || t ]; const o = r.at(-1); if (isRecord(i) && o && !Object.hasOwn(i, o)) continue; const s = getPathValue(n, r) === void 0; n = preserveSourceValueAtPath({ ...e, persistedCandidate: n, path: s ? r : [...r, "params"], sourceValue: s ? a : a.params }); } return n; } function isRootOwnedArray(e, t, n) { return (e === void 0 || Array.isArray(e)) && collectIncludeOwnedPaths(e).length === 0 && (Array.isArray(n) ? (e?.length ?? 0) === n.length : Array.isArray(e) && isDeepStrictEqual(e, t)); } function projectRootAuthoredIncludeSibling(e) { if (e.nextPresent && e.baselinePresent && isDeepStrictEqual(e.next, e.baseline)) return { ok: true, present: true, value: e.authored }; if (!e.nextPresent) return collectIncludeOwnedPaths(e.authored).length > 0 ? { ok: false } : { ok: true, present: false }; if (!e.baselinePresent) return { ok: true, present: true, value: e.next }; if (hasOwnValidIncludeDirective(e.authored)) return { ok: false }; if (Array.isArray(e.authored)) return (Array.isArray(e.next) ? isRootOwnedArray(e.authored, e.baseline, e.sourceBeforeMigrations) : collectIncludeOwnedPaths(e.authored).length === 0) ? { ok: true, present: true, value: e.next } : { ok: false }; if (!isRecord(e.authored)) return { ok: true, present: true, value: e.next }; if (!isRecord(e.next)) return collectIncludeOwnedPaths(e.authored).length > 0 ? { ok: false } : { ok: true, present: true, value: e.next }; if (!isRecord(e.baseline)) return { ok: true, present: true, value: e.next }; const t = { ...e.authored }; const n = /* @__PURE__ */ new Set([ ...Object.keys(e.authored), ...Object.keys(e.baseline), ...Object.keys(e.next) ]); for (const r of n) { if (isBlockedObjectKey(r)) continue; const n = Object.hasOwn(e.authored, r); const i = Object.hasOwn(e.baseline, r); const a = Object.hasOwn(e.next, r); if (!n) { if (i && a && isDeepStrictEqual(e.baseline[r], e.next[r])) continue; if (!a) return { ok: false }; if (i && Array.isArray(e.baseline[r]) && Array.isArray(e.next[r])) return { ok: false }; } const o = projectRootAuthoredIncludeSibling({ authored: n ? e.authored[r] : {}, baseline: e.baseline[r], sourceBeforeMigrations: getPathValue(e.sourceBeforeMigrations, [r]), next: e.next[r], baselinePresent: i, nextPresent: a }); if (!o.ok) return o; if (o.present) t[r] = o.value; else delete t[r]; } return { ok: true, present: true, value: t }; } function includeOwnershipError(e, t) { const n = getPathValue(e, [...t, "$include"]); const r = (Array.isArray(n) ? n : [n]).filter((e) => typeof e === "string"); return createConfigIncludeOwnershipError({ ownedConfigPath: t.length > 0 ? t.join(".") : "<root>", ...r.length > 0 ? { includeTargets: r } : {} }); } function preserveUntouchedIncludes(e) { let t = e.persistedCandidate; for (const n of collectIncludeOwnedPaths(e.rootAuthoredConfig)) { const r = findContainingArrayPath(e.rootAuthoredConfig, n); const i = r !== void 0 && n.length === r.length + 1; const a = i ? n : r ?? n; const o = collectMutableSiblingPathsAtInclude(e.rootAuthoredConfig, n); const s = o.map((e) => e.slice(a.length)); const omitMutableSiblingValues = (e) => s.reduce((e, t) => deletePathValue(e, t), e); const c = omitMutableSiblingValues(getPathValue(e.nextConfig, a)); const l = omitMutableSiblingValues(getPathValue(e.sourceConfig, a)); const u = omitMutableSiblingValues(getPathValue(e.runtimeConfig, a)); if (!isDeepStrictEqual(c, l) && !isDeepStrictEqual(c, u)) throw includeOwnershipError(e.rootAuthoredConfig, n); if (i) { const t = parseConfigPathArrayIndex(n.at(-1) ?? ""); const i = getPathValue(e.nextConfig, r); const a = getPathValue(e.sourceConfig, r); const o = getPathValue(e.runtimeConfig, r); if (t !== void 0 && (hasChangedEquivalentArraySibling(a, i, t) || hasChangedEquivalentArraySibling(o, i, t) || hasNewEquivalentArraySibling(a, i, t) || hasNewEquivalentArraySibling(o, i, t))) throw includeOwnershipError(e.rootAuthoredConfig, n); } let d = getPathValue(e.rootAuthoredConfig, n); for (const t of o) { const r = t.slice(n.length); const i = hasPathValue(e.persistedCandidate, t); const projectAgainst = (n) => projectRootAuthoredIncludeSibling({ authored: getPathValue(e.rootAuthoredConfig, t), baseline: getPathValue(n, t), sourceBeforeMigrations: getPathValue(e.sourceConfigBeforeMigrations, t), next: getPathValue(e.persistedCandidate, t), baselinePresent: hasPathValue(n, t), nextPresent: i }); const a = projectAgainst(e.sourceConfig); const o = a.ok ? a : projectAgainst(e.runtimeConfig); if (!o.ok) throw includeOwnershipError(e.rootAuthoredConfig, n); d = o.present ? setPathValue(d, r, o.value) : deletePathValue(d, r); } t = setPathValue(t, n, d); } return t; } function hasPathValue(e, t) { let n = e; for (const e of t) if (Array.isArray(n)) { const t = parseConfigPathArrayIndex(e); if (t === void 0 || t >= n.length) return false; n = n[t]; } else if (isRecord(n) && !isBlockedObjectKey(e) && Object.hasOwn(n, e)) n = n[e]; else return false; return true; } function mergeMissingExplicitValues(e, t) { if (hasOwnValidIncludeDirective(e)) return e; if (!(isRecord(e) && isRecord(t)) && !(Array.isArray(e) && Array.isArray(t))) return e; let n = false; const r = Array.isArray(e) ? [...e] : { ...e }; for (const [e, i] of Object.entries(t)) { if (Array.isArray(r) ? parseConfigPathArrayIndex(e) === void 0 : isBlockedObjectKey(e)) continue; const t = Array.isArray(r) ? Number(e) >= r.length || r[Number(e)] === void 0 : !Object.hasOwn(r, e); const a = t ? void 0 : Reflect.get(r, e); const o = t ? i : mergeMissingExplicitValues(a, i); if (t || !Object.is(o, a)) { Reflect.set(r, e, o); n = true; } } return n ? r : e; } function injectExplicitlySetPaths(e) { if (!e.explicitSetPaths || e.explicitSetPaths.length === 0) return e.persistedCandidate; const t = collectIncludeOwnedPaths(e.rootAuthoredConfig); let n = e.persistedCandidate; explicitPath: for (const r of e.explicitSetPaths) { if (r.length === 0 || r.some(isBlockedObjectKey)) continue; const i = e.rootAuthoredConfig ? findOverlappingIncludeOwnedPath(e.rootAuthoredConfig, [...r]) : void 0; const a = i && e.preserveDescendantIncludes === true && i.length > r.length && pathStartsWith(i, r); const o = i !== void 0 && i.length < r.length && pathStartsWith(r, i) && e.allowIncludeAncestorExplicitSetPaths === true; if (i && !a && !o) throw includeOwnershipError(e.rootAuthoredConfig, i); let s = getPathValue(e.valueSource, r); if (s === void 0) continue; const c = t.length > 0 ? [...r.flatMap((t, n) => { const i = r.slice(0, n); return Array.isArray(getPathValue(e.valueSource, i)) ? [i] : []; }), ...collectConfigPaths(s, [...r], Array.isArray, (e) => hasOwnValidIncludeDirective(getPathValue(n, e)))] : []; for (const i of c) { const a = t.find((e) => pathStartsWith(i, e)); if (a && !isRootOwnedArray(getPathValue(e.rootAuthoredConfig, i), getPathValue(e.sourceConfig, i), getPathValue(e.sourceConfigBeforeMigrations, i))) { const t = i.length < r.length ? r : i; const o = getPathValue(e.valueSource, t); if (!isDeepStrictEqual(o, getPathValue(e.sourceConfig, t)) && !isDeepStrictEqual(o, getPathValue(e.runtimeConfig, t))) throw includeOwnershipError(e.rootAuthoredConfig, a); if (i.length <= r.length) continue explicitPath; const c = getPathValue(n, i); const l = i.slice(r.length); s = c === void 0 ? deletePathValue(s, l) : setPathValue(s, l, c); } } if (!hasPathValue(n, r)) { n = setPathValue(n, r, s, true); continue; } const l = getPathValue(n, r); const u = mergeMissingExplicitValues(l, s); if (!Object.is(u, l)) n = setPathValue(n, r, u); } return n; } function pathTouchesAgentRoster(e) { return AGENT_ROSTER_PATHS.some((t) => pathStartsWith(e, t) || pathStartsWith(t, e)); } function pathTargetsAgentRoster(e) { return AGENT_ROSTER_PATHS.some((t) => pathStartsWith(e, t)); } function hasOnlyPreparedKeyedAgentEntryRosterIncludes(e, t) { const n = getPathValue(e, ["agents", "entries"]); if (!isRecord(n) || !t || t.length === 0) return false; const r = collectIncludeOwnedPaths(e).filter((e) => pathTouchesAgentRoster(e)); return r.length > 0 && r.every((e) => e.length === 3 && e[0] === "agents" && e[1] === "entries" && t.some((t) => t.length === e.length && e.every((e, n) => e === t[n]))) && t.length === r.length; } function canCanonicalizeAgentRoster(e) { const t = readAgentRosterProperty(e); if (!t) return false; if (t.kind === "list") { if (!Array.isArray(t.value) || !t.value.every((e) => isRecord(e) && typeof e.id === "string")) return false; assertUniqueNormalizedLegacyRosterIds(t.value); return true; } return isRecord(t.value) && Object.values(t.value).every(isRecord); } function shouldPersistCanonicalAgentRoster(e) { if (!canCanonicalizeAgentRoster(e.nextConfig)) return false; if (e.persistCanonicalAgentRoster === true || e.explicitSetPaths?.some(pathTouchesAgentRoster) || e.unsetPaths?.some(pathTouchesAgentRoster)) return true; const t = toAgentEntriesRecord(listAgentEntries(e.runtimeConfig)); const n = toAgentEntriesRecord(listAgentEntries(e.sourceConfig)); const r = toAgentEntriesRecord(listAgentEntries(e.nextConfig)); return !isDeepStrictEqual(t, r) && !isDeepStrictEqual(n, r); } function assertCanonicalAgentRosterRetainsEntries(e) { const t = new Set((e.allowedRemovals ?? []).map((e) => normalizeAgentId(e))); const n = new Set(listAgentEntries(e.canonicalConfig).map((e) => normalizeAgentId(e.id))); const r = readAgentRosterProperty(e.currentConfig); const i = (r?.kind === "list" && Array.isArray(r.value) ? projectLegacyAgentRosterEntries(r.value).entries : listAgentEntries(e.currentConfig)).filter((e) => { const r = normalizeAgentId(e.id); return !n.has(r) && !t.has(r); }).map((e) => e.id).toSorted(); if (i.length === 0) return; throw new Error(`Config write would drop agent roster entries without an explicit deletion: ${i.join(", ")}.`); } function containsAuthoredRosterReference(e, t) { if (typeof e === "string") return t && containsEnvVarReference(e); if (Array.isArray(e)) return e.some((e) => containsAuthoredRosterReference(e, t)); if (!isRecord(e)) return false; return isSecretRefShape(e) || Object.values(e).some((e) => containsAuthoredRosterReference(e, t)); } function indexAgentRosterSourcePaths(e, t) { return new Map(listAgentEntriesWithSource(e).flatMap(({ entry: e, source: n }) => { const r = n.kind === "list" ? t.get(n.index) : e.id; return r === void 0 ? [] : [[normalizeAgentId(r), n.kind === "list" ? `agents.list[${n.index}]` : appendConfigPathSegment("agents.entries", n.key)]]; })); } function readRosterChild(e, t) { if (t === void 0) return { value: void 0, present: false }; if (typeof t === "number") { const n = Array.isArray(e) ? e : []; return { value: n[t], present: t < n.length }; } const n = isRecord(e) ? e : {}; return { value: n[t], present: Object.hasOwn(n, t) }; } function projectAuthoredRosterValue(e) { const t = e.explicitPaths.some((t) => pathStartsWith(e.path, t)); if (isRecord(e.next)) { const t = {}; for (const [n, r] of Object.entries(e.next)) { if (isBlockedObjectKey(n)) continue; t[n] = projectAuthoredRosterValue({ authored: readRosterChild(e.authored.value, n), explicit: readRosterChild(e.explicit.value, n), explicitPaths: e.explicitPaths, path: [...e.path, n], runtime: readRosterChild(e.runtime.value, n), source: readRosterChild(e.source.value, n), next: r }); } return t; } if (Array.isArray(e.next)) { if (t && e.explicit.present && Array.isArray(e.explicit.value)) return e.explicit.value; const n = Array.isArray(e.runtime.value) ? e.runtime.value : []; const r = Array.isArray(e.source.value) ? e.source.value : []; const i = /* @__PURE__ */ new Set(); const a = /* @__PURE__ */ new Set(); const claimMatchingIndex = (e, t, n, r) => { if (r < e.length && !t.has(r) && isDeepStrictEqual(e[r], n)) { t.add(r); return r; } const i = e.findIndex((e, r) => !t.has(r) && isDeepStrictEqual(e, n)); if (i < 0) return; t.add(i); return i; }; return e.next.map((t, o) => { const s = claimMatchingIndex(n, i, t, o); const c = claimMatchingIndex(r, a, t, o); const l = !i.has(o) && !a.has(o); const u = s ?? c ?? (l ? o : void 0); return projectAuthoredRosterValue({ authored: readRosterChild(e.authored.value, u), explicit: readRosterChild(e.explicit.value, o), explicitPaths: e.explicitPaths, path: [...e.path, String(o)], runtime: readRosterChild(n, s ?? (l ? o : void 0)), source: readRosterChild(r, c ?? (l ? o : void 0)), next: t }); }); } if (t && e.explicit.present) return e.explicit.value; const n = e.runtime.present && isDeepStrictEqual(e.runtime.value, e.next); const r = e.source.present && isDeepStrictEqual(e.source.value, e.next); return e.authored.present && (n || r) ? e.authored.value : e.next; } function readLegacyAgentList(e) { const t = readAgentRosterProperty(e); return t?.kind === "list" && Array.isArray(t.value) ? t.value : void 0; } function indexAgentRosterForWrite(e, t) { const n = readLegacyAgentList(e); if (!n) return toAgentEntriesRecord(listAgentEntries(e)); return Object.fromEntries(n.flatMap((e, n) => { const r = t.get(n); if (!isRecord(e) || r === void 0) return []; const { id: i, ...a } = e; return [[r, a]]; })); } function canonicalizeAgentRosterForExplicitWrite(e) { const t = readLegacyAgentList(e.rootAuthoredConfig); const n = readLegacyAgentList(e.sourceConfigBeforeMigrations); const r = new Map(projectLegacyAgentRosterEntries(n ?? t ?? []).entries.map(({ sourceIndex: e, id: t }) => [e, t])); const i = indexAgentRosterForWrite(e.rootAuthoredConfig, r); const a = indexAgentRosterForWrite(e.runtimeConfig, r); const o = indexAgentRosterForWrite(e.sourceConfig, r); const s = toAgentEntriesRecord(listAgentEntries(e.nextConfig)); const c = readLegacyAgentList(e.valueSource); const l = coerceConfig(e.sourceConfigBeforeMigrations ?? e.rootAuthoredConfig); const u = indexAgentRosterSourcePaths(l, r); const d = getConfigResolutionFacts(l) !== null; const f = new Set((e.explicitSetPaths ?? []).flatMap((e) => { if (e[0] !== "agents" || e[1] !== "list" || e.length !== 4 || e[3] !== "id") return []; const t = parseConfigPathArrayIndex(e[2] ?? ""); return t === void 0 ? [] : [t]; })); const p = new Set(f); for (const t of e.explicitSetPaths ?? []) { if (t[0] !== "agents" || t[1] !== "list") continue; if (t.length === 2 && c) { c.forEach((e, t) => p.add(t)); continue; } if (t.length === 3) { const e = parseConfigPathArrayIndex(t[2] ?? ""); if (e !== void 0) p.add(e); } } for (const e of f) { const t = c ? c[e] : void 0; if (isRecord(t) && typeof t.id === "string" && (hasUnresolvedConfigPath(l, `agents.list[${e}].id`) || !d && containsEnvVarReference(t.id))) throw new Error("Config write cannot safely resolve an env-backed renamed agent id; set the resolved literal id or rename the authored entry directly."); } const resolveExplicitLegacyEntryId = (e, r) => { const i = e.id; if (typeof i !== "string") return; if (f.has(r) || Object.hasOwn(s, i)) return i; if (t) { const e = t.findIndex((e) => isRecord(e) && e.id === i); const r = e < 0 ? void 0 : n?.[e]; if (isRecord(r) && typeof r.id === "string") return r.id; } return hasUnresolvedConfigPath(l, `agents.list[${r}].id`) || containsEnvVarReference(i) ? void 0 : i; }; if (c) assertUniqueNormalizedLegacyRosterIds(c, resolveExplicitLegacyEntryId); const m = c ? Object.fromEntries(c.flatMap((e, t) => { if (!isRecord(e)) return []; const n = p.has(t) ? resolveExplicitLegacyEntryId(e, t) : r.get(t) ?? e.id; if (typeof n !== "string") { if (p.has(t) && typeof e.id === "string") throw new Error(`Config write cannot safely resolve an explicitly replaced agent list slot for id "${e.id}"; use a resolved literal id before writing the roster.`); return []; } const { id: i, ...a } = e; return [[n, a]]; })) : toAgentEntriesRecord(listAgentEntries(e.valueSource)); const h = (e.explicitSetPaths ?? []).flatMap((e) => { if (e[0] !== "agents") return []; if (e.length === 1) return [[]]; if (e[1] === "entries") return [e.slice(2)]; if (e[1] !== "list") return []; if (e.length === 2) return [[]]; const t = parseConfigPathArrayIndex(e[2] ?? ""); const n = c && t !== void 0 ? c[t] : void 0; const i = t !== void 0 && (f.has(t) || e.length === 3 && p.has(t)) && isRecord(n) ? n.id : t === void 0 ? void 0 : r.get(t); return typeof i === "string" ? [[i, ...e.slice(3)]] : []; }); const g = /* @__PURE__ */ new Map(); for (const e of Object.keys(s)) if (Object.hasOwn(a, e) || Object.hasOwn(o, e)) g.set(e, e); if (t && c) for (const e of f) { const t = c[e]; const n = r.get(e); const i = isRecord(t) ? t.id : void 0; if (typeof n === "string" && typeof i === "string") g.set(i, n); } const _ = /* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(o)]); const v = [..._].filter((e) => !Object.hasOwn(s, e)); const y = Object.keys(s).filter((e) => !_.has(e)); const b = new Set(g.values()); for (const e of y) { if (g.has(e)) continue; const t = v.filter((t) => !b.has(t) && (isDeepStrictEqual(s[e], a[t]) || isDeepStrictEqual(s[e], o[t]))); if (t.length === 1) { const n = t[0]; g.set(e, n); b.add(n); } } const x = y.filter((e) => !g.has(e)); const S = v.filter((e) => !b.has(e)); if (x.length > 0 && S.some((e) => { const t = u.get(normalizeAgentId(e)); return containsAuthoredRosterReference(i[e], !d) || Boolean(t && hasUnresolvedConfigPathInSubtree(l, t)); })) throw new Error("Config write cannot safely match renamed agent entries with authored references; rename agents one at a time."); let C = Object.fromEntries(Object.entries(s).map(([e, t]) => { const n = g.get(e) ?? e; const r = projectAuthoredRosterValue({ authored: readRosterChild(i, n), explicit: readRosterChild(m, e), explicitPaths: h, path: [e], runtime: readRosterChild(a, n), source: readRosterChild(o, n), next: t }); if (isRecord(r) && isRecord(t)) { if (Object.hasOwn(t, "default")) { const e = u.get(normalizeAgentId(n)); if (!(Object.hasOwn(r, "default") && (containsAuthoredRosterReference(r.default, !d) || Boolean(e && hasUnresolvedConfigPathInSubtree(l, `${e}.default`))) && (Object.hasOwn(a, n) && isRecord(a[n]) && isDeepStrictEqual(a[n].default, t.default) || Object.hasOwn(o, n) && isRecord(o[n]) && isDeepStrictEqual(o[n].default, t.default)))) r.default = t.default; } else delete r.default; } return [e, r]; })); if (t) { const t = new Map([...g].map(([e, t]) => [t, e])); const resolveExplicitLegacyIdCandidate = (e) => { if (!c) return; const t = c[e]; if (!isRecord(t)) return; const n = resolveExplicitLegacyEntryId(t, e); return n === void 0 ? void 0 : normalizeAgentId(n); }; const resolveExplicitLegacyId = (e) => { const t = resolveExplicitLegacyIdCandidate(e); if (!t || !c) throw new Error("Config write cannot safely resolve an explicitly replaced agent list slot for unset."); for (const [n] of c.entries()) { if (n === e) continue; const r = resolveExplicitLegacyIdCandidate(n); if (!r) throw new Error("Config write cannot safely resolve every explicit agent id across an indexed list unset."); if (r === t) throw new Error("Config write cannot safely resolve duplicate agent ids across an indexed list unset."); } return t; }; for (const n of e.unsetPaths ?? []) { if (n[0] !== "agents" || n[1] !== "list") continue; if (n.length === 2) { C = void 0; break; } if (n.length === 4 && n[3] === "id") throw new Error("Config write cannot unset an agent id; delete the complete roster entry instead."); const e = parseConfigPathArrayIndex(n[2] ?? ""); const i = e !== void 0 && p.has(e) && e !== void 0 ? resolveExplicitLegacyId(e) : void 0; const a = i !== void 0 ? i : e === void 0 ? void 0 : r.get(e); if (typeof a !== "string") continue; const o = i !== void 0 ? a : t.get(a) ?? a; C = deletePathValue(C, [o, ...n.slice(3)]); } } const w = deletePathValue(e.valueSource, ["agents", "list"]); return C === void 0 ? deletePathValue(w, ["agents", "entries"]) : setPathValue(w, ["agents", "entries"], C, true); } function restoreAuthoredAgentRoster(e, t) { const n = readAgentRosterProperty(t); let r = deletePathValue(e, ["agents", n?.kind === "entries" ? "list" : "entries"]); if (n) return setPathValue(r, ["agents", n.kind], n.value, true); r = deletePathValue(r, ["agents", "list"]); return !hasPathValue(t, ["agents"]) && isDeepStrictEqual(getPathValue(r, ["agents"]), {}) ? deletePathValue(r, ["agents"]) : r; } function projectAuthoredAgentRosterForWrite(e) { const t = readLegacyAgentList(e.rootAuthoredConfig); if (!t) return e.rootAuthoredConfig; const n = readLegacyAgentList(e.sourceConfigBeforeMigrations); if (collectIncludeOwnedPaths(t).length > 0 && !parseLegacyAgentRoster(n ?? t)) throw new Error("Config write cannot safely match $include-owned legacy agent entries; repair their ids in the authored config first."); const r = new Map(projectLegacyAgentRosterEntries(n ?? t).entries.map(({ sourceIndex: e, id: t }) => [e, t])); const i = indexAgentRosterForWrite(e.rootAuthoredConfig, r); return setPathValue(deletePathValue(deletePathValue(e.rootAuthoredConfig, ["agents", "list"]), ["agents", "entries"]), ["agents", "entries"], i, true); } function projectConfigWriteSource(e) { const t = e.inputBasis ?? { kind: "runtime", config: e.runtimeConfig }; if (t.kind === "source") return structuredClone(e.nextConfig); const n = createMergePatch(t.config, e.nextConfig); const r = normalizeTouchedAgentModelMapEntries({ projectedSource: e.sourceConfig, patch: n, touchedPaths: [...e.explicitSetPaths ?? [], ...e.unsetPaths ?? []], explicitSetValueSource: e.explicitSetValueSource ?? e.nextConfig }); return projectRuntimeChangesOntoSource(r, t.config, e.nextConfig); } function resolvePersistCandidateForWrite(e) { const t = e.inputBasis ?? { kind: "runtime", config: e.runtimeConfig }; const n = e.rootAuthoredConfig ?? e.sourceConfig; const r = shouldPersistCanonicalAgentRoster(e); const i = r && configIncludeOwnsAgentRosterValues({ parsed: n, sourceConfigBeforeMigrations: e.sourceConfigBeforeMigrations ?? e.sourceConfig, includeContributesRoster: e.agentRosterIncludeOwned }); const a = i && hasOnlyPreparedKeyedAgentEntryRosterIncludes(n, e.keyedAgentEntryIncludePaths); if (i && !a) throw createConfigIncludeOwnershipError({ ownedConfigPath: "agents" }); const o = r && !a; const s = o ? projectAuthoredAgentRosterForWrite({ rootAuthoredConfig: n, sourceConfigBeforeMigrations: e.sourceConfigBeforeMigrations }) : n; const c = o ? projectAuthoredAgentRosterForWrite({ rootAuthoredConfig: e.sourceConfigBeforeMigrations }) : e.sourceConfigBeforeMigrations; const l = o && !hasAgentRosterProperty(s) ? setPathValue(s, ["agents", "entries"], toAgentEntriesRecord(listAgentEntries(e.sourceConfig)), true) : s; const u = o ? e.explicitSetPaths?.filter((e) => !pathTargetsAgentRoster(e)) : a ? (e.explicitSetPaths ?? []).filter((e) => findOverlappingIncludeOwnedPath(l, [...e]) === void 0) : e.explicitSetPaths; const d = o ? canonicalizeAgentRosterForExplicitWrite({ ...e, valueSource: e.explicitSetValueSource ?? e.nextConfig, rootAuthoredConfig: n }) : e.explicitSetValueSource ?? e.nextConfig; let f = projectConfigWriteSource(e); if (o) { f = deletePathValue(f, ["agents", "entries"]); f = deletePathValue(f, ["agents", "list"]); const e = getPathValue(d, ["agents", "entries"]); if (e !== void 0) f = setPathValue(f, ["agents", "entries"], e, true); } const p = { ...e, runtimeConfig: t.config, rootAuthoredConfig: l, sourceConfigBeforeMigrations: c }; const m = preserveUntouchedIncludes({ ...p, persistedCandidate: f }); const h = injectExplicitlySetPaths({ ...p, valueSource: d, persistedCandidate: m, explicitSetPaths: u, preserveDescendantIncludes: o }); const g = canCanonicalizeAgentRoster(e.nextConfig) || e.preserveLegacyAgentRoster === true; const _ = r || !g ? h : restoreAuthoredAgentRoster(h, n); if (r) assertCanonicalAgentRosterRetainsEntries({ currentConfig: e.sourceConfig, canonicalConfig: _, allowedRemovals: e.allowedAgentRosterRemovals }); const v = preserveRootSchemaUri({ rootAuthoredConfig: n, nextConfig: e.nextConfig, persistedCandidate: _ }); return e.sourceConfigValid === false || t.kind === "source" ? v : preserveAuthoredAgentParams({ ...e, rootAuthoredConfig: n, persistedCandidate: v }); } function preserveRootSchemaUri(e) { if (isRecord(e.nextConfig) && Object.hasOwn(e.nextConfig, "$schema")) return e.persistedCandidate; const t = readStringField(asOptionalRecord(e.rootAuthoredConfig), "$schema"); if (t === void 0 || !isRecord(e.persistedCandidate)) return e.persistedCandidate; return { ...e.persistedCandidate, $schema: t }; } //#endregion export { resolvePersistCandidateForWrite as a, projectConfigWriteSource as i, prepareConfigWriteValues as n, projectAuthoredAgentRosterForWrite as r, injectExplicitlySetPaths as t };