openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
535 lines (534 loc) • 16.9 kB
JavaScript
import { a as asOptionalRecord } from "./record-coerce-CVPuDqcc.mjs";
import { o as racePromiseWithAbortSignal } from "./src-BPmQBLJp.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { t as AgentHarnessPreflightError } from "./errors-0Ou7CzqA.mjs";
import "./string-coerce-runtime-BwAZZDf5.mjs";
import { t as log } from "./logger-DgCpB-Fs.mjs";
import { i as buildCurrentInboundPrompt } from "./runtime-context-prompt-CRmsG0oC.mjs";
import { t as SessionManager } from "./session-manager-DuaaMI5O.mjs";
import { a as clearActiveEmbeddedRun, h as setActiveEmbeddedRun, v as resolveAgentHarnessBeforePromptBuildResult } from "./agent-harness-runtime-BCklzcv7.mjs";
import { a as createAgentHarnessAttemptLifecycle, c as emitAgentHarnessAttemptEvent, i as createAgentHarnessAttemptDeadlineController, l as resolveAgentHarnessHistoryLimits, r as createAgentHarnessAttemptCancellation, t as AgentHarnessProjectionSettlement } from "./agent-harness-attempt-runtime-DFFgKWgF.mjs";
import "./agent-sessions-C-CdVZCo.mjs";
import { t as createAgentsApiAttemptHooks } from "./agentsapi-attempt-hooks-CK5TzzPr.mjs";
import { t as AgentsApiClient } from "./agentsapi-client-BkGGOio6.mjs";
import { i as resolveAgentsApiSessionAccessError } from "./agentsapi-errors-ByxEsPsd.mjs";
import { i as uploadInputs, n as prepareInputs, r as prepareSelfHostedInputs, t as collectOutputs } from "./agentsapi-files-DVFvg2Ah.mjs";
import { t as buildAgentsApiMcpTools } from "./agentsapi-mcp-CLo_Gpkq.mjs";
import { n as bindAgentsApiTranscriptAuthority, s as recordAgentsApiNativeHistory } from "./agentsapi-transcript-Cs7zhDPb.mjs";
import { t as AgentsApiMessageProjection } from "./agentsapi-messages-BD_RAWDn.mjs";
import { n as buildAgentsApiInstructions, r as buildAgentsApiTurnInput, t as HOSTED_ATTACHMENT_UPLOAD_UNAVAILABLE_FEEDBACK } from "./agentsapi-prompt-B7ib30z6.mjs";
import { t as resolveAgentsApiReasoningEffort } from "./agentsapi-reasoning-DM_CoYmp.mjs";
import { t as createAgentsApiSession } from "./agentsapi-session-DT7X3oBR.mjs";
import { t as buildAgentsApiToolSurface } from "./agentsapi-tools-_fFoDUTB.mjs";
import { i as resolveAgentsApiNativeToolPolicy, n as requireAgentsApiSessionFingerprint, r as resolveAgentsApiEnvironment, t as agentsApiConfigSchema } from "./config-ClWEtS9v.mjs";
//#region extensions/agentsapi/agentsapi-attempt.ts
async function runAgentsApiAttempt(e, t, n, r, i, a, o, s, c) {
const l = Date.now();
const u = performance.now();
const d = {
explicitCancellationObserved: false,
terminalOutcomeFrozen: false,
sharedAbortAllowedAfterTerminalOutcome: false
};
const f = createAgentHarnessAttemptCancellation({
upstreamSignal: e.abortSignal,
onAttemptAbort: e.onAttemptAbort,
state: d
});
const { controller: p } = f;
const m = bindAgentsApiTranscriptAuthority(r, p.signal);
let h = false;
let g;
const assertProjectionCurrent = () => {
r();
if (h) g?.throwIfAborted();
else p.signal.throwIfAborted();
};
let _;
let v = false;
const y = e.observeToolTerminal;
const b = y ? {
...e,
observeToolTerminal: (e) => {
assertProjectionCurrent();
const t = y(e);
assertProjectionCurrent();
v = true;
_ = t.lastToolError;
return t;
}
} : e;
let x;
let S;
let C;
let w = false;
let T;
const E = createAgentHarnessAttemptDeadlineController({
startedAtMs: l,
startedAtMonotonicMs: u,
timeoutMs: e.timeoutMs,
settlementTimeoutMs: 3e4,
signal: p.signal,
onDeadlineChanged: (t) => {
if (w && t.kind === "bounded") T = t.deadlineAtMs;
e.onAttemptDeadlineChanged?.(t);
},
onTimeout: (t) => {
x = t;
const n = /* @__PURE__ */ new Error(`Agents API ${t.kind} timed out`);
e.onAttemptTimeout?.(n);
f.abortExplicitly(n);
}
});
const beginSettlement = () => {
S?.dispose();
w = true;
E.beginSettlement(Date.now());
};
const emitEvent = (t) => emitAgentHarnessAttemptEvent(e, t, {
label: "Agents API",
log
});
const D = createAgentHarnessAttemptLifecycle({
attempt: e,
backend: "agentsapi",
startedAtMs: l,
state: {
lifecycleStarted: false,
lifecycleTerminalEmitted: false
},
emitEvent
});
const O = createAgentsApiAttemptHooks(e, a.agentId, l);
let k;
let A = t?.sessionId;
const logNativeSession = (t) => log.info(t, {
runId: e.runId,
sessionId: e.sessionId,
nativeSessionId: A?.slice(0, 128)
});
const logFailure = (t, n) => log.warn(t, {
error: formatErrorMessage(n),
runId: e.runId,
sessionId: e.sessionId,
nativeSessionId: A
});
const saveBinding = async (t) => {
await n(t);
logNativeSession("Agents API native session bound");
c?.(t, e.resolvedApiKey);
};
let j = { kind: "ok" };
let M;
let N;
let P = false;
let F = false;
const I = new AgentHarnessProjectionSettlement(b, () => {
if (F || p.signal.aborted) return false;
try {
r();
return true;
} catch {
return false;
}
}, { label: "Agents API" });
let L;
const R = [];
let z;
let B;
let V = 0;
let H = 0;
const U = {
kind: "embedded",
toolAuthorityFingerprint: e.toolAuthorityFingerprint,
sourceReplyDeliveryMode: e.sourceReplyDeliveryMode,
taskSuggestionDeliveryMode: e.taskSuggestionDeliveryMode,
supportsTranscriptCommitWait: true,
runId: e.runId,
startedAtMs: l,
queueMessage: async (e, t) => {
m();
if (!k?.isAvailable()) throw new Error("Agents API turn is not ready for steering");
if (t?.images?.length || t?.media?.length) throw new Error("Agents API attachments require a separate turn");
await k.queueMessage(buildCurrentInboundPrompt({
context: t?.currentInboundContext,
prompt: e
}), async () => {
await t?.userTurnTranscriptRecorder?.persistApproved();
});
t?.userTurnTranscriptRecorder?.markSentToProvider?.();
},
isStreaming: () => k?.isAvailable() ?? false,
isStopped: () => p.signal.aborted || (k?.isSettled() ?? false),
isAborted: () => p.signal.aborted,
isCompacting: () => false,
abort: () => f.abortExplicitly(/* @__PURE__ */ new Error("Agents API turn interrupted")),
cancel: () => f.abortExplicitly(/* @__PURE__ */ new Error("Agents API turn interrupted"))
};
let W;
try {
W = setActiveEmbeddedRun(e.sessionId, U, e.sessionKey, e.sessionFile, e.agentId);
m();
logNativeSession("Agents API attempt started");
if (t) c?.(t, e.resolvedApiKey);
const n = agentsApiConfigSchema.parse(o() ?? {});
const { webSearchEnabled: l, nativeTools: u } = resolveAgentsApiNativeToolPolicy(e, n);
const d = resolveAgentsApiEnvironment(n, e.workspaceDir);
const f = n.forwarding.gatewayTools ? await buildAgentsApiToolSurface(b, p.signal, m, (e) => R.push(e)) : void 0;
z = f;
const g = f?.declarations ?? [];
const _ = n.forwarding.mcpServers ? await buildAgentsApiMcpTools(e) : [];
m();
const v = requireAgentsApiSessionFingerprint({
existingFingerprint: t?.configFingerprint,
model: e.model.id,
environment: d,
mcpTools: _,
webSearchEnabled: l,
forwarding: n.forwarding
});
const y = d.type === "openai_hosted" && e.hostCapabilities.resolveInputAttachmentMedia ? await e.hostCapabilities.resolveInputAttachmentMedia() : e.media;
m();
const x = d.type === "openai_hosted" ? await prepareInputs(y, e.workspaceDir, m, p.signal) : await prepareSelfHostedInputs(e, m, p.signal);
const w = new AgentsApiClient(e.resolvedApiKey, r);
const T = resolveAgentsApiReasoningEffort(e);
const E = !A;
const F = E ? await buildAgentsApiInstructions(e, g, d) : "";
m();
const G = e.userTurnTranscriptRecorder;
const K = G?.message ?? await G?.resolveMessage();
m();
const q = resolveAgentHarnessHistoryLimits(e.contextWindowInfo?.tokens ?? e.contextTokenBudget);
const J = JSON.stringify([
e.runId,
a.agentId,
a.sessionId,
a.sessionKey,
a.storePath,
e.workspaceDir,
q
]);
let Y;
const X = await resolveAgentHarnessBeforePromptBuildResult({
prompt: e.prompt,
currentInboundContext: e.currentInboundContext,
currentUserMessage: K ?? e.prompt,
developerInstructions: F,
messages: async () => {
m();
const t = G && s.get(G);
if (t?.scope === J && t.nativeSessionId === A) return t.messages;
if (G) s.delete(G);
const n = await SessionManager.openModelContextAsync(a, {
cwd: e.workspaceDir,
admission: G?.getAdmissionReceipt(),
signal: p.signal,
limits: q
});
m();
Y = n.buildSessionContext().messages;
return Y;
},
ctx: O.hookContext,
bootstrapContextRunKind: e.bootstrapContextRunKind,
toolAuthority: {
fingerprint: e.toolAuthorityFingerprint,
activeToolNames: () => g.map((e) => e.name),
assertActive: m
}
});
m();
S = createAgentHarnessAttemptDeadlineController({
startedAtMs: Date.now(),
startedAtMonotonicMs: performance.now(),
timeoutMs: 12e4,
settlementTimeoutMs: 3e4,
signal: p.signal,
onTimeout: () => {
const e = "Agents API startup stalled for 120 seconds without a native event. Inspect the native session or use /reset to settle it before starting fresh; if reset fails, resolve the native service failure and retry reset. OpenClaw will not replace the native session automatically.";
C = new AgentHarnessPreflightError(e, { userMessage: e });
p.abort(C);
}
});
if (!A) {
A = await w.create(p.signal, X.developerInstructions, e.model.id, {
nativeTools: u,
functions: g,
mcpTools: _,
files: x.files,
environment: d,
reasoning: {
effort: T,
...e.reasoningLevel && e.reasoningLevel !== "off" ? { summary: "auto" } : {}
}
});
m();
await saveBinding({
sessionId: A,
configFingerprint: v
});
} else await w.setReasoningEffort(A, T, p.signal);
m();
if (G && Y) s.set(G, {
scope: J,
nativeSessionId: A,
messages: Y
});
if (!E && x.files.length) {
if ((await uploadInputs(w, A, x.files, m, p.signal)).status === "unavailable") {
x.mappingText = "";
x.feedbackText = [x.feedbackText, HOSTED_ATTACHMENT_UPLOAD_UNAVAILABLE_FEEDBACK].filter(Boolean).join("\n");
}
}
N = new AgentsApiMessageProjection(I.params, A, async (e) => {
m();
await emitEvent(e);
m();
}, assertProjectionCurrent);
M = N.reply;
k = createAgentsApiSession({
client: w,
cleanupClient: new AgentsApiClient(e.resolvedApiKey, i),
sessionId: A,
signal: p.signal,
assertCurrent: m,
onSettled: beginSettlement,
onReconcile: (e, t) => N.reconcile(e, t, { presentation: !h }),
onUsageError: (e) => logFailure("Agents API token accounting unavailable", e),
onTranscriptOrderingGap: () => N.reportTranscriptOrderingGap(),
onReconcileHistory: (e) => recordAgentsApiNativeHistory(b, A, e, assertProjectionCurrent),
executeFunction: async (e) => {
m();
if (!f) throw new Error(`Agents API Gateway tool forwarding is disabled; refusing remote function call: ${e.name}`);
V++;
await emitEvent({
stream: "tool",
data: {
phase: "start",
name: e.name,
toolCallId: e.call_id,
args: asOptionalRecord(e.arguments)
}
});
m();
const t = await f.execute(e);
m();
N.recordGatewayTranscriptReceipt(e.turn_id, e.call_id);
return t;
},
onFunctionResult: async (e, t) => {
H++;
await emitEvent({
stream: "tool",
data: {
phase: "result",
name: e.name,
toolCallId: e.call_id,
isError: !t.success,
result: { content: [{
type: "text",
text: t.success ? t.output : t.error
}] }
}
});
m();
},
onEvent: async (t) => {
await N.observe(t);
m();
S?.dispose();
e.onRunProgress?.({
reason: t.type,
provider: "openai",
model: e.model.id,
backend: "agentsapi"
});
}
});
D.emitLifecycleStart({
provider: "openai",
model: e.model.id
});
const Z = await buildAgentsApiTurnInput(e, g, X.prompt, x.mappingText, d.type, m, x.feedbackText);
m();
const Q = await k.run(Z, async () => {
await e.userTurnTranscriptRecorder?.persistApproved();
}, () => e.userTurnTranscriptRecorder?.markSentToProvider?.());
L = Q.turn.id;
const $ = await k.readUsageTurns();
m();
N.recordUsage(e.model, $);
P = true;
e.hostCapabilities.reportOutputTokens?.(M.usage?.output ?? 0);
if (Q.cancelled) j = {
kind: "aborted",
source: "runtime"
};
else if (Q.terminatedByTool) {
await N.commitUsage(Q.turn);
m();
} else {
const t = await w.items(A, Q.turn.id, p.signal);
m();
try {
if (d.type === "openai_hosted") B = await collectOutputs(w, A, Q.turn.id, m, p.signal, e.hostCapabilities.prepareReplyMedia);
} finally {
await N.commit(Q.turn, t);
m();
}
}
} catch (t) {
j = C ? {
kind: "failed",
source: "prompt",
error: C
} : x ? {
kind: "timeout",
phase: "prompt",
source: "runtime",
aborted: true
} : e.abortSignal?.aborted ? {
kind: "aborted",
source: "external"
} : d.explicitCancellationObserved ? {
kind: "aborted",
source: "runtime"
} : {
kind: "failed",
source: "prompt",
error: t
};
if (j.kind === "failed") logFailure("Agents API session failed", t);
} finally {
beginSettlement();
const t = Math.max(0, Math.min(3e4, (T ?? Date.now() + 3e4) - Date.now()));
const n = t > 0 ? AbortSignal.timeout(t) : AbortSignal.abort(/* @__PURE__ */ new Error("Agents API settlement timed out"));
try {
await k?.close();
} catch (e) {
logFailure("Agents API native cleanup failed", e);
j = {
kind: "failed",
source: "prompt",
error: e
};
}
try {
if (k && N && !P) {
const t = await k.readUsageTurns();
i();
N.recordUsage(e.model, t);
}
} catch (e) {
logFailure("Agents API usage recording failed", e);
j = {
kind: "failed",
source: "prompt",
error: e
};
}
if ((p.signal.aborted || j.kind !== "ok") && k && N) {
let e = false;
try {
r();
e = true;
} catch {}
if (e) {
h = true;
g = n;
try {
await k.reconcileAfterClose(n);
} catch (e) {
logFailure("Agents API terminal history reconciliation failed", e);
} finally {
h = false;
g = void 0;
}
}
}
try {
await racePromiseWithAbortSignal(I.drain(), n);
} catch (e) {
logFailure("Agents API projection settlement failed", e);
if (!p.signal.aborted) j = {
kind: "failed",
source: "prompt",
error: e
};
}
F = true;
if (C) j = {
kind: "failed",
source: "prompt",
error: C
};
else if (x) j = {
kind: "timeout",
phase: "prompt",
source: "runtime",
aborted: true
};
else if (j.kind === "ok" && p.signal.aborted) j = {
kind: "aborted",
source: e.abortSignal?.aborted ? "external" : "runtime"
};
f.freezeTerminalOutcome();
E.dispose();
f.dispose();
p.abort();
for (const e of R.toReversed()) try {
await e("Agents API attempt settled");
} catch (e) {
logFailure("Agents API tool cleanup failed", e);
}
clearActiveEmbeddedRun(e.sessionId, U, e.sessionKey, e.sessionFile, void 0, W);
D.emitLifecycleTerminal({ phase: j.kind === "failed" ? "error" : "end" });
}
if (j.kind === "failed") j = {
...j,
error: resolveAgentsApiSessionAccessError(j.error, A)
};
const G = {
terminal: j,
sessionIdUsed: e.sessionId,
sessionFileUsed: e.sessionFile,
agentHarnessId: "agentsapi",
messagesSnapshot: (await SessionManager.openAsync(a, e.workspaceDir)).buildSessionContext().messages,
assistantTexts: M?.lastAssistant?.content.filter((e) => e.type === "text").map((e) => e.text) ?? [],
lastAssistant: M?.lastAssistant,
currentAttemptAssistant: M?.lastAssistant,
currentAttemptCompletedAssistant: M?.lastAssistant,
assistantTranscriptOwned: Boolean(M?.lastAssistant),
assistantTranscriptIdempotencyKey: M?.lastAssistant && L ? `agentsapi:${A}:${L}` : void 0,
toolMetas: [...N?.toolMetas ?? [], ...z?.toolMetas ?? []],
lastToolError: v ? _ : z?.lastToolError ?? N?.lastToolError,
...z?.runtimeFacts,
didSendViaMessagingTool: false,
messagingToolSentTexts: [],
messagingToolSentMediaUrls: [],
messagingToolSentTargets: [],
...z?.delivery,
...B && {
hostOwnedToolMediaUrls: [...B],
toolMediaUrls: [.../* @__PURE__ */ new Set([...z?.delivery.toolMediaUrls ?? [], ...B])],
toolTrustedLocalMedia: B.length && !z?.delivery.toolMediaUrls?.length ? true : z?.delivery.toolTrustedLocalMedia
},
cloudCodeAssistFormatError: false,
attemptUsage: N?.tokenUsage,
agentHarnessResultClassification: N?.resultClassification,
replayMetadata: {
hadPotentialSideEffects: k?.wasSubmitted() ?? false,
replaySafe: !k?.wasSubmitted()
},
itemLifecycle: {
startedCount: V + (N?.itemLifecycle.startedCount ?? 0),
completedCount: H + (N?.itemLifecycle.completedCount ?? 0),
activeCount: Math.max(0, V - H) + (N?.itemLifecycle.activeCount ?? 0)
}
};
i();
await O.complete(G);
return G;
}
//#endregion
export { runAgentsApiAttempt as t };