UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

251 lines (250 loc) • 8.85 kB
import { a as asOptionalRecord } from "./record-coerce-CVPuDqcc.mjs"; import "./string-coerce-runtime-BwAZZDf5.mjs"; import { o as createAgentHarnessToolCallMessage, s as createAgentHarnessToolResultMessage } from "./agent-harness-attempt-runtime-DFFgKWgF.mjs"; import { g as withSessionTranscriptWrite, r as appendSessionTranscriptMessageByIdentityStrict, s as publishSessionTranscriptUpdateByIdentity } from "./session-transcript-runtime-Bmol1TH_.mjs"; import { i as agentsApiNativeToolOutput, n as agentsApiNativeToolDetails, r as agentsApiNativeToolOutcome, t as agentsApiNativeTool } from "./agentsapi-native-items-zUwQ9-AT.mjs"; import { t as requireAgentsApiSessionTarget } from "./agentsapi-target-C7MYo4WF.mjs"; //#region extensions/agentsapi/agentsapi-transcript.ts function bindAgentsApiTranscriptAuthority(e, t) { const assertCurrent = () => { e(); t.throwIfAborted(); }; const n = e.prepareSessionSource; return n ? Object.assign(assertCurrent, { async prepareSessionSource() { const e = await n(); return { ...e, assertCurrent: () => { e.assertCurrent(); t.throwIfAborted(); }, assertPreparedCurrent: () => { (e.assertPreparedCurrent ?? e.assertCurrent)(); t.throwIfAborted(); } }; } }) : assertCurrent; } /** Canonical native facts use the same durable identities during live and historical repair. */ async function recordAgentsApiNativeToolTranscript(e, t, n, r, i, a, o = {}) { i(); const s = agentsApiNativeTool(r, e); if (!s || ![ "completed", "failed", "incomplete" ].includes(r.status ?? "")) return false; const c = `agentsapi:${t}:${n}:${r.id}`; const l = agentsApiNativeToolOutcome(r, o.enclosingStatus); const u = agentsApiNativeToolOutput(r, o.capturedOutput); const d = agentsApiNativeToolDetails(t, n, r, l, o.capturedOutput); const f = u ?? (r.type === "web_search_call" ? `Web search ${l.status}; native search results are unavailable.` : l.error ?? `${s.name} ${l.status}`); await recordAgentsApiNativeToolInvocation(e, t, n, r, i, a, o.historical); await appendAgentsApiTranscriptMessage(e, { ...createAgentHarnessToolResultMessage({ id: c, name: s.name, text: f, isError: l.isError, details: d }, a()), __openclaw: { toolOutput: { source: "execution", modelInput: "unverified", ...l.outcomeUnknown ? { outcome: "unknown" } : {}, ...o.captureTruncated ? { captureTruncated: true } : {} }, ...r.type === "web_search_call" ? { resultContentSource: "network" } : {} }, idempotencyKey: `${c}:result` }, i, void 0, o.historical); return true; } /** Canonical invocation facts can precede completion of the native tool. */ async function recordAgentsApiNativeToolInvocation(e, t, n, r, i, a, o = false) { i(); const s = agentsApiNativeTool(r, e); if (!s || !canRecordAgentsApiNativeToolInvocation(r)) return false; const c = `agentsapi:${t}:${n}:${r.id}`; await appendAgentsApiTranscriptMessage(e, { ...createAgentHarnessToolCallMessage({ api: "openai-agents", provider: "openai", modelId: e.model.id }, { id: c, name: s.name, arguments: s.args }, a()), idempotencyKey: `${c}:call` }, i, void 0, o); return true; } /** Persist host tool evidence before its result is acknowledged by the native session. */ async function recordAgentsApiToolTranscript(e, t, n, r, i) { const a = `agentsapi:tool:${t.turn_id}:${t.call_id}`; const o = { api: "openai-agents", provider: "openai", modelId: e.model.id }; const s = { ...createAgentHarnessToolCallMessage(o, { id: t.call_id, name: t.name, arguments: asOptionalRecord(t.arguments) ?? {} }, Date.now()), idempotencyKey: `${a}:call` }; const c = { ...createAgentHarnessToolResultMessage({ id: t.call_id, name: t.name, content: n.content, details: n.details, isError: r }, Date.now()), idempotencyKey: `${a}:result` }; await appendAgentsApiTranscriptMessage(e, s, i); await appendAgentsApiTranscriptMessage(e, c, i); } async function appendAgentsApiTranscriptMessage(e, t, n, r, i = false) { n(); const a = requireAgentsApiSessionTarget(e); let o = i ? void 0 : e.runId; let s = t; const c = asOptionalRecord(t)?.idempotencyKey; if (typeof c === "string") { const e = await withSessionTranscriptWrite(a, (e) => e.readMessageFacts({ idempotencyKeys: [c] })); n(); if (e.existingIdempotencyKeys.has(c)) { const n = asOptionalRecord(e.messagesByIdempotencyKey.get(c)); const r = asOptionalRecord(n?.["__openclaw"])?.runId; o = typeof r === "string" ? r : void 0; const i = asOptionalRecord(asOptionalRecord(t)?.["__openclaw"]); if (i) { const { runId: e, ...n } = i; s = { ...t, __openclaw: { ...n, ...o ? { runId: o } : {} } }; } } } const l = await appendSessionTranscriptMessageByIdentityStrict({ ...a, config: e.config, runId: o, message: s, preparation: { source: n } }); n(); if (l.kind !== "result") throw new Error("Agents API transcript append was refused"); if (r) { await publishSessionTranscriptUpdateByIdentity({ ...a, update: { message: l.result.message, messageId: l.result.messageId, ...l.result.anchor ? { messageSeq: l.result.anchor.activeMessagePosition + 1 } : {}, runId: e.runId, assistantItemIds: r } }); n(); } return l.result.message; } /** Walk the retrieved native prefix without another transcript queue or cursor. */ function* iterateAgentsApiTranscriptItems(e, t, n, r, i, a) { let o = true; let s = false; for (const c of t) { if (c.turn_id && c.turn_id !== e) throw new Error("Agents API saved item belongs to a different turn"); const t = a(c.id); const l = r || [ "completed", "failed", "incomplete" ].includes(c.status ?? "") || c.status == null && t; if (o && (s && hasAgentsApiTranscriptRecord(c) || !canRecordAgentsApiTranscriptItem(e, c, n, i, t))) o = false; s ||= isAgentsApiDeferredFinalText(c); yield { item: c, terminal: l, transcriptReady: o }; } } /** Nonterminal calls require retrieved invocation fields, rather than streamed guesses. */ function canRecordAgentsApiNativeToolInvocation(e) { if ([ "completed", "failed", "incomplete" ].includes(e.status ?? "")) return [ "command_execution", "mcp_call", "web_search_call" ].includes(e.type); if (e.type === "command_execution") return e.command !== void 0 && e.cwd !== void 0; return false; } /** Backend publication stops before invocation or text facts that are still incomplete. */ function canRecordAgentsApiTranscriptItem(e, t, n, r, i = false) { if ([ "command_execution", "mcp_call", "web_search_call" ].includes(t.type)) return canRecordAgentsApiNativeToolInvocation(t); if (t.type === "function_call") return t.call_id !== void 0 && r.has(`${e}:${t.call_id}`); if (t.type === "reasoning" || t.type === "message" && t.role === "assistant" && t.phase === "commentary") return canRecordAgentsApiTranscriptText(t, n, i); return true; } function canRecordAgentsApiTranscriptText(e, t, n = false) { if ([ "completed", "failed", "incomplete" ].includes(e.status ?? "")) return true; return e.status == null && (n || e.type === "reasoning" && t === "completed"); } function isAgentsApiDeferredFinalText(e) { return e.type === "message" && e.role === "assistant" && e.phase !== "commentary" && e.status === "completed" && Boolean(e.content?.some((e) => e.type === "output_text" && e.text)); } function hasAgentsApiTranscriptRecord(e) { return [ "command_execution", "mcp_call", "web_search_call", "function_call" ].includes(e.type) || e.type === "reasoning" && Boolean(e.summary?.some((e) => e.type === "summary_text" && e.text)) || e.type === "message" && e.role === "assistant" && e.phase === "commentary" && Boolean(e.content?.some((e) => e.type === "output_text" && e.text)); } function readTextParts(e, t) { const n = /* @__PURE__ */ new Map(); e?.forEach((e, r) => { if (e.type === t) n.set(r, e.text ?? ""); }); return n; } function joinTextParts(e) { return [...e.entries()].toSorted(([e], [t]) => e - t).map(([, e]) => e).join(""); } /** Historical items keep their native identity without acquiring the current run's attribution. */ async function recordAgentsApiNativeHistory(e, t, n, r) { for (const { turn: i, items: a } of n) for (const n of a) { await recordAgentsApiNativeToolTranscript(e, t, i.id, n, r, Date.now, { enclosingStatus: i.status, historical: true }); r(); } } //#endregion export { joinTextParts as a, recordAgentsApiNativeToolInvocation as c, iterateAgentsApiTranscriptItems as i, recordAgentsApiNativeToolTranscript as l, bindAgentsApiTranscriptAuthority as n, readTextParts as o, canRecordAgentsApiTranscriptText as r, recordAgentsApiNativeHistory as s, appendAgentsApiTranscriptMessage as t, recordAgentsApiToolTranscript as u };