openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
335 lines (334 loc) • 10.4 kB
JavaScript
import { n as formatConcreteConfigPath } from "./dot-path-BJ4tyWKJ.mjs";
import { A as withTimeout } from "./fs-safe-BbWvmdVn.mjs";
import { n as WizardCancelledError, r as WizardNavigationError } from "./prompts-CCXo2K24.mjs";
//#region src/flows/memory-setup.ts
const PROBE_TIMEOUT_MS = 15e4;
const CLOSE_TIMEOUT_MS = 1e3;
async function closeProvider(e) {
try {
await withTimeout(Promise.resolve().then(() => e.close?.()), CLOSE_TIMEOUT_MS);
} catch {}
}
/** Optional, non-indexing embedding setup. The caller owns persistence. */
async function runMemorySetupFlow(e, t, n = {}) {
await t.note("Embeddings add semantic memory search. Choose a cloud provider or a running local Ollama/LM Studio server. This check sends only synthetic text, does not index memory or download models, and may load an already-downloaded model. Stored OAuth access depends on the account and model. Skipping keeps your current settings.", "Memory search");
if (!await t.confirm({
message: "Set up memory embeddings?",
initialValue: false
})) return e;
let r;
let i;
try {
const [{ loadManifestContractSnapshot: t, listAvailableManifestContractValues: n }, { resolveConfiguredGenericEmbeddingProviderId: a }, { resolveMemorySearchProviderId: o }] = await Promise.all([
import("./manifest-contract-eligibility-D8Uu36ng.mjs"),
import("./embedding-provider-config-CpTid1Xu.mjs"),
import("./memory-search-DwpSCOOd.mjs")
]);
i = o(e.memory?.search?.provider);
const s = /* @__PURE__ */ new Set(["openai-compatible"]);
if (e.plugins?.enabled !== false) {
const r = t({ config: e });
for (const t of n({
snapshot: r,
contract: "embeddingProviders",
config: e
})) s.add(t);
}
s.delete("local");
s.delete("llama-cpp");
for (const t of Object.keys(e.models?.providers ?? {})) {
const n = a(t, e);
if (n && s.has(n)) s.add(t);
}
if (!e.models?.providers?.["openai-compatible"]?.baseUrl && !(e.memory?.search?.provider === "openai-compatible" && e.memory.search.remote?.baseUrl)) s.delete("openai-compatible");
r = [...s].toSorted((e, t) => e.localeCompare(t));
} catch {
await t.note("Embedding providers could not be listed. Check plugin configuration and try again.", "Memory setup unchanged");
return e;
}
if (r.length === 0) {
await t.note("No HTTP embedding providers are available. Check plugin configuration, or use the manual memory-search setup docs for managed local embeddings.", "Memory setup unchanged");
return e;
}
const a = e.memory?.search;
const o = await t.select({
message: "Embedding provider",
options: r.map((e) => ({
value: e,
label: e
})),
initialValue: r.includes(i) ? i : r[0]
});
let s;
try {
const { getEmbeddingProvider: t } = await import("./embedding-provider-runtime-Cjp4abO3.mjs");
s = t(o, e);
} catch {
await t.note("The selected embedding provider could not be loaded. Check plugin configuration and try again.", "Memory setup unchanged");
return e;
}
if (!s || s.transport === "local") {
await t.note("This provider is unavailable for this setup flow. Use the manual memory-search setup docs for managed local embeddings.", "Memory setup unchanged");
return e;
}
const { isSameMemorySearchProvider: c } = await import("./memory-search-DwpSCOOd.mjs");
const l = c(o, i);
const u = (l ? a?.model : void 0) || s.defaultModel || "";
const d = (await t.text({
message: "Embedding model ID",
initialValue: u || void 0,
placeholder: "Enter the model ID accepted by this provider",
validate: (e) => e.trim() ? void 0 : "Enter an embedding model ID."
})).trim();
if (!d) {
await t.note("An embedding model ID is required.", "Memory setup unchanged");
return e;
}
const f = l ? { ...a?.remote } : a?.remote?.batch ? { batch: a.remote.batch } : {};
const p = await t.select({
message: "Embedding credential",
options: [
{
value: "existing",
label: "Use existing credentials / no key",
hint: "Saved key, provider auth, environment, or unauthenticated local server"
},
...n.secretInputMode === "ref" ? [] : [{
value: "key",
label: "Enter API key",
hint: "Masked input"
}],
{
value: "ref",
label: "Use SecretRef",
hint: "Store a reference, not the key"
}
],
initialValue: n.secretInputMode === "ref" && !(l && f.apiKey) ? "ref" : "existing"
});
let m;
let h;
if (p === "key" && n.secretInputMode !== "ref") {
const e = (await t.text({
message: "Embedding API key",
sensitive: true,
validate: (e) => e.trim() ? void 0 : "Enter an API key."
})).trim();
m = e;
h = e;
} else if (p === "ref") try {
const { promptSecretRefForSetup: n } = await import("./provider-auth-ref-gTo--D36.mjs");
const r = await n({
provider: s.authProviderId ?? o,
config: e,
prompter: t
});
m = r.ref;
h = r.resolvedValue;
} catch (n) {
if (n instanceof WizardCancelledError || n instanceof WizardNavigationError) throw n;
await t.note("The secret reference could not be resolved. Check its source and try again.", "Memory setup unchanged");
return e;
}
const g = { ...f };
if (p !== "existing") delete g.apiKey;
if (m !== void 0) g.apiKey = m;
let _ = { ...g };
const v = {
...a,
provider: o,
model: d,
enabled: true,
remote: g
};
let y = {
...e,
memory: {
...e.memory,
search: v
}
};
try {
const { resolveMemorySearchConfig: t } = await import("./memory-search-DwpSCOOd.mjs");
if (!l && e.agents?.entries) {
const n = { ...e.agents.entries };
for (const [r, i] of Object.entries(n)) {
const o = i.memory?.search;
const s = [
o?.remote?.baseUrl,
o?.remote?.apiKey,
o?.remote?.headers
].some((e) => e !== void 0);
const c = o?.provider !== void 0 && [
a?.remote?.baseUrl,
a?.remote?.apiKey,
a?.remote?.headers
].some((e) => e !== void 0);
if (!o || !s && !c) continue;
const l = t({
...e,
agents: {
...e.agents,
entries: {
...n,
[r]: {
...i,
memory: {
...i.memory,
search: {
...o,
enabled: true
}
}
}
}
}
}, r);
if (!l) continue;
const { baseUrl: u, apiKey: d, headers: f } = l.remote ?? {};
n[r] = {
...i,
memory: {
...i.memory,
search: {
...o,
provider: l.provider,
model: l.model,
remote: {
...o.remote,
baseUrl: u ?? "",
apiKey: d ?? "",
headers: f ?? {}
}
}
}
};
}
y = {
...y,
agents: {
...e.agents,
entries: n
}
};
}
t({
...y,
agents: void 0
}, "main");
for (const n of Object.keys(e.agents?.entries ?? {})) t(y, n);
} catch {
await t.note("The selected provider, model, or fallback is not compatible with the retained memory settings. Check the memory search configuration and try again.", "Memory setup unchanged");
return e;
}
let b;
try {
const { resolveSetupSecretInputString: t } = await import("./setup.secret-input-Dx-R9RWa.mjs");
if (_.apiKey !== void 0) h = h ?? await t({
config: e,
value: _.apiKey,
path: "memory.search.remote.apiKey"
});
_ = {
..._,
...h ? { apiKey: h } : {}
};
b = {
...e,
memory: {
...e.memory,
search: {
...v,
remote: _
}
}
};
const n = e.models?.providers?.[o] ? o : s.authProviderId ?? o;
const r = b.models?.providers?.[n];
if (r) {
const [{ resolveCommandConfigWithSecrets: e }, { getMemoryEmbeddingCommandSecretTargetIds: t }] = await Promise.all([import("./command-config-resolution-BNTKgU_O.mjs"), import("./command-secret-targets-CYdGJLhL.mjs")]);
const i = /* @__PURE__ */ new Set([formatConcreteConfigPath([
"models",
"providers",
n,
"apiKey"
]), ...Object.keys(r.headers ?? {}).map((e) => formatConcreteConfigPath([
"models",
"providers",
n,
"headers",
e
]))]);
b = (await e({
config: b,
commandName: "memory embedding setup probe",
targetIds: t(),
allowedPaths: i,
autoEnable: false
})).effectiveConfig;
}
} catch (n) {
if (n instanceof WizardCancelledError || n instanceof WizardNavigationError) throw n;
await t.note("An existing embedding credential could not be resolved. Check its source and try again.", "Memory setup unchanged");
return e;
}
const x = t.progress("Checking embedding readiness (local model loading can take two minutes)…");
const S = s;
const C = b;
const w = n.agentDir;
const T = _;
let E;
const D = new AbortController();
let O = null;
const check = async () => {
const e = {
config: C,
agentDir: w,
provider: o,
model: d,
remote: T,
inputType: v.inputType,
queryInputType: v.queryInputType,
documentInputType: v.documentInputType,
dimensions: v.outputDimensionality
};
const t = await S.create({
...e,
model: S.normalizeModel?.(e) ?? e.model
});
if (D.signal.aborted) {
if (t.provider) await closeProvider(t.provider);
return false;
}
O = t.provider;
if (!O) return false;
const n = await O.embed("ping", {
signal: D.signal,
inputType: "query"
});
return Array.isArray(n) && n.length > 0 && n.every(Number.isFinite);
};
try {
E = await withTimeout(check(), PROBE_TIMEOUT_MS, { createError: () => {
D.abort();
return /* @__PURE__ */ new Error("embedding probe timed out");
} });
} catch {
E = false;
} finally {
if (O) await closeProvider(O);
}
x.stop(E ? "Embedding check passed" : "Embedding check failed");
if (!E) {
await t.note("The selected embedding provider did not complete a small readiness check. Check its model, endpoint, and credentials, then try again.", "Memory setup unchanged");
return e;
}
await t.note("Embedding readiness passed in this CLI session. The Gateway daemon must also be able to resolve any environment-based SecretRef. This changes shared memory defaults. On a provider change, agents with remote overrides retain their previous embedding destination and model. If the provider or model changes, rebuild the index explicitly with `openclaw memory index --force` before vector search resumes.", "Ready to save");
if (!await t.confirm({
message: "Save and enable these shared memory embedding defaults?",
initialValue: false
})) return e;
return y;
}
//#endregion
export { runMemorySetupFlow };