openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
426 lines (425 loc) • 16.2 kB
JavaScript
import { c as resolveUserPath } from "./home-dir-EKmgmdPG.mjs";
import "./utils-C8YECn2Q.mjs";
import { j as parseAgentSessionKey } from "./session-key-CqAyZeVk.mjs";
import { C as resolveSessionAgentIds, a as resolveAgentDir } from "./agent-scope-config-DmXgFGKP.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import "./agent-scope-BwB8YH6y.mjs";
import { n as withPluginRuntimeGenerationScope } from "./generation-scope-Cq7RLFex.mjs";
import { a as normalizeOptionalAgentRuntimeId, r as isDefaultAgentRuntimeId } from "./agent-runtime-id-D8s1CaYB.mjs";
import { r as isOpenAIProvider } from "./openai-routing-Dakz1nVk.mjs";
import { f as prepareSystemAgentRunAdmission } from "./admitted-run-context-D3Jvk_f_.mjs";
import { t as resolveAgentHarnessPolicy } from "./policy-DzaOuofI.mjs";
import { a as resolveAgentHarnessOwnerPluginId, s as resolveCodexAgentHarnessNativeCompaction } from "./registry-ubpieJjd.mjs";
import { r as projectPreparedModelProvider } from "./support-LWqLDjUq.mjs";
import { a as isCliRuntimeProvider, i as isCliRuntimeAliasForProvider } from "./model-runtime-aliases-DZy9Ea2c.mjs";
import { g as attachProviderAuthAuthority, h as assertProviderAuthAuthority, v as getProviderAuthAuthority } from "./provider-request-config-CCij-nof.mjs";
import { c as ensureAuthProfileStoreWithoutExternalProfilesAsync, i as ensureAuthProfileStoreAsync } from "./store-runtime-dW0pXLJI.mjs";
import { i as unwrapSecretSentinelsForProviderEgress, r as unwrapModelHeaderSentinelsForProviderEgress } from "./provider-secret-egress-DZ6iOD2F.mjs";
import { t as runWithAsyncWorkResources } from "./async-work-resources-BF09U4aO.mjs";
import { n as applySecretRefHeaderSentinels } from "./model-auth-CEsyk_Yg.mjs";
import { n as resolveModelAsync } from "./model-BmrpLWB9.mjs";
import { r as prepareAgentRuntimeAuth, t as agentRuntimeAuthPlanMatchesTarget } from "./prepare-auth-Ck7RPVAG.mjs";
import { t as materializePreparedRuntimeModel } from "./materialize-model-DK894Ocx.mjs";
import { n as resolvePreparedRuntimeModelAuth, t as resolvePreparedRuntimeAuthAttempts } from "./resolve-auth-Cds1OOn0.mjs";
import { r as prepareAgentHarnessNativeToolPolicyRestricted } from "./execution-environment-BrTopau0.mjs";
import { t as assertCompactionSource } from "./host-source-authority-BR6Oinwf.mjs";
import { i as selectAgentHarnessForPreparedModelProviders, r as selectAgentHarness } from "./selection-Dmb46Mcc.mjs";
import { randomUUID } from "node:crypto";
//#region src/agents/harness/compaction-recovery.ts
function isRecoverableNativeHarnessBindingReason(e) {
if (typeof e !== "string") return false;
const t = e.trim().toLowerCase();
return t === "missing_thread_binding" || t === "stale_thread_binding" || t.includes("thread not found") || t.includes("no thread binding");
}
/** Native binding failures permit context-engine fallback after clearing the stale binding. */
function isRecoverableNativeHarnessBindingFailure(e) {
return e?.ok === false && (isRecoverableNativeHarnessBindingReason(e.failure?.reason) || isRecoverableNativeHarnessBindingReason(e.reason));
}
//#endregion
//#region src/agents/harness/compaction.ts
const log = createSubsystemLogger("agents/harness-compaction");
function runtimePlanRequiresHostApiKey(e) {
return e?.modelRoute?.authRequirement === "api-key";
}
function unsupportedHarnessCompaction(e) {
return e === "openclaw" ? void 0 : {
ok: false,
compacted: false,
reason: `Agent harness "${e}" does not support compaction.`,
failure: { reason: "unsupported_harness_compaction" }
};
}
function resolveHarnessCompactIdentity(e) {
const t = resolveSessionAgentIds({
sessionKey: e.sessionKey,
config: e.config,
agentId: e.agentId
});
return {
agentDir: e.agentDir ?? resolveAgentDir(e.config ?? {}, t.sessionAgentId),
agentId: e.agentId ?? t.sessionAgentId
};
}
function stripHarnessOwnedAuthInputs(e) {
const t = { ...e };
delete t.resolvedApiKey;
delete t.runtimeModel;
return t;
}
async function resolveHarnessCompactApiKey(e) {
const { agentDir: t, compactParams: n, initialHarness: r } = e;
if (!n.provider?.trim() || !n.model?.trim()) {
const e = n.resolvedApiKey?.trim();
return e ? {
harness: r,
apiKey: e
} : { harness: r };
}
const i = n.provider;
const a = n.model;
const o = n.runtimeAuthPlan ?? n.runtimePlan?.auth;
const s = o && agentRuntimeAuthPlanMatchesTarget(o, {
provider: i,
modelId: a
}) ? o : void 0;
const c = resolveUserPath(n.workspaceDir);
const l = e.preparedModelRuntime.createStores();
const u = n.runtimeModel;
const fallbackResolution = (e, t, r) => {
const o = n.resolvedApiKey?.trim() || void 0;
if (e.authBootstrap === "harness" && !r && o) throw new Error(`Unable to prepare a route-locked native compaction attempt for ${i}/${a}; refusing harness-owned ambient auth.`);
return {
harness: e,
...o ? { apiKey: o } : {},
...t ? { runtimeModel: t } : {},
...r ? { runtimeAuthPlan: r } : {}
};
};
const selectPreparedHarness = (t, r) => selectAgentHarnessForPreparedModelProviders({
provider: i,
modelId: a,
modelProviders: t.map((e) => projectPreparedModelProvider({
model: r,
plan: e.plan,
attemptKind: e.kind
})),
config: n.config,
agentId: parseAgentSessionKey(e.sessionKey) ? void 0 : e.agentId,
sessionKey: e.sessionKey,
agentHarnessId: e.pinnedHarnessId
});
if (s) {
const e = selectPreparedHarness([{
kind: "implicit",
plan: s
}], u);
if ((e.authBootstrap === "harness" || s.harnessAuthProvider) && !runtimePlanRequiresHostApiKey(s)) return fallbackResolution(e, u, s);
}
const resolvePreparedModel = ({ config: r, authProfileId: o, authProfileMode: s }) => resolveModelAsync(i, a, t, r, {
abortSignal: n.abortSignal,
...l,
preparedModelRuntime: e.preparedModelRuntime,
authProfileId: o,
authProfileMode: s,
skipAgentDiscovery: true,
allowBundledStaticCatalogFallback: true,
workspaceDir: c
});
let d = u;
if (!d) try {
d = (await resolveModelAsync(i, a, t, n.config, {
abortSignal: n.abortSignal,
...l,
preparedModelRuntime: e.preparedModelRuntime,
authProfileId: s?.forwardedAuthProfileId ?? n.authProfileId?.trim() ?? void 0,
workspaceDir: c
})).model;
} catch (e) {
n.abortSignal?.throwIfAborted();
log.warn(`native compaction model resolution failed for ${i}/${a}: ${e instanceof Error ? e.message : String(e)}`);
return fallbackResolution(r);
}
if (!d) return fallbackResolution(r);
const f = isOpenAIProvider(i) ? await ensureAuthProfileStoreAsync(t, {
profileId: n.authProfileId ?? s?.forwardedAuthProfileId,
externalCliProviderIds: ["openai"],
allowKeychainPrompt: false
}) : await ensureAuthProfileStoreWithoutExternalProfilesAsync(t, {
profileId: n.authProfileId ?? s?.forwardedAuthProfileId,
allowKeychainPrompt: false
});
const prepareRuntimeAuth = (r) => prepareAgentRuntimeAuth({
provider: i,
modelId: a,
modelApi: d.api,
modelBaseUrl: d.baseUrl,
config: n.config,
agentId: e.agentId,
env: process.env,
agentDir: t,
workspaceDir: c,
authProfileStore: f,
sessionAuthProfileId: n.authProfileId,
sessionAuthProfileSource: n.authProfileIdSource,
harnessId: r.id,
harnessRuntime: r.id,
harnessAuthBootstrap: r.authBootstrap
});
let p;
if (s) p = {
plan: s,
attempts: [{
kind: "implicit",
plan: s
}]
};
else try {
p = prepareRuntimeAuth(r);
} catch (e) {
log.warn(`native compaction auth preparation failed for ${i}/${a}: ${e instanceof Error ? e.message : String(e)}`);
return fallbackResolution(r, d);
}
let m = e.pinnedHarnessId ? r : selectPreparedHarness(p.attempts, d);
if (!e.pinnedHarnessId && !s && m.id !== r.id) {
try {
p = prepareRuntimeAuth(m);
} catch (e) {
log.warn(`native compaction auth preparation failed for ${i}/${a}: ${e instanceof Error ? e.message : String(e)}`);
return fallbackResolution(m, d);
}
const e = selectPreparedHarness(p.attempts, d);
if (e.id !== m.id) throw new Error(`Prepared native compaction auth routes did not converge on one agent harness for ${i}/${a}.`);
m = e;
}
const materializeModel = async (t) => {
const r = await materializePreparedRuntimeModel({
plan: t.plan,
provider: i,
modelId: a,
config: n.config,
workspaceDir: c,
metadataSnapshot: e.preparedModelRuntime.metadataSnapshot,
model: t.model,
forceResolve: t.forceResolve,
rejectMismatchedModel: true,
resolveModel: resolvePreparedModel
});
if (!r) throw new Error(`Unable to materialize ${i}/${a} for native compaction.`);
return applySecretRefHeaderSentinels(r, n.config);
};
let h;
try {
h = await resolvePreparedRuntimeAuthAttempts({
attempts: p.attempts,
store: f,
modelId: a,
model: d,
materializeModel,
resolveAuth: async ({ attempt: e, model: r }) => {
if ((m.authBootstrap === "harness" || e.plan.harnessAuthProvider) && !runtimePlanRequiresHostApiKey(e.plan)) return {
plan: e.plan,
auth: {}
};
const i = e.plan.forwardedAuthProfileSource === "auto" && Boolean(e.plan.forwardedAuthProfileId || e.plan.forwardedAuthProfileCandidateIds?.length) ? void 0 : n.resolvedApiKey?.trim();
if (i) return {
plan: e.plan,
auth: attachProviderAuthAuthority({ apiKey: i }, getProviderAuthAuthority(u))
};
const a = await resolvePreparedRuntimeModelAuth({
plan: e.plan,
model: r,
cfg: n.config,
store: f,
agentDir: t,
workspaceDir: c,
...e.allowAuthProfileFallback !== void 0 ? { allowAuthProfileFallback: e.allowAuthProfileFallback } : {},
secretSentinels: true
});
return {
plan: a.plan,
auth: {
...a.auth,
apiKey: a.auth.apiKey?.trim() || void 0
}
};
},
errorMessage: `Prepared native compaction auth attempts could not be resolved for ${i}/${a}.`
});
} catch (e) {
n.abortSignal?.throwIfAborted();
log.warn(`native compaction prepared auth resolution failed for ${i}/${a}: ${e instanceof Error ? e.message : String(e)}`);
return fallbackResolution(m, d, p.plan);
}
return {
harness: m,
apiKey: h.auth.apiKey,
runtimeModel: attachProviderAuthAuthority(h.model, getProviderAuthAuthority(h.auth)),
runtimeAuthPlan: h.plan
};
}
/** Runs harness-provided compaction when the selected runtime supports it. */
async function maybeCompactAgentHarnessSession(e, t) {
return await withPluginRuntimeGenerationScope(t.preparedModelRuntime, () => maybeCompactAgentHarnessSessionInGeneration(e, t));
}
async function maybeCompactAgentHarnessSessionInGeneration(e, t) {
const n = normalizeOptionalAgentRuntimeId(e.agentHarnessId);
const r = n && !isDefaultAgentRuntimeId(n) ? n : void 0;
if (!r && e.provider && isCliRuntimeProvider(e.provider, { config: e.config })) return;
const i = e.sandboxSessionKey ?? e.sessionKey;
const a = e.sandboxAgentId ?? (e.sandboxSessionKey && parseAgentSessionKey(e.sandboxSessionKey) ? void 0 : e.agentId);
const o = e.runtimeAuthPlan ?? e.runtimePlan?.auth;
const s = o?.modelRoute;
if (o && s && (!e.provider || !e.model || !agentRuntimeAuthPlanMatchesTarget(o, {
provider: e.provider,
modelId: e.model ?? ""
}))) throw new Error(`Prepared runtime auth route ${s.provider}/${s.modelId} does not match the compaction target ${e.provider ?? "unknown"}/${e.model ?? "unknown"}.`);
const c = resolveAgentHarnessPolicy({
provider: e.provider,
modelId: e.model,
config: e.config,
agentId: a,
sessionKey: i
}).runtime;
if (isCliRuntimeAliasForProvider({
runtime: r ?? c,
provider: e.provider,
cfg: e.config
})) return;
const l = {
provider: e.provider ?? "",
modelId: e.model,
config: e.config,
agentId: a,
sessionKey: i,
agentHarnessId: r
};
let u = o ? selectAgentHarnessForPreparedModelProviders({
...l,
modelProviders: [projectPreparedModelProvider({
model: e.runtimeModel,
plan: o
})]
}) : selectAgentHarness(l);
const d = resolveCodexAgentHarnessNativeCompaction(u);
if (t.nativeCompactionRequest === "after_context_engine" && !d) return;
if (!t.nativeCompactionRequest && !u.compact) return unsupportedHarnessCompaction(u.id);
const f = resolveHarnessCompactIdentity(e);
const p = t.sourceAuthority;
assertCompactionSource(p);
const m = [e.abortSignal, p.operatorAuthority?.signal].filter((e) => e !== void 0);
const h = m.length > 0 ? AbortSignal.any(m) : void 0;
const assertSourceCurrent = () => {
h?.throwIfAborted();
assertCompactionSource(p);
};
return await runWithAsyncWorkResources(async (n) => {
const s = `${e.runId ?? e.sessionId}:harness-compact:${randomUUID()}`;
const c = prepareSystemAgentRunAdmission(e.config ?? {}, s, f.agentId, "agents.harness-compaction", assertSourceCurrent, p.operatorAuthority);
const l = {};
n({
release: () => {
try {
l.releaseUnqualifiedModelSource?.();
l.host?.close();
} finally {
c.close();
}
},
releaseBeforeResultWhenIdle: true
});
const d = {
...e,
abortSignal: h,
agentDir: f.agentDir,
agentId: f.agentId
};
const m = await resolveHarnessCompactApiKey({
agentDir: f.agentDir,
compactParams: d,
initialHarness: u,
agentId: f.agentId,
sessionKey: i,
pinnedHarnessId: r,
preparedModelRuntime: t.preparedModelRuntime
});
assertSourceCurrent();
u = m.harness;
const g = await prepareAgentHarnessNativeToolPolicyRestricted({
...e,
agentId: f.agentId,
sandboxAgentId: a,
provider: e.provider ?? "",
modelId: e.model ?? ""
}, u);
d.nativeToolSurface = g ? "host-isolated" : "unrestricted";
const _ = m.runtimeAuthPlan ?? o;
const v = resolveCodexAgentHarnessNativeCompaction(u);
if (t.nativeCompactionRequest === "after_context_engine" && !v) return;
if (!t.nativeCompactionRequest && !u.compact) return unsupportedHarnessCompaction(u.id);
if (g && u.id !== "openclaw" && u.conversationToolPolicySupport !== "exact") throw new Error(`Agent harness ${u.id} cannot enforce the host-isolated tool policy required for compaction`);
const y = u.authBootstrap === "harness" && !runtimePlanRequiresHostApiKey(_);
const b = y ? void 0 : m.apiKey;
const x = y && !_ ? void 0 : m.runtimeModel;
const S = _ ? {
...d,
authProfileId: _.forwardedAuthProfileId,
authProfileIdSource: _.forwardedAuthProfileSource,
runtimeAuthPlan: _,
...d.runtimePlan ? { runtimePlan: {
...d.runtimePlan,
auth: _
} } : {}
} : d;
const C = y ? stripHarnessOwnedAuthInputs(S) : S;
const w = b || x ? {
...C,
...b ? { resolvedApiKey: unwrapSecretSentinelsForProviderEgress(b, "plugin harness compaction handoff") } : {},
...x ? { runtimeModel: unwrapModelHeaderSentinelsForProviderEgress(x, "plugin harness compaction handoff") } : {}
} : C;
const { createAgentHarnessHostCapabilities: T } = await import("./host-capability-BaSfw6Rq.mjs");
const E = await c.admit("plugin-harness", u.id);
assertSourceCurrent();
const { model: D, trigger: O, ...k } = w;
const A = T({
attempt: {
...k,
modelId: D,
runId: s,
admittedRunContext: E
},
pluginId: resolveAgentHarnessOwnerPluginId(u),
nativeModelPolicySupport: u.nativeModelPolicySupport
});
l.host = A;
const j = A.capabilities.retainSourceAuthority;
if (!j) throw new Error("Compaction host cannot retain its original source authority");
const M = u.nativeModelPolicySupport === "exact" ? void 0 : j();
l.releaseUnqualifiedModelSource = M?.release;
const N = {
...w,
...M?.signal ? { abortSignal: AbortSignal.any([M.signal, ...h ? [h] : []]) } : {},
hostCapabilities: Object.freeze({
kind: A.capabilities.kind,
version: A.capabilities.version,
assertActive: A.capabilities.assertActive,
retainSourceAuthority: j
})
};
if (p.prepareDispatch) await p.prepareDispatch();
assertSourceCurrent();
assertProviderAuthAuthority(N.runtimeModel);
if (t.nativeCompactionRequest) {
if (v) {
t.onNativeCompactionCapabilityUsed?.();
return await v({
...N,
nativeCompactionRequest: t.nativeCompactionRequest
});
}
if (!u.compact) return;
}
return await u.compact?.(N);
});
}
//#endregion
export { isRecoverableNativeHarnessBindingFailure as n, maybeCompactAgentHarnessSession as t };