UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

416 lines (415 loc) • 14.4 kB
import { d as normalizeUsage } from "./usage-CHLnzpJG.mjs"; import { r as calculateCost } from "./llm-Bp_VCUmP.mjs"; import { t as log } from "./logger-DgCpB-Fs.mjs"; import { i as classifyAgentHarnessTerminalOutcome } from "./agent-harness-runtime-BCklzcv7.mjs"; import { n as createAgentHarnessAssistantMessage } from "./agent-harness-attempt-runtime-DFFgKWgF.mjs"; import { n as isAgentsApiTerminalTurn } from "./agentsapi-client-BkGGOio6.mjs"; import { a as joinTextParts, i as iterateAgentsApiTranscriptItems, o as readTextParts, r as canRecordAgentsApiTranscriptText, t as appendAgentsApiTranscriptMessage } from "./agentsapi-transcript-Cs7zhDPb.mjs"; import { t as AgentsApiNativeToolProjection } from "./agentsapi-native-tool-projection-DDpXloY4.mjs"; import { t as readAgentsApiFinalText } from "./agentsapi-text-BTHJuIKD.mjs"; import { n as makeAgentsApiZeroUsage, t as aggregateAgentsApiUsage } from "./agentsapi-usage-DUzNo9KK.mjs"; //#region extensions/agentsapi/agentsapi-messages.ts /** Native identities keep saved-state recovery and live events on the same projection. */ var AgentsApiMessageProjection = class { constructor(e, t, n, r) { this.params = e; this.remoteSessionId = t; this.emitEvent = n; this.assertCurrent = r; this.reply = { assistantUsage: makeAgentsApiZeroUsage() }; this.items = /* @__PURE__ */ new Map(); this.turnByItem = /* @__PURE__ */ new Map(); this.usageByTurn = /* @__PURE__ */ new Map(); this.canonicalUsageRecorded = false; this.reasoningOpen = false; this.lastReasoningText = ""; this.timestamp = Date.now(); this.presentationEnabled = true; this.transcriptOrderingGapReported = false; this.recordedGatewayCallIds = /* @__PURE__ */ new Set(); this.nativeTools = new AgentsApiNativeToolProjection(e, t, (e) => this.emit(e), r, () => this.nextTimestamp(), () => this.presentationEnabled); } get toolMetas() { return this.nativeTools.toolMetas; } get lastToolError() { return this.nativeTools.lastToolError; } get itemLifecycle() { const e = [...this.items.values()]; const t = e.filter((e) => e.terminal).length; const n = this.nativeTools.itemLifecycle; return { startedCount: e.length + n.startedCount, completedCount: t + n.completedCount, activeCount: e.length - t + n.activeCount }; } get resultClassification() { return this.classification; } recordUsage(e, t) { const n = new Map(this.usageByTurn); for (const e of new Map(t.map((e) => [e.id, e])).values()) { const t = normalizeUsage(e.usage); if (t) n.set(e.id, t); } this.canonicalUsageRecorded = true; const r = aggregateAgentsApiUsage(e, n.values()); this.reply.usage = r.usage; this.reply.assistantUsage = r.assistantUsage; } get tokenUsage() { if (this.canonicalUsageRecorded) return this.reply.usage; const e = { contextUsage: { state: "unavailable" } }; for (const t of this.usageByTurn.values()) for (const n of [ "input", "output", "cacheRead", "cacheWrite", "reasoningTokens", "total" ]) { const r = t[n]; if (r !== void 0) e[n] = (e[n] ?? 0) + r; } return e; } async observe(e) { this.assertCurrent(); if (this.finalTurnId) return; if (e.turn?.subagent_id === null && [ "agent.session.turn.completed", "agent.session.turn.failed", "agent.session.turn.cancelled" ].includes(e.type)) this.recordTurnUsage({ ...e.turn, usage: e.usage ?? e.turn.usage }); if (e.item) { const t = e.item.turn_id ?? e.turn_id ?? this.turnByItem.get(e.item.id) ?? this.nativeTools.resolveTurnId(e.item.id); if (!t) throw new Error("Agents API output item has no turn identity"); await this.recordItem(t, e.item, e.type === "agent.session.turn.item.done"); return; } if (e.type === "agent.output.command_execution_output.delta") { await this.nativeTools.observeOutput(e); return; } if (e.type === "agent.session.turn.output_text.delta" || e.type === "agent.session.turn.output_text.done" || (e.type === "agent.session.turn.content_part.added" || e.type === "agent.session.turn.content_part.done") && e.part?.type === "output_text") { const t = this.eventItem(e); if (!t) return; const n = e.content_index ?? 0; t.texts.set(n, e.type.endsWith(".delta") ? (t.texts.get(n) ?? "") + (e.delta ?? "") : e.text ?? e.part?.text ?? ""); await this.emitAssistant(t, false, e.delta ?? ""); return; } if (e.type.startsWith("agent.session.turn.reasoning_summary_")) { const t = this.eventItem(e); if (!t) return; const n = e.summary_index ?? 0; if (e.type.endsWith("text.delta")) t.summaries.set(n, (t.summaries.get(n) ?? "") + (e.delta ?? "")); else if (e.type.endsWith("text.done") || e.type.endsWith("part.done")) t.summaries.set(n, e.text ?? e.part?.text ?? ""); else if (e.part?.text) t.summaries.set(n, e.part.text); await this.emitReasoning(); return; } if (e.type.startsWith("agent.session.environment.")) await this.emitEnvironment(e); } recordGatewayTranscriptReceipt(e, t) { this.assertCurrent(); this.recordedGatewayCallIds.add(`${e}:${t}`); } reportTranscriptOrderingGap() { this.assertCurrent(); if (this.transcriptOrderingGapReported) return; this.transcriptOrderingGapReported = true; log.warn("Agents API saved transcript prefix is unavailable; host input and tool receipts retain their existing placement"); } async reconcile(e, t, n = {}) { this.assertCurrent(); if (this.finalTurnId) return true; const r = this.presentationEnabled; this.presentationEnabled = r && n.presentation !== false; try { let n = true; const r = isAgentsApiTerminalTurn(e.status); for (const i of iterateAgentsApiTranscriptItems(e.id, t, e.status, r, this.recordedGatewayCallIds, (t) => this.items.get(this.identity(e.id, t))?.completionObserved === true)) { const { item: t, terminal: a } = i; n = i.transcriptReady; await this.recordItem(e.id, t, a, e.status, true, n || r); } this.recordTurnUsage(e); if (isAgentsApiTerminalTurn(e.status)) { for (const t of this.items.values()) { if (t.turnId !== e.id || t.terminal) continue; t.terminal = true; } n = await this.nativeTools.reconcileRemaining(e.id, e.status, new Set(t.map((e) => e.id))) && n; if (!n) this.reportTranscriptOrderingGap(); } return n; } finally { this.presentationEnabled = r; } } async commit(e, t) { this.assertCurrent(); if (this.finalTurnId) { if (this.finalTurnId !== e.id) throw new Error("Agents API reply was already committed for a different terminal turn"); return; } if (!await this.reconcile(e, t)) this.reportTranscriptOrderingGap(); await this.endReasoning(); const n = readAgentsApiFinalText(t); const r = createAgentHarnessAssistantMessage(this.attribution(), n, { tokenUsage: this.tokenUsage, aborted: e.status === "cancelled", promptError: e.error?.message, timestamp: this.nextTimestamp() }); if (this.canonicalUsageRecorded) r.usage = this.reply.assistantUsage; else { if (this.usageByTurn.size > 0) calculateCost(this.params.model, r.usage); this.reply.usage = normalizeUsage(r.usage); this.reply.assistantUsage = r.usage; } this.classification = classifyAgentHarnessTerminalOutcome({ assistantTexts: [n], reasoningText: this.reasoningText(), promptError: e.error, turnCompleted: isAgentsApiTerminalTurn(e.status) }); const i = `agentsapi:${this.remoteSessionId}:${e.id}:reply`; if (n) { const t = this.visibleAssistantItemId ? [this.visibleAssistantItemId, i] : [i]; this.reply.lastAssistant = await this.append({ ...r, idempotencyKey: `agentsapi:${this.remoteSessionId}:${e.id}` }, t); this.assertCurrent(); await this.params.onAssistantMessageStart?.(); this.assertCurrent(); } await this.emitAssistantSnapshot(i, n); if (n) { this.assertCurrent(); await this.params.onPartialReply?.({ text: n }); this.assertCurrent(); } this.finalTurnId = e.id; } async commitUsage(e) { this.assertCurrent(); if (this.reply.usage?.total === void 0) return; await this.append({ ...createAgentHarnessAssistantMessage(this.attribution(), "", { aborted: false, content: [], timestamp: this.nextTimestamp() }), usage: this.reply.assistantUsage, idempotencyKey: `agentsapi:${this.remoteSessionId}:${e.id}` }); } async recordItem(e, t, n, r, i = false, a = true) { if (t.type === "function_call" || t.type === "function_call_output" || t.role === "user") return; if (await this.nativeTools.recordItem(e, t, n, r, i, a)) return; if (t.type !== "message" && t.type !== "reasoning") return; const o = this.identity(e, t.id); let s = this.items.get(o); if (s?.terminal && !i) return; if (!s) { s = { turnId: e, item: t, terminal: false, completionObserved: false, texts: /* @__PURE__ */ new Map(), summaries: /* @__PURE__ */ new Map(), recoveredPartial: false }; this.items.set(o, s); this.turnByItem.set(t.id, e); } s.item = t; if (!i && n) s.completionObserved = true; if (i && !n) s.recoveredPartial = true; if (t.type === "message" && t.role === "assistant") { if (n || i || s.texts.size === 0) s.texts = readTextParts(t.content, "output_text"); await this.emitAssistant(s, n); if (i && a && canRecordAgentsApiTranscriptText(t, r, s.completionObserved) && t.phase === "commentary" && joinTextParts(s.texts)) await this.append({ ...createAgentHarnessAssistantMessage(this.attribution(), joinTextParts(s.texts), { aborted: false, timestamp: this.nextTimestamp() }), openclawStreamFallback: { replacementText: joinTextParts(s.texts), source: "segment", itemId: o }, idempotencyKey: `${o}:commentary` }); } else if (t.type === "reasoning") { if (n || i || s.summaries.size === 0) s.summaries = readTextParts(t.summary, "summary_text"); await this.emitReasoning(); if (n) { const e = joinTextParts(s.summaries); if (i && a && canRecordAgentsApiTranscriptText(t, r, s.completionObserved) && e) await this.append({ ...createAgentHarnessAssistantMessage(this.attribution(), "", { aborted: false, timestamp: this.nextTimestamp(), content: [{ type: "thinking", thinking: e }] }), idempotencyKey: `${o}:reasoning` }); await this.endReasoning(); } } s.terminal = n; } async emitAssistant(e, t, n = "") { const r = this.identity(e.turnId, e.item.id); const i = joinTextParts(e.texts); if (e.item.phase === "commentary") { if (this.visibleAssistantItemId === r) { this.visibleAssistantItemId = void 0; e.lastAssistantText = void 0; await this.emit({ stream: "assistant", data: { itemId: r, text: "", delta: "", replace: true } }); } const n = t ? "end" : "update"; if (!i.trim() || e.lastCommentary?.phase === n && e.lastCommentary.text === i) return; e.lastCommentary = { phase: n, text: i }; await this.emit({ stream: "item", data: { itemId: r, kind: "preamble", title: "Preamble", phase: n, progressText: i, source: "agentsapi" } }); return; } if (!i || e.lastAssistantText === i) return; e.lastAssistantText = i; await this.emitAssistantSnapshot(r, i, n); } async emitAssistantSnapshot(e, t, n = "") { const r = this.visibleAssistantItemId !== e; this.visibleAssistantItemId = e; await this.emit({ stream: "assistant", data: { itemId: e, text: t, delta: r ? "" : n, replaceable: true, ...r ? { replace: true } : {} } }); } async emitReasoning() { this.assertCurrent(); if (!this.presentationEnabled) return; const e = this.reasoningText(); if (!e.trim() || e === this.lastReasoningText) return; this.lastReasoningText = e; this.reasoningOpen = true; await this.params.onReasoningStream?.({ text: e, isReasoningSnapshot: true }); this.assertCurrent(); } async endReasoning() { if (!this.reasoningOpen) return; this.reasoningOpen = false; this.assertCurrent(); if (!this.presentationEnabled) return; await this.params.onReasoningEnd?.(); this.assertCurrent(); } reasoningText() { return [...this.items.values()].filter((e) => e.item.type === "reasoning").map((e) => joinTextParts(e.summaries)).filter((e) => e.trim()).join("\n\n"); } recordTurnUsage(e) { this.assertCurrent(); if (this.canonicalUsageRecorded) return; const t = normalizeUsage(e.usage) ?? this.usageByTurn.get(e.id); if (!t) return; this.usageByTurn.set(e.id, { ...t, contextUsage: { state: "unavailable" } }); } async emitEnvironment(e) { const t = e.type.slice(26); if (!ENVIRONMENT_TITLES.has(t)) return; await this.emit({ stream: "item", data: { itemId: `agentsapi:${this.remoteSessionId}:environment`, kind: "environment", title: ENVIRONMENT_TITLES.get(t), phase: t === "pending" ? "start" : "end", ...t === "disconnected" ? { summary: "Connection unavailable" } : { status: t === "failed" ? "failed" : t === "pending" ? "running" : "completed" }, source: "agentsapi" } }); } eventItem(e) { if (!e.item_id) throw new Error("Agents API output event has no item identity"); const t = e.turn_id ?? this.turnByItem.get(e.item_id); const n = t ? this.items.get(this.identity(t, e.item_id)) : void 0; return n && !n.terminal && (!n.recoveredPartial || e.type.endsWith(".done")) ? n : void 0; } identity(e, t) { return `agentsapi:${this.remoteSessionId}:${e}:${t}`; } attribution() { return { api: "openai-agents", provider: "openai", modelId: this.params.model.id }; } nextTimestamp() { this.timestamp = Math.max(Date.now(), this.timestamp + 1); return this.timestamp; } async emit(e) { this.assertCurrent(); if (!this.presentationEnabled) return; await this.emitEvent(e); this.assertCurrent(); } append(e, t) { return appendAgentsApiTranscriptMessage(this.params, e, this.assertCurrent, t); } }; const ENVIRONMENT_TITLES = /* @__PURE__ */ new Map([ ["pending", "Agent environment starting"], ["ready", "Agent environment ready"], ["connected", "Agent environment connected"], ["disconnected", "Agent environment disconnected"], ["failed", "Agent environment failed"] ]); //#endregion export { AgentsApiMessageProjection as t };