UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

474 lines (473 loc) • 14.1 kB
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import "./error-runtime-BM740gJj.mjs"; import { n as isAgentsApiTerminalTurn } from "./agentsapi-client-BkGGOio6.mjs"; import { n as isAgentsApiOptionalHistoryReadFailure, r as isAgentsApiTransportDisconnect, t as AgentsApiError } from "./agentsapi-errors-ByxEsPsd.mjs"; import { n as waitForAgentsApiEventOrRecovery, t as createAgentsApiSessionHistory } from "./agentsapi-session-history-BOHJTqoR.mjs"; import { setTimeout } from "node:timers/promises"; import { APIUserAbortError } from "openai"; //#region extensions/agentsapi/agentsapi-session.ts /** Native input receipts and session idle, together, establish Agents API completion. */ function createAgentsApiSession(e) { const { client: t, cleanupClient: n, sessionId: r, signal: i, assertCurrent: a } = e; let o = new AbortController(); let s = e.initialInputSubmitted ?? false; let c = false; let l = false; let u = false; let d = false; let f; let p; let m = false; let h = Promise.resolve(); let g = Promise.resolve(); let _; let v = s ? 1 : 0; let y; let b = s; const x = /* @__PURE__ */ new Set(); let S = /* @__PURE__ */ new Set(); const C = /* @__PURE__ */ new Set(); const w = /* @__PURE__ */ new Set(); const T = /* @__PURE__ */ new Map(); const E = /* @__PURE__ */ new Set(); let D; let O; let k = false; let A = e.initialInputSubmitted ?? false; const isAvailable = () => s && !c && !l && !d && !f && !i.aborted; const submit = (e, n) => { a(); i.throwIfAborted(); if (c || l || d || f) throw new Error("Agents API turn is stopped"); h = h.then(async () => { a(); if (l || d || f || i.aborted) throw new Error("Agents API turn settled before input was submitted"); await n?.(); a(); i.throwIfAborted(); if (l || d || f) throw new Error("Agents API turn settled before input was submitted"); v++; s = true; g = t.message(r, e, AbortSignal.timeout(6e4)); return g; }); h.catch(() => {}); return h; }; const cancel = () => { l = true; o.abort(); if (!s || d) return Promise.resolve(); _ ??= (async () => { let e; try { await g; } catch (t) { e = t; } await n.cancel(r, AbortSignal.timeout(3e4)); d = true; if (e !== void 0) throw e instanceof Error ? e : new Error(formatErrorMessage(e), { cause: e }); })(); _.catch(() => {}); return _; }; const onAbort = () => { cancel(); }; i.addEventListener("abort", onAbort, { once: true }); const readAdmittedTurns = async (e, t) => { const n = await e.turns(r, t, y); t.throwIfAborted(); for (const e of n) { C.add(e.id); w.delete(e.id); } const i = n.at(-1); D = i?.id; f = i && isAgentsApiTerminalTurn(i.status) ? i : void 0; p = i?.status === "failed" ? new AgentsApiError(i.error?.message ?? "Agents API turn failed", i.error ?? {}) : void 0; m = !k && i?.status === "cancelled"; return n; }; const rememberItemTurn = (e, t) => { const n = T.get(e); if (n && n !== t) throw new Error("Agents API item belongs to different admitted turns"); T.set(e, t); E.delete(e); }; const j = createAgentsApiSessionHistory({ sessionId: r, cleanupClient: n, getBaselineTurnId: () => y, coordinatorTurnIds: C, priorInputItemIds: x, readAdmittedTurns, rememberItemTurn, observeInputItems: (e) => { S = e; }, callbacks: e }); return { isAvailable, wasSubmitted: () => s, isSettled: () => d, queueMessage: submit, readUsageTurns() { if (!s || !d) return Promise.resolve([]); return O ??= j.readUsageTurns(); }, async run(s, l, u) { i.throwIfAborted(); if (!e.initialInputSubmitted) { const e = (await t.turns(r, i, void 0, true))[0]; a(); y = e?.id; if (e && !isAgentsApiTerminalTurn(e.status)) { const n = await t.turns(r, i); a(); const o = n.findIndex((t) => t.id === e.id); if (o < 0) throw new Error("Agents API continuation lost its active root turn"); y = n[o - 1]?.id; const s = await t.items(r, e.id, i); a(); for (const e of s) if (e.type === "message" && e.role === "user") x.add(e.id); } b = true; if (y) w.add(y); } const _ = /* @__PURE__ */ new Map(); const relayFunctions = async () => { a(); i.throwIfAborted(); let s = h; await awaitReceipt(s); a(); const l = v; const u = await t.pendingFunctionCalls(r, i); if (!u.length) return; if (!e.executeFunction) throw new Error("Agents API MVP cannot continue: agent.session.requires_action"); for (const e of u) { const t = `${r}:${e.turn_id}:${e.call_id}`; if (!_.has(t)) _.set(t, { inputCount: l, relayed: false }); } const p = await readAdmittedTurns(t, i); a(); if (s !== h) return relayFunctions(); const m = p.at(-1); if (!m) throw new Error("Agents API function request has no current attempt root turn"); D = m.id; const y = v; let b; const x = AbortSignal.any([i, AbortSignal.timeout(5e3)]); try { b = await j.readItemsByTurn(t, x); a(); } catch (t) { i.throwIfAborted(); a(); if (!(x.aborted && (t === x.reason || t instanceof APIUserAbortError)) && !isAgentsApiOptionalHistoryReadFailure(t)) throw t; e.onTranscriptOrderingGap?.(); a(); } for (const l of u) { if (l.turn_id !== m.id || !["in_progress", "waiting"].includes(m.status)) throw new Error("Agents API function request belongs to a different or settled root turn"); const u = `${r}:${l.turn_id}:${l.call_id}`; const x = _.get(u); if (x.relayed) continue; const S = b?.get(l.turn_id); const C = S?.findIndex((e) => e.type === "function_call" && e.call_id === l.call_id) ?? -1; if (S) { const t = C >= 0 ? S.slice(0, C) : S; const n = await j.projectSavedState(p.map((e) => ({ turn: e, items: e.id === l.turn_id ? t : b.get(e.id) ?? [] })), i); a(); if (!n || C < 0) { e.onTranscriptOrderingGap?.(); a(); } } else { e.onTranscriptOrderingGap?.(); a(); } if (s !== h || y !== v) return relayFunctions(); x.relayed = true; const w = await e.executeFunction(l); a(); i.throwIfAborted(); const T = w.terminate; if (T) c = true; h = h.then(() => { a(); i.throwIfAborted(); g = t.toolResult(r, l, w, AbortSignal.timeout(6e4)); return g; }); h.catch(() => {}); const E = h; await awaitReceipt(E); s = E; await e.onFunctionResult?.(l, w); a(); if (T) { if (v !== x.inputCount) { c = false; return relayFunctions(); } await n.cancel(r, AbortSignal.timeout(3e4)); k = true; await settleFromSavedState(); if (!d || !f || !["completed", "cancelled"].includes(f.status ?? "")) throw new Error("Agents API tool termination did not settle its native root turn and inputs"); o.abort(); return; } } }; let O = await t.subscribe(r, AbortSignal.any([i, o.signal])); let M = O.next(); M.catch(() => {}); const N = []; const reconnectEvents = async () => { A = true; o.abort(); await O.return(void 0).catch((e) => { if (!isAgentsApiTransportDisconnect(e)) throw e; }); while (true) { await setTimeout(500, void 0, { signal: i }); a(); o = new AbortController(); try { O = await t.subscribe(r, AbortSignal.any([i, o.signal])); break; } catch (e) { o.abort(); i.throwIfAborted(); a(); if (!isAgentsApiTransportDisconnect(e)) throw e; } } M = O.next(); M.catch(() => {}); }; const disconnectedEvent = (e) => { i.throwIfAborted(); a(); if (!isAgentsApiTransportDisconnect(e)) throw e; return { done: true, value: void 0 }; }; const awaitReceipt = async (e) => { const t = e.then(() => ({ kind: "acknowledged" }), (e) => ({ kind: "failed", error: e })); while (true) { i.throwIfAborted(); let e; try { e = await Promise.race([t, M]); } catch (t) { e = disconnectedEvent(t); } if ("kind" in e) { if (e.kind === "failed") throw e.error; return; } if (e.done) { await reconnectEvents(); continue; } N.push(e.value); M = O.next(); M.catch(() => {}); } }; const settleFromSavedState = async (n = false) => { const o = h; await awaitReceipt(o); a(); const s = v; const c = await j.readSavedState(t, i); a(); const l = await t.session(r, i); a(); if (l.status === "failed") throw new Error(l.error ?? "Agents API session failed"); if (l.status === "requires_action") { await relayFunctions(); if (d) return; } d = Boolean(f && f.id === c.turns.at(-1)?.id && l.status === "idle" && o === h && s === v && S.size === s); if (d) e.onSettled?.(); if (d || n) { if (d) { await j.reconcilePriorHistory(t, i, c.itemsByTurn); a(); } await j.projectSavedState(c.entries, i); a(); } }; const belongsToAttempt = async (e) => { if (e.item && e.item_id && e.item.id !== e.item_id) throw new Error("Agents API event contains different item identities"); const n = e.item?.id ?? e.item_id; const r = new Set([ e.turn?.id, e.turn_id, e.item?.turn_id, n ? T.get(n) : void 0 ].filter((e) => typeof e === "string" && e.length > 0)); if (r.size > 1) throw new Error("Agents API event contains different turn identities"); const o = r.values().next().value; if (!o) { if (n) { if (E.has(n)) return false; const e = await j.readSavedState(t, i); a(); if (!T.has(n)) { E.add(n); return false; } await j.projectSavedState(e.entries, i); a(); return true; } if (e.item || e.type === "agent.output.command_execution_output.delta") throw new Error("Agents API output event is missing its turn ID"); return true; } if (w.has(o)) { if (n) E.add(n); return false; } if (!C.has(o)) { await readAdmittedTurns(t, i); a(); if (!C.has(o)) { w.add(o); if (n) E.add(n); return false; } } if (e.item) rememberItemTurn(e.item.id, o); return true; }; try { await l(); a(); i.throwIfAborted(); if (!e.initialInputSubmitted) await awaitReceipt(submit(s)); u(); if (e.initialInputSubmitted) await settleFromSavedState(true); while (true) { if (d) break; let n; let o = false; try { const e = N.shift(); if (e) { o = true; n = { done: false, value: e }; } else if (A) n = await waitForAgentsApiEventOrRecovery(M, i); else n = await M; } catch (e) { n = disconnectedEvent(e); } if (!n) { await settleFromSavedState(true); continue; } if (n.done) { await reconnectEvents(); await settleFromSavedState(true); continue; } const s = n.value; if (!o) { M = O.next(); M.catch(() => {}); } a(); if (!await belongsToAttempt(s)) continue; a(); await e.onEvent(s); a(); if (s.type === "agent.session.idle") { A = true; await settleFromSavedState(); continue; } if ((s.type === "agent.session.turn.item.added" || s.type === "agent.session.turn.item.done") && s.item?.type === "message" && s.item.role === "user" && s.item.id && !x.has(s.item.id) && !S.has(s.item.id)) { S.add(s.item.id); if (!(s.item.turn_id ?? s.turn_id ?? T.get(s.item.id))) throw new Error("Agents API input item is missing its turn ID"); await settleFromSavedState(); } if (s.type === "error") throw new AgentsApiError(s.error?.message ?? "Agents API stream error", s.error); if (s.type === "agent.session.requires_action") { await relayFunctions(); continue; } if (s.type === "agent.session.failed") { const e = await t.session(r, i); a(); if (e.status !== "failed") continue; throw new AgentsApiError(e.error ?? "Agents API session failed", s.error); } if (s.type === "agent.session.environment.failed") { const e = s.environment?.error ?? s.error; throw new AgentsApiError(e?.message ?? s.session?.error ?? `Agents API cannot continue: ${s.type}`, e ?? {}); } if ((s.type === "agent.session.turn.completed" || s.type === "agent.session.turn.failed" || s.type === "agent.session.turn.cancelled") && s.turn?.subagent_id === null && s.turn.id === D) { A = true; f = s.turn; p = s.type.endsWith(".failed") ? new AgentsApiError(s.turn.error?.message ?? "Agents API turn failed", s.turn.error ?? {}) : void 0; m = s.type.endsWith(".cancelled"); await settleFromSavedState(); } } } finally { o.abort(); await O.return(void 0); } if (!f || !d) throw new Error("Agents API stream closed before the root turn settled; reset or inspect the session before retrying"); if (p) throw p; return { turn: f, cancelled: m, terminatedByTool: k }; }, async reconcileAfterClose(e) { if (!u) throw new Error("Agents API session cleanup requires a closed session attempt"); if (!s || !b) return; e.throwIfAborted(); const t = await n.session(r, e); e.throwIfAborted(); if (t.status !== "idle" && t.status !== "failed") throw new Error("Agents API session cleanup requires native work to be retired"); const i = await j.readSavedState(n, e); await j.reconcilePriorHistory(n, e, i.itemsByTurn); await j.projectSavedState(i.entries, e); return i.turns.at(-1); }, async close() { i.removeEventListener("abort", onAbort); o.abort(); if (s && !d) await cancel(); await _; l = true; u = true; } }; } //#endregion export { createAgentsApiSession as t };