openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
737 lines (736 loc) • 25.6 kB
JavaScript
import { o as racePromiseWithAbortSignal } from "./src-BPmQBLJp.mjs";
import "./abort-signal-D4Q6SEw7.mjs";
import { l as trackAsyncWork } from "./async-work-scope-BXagjUap.mjs";
import { _ as resolveDefaultAgentId, a as resolveAgentDir, f as resolveAgentWorkspaceDir } from "./agent-scope-config-DmXgFGKP.mjs";
import { n as createQueuedDiagnosticPhaseEmitter, p as isDiagnosticsEnabled, s as emitTrustedDiagnosticEvent } from "./diagnostic-events-BjAH1Kbx.mjs";
import { d as normalizeUsage, f as toDiagnosticUsage, s as hasObservedModelUsage } from "./usage-CHLnzpJG.mjs";
import { n as resolvePreferredOpenClawTmpDir } from "./tmp-openclaw-dir-Bf0oU1Cn.mjs";
import { r as scheduleAbsoluteDeadline } from "./absolute-deadline-kK4DcdPs.mjs";
import "./agent-scope-BwB8YH6y.mjs";
import { n as withPluginRuntimeGenerationScope } from "./generation-scope-Cq7RLFex.mjs";
import { o as resolveCliBackendConfig } from "./cli-backends-B8PrIwPC.mjs";
import { f as prepareSystemAgentRunAdmission, i as bindOperatorModelExecution, r as assertOperatorModelAllowed } from "./admitted-run-context-D3Jvk_f_.mjs";
import { n as recordModelFallbackStop } from "./model-fallback-stop-BN_k3Te_.mjs";
import { r as listModelCatalogObservedRoutes, t as createModelCatalogSnapshotView } from "./model-catalog-view-CsclLtvK.mjs";
import { n as estimateAggregateUsageCost } from "./usage-format-BisQoUIV.mjs";
import { i as ensureAuthProfileStoreAsync } from "./store-runtime-dW0pXLJI.mjs";
import { A as readAdmittedPublishedModelCatalog, a as acquireReadOnlyPreparedModelRuntime, t as acquireAgentRunPreparedModelRuntime } from "./prepared-model-runtime-Bbo9uBdt.mjs";
import { i as unwrapSecretSentinelsForProviderEgress, r as unwrapModelHeaderSentinelsForProviderEgress } from "./provider-secret-egress-DZ6iOD2F.mjs";
import { a as reconcileAuthProfileQuotaBlocks } from "./usage-wMHUW27k.mjs";
import { t as runWithAsyncWorkResources } from "./async-work-resources-BF09U4aO.mjs";
import { n as isTerminalAssistantError } from "./retry-B3fOvo7T.mjs";
import { n as classifyAssistantFailoverReason, t as buildAssistantFailoverSignal } from "./assistant-message-failures-Cv3Qnsh5.mjs";
import "./model-auth-CEsyk_Yg.mjs";
import { t as ensureSelectedAgentHarnessPlugin } from "./runtime-plugin-Cug3vi2h.mjs";
import { n as resolveModelAsync } from "./model-BmrpLWB9.mjs";
import { i as preparedAgentRuntimeProfileAttemptHasCandidate, n as canRunPreparedAgentRuntimeAuthAttempt, r as prepareAgentRuntimeAuth } from "./prepare-auth-Ck7RPVAG.mjs";
import { a as selectIsolatedHarnessAuthAttempt, n as resolveIsolatedCompletionProvider, r as resolveIsolatedCompletionRoute, t as resolveIsolatedCompletionAuthorizationOwner } from "./isolated-completion-route-BoVdyMf9.mjs";
import { o as requiredWorkerHelperError } from "./required-worker-profile-BtG0rBjX.mjs";
import { t as materializePreparedRuntimeModel } from "./materialize-model-DK894Ocx.mjs";
import { r as scopeAuthProfileStoreToPreparedPlan } from "./resolve-auth-Cds1OOn0.mjs";
import { i as prepareSimpleCompletionModel } from "./simple-completion-runtime-DzeSgPc1.mjs";
import { a as normalizeCliModel } from "./helpers-aqu9cn2k.mjs";
import path from "node:path";
import { randomUUID } from "node:crypto";
import { performance } from "node:perf_hooks";
import { withTempWorkspace } from "@openclaw/fs-safe/temp";
import { adjustMaxTokensForThinking } from "@openclaw/ai/internal/shared";
//#region src/agents/isolated-completion-diagnostics.ts
/** Plugin completions finalize usage with host-plugin attribution; core callers have no other path. */
function emitIsolatedCompletionUsage(e) {
const { config: t, result: n } = e;
if (e.purpose === "plugin-completion" || !isDiagnosticsEnabled(t)) return;
const r = normalizeUsage(n?.diagnosticUsage ?? n?.usage);
const i = hasObservedModelUsage(r) && r.usageReport?.state !== "unavailable";
const a = n?.provider ?? e.provider;
const o = n?.model ?? e.model;
emitTrustedDiagnosticEvent({
type: "model.usage",
agentId: e.agentId,
provider: a,
model: o,
purpose: e.purpose ?? "isolated-completion",
runtimeKind: e.runtimeKind,
completionId: e.completionId,
attemptId: e.attemptId,
sessionId: e.sessionId,
sessionKey: e.sessionKey,
usageReport: i ? r.usageReport : { state: "unavailable" },
usage: i ? toDiagnosticUsage(r) : {},
...i ? { costUsd: estimateAggregateUsageCost({
usage: r,
provider: a,
model: o,
config: t,
agentDir: e.agentDir
}) } : {}
});
}
/** Account for a dispatched attempt even when its result is rejected or its caller has retired. */
async function observeIsolatedCompletionUsage(e, t, n) {
const r = randomUUID();
let i = false;
const observe = (t) => {
if (i) return;
i = true;
try {
emitIsolatedCompletionUsage({
...e,
attemptId: r,
...t === void 0 ? {} : { result: n(t) }
});
} catch {}
};
try {
const e = await t(observe);
observe(e);
return e;
} finally {
observe();
}
}
/** Measure runtime dispatch, not provider-wire inference or an inferred queue wait. */
function createIsolatedCompletionDiagnostics(e) {
const t = createQueuedDiagnosticPhaseEmitter();
if (!t) return;
const { purpose: n, provider: r, model: i } = e;
const a = Date.now();
const o = performance.now();
let s = e.config;
let c;
let l;
let u = 0;
let d = 0;
let f = o;
let p = "error";
return {
setConfig(e) {
s = e;
},
dispatch(e, t) {
c = e;
const n = performance.now();
l ??= n;
d++;
const finish = () => {
u += performance.now() - n;
};
try {
return t().finally(finish);
} catch (e) {
finish();
throw e;
}
},
complete(e) {
f = performance.now();
p = e;
},
settle(e) {
if (!isDiagnosticsEnabled(s)) return;
try {
const s = performance.now();
t({
name: "isolated-completion",
startedAt: a,
endedAt: Date.now(),
durationMs: s - o,
details: {
purpose: n ?? "isolated-completion",
provider: r,
model: i,
...c ? { runtimeKind: c } : {},
outcome: p,
settlementOutcome: e,
attempts: d,
initialPreparationMs: (l ?? f) - o,
runtimeDurationMs: u,
resultDurationMs: f - o,
settlementDurationMs: s - f
}
});
} catch {}
}
};
}
//#endregion
//#region src/agents/isolated-completion-model-authority.ts
function resolveIsolatedStreamParams({ answerTokenBudget: e, streamParams: t, thinkLevel: n }, r) {
let i = e ?? t?.maxTokens;
if (i === void 0) return t;
const a = r?.maxTokens ?? Number.POSITIVE_INFINITY;
if (e !== void 0 && r?.reasoning && n !== "off") i = adjustMaxTokensForThinking(e, a, "medium").maxTokens;
return {
...t,
maxTokens: Math.min(i, a, t?.maxTokens ?? i)
};
}
function prepareIsolatedHostAuthorization(e, t) {
if (e.id === "openclaw") return t;
const n = "plugin harness isolated completion handoff";
const r = t.auth.apiKey ? unwrapSecretSentinelsForProviderEgress(t.auth.apiKey, n) : t.auth.apiKey;
const i = unwrapModelHeaderSentinelsForProviderEgress(t.model, n);
if (r === t.auth.apiKey && i === t.model) return t;
return {
...t,
model: i,
auth: {
...t.auth,
apiKey: r
}
};
}
/** A completion keeps its selected-model fence through the runtime's physical cleanup. */
function createIsolatedCompletionModelAuthority(e) {
const t = new AsyncDisposableStack();
let n;
return {
bind(r) {
e.assertCurrent();
if (!n || n.model?.provider !== r?.provider || n.model?.model !== r?.model) {
const i = bindOperatorModelExecution(e.operatorAuthority, r, e.mapOperatorAuthorizationError);
if (!i) return {};
t.defer(i.release);
n = {
model: r ? { ...r } : void 0,
execution: i
};
}
const { execution: i } = n;
i.assertCurrent();
return {
abortSignal: e.abortSignal ? AbortSignal.any([e.abortSignal, i.signal]) : i.signal,
assertCurrent: () => {
e.assertCurrent();
i.assertCurrent();
}
};
},
async release() {
try {
await e.runtime[Symbol.asyncDispose]();
} finally {
await t.disposeAsync();
}
}
};
}
//#endregion
//#region src/agents/isolated-completion-output.ts
var IsolatedCompletionError = class extends Error {
constructor(e, t, n) {
super(t, n);
this.name = "IsolatedCompletionError";
this.code = e;
}
};
function requireIsolatedAssistantText(e) {
if (e.stopReason !== "stop" && e.stopReason !== "length") {
const t = new IsolatedCompletionError("output-rejected", e.errorMessage?.trim() || `Isolated completion failed with stop reason ${e.stopReason}.`, e.stopReason === "error" && !isTerminalAssistantError(e) || e.stopReason === "aborted" ? { cause: buildAssistantFailoverSignal(e) } : void 0);
if (isTerminalAssistantError(e)) recordModelFallbackStop(t);
throw t;
}
const t = [];
for (const n of e.content) {
if (n.type === "text") {
t.push(n.text);
continue;
}
if (n.type === "thinking") continue;
throw new IsolatedCompletionError("output-rejected", "Isolated completion returned a tool call; the result was rejected.");
}
return t.join("").trim();
}
/** Account quota failures can rotate; terminal or tool-bearing output cannot be replayed. */
function isRetryableIsolatedQuotaFailure(e) {
const t = classifyAssistantFailoverReason(e);
return (t === "rate_limit" || t === "billing") && e.content.every((e) => e.type === "text" || e.type === "thinking");
}
//#endregion
//#region src/agents/isolated-completion.ts
/**
* Fresh, prompt-only inference through the selected runtime.
*
* This operation deliberately bypasses the ordinary agent attempt, retry,
* transcript, hook, and delivery lifecycle. Execution owners either prove a
* literal empty native tool surface or fail before inference starts, except
* Agents API: its restricted sessions may retain service-owned helpers.
*/
/** Run one fresh completion with the selected runtime's documented isolation boundary. */
async function runIsolatedCompletion(e) {
const t = performance.now() + e.timeoutMs;
const n = createIsolatedCompletionDiagnostics(e);
const r = e.abortSignal;
const i = new AbortController();
const a = r ? AbortSignal.any([r, i.signal]) : i.signal;
const expire = () => i.abort(e.timeoutError ?? new IsolatedCompletionError("runtime-unavailable", "Isolated completion timed out."));
const remainingTimeoutMs = () => {
const e = t - performance.now();
if (e <= 0 && !a.aborted) expire();
a.throwIfAborted();
return Math.ceil(e);
};
const o = scheduleAbsoluteDeadline(t, expire, () => performance.now());
return await runWithAsyncWorkResources(async (t, i) => {
let o;
t({ release: async () => {
let e = "error";
try {
await o?.();
e = "completed";
} finally {
n?.settle(e);
}
} });
try {
const t = await racePromiseWithAbortSignal(() => trackAsyncWork(() => runIsolatedCompletionOwned({
...e,
abortSignal: a
}, (e) => {
o = e.release;
}, i, n, remainingTimeoutMs)), a, (e) => e.reason);
remainingTimeoutMs();
n?.complete("completed");
return t;
} catch (e) {
n?.complete(r?.aborted ? "aborted" : "error");
throw e;
}
}).finally(o);
}
async function runIsolatedCompletionOwned(e, t, n, r, i) {
const a = {
...e,
streamParams: e.streamParams && { ...e.streamParams }
};
const o = randomUUID();
const s = a.config ?? {};
const c = a.agentId ?? resolveDefaultAgentId(s);
const l = a.agentDir ?? resolveAgentDir(s, c);
const u = a.workspaceDir ?? resolveAgentWorkspaceDir(s, c);
const { provider: d, runtimeOverride: f } = resolveIsolatedCompletionProvider({
provider: a.provider,
config: s,
agentHarnessRuntimeOverride: a.agentHarnessRuntimeOverride
});
let p = false;
let m = {
provider: d,
model: a.model
};
const assertCurrent = () => {
if (p) throw new IsolatedCompletionError("runtime-unavailable", "Isolated completion has ended.");
a.assertCurrent?.();
try {
assertOperatorModelAllowed(a.operatorAuthority, m);
} catch (e) {
throw a.mapOperatorAuthorizationError?.(e) ?? e;
}
i();
};
const resolveAuthorizedModel = async (...e) => {
const t = await resolveModelAsync(...e);
if (t.model) {
m = t.logicalRef;
assertCurrent();
}
return t;
};
assertCurrent();
const h = a.preparedModelRuntimeMode === "isolated-read-only";
const g = await (h ? acquireReadOnlyPreparedModelRuntime : acquireAgentRunPreparedModelRuntime)({
config: s,
agentId: c,
agentDir: l,
workspaceDir: u,
preserveWorkspaceDirOnRefresh: a.workspaceDir !== void 0,
runtimePluginPurpose: "isolated-completion",
...h ? { loadRuntimePlugins: true } : {}
}, {
catalogMode: "static",
abortSignal: a.abortSignal,
deriveRuntimePluginSelections: () => [{
provider: d,
modelId: a.model,
...f ? { runtime: f } : {},
agentId: c
}]
});
const _ = createIsolatedCompletionModelAuthority({
operatorAuthority: a.operatorAuthority,
mapOperatorAuthorizationError: a.mapOperatorAuthorizationError,
abortSignal: a.abortSignal,
assertCurrent,
runtime: g
});
t({ release: () => _.release() });
r?.setConfig(g.snapshot.config);
try {
assertCurrent();
const run = async () => {
n();
const e = {
config: g.snapshot.config,
agentId: c,
agentDir: g.snapshot.agentDir,
workspaceDir: g.snapshot.workspaceDir ?? u
};
const { config: t, agentDir: s, workspaceDir: l } = e;
const p = {
config: t,
agentId: c,
agentDir: s,
provider: d,
model: a.model,
purpose: a.purpose,
completionId: o,
sessionId: a.sessionId,
sessionKey: a.sessionKey
};
const h = requiredWorkerHelperError(t);
if (h) throw new IsolatedCompletionError("unsupported", h.error);
const v = {
...a,
...e,
assertCurrent
};
await ensureSelectedAgentHarnessPlugin({
provider: d,
modelId: v.model,
...e,
agentHarnessRuntimeOverride: f,
pluginRegistry: g.snapshot.pluginRegistry
});
assertCurrent();
const { selection: y, cliOwner: b } = await resolveIsolatedCompletionRoute({
provider: d,
model: v.model,
authProfileId: v.authProfileId,
runtimeOverride: f,
explicitRuntimeOverride: v.agentHarnessRuntimeOverride,
...e
});
if (b) return await withTempWorkspace({
rootDir: resolvePreferredOpenClawTmpDir(),
prefix: "openclaw-isolated-completion-"
}, async ({ dir: e }) => {
const { runCliAgent: n } = await import("./cli-runner.runtime.js");
v.assertCurrent?.();
const { cliBackendAcceptsAuthProfileForwarding: a, resolveCliExecutionAuthProfileId: o } = await import("./cli-execution-auth-DKYcEhe_.mjs");
v.assertCurrent?.();
const s = a({
provider: b,
config: v.config,
agentId: v.agentId
}) ? await o({
cliExecutionProvider: b,
authProfileProvider: d,
config: v.config,
agentDir: v.agentDir,
selected: { authProfileId: v.authProfileId }
}) : v.authProfileId;
v.assertCurrent?.();
const l = `isolated-completion-${randomUUID()}`;
const u = prepareSystemAgentRunAdmission(t, l, v.agentId, "isolated-completion", v.assertCurrent, v.operatorAuthority);
try {
v.assertCurrent?.();
const execute = () => n({
preparedRunAdmission: u,
sessionId: l,
sessionFile: path.join(e, "session.json"),
workspaceDir: v.workspaceDir,
cwd: e,
agentDir: v.agentDir,
agentId: v.agentId,
config: t,
prompt: v.prompt,
extraSystemPrompt: v.systemPrompt,
timeoutMs: i(),
runId: l,
provider: b,
modelProvider: d,
requesterModel: {
provider: d,
model: v.model
},
model: v.model,
authProfileId: s,
thinkLevel: v.thinkLevel,
streamParams: resolveIsolatedStreamParams(v),
abortSignal: v.abortSignal,
assertCurrent: v.assertCurrent,
mapOperatorAuthorizationError: v.mapOperatorAuthorizationError,
executionMode: "side-question",
cliToolAvailability: {
native: [],
openClaw: []
},
disableTools: true,
disableCliLiveSession: true,
cleanupCliLiveSessionOnRunEnd: true,
cleanupBundleMcpOnRunEnd: true,
requireExplicitMessageTarget: true,
isolatedCompletion: true,
isolatedCompletionPurpose: v.purpose ?? "isolated-completion",
outputTextPolicy: v.outputTextPolicy
});
const dispatch = () => observeIsolatedCompletionUsage({
...p,
runtimeKind: "cli"
}, execute, (e) => {
const n = resolveCliBackendConfig(b, t, { agentId: c });
return {
provider: d,
model: n ? normalizeCliModel(v.model, n.config) : v.model,
usage: e.meta?.agentMeta?.usage,
diagnosticUsage: e.meta?.agentMeta?.diagnosticUsage
};
});
const a = await (r ? r.dispatch("cli", dispatch) : dispatch());
if (a.didSendViaMessagingTool || a.didDeliverSourceReplyViaMessageTool || a.messagingToolSentTexts?.length || a.messagingToolSentMediaUrls?.length || a.messagingToolSentTargets?.length || a.messagingToolSourceReplyPayloads?.length || a.acceptedSessionSpawns?.length || a.successfulCronAdds) throw new IsolatedCompletionError("output-rejected", "Isolated CLI completion returned side-effect evidence; result rejected.");
const o = a.payloads ?? [];
if (o.some((e) => e.isError || e.mediaUrl || e.mediaUrls?.length || e.audioAsVoice || e.channelData)) throw new IsolatedCompletionError("output-rejected", "Isolated CLI completion returned non-text output; result rejected.");
const f = o.filter((e) => !e.isReasoning && e.text !== void 0).map((e) => e.text ?? "").join("\n").trim();
const m = resolveCliBackendConfig(b, v.config, { agentId: v.agentId });
if (!m) throw new IsolatedCompletionError("runtime-unavailable", `CLI backend ${b} became unavailable after execution.`);
const { usage: h, diagnosticUsage: g } = a.meta?.agentMeta ?? {};
return {
text: f,
provider: d,
model: normalizeCliModel(v.model, m.config),
owner: {
kind: "cli",
id: b
},
...h ? { usage: h } : {},
...g ? { diagnosticUsage: g } : {}
};
} finally {
u.close();
}
});
const x = y.builtIn ? (await import("./builtin-openclaw-vkHGdrs-.mjs")).createOpenClawAgentHarness() : y.harness;
assertCurrent();
if (!x.runIsolatedCompletionV2 && !x.runIsolatedCompletion) throw new IsolatedCompletionError("unsupported", `Agent harness ${x.id} does not support isolated completion.`);
const S = {
provider: d,
modelId: v.model,
...e,
systemPrompt: v.systemPrompt,
prompt: v.prompt,
abortSignal: v.abortSignal,
assertCurrent,
thinkLevel: v.thinkLevel,
outputTextPolicy: v.outputTextPolicy,
onRequestComplete: v.onRequestComplete
};
const prepareHostAuthorization = async (e) => {
const n = await prepareSimpleCompletionModel({
cfg: t,
agentId: c,
provider: d,
modelId: v.model,
agentDir: s,
profileId: e,
allowMissingApiKeyModes: ["aws-sdk"],
allowBundledStaticCatalogFallback: true,
skipAgentDiscovery: true,
bindAuthOwner: true,
workspaceDir: l,
preparedModelRuntime: g.snapshot,
signal: v.abortSignal,
modelResolver: resolveAuthorizedModel
}, assertCurrent);
assertCurrent();
if ("error" in n) throw new Error(`Isolated completion preparation failed: ${n.error}`);
return {
owner: "host",
...n
};
};
let C;
if (x.runIsolatedCompletionV2) {
let n;
if (x.authBootstrap === "harness") {
const r = await resolveAuthorizedModel(d, v.model, s, t, {
abortSignal: v.abortSignal,
assertCurrent,
...g.snapshot.createStores(),
preparedModelRuntime: g.snapshot,
workspaceDir: l,
authProfileId: v.authProfileId,
skipAgentDiscovery: true,
allowBundledStaticCatalogFallback: true,
preferBundledStaticCatalogTransport: true
});
if (!r.model) throw new IsolatedCompletionError("runtime-unavailable", r.error ?? `Unknown isolated completion model ${d}/${v.model}.`);
const i = r.model;
assertCurrent();
const a = await ensureAuthProfileStoreAsync(s, {
profileId: v.authProfileId,
readOnly: true,
allowKeychainPrompt: false,
config: t
});
const o = readAdmittedPublishedModelCatalog(g.snapshot) ?? g.snapshot.modelCatalog;
const c = o && createModelCatalogSnapshotView(t, o).variantsOf({
provider: i.provider,
id: i.id
});
const u = {
provider: i.provider,
modelId: i.id,
...c ? { observedRoutes: listModelCatalogObservedRoutes(c) } : {
modelApi: i.api,
modelBaseUrl: i.baseUrl
},
...e,
env: process.env,
authProfileStore: a,
sessionAuthProfileId: v.authProfileId,
sessionAuthProfileSource: v.authProfileId ? "user" : void 0,
...v.authProfileId ? { allowAuthProfileFallback: false } : {},
harnessId: x.id,
harnessRuntime: x.id,
harnessAuthBootstrap: x.authBootstrap
};
await reconcileAuthProfileQuotaBlocks(u);
assertCurrent();
n = {
model: i,
store: a,
attempts: prepareAgentRuntimeAuth(u).attempts
};
}
const hasAuthCandidate = (e) => e?.kind !== "profile" || !n || preparedAgentRuntimeProfileAttemptHasCandidate({
attempt: e,
store: n.store,
modelId: n.model.id
});
let a;
let o = false;
for (const e of n?.attempts ?? [void 0]) {
assertCurrent();
const c = e && selectIsolatedHarnessAuthAttempt(e);
if (c && !canRunPreparedAgentRuntimeAuthAttempt({
attempt: c,
priorProfileAttempted: o
})) {
a ??= /* @__PURE__ */ new Error("Prepared direct auth requires a prior profile attempt.");
continue;
}
if (!hasAuthCandidate(c)) {
a ??= /* @__PURE__ */ new Error("Prepared runtime auth candidates are temporarily unavailable.");
continue;
}
try {
let e;
let a;
if (c && n && resolveIsolatedCompletionAuthorizationOwner(c.plan) === "harness") {
const r = c.plan;
const { model: i, store: o } = n;
a = await materializePreparedRuntimeModel({
plan: r,
provider: i.provider,
modelId: i.id,
model: i,
config: t,
workspaceDir: l,
metadataSnapshot: g.snapshot.metadataSnapshot,
resolveModel: ({ config: e, authProfileId: t, authProfileMode: n }) => resolveAuthorizedModel(i.provider, i.id, s, e, {
abortSignal: v.abortSignal,
assertCurrent,
modelIdSource: "selected",
preparedModelRuntime: g.snapshot,
workspaceDir: l,
authProfileId: t,
authProfileMode: n,
skipAgentDiscovery: true,
allowBundledStaticCatalogFallback: true
})
});
assertCurrent();
e = {
owner: "harness",
plan: r,
authProfileStore: scopeAuthProfileStoreToPreparedPlan(o, r)
};
} else {
e = await prepareHostAuthorization(c?.kind === "profile" ? c.profileId : v.authProfileId);
a = e.model;
}
if (!hasAuthCandidate(c)) throw new Error("Prepared runtime auth candidates are temporarily unavailable.");
assertCurrent();
const u = _.bind(m);
const dispatch = () => observeIsolatedCompletionUsage({
...p,
runtimeKind: "harness"
}, (t) => x.runIsolatedCompletionV2({
...S,
...u,
onResult: t,
timeoutMs: i(),
authorization: e.owner === "host" ? prepareIsolatedHostAuthorization(x, e) : e,
...v.outputSchema ? { outputSchema: v.outputSchema } : {},
streamParams: resolveIsolatedStreamParams(v, a)
}), (e) => e.assistant);
const d = r ? r.dispatch("harness", dispatch) : dispatch();
o ||= c?.kind === "profile";
const f = await d;
u.assertCurrent?.();
assertCurrent();
if (isRetryableIsolatedQuotaFailure(f.assistant)) requireIsolatedAssistantText(f.assistant);
C = f;
break;
} catch (e) {
assertCurrent();
a ??= e;
}
}
if (!C) throw a instanceof Error ? a : new Error("No prepared auth attempt succeeded.", { cause: a });
} else {
const e = await prepareHostAuthorization(v.authProfileId);
const t = {
...S,
streamParams: resolveIsolatedStreamParams(v, e.model),
model: e.model,
auth: e.auth,
sourceAuthFingerprint: e.sourceAuthFingerprint
};
assertCurrent();
const n = _.bind(m);
const dispatch = () => observeIsolatedCompletionUsage({
...p,
runtimeKind: "harness"
}, (e) => x.runIsolatedCompletion(prepareIsolatedHostAuthorization(x, {
...t,
...n,
onResult: e,
timeoutMs: i()
})), (e) => e.assistant);
C = await (r ? r.dispatch("harness", dispatch) : dispatch());
n.assertCurrent?.();
}
return {
text: requireIsolatedAssistantText(C.assistant),
provider: C.assistant.provider,
model: C.assistant.model,
owner: {
kind: "harness",
id: x.id
},
usage: C.assistant.usage
};
};
return await withPluginRuntimeGenerationScope(g.snapshot, async () => {
const e = await run();
assertCurrent();
if (!e.text && a.outputTextPolicy !== "strict-visible") throw new IsolatedCompletionError("output-rejected", "Isolated completion returned empty output.");
return e;
});
} finally {
p = true;
}
}
//#endregion
export { runIsolatedCompletion as t };