openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
232 lines (231 loc) • 12.7 kB
JavaScript
import { c as isRecord } from "../record-coerce-DItp3I4t.js";
import { r as normalizeProviderId } from "../provider-id-DMd-TDFp.js";
import { l as normalizePluginsConfig } from "../config-state-BkU1frVq.js";
import { u as restorePluginMetadataSnapshot } from "../plugin-metadata-snapshot-w-4EjxI4.js";
import { d as restoreConfigResolutionFacts, n as copyConfigResolutionFacts } from "../resolution-facts-Dks1tbik.js";
import { E as setRuntimeConfigSnapshot } from "../runtime-snapshot-BaQikjTR.js";
import { n as isManifestPluginAvailableForControlPlane } from "../manifest-contract-eligibility-BbV7X6pV.js";
import { _ as mergeRuntimeExternalProfileReferences } from "../persisted-B_qhhBlh.js";
import { a as listExternalCliSyncProviderIds, n as overlayExternalAuthProfiles } from "../external-auth-D5zyqyNH.js";
import { i as listRuntimePluginIdsFromRegistry } from "../active-runtime-registry-C5SJbS7x.js";
import { t as manifestPluginResolvesRuntimeModelCatalogAugment } from "../providers-DCe4UB6a.js";
import { n as withPluginRuntimeGenerationScope } from "../generation-scope-Cf83d_iq.js";
import { b as replaceRuntimeAuthProfileStoreSnapshots } from "../runtime-snapshots-CHAErv1O.js";
import { h as preserveResolvedSecretBackedCredentials, m as loadAuthProfileStoreWithoutExternalProfiles } from "../store-F1B2duCT.js";
import { V as restorePreparedSyntheticAuthFacts } from "../provider-runtime-BRJDPNgk.js";
import { i as resolveRuntimeSyntheticAuthProviderRefs } from "../synthetic-auth.runtime-C_hXZLB9.js";
import { h as resolveUsableAgentCredentialModes, m as resolveAgentCredentialMapFromStore, p as resolveAmbientAgentCredentialsForDiscovery } from "../prepared-model-runtime.plugin-generation-t_16307i.js";
import { xt as AuthStorage } from "../sessions-BdNAJTEP.js";
import { r as serveWorkerTasks } from "../worker-task-pool-BNbf5LmH.js";
import { r as planRuntimePluginDiscovery } from "../provider-discovery-BPqo7Vo1.js";
import { i as resolveImplicitProviderDiscoveryScope } from "../models-config-FHEukKjA.js";
import { c as scopeSyntheticAuthProviderRefs } from "../prepared-model-runtime.facts-vxXJKbiM.js";
import { t as prepareOwnedPluginLoadContext } from "../prepared-model-runtime.plugin-context-Cfpk1nYL.js";
import { t as loadAgentRuntimePluginRegistryHandle } from "../runtime-plugins-BDPJ7y4t.js";
import { n as fingerprintPreparedModelCatalogGeneration, r as fingerprintPreparedModelWorkerRequest } from "../prepared-model-catalog-worker-CF5u1MTG.js";
import { parentPort, workerData } from "node:worker_threads";
//#region src/agents/prepared-model-catalog.worker.ts
/** Worker-thread entrypoint for complete model-catalog discovery. */
function refreshAuthStore(params) {
const durable = preserveResolvedSecretBackedCredentials({
next: loadAuthProfileStoreWithoutExternalProfiles(params.agentDir, {
allowKeychainPrompt: false,
...params.inheritedAuthDir ? { inheritedAuthDir: params.inheritedAuthDir } : {}
}),
existing: params.authStore
});
const persistedProfileIds = new Set(params.authStore.runtimePersistedProfileIds ?? []);
const externalProfileIds = new Set(params.authStore.runtimeExternalProfileIds ?? []);
for (const [profileId, credential] of Object.entries(params.authStore.profiles)) if (!persistedProfileIds.has(profileId) && !externalProfileIds.has(profileId) && durable.profiles[profileId] === void 0) durable.profiles[profileId] = credential;
const prepared = mergeRuntimeExternalProfileReferences({
next: durable,
existing: params.authStore
});
return withPluginRuntimeGenerationScope({
metadataSnapshot: params.pluginGeneration.pluginMetadataSnapshot,
pluginRegistry: params.pluginGeneration.pluginRegistry
}, () => overlayExternalAuthProfiles(prepared, {
config: params.config,
env: params.env,
...params.providerIds ? { externalCliProviderIds: params.providerIds } : {},
...params.profileIds ? { externalCliProfileIds: params.profileIds } : {},
allowKeychainPrompt: false
}));
}
async function prepareWorkerGeneration(value) {
restoreConfigResolutionFacts(value.input.config, value.configResolutionFacts);
if (value.sourceConfigResolutionFacts === value.configResolutionFacts) copyConfigResolutionFacts(value.input.config, value.sourceConfigForSecrets);
else restoreConfigResolutionFacts(value.sourceConfigForSecrets, value.sourceConfigResolutionFacts);
setRuntimeConfigSnapshot(value.input.config, value.sourceConfigForSecrets);
const { prepareWorkspaceBuildGroup } = await import("../prepared-model-runtime.facts-BHzCkfjv.js");
const metadata = restorePluginMetadataSnapshot(value.pluginMetadataSnapshot);
const normalizedConfig = normalizePluginsConfig(value.input.config.plugins);
const basePluginIds = metadata.plugins.filter((plugin) => (manifestPluginResolvesRuntimeModelCatalogAugment(plugin) || plugin.cliBackends.length > 0 || Boolean(plugin.setup?.cliBackends?.length) || Boolean(plugin.activation?.onAgentHarnesses?.length)) && isManifestPluginAvailableForControlPlane({
snapshot: metadata,
plugin,
config: value.input.config,
normalizedConfig,
...value.input.env ? { env: value.input.env } : {}
})).map((plugin) => plugin.id).toSorted((left, right) => left.localeCompare(right));
const prepared = await prepareWorkspaceBuildGroup([value.input], "live", {
preferBuiltPluginArtifacts: value.preferBuiltPluginArtifacts,
basePluginIds
}, void 0, void 0, metadata);
const agentFacts = prepared.agentFacts[0];
if (!agentFacts) throw new Error("prepared model catalog worker produced no agent facts");
const reconstructedFingerprint = fingerprintPreparedModelCatalogGeneration({
input: value.input,
sourceConfigForSecrets: value.sourceConfigForSecrets,
configResolutionFacts: value.configResolutionFacts,
sourceConfigResolutionFacts: value.sourceConfigResolutionFacts,
authStore: value.authStore,
providerIds: value.providerIds,
preferBuiltPluginArtifacts: prepared.pluginGeneration.preferBuiltPluginArtifacts,
pluginMetadataSnapshot: prepared.pluginGeneration.pluginMetadataSnapshot
});
return {
agentFacts,
pluginGeneration: prepared.pluginGeneration,
reconstructedFingerprint
};
}
async function runPreparedModelCatalogWorkerRequest(value, request, prepareGeneration = () => prepareWorkerGeneration(value)) {
try {
restorePreparedSyntheticAuthFacts(value.input.config, request.syntheticAuth, {
env: value.input.env,
workspaceDir: value.input.workspaceDir
});
restorePreparedSyntheticAuthFacts(value.input.config, request.syntheticAuth, { workspaceDir: value.input.workspaceDir });
const generationFingerprint = fingerprintPreparedModelWorkerRequest(value, request);
const prepared = await prepareGeneration();
if (prepared.reconstructedFingerprint !== value.generationFingerprint) return {
status: "generation-mismatch",
generationFingerprint: value.generationFingerprint,
reconstructedFingerprint: prepared.reconstructedFingerprint
};
const pluginGenerationScope = {
metadataSnapshot: prepared.pluginGeneration.pluginMetadataSnapshot,
pluginRegistry: prepared.pluginGeneration.pluginRegistry
};
const resolveSyntheticCredentials = (providerIds) => withPluginRuntimeGenerationScope(pluginGenerationScope, () => resolveAmbientAgentCredentialsForDiscovery({
config: value.input.config,
env: value.input.env,
authoritativeSyntheticAuthProviderRefs: prepared.pluginGeneration.pluginMetadataSnapshot.owners.cliBackends.keys(),
syntheticAuthProviderRefs: scopeSyntheticAuthProviderRefs(resolveRuntimeSyntheticAuthProviderRefs(), providerIds),
...value.input.workspaceDir ? { workspaceDir: value.input.workspaceDir } : {}
}));
if (request.kind === "auth-refresh") {
const authStore = refreshAuthStore({
agentDir: value.input.agentDir,
inheritedAuthDir: value.input.inheritedAuthDir,
authStore: value.authStore,
config: value.input.config,
env: value.input.env ?? process.env,
...request.profileIds ? { profileIds: request.profileIds } : {},
providerIds: request.providerIds,
pluginGeneration: prepared.pluginGeneration
});
return {
status: "ok",
kind: "auth-refresh",
generationFingerprint,
authStore,
authModes: resolveUsableAgentCredentialModes({
...resolveSyntheticCredentials(request.providerIds),
...resolveAgentCredentialMapFromStore(authStore, { config: value.input.config })
})
};
}
const { prepareAgentCatalogSource } = await import("../prepared-model-runtime.facts-BHzCkfjv.js");
const { prepareFullCatalogFacts } = await import("../prepared-model-runtime.full-catalog-DCNJNqyJ.js");
const authStore = refreshAuthStore({
agentDir: value.input.agentDir,
inheritedAuthDir: value.input.inheritedAuthDir,
authStore: value.authStore,
config: value.input.config,
env: value.input.env ?? process.env,
providerIds: listExternalCliSyncProviderIds(),
pluginGeneration: prepared.pluginGeneration
});
replaceRuntimeAuthProfileStoreSnapshots([{
agentDir: value.input.agentDir,
store: authStore
}]);
const ambientCredentials = resolveSyntheticCredentials(value.providerIds);
const startupProviderIds = new Set(value.providerIds.map(normalizeProviderId));
const credentials = {
...ambientCredentials,
...resolveAgentCredentialMapFromStore(authStore, { config: value.input.config })
};
const exactAgentFacts = {
...prepared.agentFacts,
authStore,
templateAuthStorage: AuthStorage.inMemory(credentials),
credentials,
providerIds: [.../* @__PURE__ */ new Set([...value.providerIds, ...Object.keys(credentials)])].toSorted((left, right) => left.localeCompare(right))
};
const { pluginMetadataSnapshot, pluginRegistry } = prepared.pluginGeneration;
const discoveryPluginIds = [...resolveImplicitProviderDiscoveryScope({
config: value.input.config,
env: value.input.env,
workspaceDir: value.input.workspaceDir,
pluginMetadataSnapshot,
providerDiscoveryProviderIds: exactAgentFacts.providerIds
})?.keys() ?? []];
const discoveryPlan = await withPluginRuntimeGenerationScope(pluginGenerationScope, () => planRuntimePluginDiscovery({
config: value.input.config,
env: value.input.env,
workspaceDir: value.input.workspaceDir,
pluginMetadataSnapshot,
onlyPluginIds: discoveryPluginIds
}));
let catalogGeneration = prepared.pluginGeneration;
if (discoveryPlan.kind === "runtime") {
const catalogRegistry = loadAgentRuntimePluginRegistryHandle({
...value.input,
metadataSnapshot: pluginMetadataSnapshot,
preferBuiltPluginArtifacts: value.preferBuiltPluginArtifacts,
reusableRegistry: pluginRegistry,
basePluginIds: [...pluginRegistry ? listRuntimePluginIdsFromRegistry(pluginRegistry) : [], ...discoveryPlan.pluginIds ?? discoveryPluginIds]
});
prepareOwnedPluginLoadContext(value.input, value.input.env ?? process.env, catalogRegistry, pluginMetadataSnapshot, value.preferBuiltPluginArtifacts);
pluginGenerationScope.pluginRegistry = catalogRegistry;
catalogGeneration = Object.freeze({
...catalogGeneration,
pluginRegistry: catalogRegistry
});
}
const source = await prepareAgentCatalogSource(exactAgentFacts, catalogGeneration, "live", false, { authStore });
const facts = await prepareFullCatalogFacts(exactAgentFacts, catalogGeneration, "live", source);
const catalogCredentials = resolveSyntheticCredentials([...facts.modelCatalog.entries, ...facts.modelCatalog.routeVariants].map((entry) => entry.provider).filter((provider) => !startupProviderIds.has(normalizeProviderId(provider))));
return {
status: "ok",
kind: "catalog",
generationFingerprint,
snapshot: facts.modelCatalog,
authStore,
authModes: resolveUsableAgentCredentialModes({
...catalogCredentials,
...credentials
})
};
} catch (error) {
return {
status: "failed",
error: error instanceof Error ? error.message : String(error)
};
}
}
function isWorkerRequest(value) {
return isRecord(value) && Array.isArray(value.syntheticAuth) && (value.kind === "catalog" || value.kind === "auth-refresh" && Array.isArray(value.providerIds) && value.providerIds.every((providerId) => typeof providerId === "string") && (value.profileIds === void 0 || Array.isArray(value.profileIds) && value.profileIds.every((profileId) => typeof profileId === "string")));
}
if (parentPort) {
const value = workerData;
let preparedGeneration;
serveWorkerTasks((request) => {
if (!isWorkerRequest(request)) throw new Error("invalid prepared model catalog worker request");
return runPreparedModelCatalogWorkerRequest(value, request, () => preparedGeneration ??= prepareWorkerGeneration(value));
});
}
//#endregion
export { runPreparedModelCatalogWorkerRequest };