openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
98 lines (97 loc) • 3 kB
JavaScript
import { n as isAgentsApiTerminalTurn } from "./agentsapi-client-BkGGOio6.mjs";
import { setTimeout } from "node:timers/promises";
//#region extensions/agentsapi/agentsapi-session-history.ts
function createAgentsApiSessionHistory(e) {
const { sessionId: t, cleanupClient: n, coordinatorTurnIds: r, priorInputItemIds: i, readAdmittedTurns: a, rememberItemTurn: o } = e;
const readItemsByTurn = async (e, n) => {
const r = await e.items(t, void 0, n);
n.throwIfAborted();
const i = /* @__PURE__ */ new Map();
for (const e of r) {
if (!e.turn_id) continue;
const t = i.get(e.turn_id) ?? [];
t.push(e);
i.set(e.turn_id, t);
}
return i;
};
const readSavedState = async (t, n) => {
const r = await a(t, n);
const s = [];
const c = /* @__PURE__ */ new Set();
const l = r.length || e.getBaselineTurnId() ? await readItemsByTurn(t, n) : /* @__PURE__ */ new Map();
for (const e of r) {
const t = l.get(e.id) ?? [];
for (const n of t) {
o(n.id, e.id);
if (n.type === "message" && n.role === "user" && !i.has(n.id)) c.add(n.id);
}
s.push({
turn: e,
items: t
});
}
e.observeInputItems(c);
return {
turns: r,
entries: s,
itemsByTurn: l
};
};
const projectSavedState = async (t, n) => {
let r = true;
for (const { turn: i, items: a } of t) {
n.throwIfAborted();
r = await e.callbacks.onReconcile?.(i, a) !== false && r;
n.throwIfAborted();
}
return r;
};
const reconcilePriorHistory = async (n, r, i) => {
if (!e.getBaselineTurnId() || !e.callbacks.onReconcileHistory) return;
const a = await n.turns(t, r);
r.throwIfAborted();
const o = a.findIndex((t) => t.id === e.getBaselineTurnId());
if (o < 0) throw new Error("Agents API historical reconciliation lost its baseline turn");
const s = a.slice(0, o + 1).filter((e) => isAgentsApiTerminalTurn(e.status));
if (!s.length) return;
await e.callbacks.onReconcileHistory(s.map((e) => ({
turn: e,
items: i.get(e.id) ?? []
})));
r.throwIfAborted();
};
const readUsageTurns = async () => {
const i = AbortSignal.timeout(5e3);
let a = [];
try {
while (true) {
a = await n.turns(t, i, e.getBaselineTurnId());
const o = new Set(a.map((e) => e.id));
if (a.length > 0 && [...r].every((e) => o.has(e)) && a.every((e) => e.usage !== null)) return a;
await setTimeout(500, void 0, { signal: i });
}
} catch (t) {
if (!i.aborted) e.callbacks.onUsageError?.(t);
return a;
}
};
return {
readItemsByTurn,
readSavedState,
projectSavedState,
reconcilePriorHistory,
readUsageTurns
};
}
/** Retain the live reader while bounding reconciliation of late saved records. */
async function waitForAgentsApiEventOrRecovery(e, t) {
const n = new AbortController();
try {
return await Promise.race([e, setTimeout(1e3, void 0, { signal: AbortSignal.any([t, n.signal]) })]);
} finally {
n.abort();
}
}
//#endregion
export { waitForAgentsApiEventOrRecovery as n, createAgentsApiSessionHistory as t };