openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1,477 lines • 51.9 kB
JavaScript
import { o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { c as resolveSessionFilePathOptions, o as resolveSessionFilePathCore } from "./paths-DvQ5AJvD.mjs";
import { f as resolveAgentWorkspaceDir } from "./agent-scope-config-DmXgFGKP.mjs";
import { p as isDiagnosticsEnabled, s as emitTrustedDiagnosticEvent } from "./diagnostic-events-BjAH1Kbx.mjs";
import { a as hasBillableUsage, d as normalizeUsage, f as toDiagnosticUsage } from "./usage-CHLnzpJG.mjs";
import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { a as createNativeModelOwnedRuntimeModel } from "./defaults-BWyoTPqn.mjs";
import { r as resolveCollapsedSessionAuthPinSource } from "./auth-profile-override-provenance-B7WULxR7.mjs";
import "./agent-scope-BwB8YH6y.mjs";
import { n as withPluginRuntimeGenerationScope } from "./generation-scope-Cq7RLFex.mjs";
import { r as isOpenAIProvider } from "./openai-routing-Dakz1nVk.mjs";
import { a as isIndexedSessionEntry } from "./session-entry-codec-CQ_dNjQf.mjs";
import { z as createEmptyAuthProfileStore } from "./runtime-snapshots-1lyYKb7Y.mjs";
import { f as prepareSystemAgentRunAdmission, g as resolveAdmittedRunActiveAssertion, r as assertOperatorModelAllowed } from "./admitted-run-context-D3Jvk_f_.mjs";
import { t as diagnosticLogger } from "./diagnostic-runtime-BxwnWXDu.mjs";
import { m as isCurrentEmbeddedRunAttachment } from "./run-state-jrY5s7TG.mjs";
import { a as readSessionEntrySummariesInWorker, d as readSessionEntryInWorker } from "./session-entry-read-runtime-1Fp1sybj.mjs";
import { n as parseSqliteSessionFileMarker } from "./legacy-sqlite-marker-D_RUp-nb.mjs";
import { l as scanSessionTranscriptTree } from "./transcript-tree-CyUZzlQ1.mjs";
import { m as readRuntimePromptMediaFacts, r as attachRuntimePromptMediaFacts } from "./media-facts-B-0Dpo5L.mjs";
import "./session-accessor-CizTbDQj.mjs";
import { l as omitRecordedModelPrompt } from "./session-transcript-rewrite-effects-BVKR4US3.mjs";
import { a as isModelSelectionLocked } from "./model-overrides-BXZ5Hz6C.mjs";
import { t as loadSessionTranscriptEvents } from "./session-transcript-events-8GUhKWqo.mjs";
import { t as prepareSessionTranscriptHydration } from "./session-transcript-hydration-B_Y3bole.mjs";
import "./sessions-D5Vvu3AE.mjs";
import { n as resolveAgentTimeoutMs } from "./timeout-BEnEcjB4.mjs";
import { a as resolveAgentHarnessOwnerPluginId } from "./registry-ubpieJjd.mjs";
import { a as resolveAgentHarnessPreparedRouteSupport, i as resolveAgentHarnessPreparedAuthSupport } from "./support-LWqLDjUq.mjs";
import { n as resolveAvailableAgentHarnessPolicy } from "./availability-C7FXoCVL.mjs";
import { i as resolveThinkingSelectionCore } from "./model-thinking-default-DTaWSs8g.mjs";
import { c as resolveCliRuntimeExecutionProvider, i as isCliRuntimeAliasForProvider } from "./model-runtime-aliases-DZy9Ea2c.mjs";
import { i as resolveSessionRuntimeOverrideForProvider } from "./session-runtime-compat-C_CO9LR_.mjs";
import { r as resolveSessionModelRef } from "./session-model-ref-Cha0Enxi.mjs";
import { i as readSessionRuntimeOwnershipAsync } from "./session-utils-model-selection-BGYqZws_.mjs";
import { g as attachProviderAuthAuthority, t as applyPreparedRuntimeAuthToModel, v as getProviderAuthAuthority } from "./provider-request-config-CCij-nof.mjs";
import { i as withGuardedFetchRequestAuthority } from "./fetch-request-authority-nK0cxa_-.mjs";
import { A as requireApiKey } from "./model-auth-provider-config-Bnc4upRS.mjs";
import { c as ensureAuthProfileStoreWithoutExternalProfilesAsync, i as ensureAuthProfileStoreAsync } from "./store-runtime-dW0pXLJI.mjs";
import { n as resolveEffectiveToolFsWorkspaceOnly } from "./tool-fs-policy-dDd9W7xo.mjs";
import { T as preparedModelRuntimeConfigsMatch, i as acquirePublishedPreparedModelRuntime } from "./prepared-model-runtime-Bbo9uBdt.mjs";
import { L as prepareProviderRuntimeAuth } from "./provider-runtime-BddjXkmv.mjs";
import { i as unwrapSecretSentinelsForProviderEgress } from "./provider-secret-egress-DZ6iOD2F.mjs";
import { n as getModelRegistryRuntime } from "./model-registry.core-DcVMaqxb.mjs";
import { t as resolvePreferredSessionKeyForSessionIdMatches } from "./session-id-resolution-jexGZkIN.mjs";
import "./diagnostic-C-GjPJGO.mjs";
import { a as reconcileAuthProfileQuotaBlocks } from "./usage-wMHUW27k.mjs";
import { t as collectTextContentBlocks } from "./content-blocks-DgfxPwgj.mjs";
import { r as resolveImageSanitizationLimits } from "./image-sanitization-CSJ5feF-.mjs";
import { r as sanitizeImageBlocks } from "./tool-images-BhKV9Bbe.mjs";
import { t as runWithAsyncWorkResources } from "./async-work-resources-BF09U4aO.mjs";
import { a as resolveUserTimezone } from "./date-time-ChxDjIEM.mjs";
import { n as buildSessionContext, s as migrateSessionEntries } from "./session-manager-codec-DTi9FkQE.mjs";
import { o as buildReplyUsageState, s as recordReplyUsageState } from "./deliver-hooks-B6z0_4Yo.mjs";
import { n as getAgentScopedMediaLocalRoots } from "./local-roots-BTz6ULME.mjs";
import { n as applySecretRefHeaderSentinels } from "./model-auth-CEsyk_Yg.mjs";
import { n as applyRuntimeContextCarrierRetention } from "./runtime-context-prompt-CRmsG0oC.mjs";
import { t as ensureSelectedAgentHarnessPlugin } from "./runtime-plugin-Cug3vi2h.mjs";
import { t as SessionManager } from "./session-manager-DuaaMI5O.mjs";
import { t as buildAgentRuntimeAuthPlan } from "./auth-DrOkaTvg.mjs";
import { r as buildBootstrapContextForFiles } from "./bootstrap-BoYamcpL.mjs";
import { o as resolveBootstrapFilesForPreparation } from "./bootstrap-files-CdJt18lf.mjs";
import { n as resolveSessionAuthSelection } from "./session-override-D6B49GCj.mjs";
import { p as resolveActiveEmbeddedRunBySessionFile, s as getActiveEmbeddedRunSnapshot } from "./runs-C1RO1Y6L.mjs";
import { n as resolveModelAsync } from "./model-BmrpLWB9.mjs";
import { r as prepareAgentRuntimeAuth } from "./prepare-auth-Ck7RPVAG.mjs";
import { t as protectPreparedProviderRuntimeAuth } from "./provider-runtime-auth-protection-CMR822Jv.mjs";
import { t as materializePreparedRuntimeModel } from "./materialize-model-DK894Ocx.mjs";
import { n as resolvePreparedRuntimeModelAuth, r as scopeAuthProfileStoreToPreparedPlan, t as resolvePreparedRuntimeAuthAttempts } from "./resolve-auth-Cds1OOn0.mjs";
import { t as createPreparedEmbeddedAgentSettingsManager } from "./agent-project-settings-CndET_5f.mjs";
import { a as parseSystemPromptRouteKey, i as createToolResultPromptProjectionState } from "./session-prompt-state-H0jXFYE1.mjs";
import { t as EmbeddedBlockChunker } from "./embedded-agent-block-chunker-D13d7ur3.mjs";
import { i as preparePluginHarnessToolPolicies, s as resolvePluginHarnessPolicyToolsAllow } from "./execution-environment-BrTopau0.mjs";
import { i as toNormalizedUsage, r as mergeUsageIntoAccumulator, t as createUsageAccumulator } from "./usage-accumulator-CWIvkatR.mjs";
import { i as selectAgentHarnessForPreparedModelProviders, r as selectAgentHarness } from "./selection-Dmb46Mcc.mjs";
import { r as prepareSessionPlacementSandbox } from "./session-placement-admission-CBCEtade.mjs";
import { t as streamWithPayloadPatch } from "./stream-payload-utils-CdDjgfPC.mjs";
import { t as applyExtraParamsToAgent } from "./extra-params-Dpi54r85.mjs";
import { t as resolveTranscriptPolicy } from "./transcript-policy-DcIEP7eH.mjs";
import { r as resolveSandboxContext } from "./context-DNnE7m_d.mjs";
import { o as restoreCacheTtlToolResultProjections } from "./tool-result-truncation-CpAX82MP.mjs";
import { m as mapThinkingLevelForProvider, p as mapThinkingLevel } from "./replay-history-generic-mEncANYP.mjs";
import { o as normalizeMessagesForLlmBoundary, t as wrapStreamFnWithMessageTransform } from "./message-transform-stream-wrapper-B--6dKUi.mjs";
import { a as materializeProviderContext } from "./images-BfGn0xAm.mjs";
import { t as resolveExternalCliAuthOverlayScopeFromSelection } from "./external-cli-auth-selection-otqdrexE.mjs";
import { t as buildConfiguredAgentSystemPrompt } from "./system-prompt-config-Cs2owSg-.mjs";
import { n as buildBtwQuestionPrompt, r as buildBtwSystemPrompt, t as buildBtwCliPrompt } from "./btw-prompts-C2b9Rs4d.mjs";
import { t as executePreparedCliRun } from "./execute.runtime-BVp53l1I.mjs";
import { t as prepareCliRunContext } from "./prepare.runtime-kogIzbCS.mjs";
import { i as wrapStreamFnSanitizeMalformedToolCalls, t as replayToolResultPromptProjections } from "./tool-result-projection-replay-BmKdixH0.mjs";
import { n as convertToLlmWithBlockImages, t as convertToLlm } from "./messages-C39ZvzzS.mjs";
import { n as limitHistoryTurns, t as getHistoryLimitFromSessionKey } from "./history-D_pzOPjp.mjs";
import { r as resolveEmbeddedAgentStream } from "./stream-resolution-DTC6X1c4.mjs";
import { t as registerProviderStreamForModel } from "./provider-stream-GeYmJKvk.mjs";
import { randomUUID } from "node:crypto";
import { independentResponsesRequest, responsesRequestLifecycle } from "@openclaw/ai/internal/openai";
import { isAnthropicOAuthApiKey } from "@openclaw/ai/internal/anthropic";
//#region src/agents/btw-transcript.ts
/**
* Reads prior session transcript context for `/btw` side-question handoffs.
*/
function normalizeBtwContentBlocks(e) {
if (Array.isArray(e)) return e;
if (e && typeof e === "object") return [e];
}
/** Resolves the persisted transcript file for a BTW session handoff. */
function resolveBtwSessionTranscriptPath(e) {
try {
const t = e.sessionKey?.split(":")[1];
const n = resolveSessionFilePathOptions({
agentId: t,
storePath: e.storePath
});
return resolveSessionFilePathCore(e.sessionId, e.sessionEntry, n);
} catch (t) {
diagnosticLogger.debug(`resolveSessionTranscriptPath failed: sessionId=${e.sessionId} err=${String(t)}`);
return;
}
}
function readSessionEntryId(e) {
const t = e.id;
return typeof t === "string" && t.trim().length > 0 ? t : void 0;
}
function buildSessionBranchEntries(e, t) {
if (t === null) return [];
if (!t) return;
const n = [];
const r = /* @__PURE__ */ new Set();
let i = t;
while (i) {
if (r.has(i)) return;
r.add(i);
const t = e.byId.get(i);
if (!t) return;
if (t.entry.type !== "leaf") n.push(t.entry.parentId === t.parentId ? t.entry : {
...t.entry,
parentId: t.parentId
});
i = t.parentId ?? void 0;
}
return n.toReversed();
}
function isTrailingUserMessage(e) {
return e?.type === "message" && e.message?.role === "user";
}
/**
* Reads prior messages for BTW continuation.
*
* When a transcript has fork links, this returns the selected snapshot branch
* instead of the full file so a resumed agent does not inherit sibling-branch
* messages.
*/
async function readBtwTranscriptMessages(e) {
try {
const t = parseSqliteSessionFileMarker(e.sessionFile);
const n = Boolean(e.agentId?.trim() && e.sessionId.trim() && e.sessionKey?.trim() && e.storePath?.trim());
const r = n ? e.agentId : e.agentId ?? t?.agentId;
const i = n ? e.sessionId : t?.sessionId ?? e.sessionId;
const a = n ? e.storePath : e.storePath ?? t?.storePath;
const o = t && !n ? (await readSessionEntrySummariesInWorker({
agentId: t.agentId,
storePath: t.storePath
})).filter(({ entry: e }) => e.sessionId === t.sessionId) : [];
const s = t && e.sessionKey && !n ? await readSessionEntryInWorker({
agentId: t.agentId,
sessionKey: e.sessionKey,
storePath: t.storePath
}) : void 0;
if (t && !n && e.sessionKey && (s && s.sessionId !== t.sessionId || !s && o.length > 0)) return [];
const c = n ? e.sessionKey : t ? s?.sessionId === t.sessionId ? e.sessionKey : resolvePreferredSessionKeyForSessionIdMatches(o.map(({ sessionKey: e, entry: t }) => [e, t]), t.sessionId) ?? (o.length === 0 ? e.sessionKey : void 0) : e.sessionKey;
if (!c || !a) return [];
const l = await loadSessionTranscriptEvents({
agentId: r,
sessionId: i,
sessionKey: c,
storePath: a
});
migrateSessionEntries(l);
const u = l.filter((e) => e.type !== "session");
const d = scanSessionTranscriptTree(u);
if (!d.hasLeafUpdate) return buildSessionContext(u).messages;
const f = e.snapshotLeafId !== void 0;
let p = f ? buildSessionBranchEntries(d, e.snapshotLeafId) : void 0;
if (f && p === void 0) diagnosticLogger.debug(`btw snapshot leaf unavailable: sessionId=${i} leaf=${e.snapshotLeafId}`);
p ??= buildSessionBranchEntries(d, d.leafId);
if (!f && isTrailingUserMessage(p?.at(-1))) {
const e = readSessionEntryId(p.at(-1));
const t = e ? d.byId.get(e)?.parentId : null;
p = t ? buildSessionBranchEntries(d, t) ?? [] : [];
}
return buildSessionContext(p ?? u).messages;
} catch {
return [];
}
}
//#endregion
//#region src/agents/btw-runtime.ts
async function prepareBtwRuntimeAuth(e) {
const { model: t } = e;
const n = {
profileId: e.authProfileId,
allowKeychainPrompt: false
};
const loadStore = async (t) => t ? await ensureAuthProfileStoreAsync(e.agentDir, {
...n,
externalCliProviderIds: t
}) : await ensureAuthProfileStoreWithoutExternalProfilesAsync(e.agentDir, n);
let r;
let i = false;
if (isOpenAIProvider(t.provider)) r = await loadStore(["openai"]);
else {
const n = {
provider: t.provider,
cfg: e.cfg,
agentId: e.agentId,
modelId: t.id,
workspaceDir: e.workspaceDir,
userPinnedAuthProfileId: e.authProfileIdSource === "user" ? e.authProfileId : void 0
};
let a = resolveExternalCliAuthOverlayScopeFromSelection(n);
r = await loadStore(a.providerIds);
if (!a.providerIds) {
a = resolveExternalCliAuthOverlayScopeFromSelection({
...n,
store: r
});
if (a.providerIds) r = await loadStore(a.providerIds);
}
i = a.ignoreAutoPreferredProfile;
}
const a = {
provider: t.provider,
modelId: t.id,
modelApi: t.api,
modelBaseUrl: t.baseUrl,
config: e.cfg,
agentId: e.agentId,
agentDir: e.agentDir,
env: process.env,
workspaceDir: e.workspaceDir,
authProfileStore: r,
sessionAuthProfileId: i && e.authProfileIdSource !== "user" ? void 0 : e.authProfileId,
sessionAuthProfileSource: e.authProfileIdSource,
harnessId: e.harnessId,
harnessRuntime: e.harnessId,
harnessAuthBootstrap: e.harnessAuthBootstrap
};
await reconcileAuthProfileQuotaBlocks(a);
return {
store: r,
preparation: prepareAgentRuntimeAuth(a)
};
}
function isBtwTextBlock(e) {
return isRecord(e) && normalizeLowercaseStringOrEmpty(e.type) === "text" && typeof e.text === "string";
}
function isBtwImageBlock(e) {
return isRecord(e) && normalizeLowercaseStringOrEmpty(e.type) === "image" && typeof e.data === "string" && typeof e.mimeType === "string";
}
async function sanitizeBtwUserMessage(e) {
const t = omitRecordedModelPrompt(e.message);
if (typeof t.content === "string") return t;
const n = normalizeBtwContentBlocks(t.content);
if (!n) return;
const r = [];
for (const t of n) {
if (isBtwTextBlock(t)) {
r.push({
type: "text",
text: t.text
});
continue;
}
if (!isBtwImageBlock(t)) continue;
const { images: n } = await sanitizeImageBlocks([t], "btw:context", e.imageLimits);
const i = n[0];
if (i) r.push(i);
}
if (r.length === 0) return;
return {
...t,
content: r
};
}
function sanitizeBtwAssistantMessage(e) {
const t = e.content;
let n;
if (typeof t === "string") {
const e = t.trim();
n = e ? [{
type: "text",
text: e
}] : [];
} else n = (normalizeBtwContentBlocks(t) ?? []).flatMap((e) => isBtwTextBlock(e) ? [{
type: "text",
text: e.text
}] : []);
return n.length > 0 ? {
...e,
content: n
} : void 0;
}
async function toSimpleContextMessages(e) {
const t = [];
for (const n of e.messages) {
const r = isRecord(n) ? n.role : void 0;
if (r !== "user" && r !== "assistant") continue;
let i;
if (r === "user") i = await sanitizeBtwUserMessage({
message: n,
imageLimits: e.imageLimits
});
else i = sanitizeBtwAssistantMessage(n);
if (i) t.push(i);
}
return t;
}
async function materializeBtwRuntimeModel(e) {
const { agentDir: t, config: n, workspaceDir: r } = e.preparedModelRuntime;
return await materializePreparedRuntimeModel({
plan: e.plan,
provider: e.provider,
modelId: e.modelId,
config: n,
workspaceDir: r,
metadataSnapshot: e.preparedModelRuntime.metadataSnapshot,
model: e.model,
...e.forceResolve !== void 0 ? { forceResolve: e.forceResolve } : {},
resolveModel: ({ config: n, authProfileId: i, authProfileMode: a }) => resolveModelAsync(e.provider, e.modelId, t, n, {
abortSignal: e.abortSignal,
modelIdSource: "selected",
authStorage: e.authStorage,
modelRegistry: e.modelRegistry,
skipAgentDiscovery: true,
allowBundledStaticCatalogFallback: true,
preparedModelRuntime: e.preparedModelRuntime,
workspaceDir: r,
authProfileId: i,
authProfileMode: a
})
}) ?? e.model;
}
async function resolveBtwPreparedRuntimeAuth(e) {
const { agentDir: t, config: n, workspaceDir: r } = e.preparedModelRuntime;
return resolvePreparedRuntimeAuthAttempts({
attempts: e.preparation.attempts,
store: e.authProfileStore,
modelId: e.modelId,
model: e.model,
materializeModel: ({ plan: t, model: n, forceResolve: r }) => materializeBtwRuntimeModel({
...e,
plan: t,
model: n,
forceResolve: r
}),
resolveAuth: async ({ attempt: i, model: a }) => await resolvePreparedRuntimeModelAuth({
plan: i.plan,
model: a,
cfg: n,
store: e.authProfileStore,
agentDir: t,
workspaceDir: r,
...i.allowAuthProfileFallback !== void 0 ? { allowAuthProfileFallback: i.allowAuthProfileFallback } : {},
secretSentinels: true
}),
errorMessage: "BTW prepared auth attempts could not be resolved."
});
}
async function resolveRuntimeModel(e) {
const t = e.preparedModelRuntime;
const { config: n, agentDir: r, workspaceDir: i } = t;
const a = await readSessionRuntimeOwnershipAsync({
...e,
config: n
});
const o = a?.modelRef ?? e;
const { authStorage: s, modelRegistry: c } = t.createStores();
if (a?.auth === "native") {
const r = buildAgentRuntimeAuthPlan({
provider: o.provider,
modelId: o.model,
config: n,
workspaceDir: i,
metadataSnapshot: t.metadataSnapshot,
harnessId: e.harnessId,
allowHarnessAuthProfileForwarding: false
});
return {
model: createNativeModelOwnedRuntimeModel({
provider: o.provider,
modelId: o.model
}),
authProfileStore: createEmptyAuthProfileStore(),
runtimeAuthPreparation: {
plan: r,
attempts: [{
kind: "implicit",
plan: r
}]
},
authStorage: s,
modelRegistry: c,
nativeOwnership: a
};
}
const l = await resolveModelAsync(o.provider, o.model, r, n, {
abortSignal: e.abortSignal,
authStorage: s,
modelRegistry: c,
preparedModelRuntime: t,
workspaceDir: i,
skipAgentDiscovery: true,
allowBundledStaticCatalogFallback: true,
preferBundledStaticCatalogTransport: Boolean(e.harnessId && e.harnessId !== "openclaw")
});
let u = l.model;
if (!u) throw new Error(l.error ?? `Unknown model: ${o.provider}/${o.model}`);
const d = u.provider;
const f = u.id;
const p = await resolveSessionAuthSelection({
cfg: n,
provider: d,
modelId: f,
agentId: e.agentId,
agentDir: r,
sessionEntry: e.sessionEntry,
sessionStore: e.sessionStore,
sessionKey: e.sessionKey,
storePath: e.storePath,
isNewSession: e.isNewSession
});
const { store: m, preparation: h } = await prepareBtwRuntimeAuth({
cfg: n,
model: u,
agentId: e.agentId,
agentDir: r,
workspaceDir: i,
authProfileId: p?.profileId,
authProfileIdSource: p?.source,
harnessId: e.harnessId,
harnessAuthBootstrap: e.harnessAuthBootstrap
});
u = await materializeBtwRuntimeModel({
abortSignal: e.abortSignal,
provider: d,
modelId: f,
preparedModelRuntime: t,
authStorage: s,
modelRegistry: c,
plan: h.plan,
model: u
});
return {
model: u,
authProfileId: h.plan.forwardedAuthProfileId,
authProfileIdSource: h.plan.forwardedAuthProfileSource,
authProfileStore: m,
runtimeAuthPreparation: h,
authStorage: s,
modelRegistry: c,
nativeOwnership: a
};
}
async function prepareBtwHarnessToolPolicies(e) {
const t = await preparePluginHarnessToolPolicies({
...e,
config: e.cfg,
provider: e.runtimeModel.provider,
modelId: e.runtimeModel.id
}, void 0, void 0, e.nativeOwnership ? e.nativeOwnership.modelRef ?? null : {
provider: e.runtimeModel.provider,
model: e.runtimeModel.id
});
return {
toolsAllow: resolvePluginHarnessPolicyToolsAllow(t),
webSearchPolicy: t.webSearchPolicy
};
}
async function runCliBtwSideQuestion(e) {
const t = resolveAgentTimeoutMs({
cfg: e.cfg,
overrideSeconds: e.opts?.timeoutOverrideSeconds,
overrideMs: e.opts?.timeoutOverrideMs
});
const n = e.authorityRunId;
const r = prepareSystemAgentRunAdmission(e.cfg, n, e.sessionAgentId, "btw.side-question");
let i;
try {
i = await prepareCliRunContext({
preparedRunAdmission: r,
sessionId: e.sessionId,
sessionKey: e.sessionKey,
sessionEntry: e.sessionEntry,
agentId: e.sessionAgentId,
trigger: "user",
sessionFile: e.sessionFile,
workspaceDir: e.workspaceDir,
config: e.cfg,
prompt: buildBtwCliPrompt(e),
extraSystemPrompt: buildBtwSystemPrompt(),
executionMode: "side-question",
provider: e.cliProvider,
model: e.model,
thinkLevel: e.resolvedThinkLevel,
disableTools: true,
timeoutMs: t,
runTimeoutOverrideMs: t,
runId: n,
authProfileId: e.authProfileId,
abortSignal: e.opts?.abortSignal,
messageChannel: e.messageChannel,
messageProvider: e.messageProvider,
currentChannelId: e.currentChannelId
});
const a = await executePreparedCliRun(i);
const o = a.text.trim();
if (!o) throw new Error(`/btw side question via ${e.cliProvider} produced no answer.`);
e.onUsage?.(normalizeUsage(a.usage));
return { text: o };
} finally {
try {
await i?.preparedBackend.cleanup?.();
} finally {
r.close();
}
}
}
/** The visible answer may finish before cooperating provider and cleanup work settles. */
async function withBtwPreparedRuntime(e, t) {
return await runWithAsyncWorkResources(async (n, r) => {
const i = await acquirePublishedPreparedModelRuntime(e);
n({ release: () => i[Symbol.asyncDispose]() });
return withPluginRuntimeGenerationScope(i.snapshot, () => {
r();
return t(i.snapshot);
});
});
}
//#endregion
//#region src/agents/embedded-agent-runner/session-fork-context.ts
function matchesModelRoute(e, t) {
const n = parseSystemPromptRouteKey(e);
return n?.provider === t.provider && n.model === t.id && n.api === t.api && n.baseUrl === (t.baseUrl ?? null);
}
/** Rebuild only when a fork is requested; the transcript and live attempt own history. */
async function prepareEmbeddedSessionForkContext(e) {
const assertCurrent = () => {
e.signal?.throwIfAborted();
e.assertCurrent();
};
assertCurrent();
const t = resolveActiveEmbeddedRunBySessionFile(e.target.sessionKey ?? e.sessionFile);
const n = t && t.sessionId === e.target.sessionId && t.agentId === e.agentId && isCurrentEmbeddedRunAttachment(t) ? t.handle.readSessionForkContext?.() : void 0;
if (n && n.model.provider === e.model.provider && n.model.id === e.model.id && n.model.api === e.model.api && n.model.baseUrl === e.model.baseUrl) {
const e = normalizeMessagesForLlmBoundary(n.projectMessages?.(n.messages) ?? n.messages, {
...n.boundary,
sessionVersion: n.sessionVersion
});
const t = structuredClone({
systemPrompt: n.systemPrompt,
tools: n.tools,
messages: e
});
e.forEach((e, n) => {
const r = readRuntimePromptMediaFacts(e);
if (r) attachRuntimePromptMediaFacts(t.messages[n], structuredClone(r));
});
const r = {
...t,
messages: convertToLlmWithBlockImages(t.messages, n.blockImages ?? false)
};
if (n.projectMessages) r.messages = convertToLlm(n.projectMessages(r.messages));
applyRuntimeContextCarrierRetention(r.messages, n.boundary?.appendOnlyRuntimeContext);
return r;
}
const r = parseSqliteSessionFileMarker(e.sessionFile);
const i = e.target.storePath ?? (r?.agentId === e.target.agentId && r.sessionId === e.target.sessionId ? r.storePath : void 0);
if (!i) throw new Error("Session fork requires an existing session transcript.");
let a = e.target.sessionKey;
if (!a) {
const t = await readSessionEntrySummariesInWorker({
agentId: e.target.agentId,
storePath: i
});
assertCurrent();
a = resolvePreferredSessionKeyForSessionIdMatches(t.filter(({ entry: t }) => t.sessionId === e.target.sessionId).map(({ sessionKey: e, entry: t }) => [e, t]), e.target.sessionId);
}
if (!a) throw new Error("Session fork could not resolve the existing session transcript.");
const o = {
...e.target,
storePath: i,
sessionKey: a
};
const s = await SessionManager.openModelContextAsync(o, {
cwd: e.workspaceDir,
signal: e.signal
});
assertCurrent();
const c = s.getBranch();
const l = prepareSessionTranscriptHydration(o, void 0, e.signal);
const u = createToolResultPromptProjectionState();
if (c.some((e) => e.type === "custom" && e.customType === "openclaw.cache-ttl")) {
const e = await l.readMaintenance({
operation: "custom-branch",
leafEntryId: s.getLeafId(),
customType: "openclaw.cache-ttl"
});
l.assertCurrent();
assertCurrent();
if (!e.events) throw new Error("Session fork transcript changed while preparing its model context.");
const t = new Map(e.events.filter(isIndexedSessionEntry).map((e) => [e.id, e]));
restoreCacheTtlToolResultProjections(u, c.map((e) => t.get(e.id) ?? e));
}
const d = c.findLastIndex((e) => e.type === "custom" && e.customType === "openclaw.system-prompt");
let f = c[d];
const p = s.getTranscriptSnapshotVersion();
if (f && p) {
const e = await l.readCurrentTurnEntry({
entryId: f.id,
version: p,
includeEntry: true
});
l.assertCurrent();
assertCurrent();
if (isIndexedSessionEntry(e.event) && e.event.type === "custom") f = e.event;
}
const m = f?.type === "custom" ? f.data : void 0;
const h = c.findLast((e) => e.type === "compaction" || e.type === "reset")?.id ?? null;
const g = isRecord(m) && matchesModelRoute(m.routeKey, e.model) && m.historyId === h && !c.slice(d + 1).some((e) => e.type === "model_change") ? m : void 0;
let _;
if (Array.isArray(g?.tools)) _ = g.tools;
let v = typeof g?.prefix === "string" ? g.prefix : void 0;
if (v === void 0) {
const t = await resolveBootstrapFilesForPreparation({
config: e.config,
workspaceDir: e.workspaceDir,
agentId: e.agentId,
sessionId: e.target.sessionId,
sessionKey: a,
bootstrapUserProfileId: e.bootstrapUserProfileId,
chatType: e.chatType
});
assertCurrent();
v = buildConfiguredAgentSystemPrompt({
config: e.config,
workspaceDir: e.workspaceDir,
agentId: e.agentId,
tools: _,
contextFiles: buildBootstrapContextForFiles(t, e),
runtimeInfo: {
agentId: e.agentId,
sessionId: e.target.sessionId,
sessionKey: a,
model: `${e.model.provider}/${e.model.id}`
}
});
}
assertCurrent();
const y = resolveTranscriptPolicy({
provider: e.model.provider,
modelId: e.model.id,
modelApi: e.model.api,
model: e.model,
config: e.config,
workspaceDir: e.workspaceDir,
directApiKey: e.directApiKey
});
const b = createPreparedEmbeddedAgentSettingsManager({
agentId: e.target.agentId,
sessionId: e.target.sessionId,
cwd: e.workspaceDir,
agentDir: e.agentDir,
cfg: e.config
});
let x = convertToLlmWithBlockImages(normalizeMessagesForLlmBoundary(replayToolResultPromptProjections(limitHistoryTurns(s.buildSessionContext().messages, getHistoryLimitFromSessionKey(a, e.config, {
accountId: e.accountId,
peerId: e.peerId,
chatType: e.chatType
})), u), {
sessionVersion: s.getHeader()?.version,
appendOnlyRuntimeContext: y.appendOnlyRuntimeContext,
inHistorySystemUpdates: y.inHistorySystemUpdates,
timezone: resolveUserTimezone(e.config?.agents?.defaults?.userTimezone)
}), b.getBlockImages());
x = convertToLlm(replayToolResultPromptProjections(x, u));
applyRuntimeContextCarrierRetention(x, y.appendOnlyRuntimeContext);
return {
systemPrompt: v,
tools: _,
messages: x
};
}
//#endregion
//#region src/agents/embedded-agent-runner/session-fork.ts
const FORK_TOOL_CHOICE_SHAPES = /* @__PURE__ */ new Map([
["anthropic-messages", "object"],
["openai-responses", "string"],
["openai-chatgpt-responses", "string"],
["openai-completions", "string"]
]);
/** Prepare and run a tool-free request only when a caller actually forks. */
async function runEmbeddedSessionFork(e) {
if (!FORK_TOOL_CHOICE_SHAPES.has(e.model.api)) throw new Error(`Session forks do not support provider API ${e.model.api}. Use OpenAI Responses, Chat Completions, or Anthropic Messages.`);
const assertCurrent = () => {
e.assertCurrent();
e.signal?.throwIfAborted();
};
assertCurrent();
const t = e.model;
const n = {
...e.context,
messages: [...e.context.messages]
};
const r = /* @__PURE__ */ new Set();
for (let e = n.messages.length - 1; e >= 0; e--) {
const t = n.messages[e];
if (t.role === "toolResult") r.add(t.toolCallId);
else if (t.role === "assistant") for (const i of t.content) {
if (i.type !== "toolCall" || r.delete(i.id)) continue;
n.messages.splice(e + 1, 0, {
role: "toolResult",
toolCallId: i.id,
toolName: i.name,
content: [{
type: "text",
text: "This tool call is still running. Its result is not available yet."
}],
isError: false,
timestamp: Date.now()
});
}
}
n.messages.push({
role: "user",
content: e.question,
timestamp: Date.now()
});
const i = createUsageAccumulator();
for (let r = 0; r < 3; r++) {
assertCurrent();
const r = {
...e.options,
apiKey: e.apiKey,
signal: e.signal,
asyncToolExecution: false,
onPayload: (e) => {
assertCurrent();
if (!isRecord(e)) throw new Error("Session fork requires an object provider request.");
if (Array.isArray(e.tools) && e.tools.length > 0) e.tool_choice = FORK_TOOL_CHOICE_SHAPES.get(t.api) === "object" ? { type: "none" } : "none";
else delete e.tool_choice;
delete e.previous_response_id;
delete e.prompt_cache_key;
return e;
}
};
independentResponsesRequest.set(r);
responsesRequestLifecycle.set(r, {
assertCurrent,
beforeDispatch: async () => assertCurrent(),
accepted: async () => assertCurrent(),
settle: async () => assertCurrent()
});
assertCurrent();
const a = await withGuardedFetchRequestAuthority(assertCurrent, async () => {
const i = await e.streamFn(t, n, r);
assertCurrent();
return await i.result();
});
assertCurrent();
mergeUsageIntoAccumulator(i, normalizeUsage(a.usage));
e.onUsage?.(toNormalizedUsage(i));
if (a.stopReason === "error" || a.stopReason === "aborted") throw new Error(a.errorMessage || "Session fork failed.");
const o = a.content.filter((e) => e.type === "toolCall");
if (o.length === 0) {
const e = collectTextContentBlocks(a.content).join("").trim();
if (!e) throw new Error("No session fork response generated.");
return e;
}
n.messages.push(a);
for (const e of o) n.messages.push({
role: "toolResult",
toolCallId: e.id,
toolName: e.name,
content: [{
type: "text",
text: "Tool execution denied for this side question. Answer without calling tools."
}],
isError: true,
timestamp: Date.now()
});
}
throw new Error("Session fork kept requesting tools after three attempts. Ask a question that can be answered without tools.");
}
//#endregion
//#region src/agents/btw-stream.ts
const log = createSubsystemLogger("agents/btw");
function resolveSideQuestionStream(e) {
const { params: t, modelRegistry: n, runtimeModel: r, auth: i, apiKey: a, resolvedAuthProfileId: o, sessionId: s, workspaceDir: c } = e;
const l = getModelRegistryRuntime(n);
const u = registerProviderStreamForModel({
model: r,
cfg: t.cfg,
agentDir: t.agentDir,
workspaceDir: c,
env: process.env,
wrapProviderStream: t.toolCalls !== "deny",
auth: i,
apiRegistry: l.apiRegistry
});
const { streamFn: d } = resolveEmbeddedAgentStream({
llmRuntime: l.llmRuntime,
currentStreamFn: l.llmRuntime.streamSimple,
providerStreamFn: u,
sessionId: s,
signal: t.opts?.abortSignal,
model: r,
resolvedApiKey: a,
authProfileId: o
});
if (t.toolCalls !== "deny") return d;
const f = r.api === "anthropic-messages" ? resolveThinkingSelectionCore({
cfg: t.cfg,
agentId: t.agentId,
provider: r.provider,
model: r.id,
level: t.resolvedThinkLevel,
agentRuntime: "openclaw"
}).level : t.resolvedThinkLevel;
const p = resolveEffectiveToolFsWorkspaceOnly({
cfg: t.cfg,
agentId: t.agentId
});
const m = { streamFn: wrapStreamFnWithMessageTransform(d, (e) => e, ({ context: e, signal: n }) => materializeProviderContext({
context: e,
signal: n,
workspaceDir: c,
agentWorkspaceDir: c,
workspaceOnly: p,
localRoots: p ? void 0 : getAgentScopedMediaLocalRoots(t.cfg, t.agentId)
})) };
const h = mapThinkingLevelForProvider(f, r);
applyExtraParamsToAgent(m, t.cfg, r.provider, r.id, void 0, h, t.agentId, c, r, t.agentDir, void 0, { auth: i });
const g = m.streamFn;
return (e, t, n) => g(e, t, {
reasoning: mapThinkingLevel(h),
...n
});
}
async function runBtwSessionFork(e) {
const { params: t, runtimeModel: n, apiKey: r, sessionId: i, workspaceDir: a, assertCurrent: o } = e;
const s = t.sessionEntry.delivery;
const c = s?.kind === "external" ? s : void 0;
const l = await prepareEmbeddedSessionForkContext({
target: {
agentId: t.agentId,
sessionId: i,
sessionKey: t.sessionKey,
storePath: t.storePath
},
sessionFile: e.sessionFile,
model: n,
directApiKey: Boolean(r) && !isAnthropicOAuthApiKey(r),
config: t.cfg,
workspaceDir: a,
agentId: t.agentId,
agentDir: t.agentDir,
chatType: t.chatType ?? t.sessionEntry.chatType,
accountId: t.agentAccountId ?? c?.route.accountId,
peerId: c?.origin.nativeDirectUserId,
signal: t.opts?.abortSignal,
assertCurrent: o
});
o();
return runEmbeddedSessionFork({
context: l,
streamFn: resolveSideQuestionStream(e),
question: t.question,
model: n,
apiKey: r,
signal: t.opts?.abortSignal,
assertCurrent: o,
onUsage: t.onUsage
});
}
async function runLightweightBtwStream(e) {
const { params: t, runtimeModel: n, apiKey: r, imageLimits: i, messages: a, inFlightPrompt: o, recordBtwUsage: s } = e;
const c = wrapStreamFnSanitizeMalformedToolCalls(resolveSideQuestionStream(e), void 0, resolveTranscriptPolicy({
provider: n.provider,
modelId: n.id,
modelApi: n.api,
model: n,
config: t.cfg,
workspaceDir: e.workspaceDir,
directApiKey: Boolean(r) && !isAnthropicOAuthApiKey(r)
}), n.provider);
const l = t.opts?.onBlockReply && t.blockReplyChunking ? new EmbeddedBlockChunker(t.blockReplyChunking) : void 0;
let u = 0;
let d = Promise.resolve();
let f = false;
let p = "";
let m = "";
let h = false;
let g = false;
const _ = t.resolvedBlockStreamingBreak === "text_end";
const emitBlockChunk = (e) => {
if (!e.trim() || !t.opts?.onBlockReply) return;
u += 1;
d = d.then(() => t.opts?.onBlockReply?.({
text: e,
btw: { question: t.question }
})).catch((e) => {
f = true;
log.warn(`Block reply delivery failed: ${String(e)}`);
});
};
const { images: v } = await sanitizeImageBlocks(t.images ?? [], "btw:question", i);
const y = await streamWithPayloadPatch(c, n, {
systemPrompt: buildBtwSystemPrompt(),
messages: [...a, {
role: "user",
content: [{
type: "text",
text: buildBtwQuestionPrompt(t.question, o)
}, ...v],
timestamp: Date.now()
}]
}, {
apiKey: r,
reasoning: void 0,
signal: t.opts?.abortSignal
}, (e) => {
if (Array.isArray(e.tools) && e.tools.length === 0) delete e.tools;
});
let b;
try {
for await (const e of y) {
b = e.type === "done" || e.type === "error" ? e : b;
if (!h && (e.type === "text_start" || e.type === "start")) {
h = true;
await t.opts?.onAssistantMessageStart?.();
}
if (e.type === "text_delta") {
g = true;
p += e.delta;
l?.append(e.delta);
if (l && _) l.drain({
force: false,
emit: emitBlockChunk
});
continue;
}
if (e.type === "text_end" && l && _) {
l.drain({
force: true,
emit: emitBlockChunk
});
continue;
}
if (e.type === "thinking_delta") {
if (t.resolvedReasoningLevel !== "off") {
m += e.delta;
await t.opts?.onReasoningStream?.({
text: m,
isReasoning: true
});
}
continue;
}
if (e.type === "thinking_end" && t.resolvedReasoningLevel !== "off") await t.opts?.onReasoningEnd?.();
}
if (l && t.resolvedBlockStreamingBreak !== "text_end" && l.hasBuffered()) l.drain({
force: true,
emit: emitBlockChunk
});
} finally {
await d;
}
if (b?.type === "error") {
const e = collectTextContentBlocks(b.error.content).join("");
throw new Error(e || b.error.errorMessage || "BTW failed.");
}
const x = b?.type === "done" ? b.message : void 0;
if (x && !g) p = collectTextContentBlocks(x.content).join("");
const S = p.trim();
if (!S) throw new Error("No BTW response generated.");
s(n, normalizeUsage(x?.usage));
if (u > 0 && !f) return;
return { text: S };
}
//#endregion
//#region src/agents/btw.ts
/** Answers a side question using sanitized session context and no tool execution. */
async function runBtwSideQuestion(e) {
let t = {
...e,
sessionEntry: { ...e.sessionEntry },
authorityRunId: e.authorityRunId ?? `btw-${randomUUID()}`
};
if (t.sessionStore && t.sessionKey) t.sessionStore[t.sessionKey] = t.sessionEntry;
const n = t.sessionEntry.sessionId?.trim();
if (!n) throw new Error("No active session context.");
const r = resolveBtwSessionTranscriptPath({
sessionId: n,
sessionEntry: t.sessionEntry,
sessionKey: t.sessionKey,
storePath: t.storePath
});
if (!r) throw new Error("No active session transcript.");
const i = resolveAgentWorkspaceDir(t.cfg, t.agentId);
const a = {
config: t.cfg,
agentId: t.agentId,
agentDir: t.agentDir,
workspaceDir: i,
...t.allowGatewaySubagentBinding ? { allowGatewaySubagentBinding: true } : {}
};
return await withBtwPreparedRuntime(a, async (e) => {
const i = e.agentId ?? t.agentId;
const a = e.workspaceDir ?? resolveAgentWorkspaceDir(e.config, i);
const o = preparedModelRuntimeConfigsMatch(e.config, t.cfg) ? {
provider: t.provider,
model: t.model
} : resolveSessionModelRef(e.config, t.sessionEntry, i);
t = {
...t,
cfg: e.config,
agentDir: e.agentDir,
provider: o.provider,
model: o.model
};
const s = /* @__PURE__ */ new Map();
const prepareHarness = async (n, r, o) => {
const c = isModelSelectionLocked(t.sessionEntry) ? t.sessionEntry.agentHarnessId : void 0;
const l = c ? void 0 : resolveSessionRuntimeOverrideForProvider({
provider: n,
entry: t.sessionEntry,
cfg: t.cfg
});
const u = [
`${n}/${r}/${c ?? l ?? "configured"}`,
o?.api ?? "",
o?.baseUrl ?? "",
o?.requestTransportOverrides ?? "",
o?.runtimePolicy?.compatibleIds.join(",") ?? "",
o?.preparedAuth?.source ?? "",
o?.preparedAuth?.mode ?? "",
o?.preparedAuth?.requirement ?? ""
].join("\0");
const d = s.get(u);
if (d) return d;
const f = {
provider: n,
modelId: r,
config: t.cfg,
agentId: i,
sessionKey: t.sessionKey,
...c ? { agentHarnessId: c } : {},
...l ? { agentHarnessRuntimeOverride: l } : {}
};
await ensureSelectedAgentHarnessPlugin({
...f,
workspaceDir: a,
pluginRegistry: e.pluginRegistry
});
const p = o ? selectAgentHarnessForPreparedModelProviders({
...f,
modelProviders: [o]
}) : selectAgentHarness(f);
s.set(u, p);
return p;
};
const c = await prepareHarness(t.provider, t.model);
let l;
const resolveRuntimeSelection = async () => {
if (!l) l = await resolveRuntimeModel({
...t,
abortSignal: t.opts?.abortSignal,
agentId: i,
harnessId: c.id,
harnessAuthBootstrap: c.authBootstrap,
preparedModelRuntime: e
});
return l;
};
const recordBtwUsage = (e, r) => {
t.onUsage?.(r);
if (t.onUsage) return;
if (!hasBillableUsage(r)) return;
const a = buildReplyUsageState({
config: t.cfg,
agentDir: t.agentDir,
agentId: i,
sessionId: n,
provider: e.provider,
model: e.id,
chatType: t.chatType,
usage: r
});
recordReplyUsageState(t.opts?.runId, a);
if (isDiagnosticsEnabled(t.cfg)) emitTrustedDiagnosticEvent({
type: "model.usage",
sessionKey: t.sessionKey,
sessionId: n,
channel: t.messageChannel,
agentId: i,
provider: e.provider,
model: e.id,
usage: toDiagnosticUsage(r),
costUsd: a.turnUsd
});
};
let u;
const runHarnessSideQuestion = async (o, s, l = false) => {
try {
var u = _usingCtx();
const d = o.id === c.id ? void 0 : await prepareBtwRuntimeAuth({
cfg: t.cfg,
model: s.model,
agentId: i,
agentDir: t.agentDir,
workspaceDir: a,
authProfileId: s.authProfileId,
authProfileIdSource: s.authProfileIdSource,
harnessId: o.id,
harnessAuthBootstrap: o.authBootstrap
});
const f = d?.preparation ?? s.runtimeAuthPreparation;
const p = d?.store ?? s.authProfileStore;
const m = s.nativeOwnership?.auth === "native";
const h = f.attempts[0];
const g = f.attempts.length === 1 && h?.kind === "implicit" && (m || o.authBootstrap === "harness" && h.plan.harnessAuthProvider) ? h.plan : void 0;
const _ = g ? {
plan: g,
model: s.model
} : await resolveBtwPreparedRuntimeAuth({
abortSignal: t.opts?.abortSignal,
preparation: f,
model: s.model,
provider: s.model.provider,
modelId: s.model.id,
preparedModelRuntime: e,
authStorage: s.authStorage,
modelRegistry: s.modelRegistry,
authProfileStore: p
});
const v = _.plan;
const y = attachProviderAuthAuthority(_.model, getProviderAuthAuthority("auth" in _ ? _.auth : void 0));
const b = m ? o : await prepareHarness(y.provider, y.id, {
api: y.api,
baseUrl: y.baseUrl,
...resolveAgentHarnessPreparedRouteSupport(v),
preparedAuth: resolveAgentHarnessPreparedAuthSupport({ plan: v })
});
if (b.id !== o.id) {
if (l) throw new Error("Agent harness selection changed after route materialization.");
return runHarnessSideQuestion(b, {
...s,
model: y,
runtimeAuthPreparation: f,
authProfileStore: p
}, true);
}
if (!o.runSideQuestion) {
if (o.id !== "openclaw" || !("auth" in _)) throw new Error(`Selected agent harness "${o.id}" does not support /btw side questions.`);
return {
kind: "openclaw",
harness: o,
runtime: {
...s,
model: y,
authProfileId: v.forwardedAuthProfileId,
authProfileIdSource: v.forwardedAuthProfileSource,
authProfileStore: p,
runtimeAuthPreparation: f
},
resolvedAttempt: _
};
}
const x = v.modelRoute?.authRequirement === "api-key" && "auth" in _ ? _.auth.apiKey?.trim() : void 0;
const S = t.authorityRunId;
const C = u.u(await prepareSessionPlacementSandbox({
agentId: i,
config: t.cfg,
sessionId: n,
sessionKey: t.sessionKey,
workspaceDir: a
}));
C.assertCurrent();
const w = C.sandbox ?? await resolveSandboxContext({
config: t.cfg,
agentId: !t.sandboxSessionKey || t.sandboxSessionKey === t.sessionKey ? i : void 0,
sessionKey: t.sandboxSessionKey ?? t.sessionKey ?? n,
workspaceDir: a
});
u.u({ [Symbol.dispose]: () => {
if (!C.sandbox) w?.[Symbol.dispose]?.();
} });
const { toolsAllow: T, webSearchPolicy: E } = await prepareBtwHarnessToolPolicies({
...t,
agentId: i,
sessionId: n,
runtimeModel: y,
nativeOwnership: s.nativeOwnership,
sandbox: w
});
const { createAgentHarnessHostCapabilities: D } = await import("./host-capability-BaSfw6Rq.mjs");
const O = prepareSystemAgentRunAdmission(t.cfg, S, i, "btw.side-question", t.assertCurrent, t.operatorAuthority);
const k = await O.admit("plugin-harness");
try {
const { model: c, authorityRunId: l, ...u } = t;
const d = D({
attempt: {
...u,
admittedRunContext: k,
config: t.cfg,
agentId: i,
sessionId: n,
sessionKey: t.sessionKey,
sandbox: w,
workspaceDir: a,
runId: S,
currentMessagingTarget: t.messageTo,
currentThreadTs: t.messageThreadId === void 0 ? void 0 : String(t.messageThreadId)
},
pluginId: resolveAgentHarnessOwnerPluginId(o),
nativeModelPolicySupport: o.nativeModelPolicySupport,
toolCalls: t.toolCalls
});
const f = {
...u,
hostCapabilities: d.capabilities,
sandbox: w,
provider: y.provider,
model: y.id,
runtimeModel: y,
preparedModelRuntime: e,
expectedSessionRuntimeOwnership: s.nativeOwnership,
preparedWebSearchPolicy: E,
preparedRuntimeAuth: {
plan: v,
authProfileStore: scopeAuthProfileStoreToPreparedPlan(p, v),
authStorage: s.authStorage,
modelRegistry: s.modelRegistry,
...x ? { resolvedApiKey: unwrapSecretSentinelsForProviderEgress(x, "BTW harness handoff") } : {}
},
sessionId: n,
sessionFile: r,
agentId: i,
workspaceDir: a,
...T ? { toolsAllow: T } : {},
authProfileId: v.modelRoute?.authRequirement === "api-key" ? void 0 : v.forwardedAuthProfileId,
opts: {
...t.opts,
runId: S
},
authProfileIdSource: v.modelRoute?.authRequirement === "api-key" ? void 0 : v.forwardedAuthProfileSource
};
let m;
try {
C.assertCurrent();
t.assertCurrent?.();
assertOperatorModelAllowed(t.operatorAuthority, {
provider: y.provider,
model: y.id
});
getProviderAuthAuthority(y)?.();
m = await o.runSideQuestion(f);
} finally {
d.close();
}
recordBtwUsage(y, m.usage);
return {
kind: "handled",
payload: { text: m.text }
};
} finally {
O.close();
}
} catch (e) {
u.e = e;
} finally {
u.d();
}
};
if (c.runSideQuestion) {
const e = await runHarnessSideQuestion(c, await resolveRuntimeSelection());
if (e.kind === "handled") return e.payload;
u = e;
}
if (c.id === "codex" && !c.runSideQuestion) throw new Error(`Selected agent harness "${c.id}" does not support /btw side questions.`);
const d = c.id === "openclaw" && t.toolCalls === "deny";
const f = getActiveEmbeddedRunSnapshot(r);
const p = resolveImageSanitizationLimits(t.cfg);
let m = [];
const h = f?.inFlightPrompt;
if (!d) {
if (f?.messages?.length) m = await toSimpleContextMessages({
messages: f.messages,
imageLimits: p
});
if (m.length === 0) m = await toSimpleContextMessages({
messages: await readBtwTranscriptMessages({
agentId: i,
sessionFile: r,
sessionId: n,
sessionKey: t.sessionKey,
storePath: t.storePath,
snapshotLeafId: f?.transcriptLeafId
}),
imageLimits: p
});
}
t.opts?.abortSignal?.throwIfAborted();
if (!d && m.length === 0 && !h?.trim()) throw new Error("No active session context.");
const g = resolveAvailableAgentHarnessPolicy({
provider: t.provider,
modelId: t.model,
config: t.cfg,
agentId: i,
sessionKey: t.sessionKey
}).runtime.trim();
const _ = t.sessionEntry.authProfileOverride?.trim() || void 0;
const v = _ ? resolveCollapsedSessionAuthPinSource(t.sessionEntry) : void 0;
const y = {
provider: t.provider,
cfg: t.cfg,
agentId: i,
modelId: t.model
};
const b = _ ? resolveCliRuntimeExecutionProvider({
...y,
authProfileId: _
})?.trim() : void 0;
const x = !_ || v === "auto" ? resolveCliRuntimeExecutionProvider(y)?.trim() : void 0;
const S = b ?? x ?? (isCliRuntimeAliasForProvider({
runtime: g,
provider: t.provider,
cfg: t.cfg
}) ? g : void 0);
if (S) {
if (t.toolCalls === "deny") throw new Error(`Session forks are not supported for CLI runtime ${S}.`);
return runCliBtwSideQuestion({
cfg: t.cfg,
onUsage: t.onUsage,
model: t.model,
question: t.question,
imageCount: t.images?.length ?? 0,
sessionId: n,
sessionFile: r,
sessionEntry: t.sessionEntry,
sessionKey: t.sessionKey,
sessionAgentId: i,
workspaceDir: a,
cliProvider: S,
authProfileId: b ? _ : void 0,
resolvedThinkLevel: t.resolvedThinkLevel,
messages: m,
inFlightPrompt: h,
opts: t.opts,
authorityRunId: t.authorityRunId,
messageChannel: t.messageChannel,
messageProvider: t.messageProvider,
currentChannelId: t.currentChannelId
});
}
const C = u;
const w = C?.runtime ?? await resolveRuntimeSelection();
const T = C?.harness ?? await prepareHarness(w.model.provider, w.model.id);
if (T.runSideQuestion) {
const e = await runHarnessSideQuestion(T, w);
if (e.kind === "handled") return e.payload;
u = e;
}
if (T.id === "codex" && !T.runSideQuestion) throw new Error(`Selected agent harness "${T.id}" does not support /btw side questions.`);
const E = u;
const { authStorage: D, model: O, modelRegistry: k, authProfileStore: A, runtimeAuthPreparation: j } = E?.runtime ?? w;
const M = E?.resolvedAttempt ?? await resolveBtwPreparedRuntimeAuth({
abortSignal: t.opts?.abortSignal,
preparation: j,
model: O,
provider: O.provider,
modelId: O.id,
preparedModelRuntime: e,
authStorage: D,
modelRegistry: k,
authProfileStore: A
});
const N = M.auth;
t.assertCurrent?.();
assertOperatorModelAllowed(t.operatorAuthority, {
provider: M.model.provider,
model: M.model.id
});
const P = M.plan.forwardedAuthProfileId;
let F = attachProviderAuthAuthority(M.model, getProviderAuthAuthority(N));
let I = N.mode === "aws-sdk" && !N.apiKey ? void 0 : requireApiKey(N, F.provider);
if (I) {
const e = protectPreparedProviderRuntimeAuth({
provider: F.provider,
preparedAuth: await prepareProviderRuntimeAuth({
provider: F.provider,
config: t.cfg,
workspaceDir: a,
env: process.env,
context: {
config: t.cfg,
agentDir: t.agentDir,
workspaceDir: a,
env: process.env,
provider: F.provider,
modelId: F.id,
model: F,
apiKey: I,
authMode: N.mode,
profileId: P
}
})
});
F = applyPreparedRuntimeAuthToModel(F, e);
if (e?.apiKey) I = e.apiKey;
}
F = applySecretRefHeaderSentinels(F, t.cfg);
if (t.toolCalls === "deny") {
const e = prepareSystemAgentRunAdmission(t.cfg, t.authorityRunId, i, "btw.session-fork", t.assertCurrent, t.operatorAuthority);
try {
const o = await e.admit("plugin-harness");
const s = resolveAdmittedRunActiveAssertion(o, t.opts?.abortSignal);
if (!s) throw new Error("Session fork admission is no longer active.");
s();
const c = await runBtwSessionFork({
params: {
...t,
agentId: i
},
modelRegistry: k,
runtimeModel: F,
auth: {
mode: N.mode,
authFlow: N.authFlow
},
apiKey: I,
resolvedAuthProfileId: P,
sessionId: n,
sessionFile: r,
workspaceDir: a,
assertCurrent: s
});
s();
return { text: c };
} finally {
e.close();
}
}
return runLightweightBtwStream({
params: t,
modelRegistry: k,
runtimeModel: F,
auth: {
mode: N.mode,
authFlow: N.authFlow
},
apiKey: I,
resolvedAuthProfileId: P,
sessionId: n,
workspaceDir: a,
imageLimits: p,
messages: m,
inFlightPrompt: h,
recordBtwUsage
});
});
}
//#endregion
export { runBtwSideQuestion as t };