openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
310 lines (309 loc) • 9.75 kB
JavaScript
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { t as parseRetryAfterHeaderSeconds } from "./retry-after-6ZDJQmkr.mjs";
import { a as createProviderCredentialMatcher, m as readProviderJsonObjectResponse } from "./provider-http-errors-Dtgw3x-5.mjs";
import { o as getModelProviderRequestTransport } from "./provider-request-config-CCij-nof.mjs";
import { n as buildTimeoutAbortSignal } from "./fetch-timeout-D62KciOm.mjs";
import { c as shouldUseEnvHttpProxyForUrl } from "./proxy-env-CZP0dXDG.mjs";
import { o as withTrustedEnvProxyGuardedFetchMode } from "./fetch-guard-BLMw2n18.mjs";
import { t as validateDecisionBatchV2 } from "./validation-v2-60LJzO-m.mjs";
import "./string-coerce-runtime-BwAZZDf5.mjs";
import "./retry-runtime-DOUvdfOa.mjs";
import "./fetch-runtime-Dz-KqFMb.mjs";
import { h as resolveProviderHttpRequestConfig } from "./shared-CfcMLHIP.mjs";
import { n as fetchWithProviderHttpGuard } from "./provider-transport-dispatcher-pool-DIU5EVl7.mjs";
import "./provider-http-LcawLneq.mjs";
import "./decisions-Cw6RZ9do.mjs";
//#region src/plugin-sdk/decisions-openai-runtime.ts
const maxQuestions = 400;
const maxChoiceAlternatives = 255;
function text(e) {
return typeof e === "string" ? e : e === void 0 ? "" : JSON.stringify(e);
}
function questions(e) {
return Object.entries(e.questions).map(([e, t]) => {
const n = text(t.instructions);
if (t.type === "boolean") return {
type: "predicate",
name: e,
instructions: t.criteria ? `${n}\nTrue criterion: ${text(t.criteria.true)}\nFalse criterion: ${text(t.criteria.false)}` : n
};
if (t.type === "choice") return {
type: "choice",
name: e,
instructions: n,
choices: Object.entries(t.criteria).map(([e, t]) => ({
value: e,
description: text(t)
}))
};
if (t.type !== "score") throw new Error("Unsupported OpenAI decision question");
return {
type: "score",
name: e,
instructions: n,
levels: t.criteria.map((e, t) => ({
label: String(t),
description: text(e)
}))
};
});
}
function probability(e) {
return typeof e === "number" && Number.isFinite(e) && e >= 0 && e <= 1;
}
function parseResult(e, t) {
const n = Object.entries(e.questions);
if (typeof t.model !== "string" || !t.model || t.model.length > 256 || !Array.isArray(t.answers) || t.answers.length !== n.length) return {
status: "unavailable",
reason: "invalid-response"
};
const r = [];
for (const [e, [i, a]] of n.entries()) {
const n = t.answers[e];
if (!isRecord(n) || n.name !== i) return {
status: "unavailable",
reason: "invalid-response"
};
if (n.type === "refusal") {
r.push([i, {
type: "error",
code: "provider-error",
providerCode: "refusal"
}]);
continue;
}
if (a.type === "boolean") {
if (n.type !== "predicate" || !probability(n.probability)) return {
status: "unavailable",
reason: "invalid-response"
};
r.push([i, {
type: "boolean",
probabilityTrue: n.probability
}]);
continue;
}
if (a.type !== "choice" && a.type !== "score") return {
status: "unavailable",
reason: "invalid-response"
};
if (n.type !== a.type || !Array.isArray(n.probabilities) || typeof n.confidence !== "number" || !Number.isFinite(n.confidence)) return {
status: "unavailable",
reason: "invalid-response"
};
const o = a.type === "choice" ? Object.keys(a.criteria) : a.criteria.map((e, t) => String(t));
const s = /* @__PURE__ */ new Map();
for (const e of n.probabilities) {
const t = isRecord(e) ? e[a.type === "choice" ? "value" : "label"] : void 0;
if (!isRecord(e) || typeof t !== "string" || !o.includes(t) || s.has(t) || !probability(e.probability) || a.type === "score" && e.value !== Number(t)) return {
status: "unavailable",
reason: "invalid-response"
};
s.set(t, e.probability);
}
if (s.size !== o.length || ![...s.values()].some((e) => e > 0)) return {
status: "unavailable",
reason: "invalid-response"
};
if (a.type === "choice") {
if (typeof n.choice !== "string" || !s.has(n.choice)) return {
status: "unavailable",
reason: "invalid-response"
};
r.push([i, {
type: "choice",
choice: n.choice,
confidence: n.confidence,
probabilities: Object.fromEntries(s)
}]);
} else {
if (typeof n.score !== "number" || !Number.isFinite(n.score) || n.score < 0 || n.score > o.length - 1) return {
status: "unavailable",
reason: "invalid-response"
};
r.push([i, {
type: "score",
score: n.score,
confidence: n.confidence,
probabilities: o.map((e) => s.get(e))
}]);
}
}
const i = t.usage;
if (!isRecord(i) || typeof i.input_tokens !== "number" || !Number.isInteger(i.input_tokens) || i.input_tokens < 0 || typeof i.output_tokens !== "number" || !Number.isInteger(i.output_tokens) || i.output_tokens < 0) return {
status: "unavailable",
reason: "invalid-response"
};
return {
status: "ok",
result: {
model: t.model,
answers: Object.fromEntries(r),
usage: {
inputTokens: i.input_tokens,
outputTokens: i.output_tokens
}
}
};
}
/** Validate before transport or credential-scoped discovery. Malformed caller data still throws. */
function supportsOpenAIDecisionBatch(e, t) {
if (!validateDecisionBatchV2(e)) return false;
const n = Object.values(e.questions);
return (e.state.type === "text" || e.state.type === "json" || e.state.type === "image") && (t === void 0 || t === "auto") && n.length <= maxQuestions && n.every((e) => [
"boolean",
"choice",
"score"
].includes(e.type)) && n.every((e) => e.type !== "choice" || Object.keys(e.criteria).length <= maxChoiceAlternatives);
}
/** Execute typed Decisions with host-prepared auth and a provider-owned effective API prefix.
* Never selects credentials, collects conversation history, or falls back to chat. */
async function evaluateOpenAICompatibleDecision(e, t, n) {
t.signal.throwIfAborted();
if (!supportsOpenAIDecisionBatch(e, t.reasoning)) return {
status: "unavailable",
reason: "unsupported-input"
};
const r = t.auth;
if (r.mode !== "api-key" || !r.apiKey) return {
status: "unavailable",
reason: "credentials-unavailable"
};
const i = t.deadlineMonotonicMs - performance.now();
if (i <= 0) return {
status: "unavailable",
reason: "transport"
};
const { signal: a, cleanup: o } = buildTimeoutAbortSignal({
signal: t.signal,
timeoutMs: i,
operation: "OpenAI decision"
});
const s = a ?? t.signal;
let c;
const assertActive = () => {
s.throwIfAborted();
let e;
try {
e = t.isAdmissible();
} catch (e) {
c = { error: e };
throw e;
}
if (performance.now() >= t.deadlineMonotonicMs || !e) throw new Error("OpenAI decision is no longer admitted.");
};
try {
const i = getModelProviderRequestTransport(t.model);
const { baseUrl: a, headers: o, dispatcherPolicy: c, allowPrivateNetwork: l } = resolveProviderHttpRequestConfig({
baseUrl: n.baseUrl,
defaultBaseUrl: n.baseUrl,
defaultHeaders: {
...!i?.auth || i.auth.mode === "provider-default" ? { Authorization: `Bearer ${r.apiKey}` } : {},
"Content-Type": "application/json",
Accept: "application/json"
},
headers: t.model.headers,
request: i ? {
proxy: i.proxy,
tls: i.tls,
allowPrivateNetwork: i.allowPrivateNetwork
} : void 0,
provider: n.provider,
capability: "other",
transport: "http"
});
const u = `${a.replace(/\/$/, "")}/decisions`;
const d = {
url: u,
signal: s,
beforeRequest: assertActive,
maxRedirects: 0,
dispatcherPolicy: c,
policy: { allowPrivateNetwork: l },
init: {
method: "POST",
headers: o,
body: JSON.stringify({
model: n.modelId ?? t.model.id,
input: e.state.type === "image" ? [{
role: "user",
content: [...e.state.text ? [{
type: "input_text",
text: e.state.text
}] : [], {
type: "input_image",
image_url: e.state.dataUri
}]
}] : e.state.type === "text" ? e.state.text : JSON.stringify(e.state.value),
questions: questions(e)
})
}
};
const { response: f, release: p } = await fetchWithProviderHttpGuard(!c && shouldUseEnvHttpProxyForUrl(u) ? withTrustedEnvProxyGuardedFetchMode(d) : d);
try {
if (!f.ok) {
await f.body?.cancel();
if (f.status === 401 || f.status === 403) return {
status: "unavailable",
reason: "authentication"
};
if (f.status === 429) {
const e = parseRetryAfterHeaderSeconds(f.headers.get("retry-after"));
return {
status: "unavailable",
reason: "rate-limited",
...e === void 0 ? {} : { retryAfterMs: e * 1e3 }
};
}
return {
status: "unavailable",
reason: [
400,
413,
422
].includes(f.status) ? "unsupported-input" : "transport"
};
}
let n;
try {
n = await readProviderJsonObjectResponse(f, "OpenAI decision", {
maxBytes: 1048576,
signal: s,
requestHeaders: o
});
} catch {
s.throwIfAborted();
return {
status: "unavailable",
reason: "invalid-response"
};
}
assertActive();
const a = JSON.stringify(n);
if (a.includes(r.apiKey) || createProviderCredentialMatcher({
headers: o,
request: i,
configuredHeaderNames: Object.keys(t.model.headers ?? {}),
defaultAuthHeader: "Authorization",
defaultAuthPrefix: "Bearer "
})(a)) return {
status: "unavailable",
reason: "invalid-response"
};
return parseResult(e, n);
} finally {
await p();
}
} catch {
t.signal.throwIfAborted();
if (c) throw c.error;
return {
status: "unavailable",
reason: "transport"
};
} finally {
o();
}
}
//#endregion
export { supportsOpenAIDecisionBatch as n, evaluateOpenAICompatibleDecision as t };