openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
364 lines (363 loc) • 16.9 kB
JavaScript
import { n as isPostgresSqlConnection } from "../../sql-connection-Beiyg5Dt.mjs";
import { _ as sql, a as executeSqliteQueryTakeFirstSync, i as executeSqliteQuerySync, s as getNodeSqliteKysely } from "../../kysely-sync-YJo2lmGV.mjs";
import { l as OPENCLAW_SQLITE_BUSY_TIMEOUT_MS } from "../../openclaw-state-db-contract-DfPjvL0M.mjs";
import { l as runSqliteWorkerTransactionSync, o as runSqliteReadSnapshotSync } from "../../sqlite-transaction-BHHu6P5-.mjs";
import { t as SqliteJsonlReadBudgetExceededError } from "../../sqlite-jsonl-budget-error-CtOAIuWx.mjs";
import { u as ensureContextEngineTurnOutboxSchema } from "../../openclaw-agent-db-schema-compatibility-DMUbFiMM.mjs";
import { l as transcriptEventNavigationSql } from "../../transcript-payload-Cb_Kmk8c.mjs";
import { r as transcriptEventJsonSql } from "../../transcript-payload-read-Dd5D3FtH.mjs";
import { t as getSessionKysely } from "../../session-accessor.sqlite-scope-helpers-5_tKUULP.mjs";
import "../../session-accessor.sqlite-scope-Cbj2BdoG.mjs";
import { t as assertSqliteJsonlReadBudget } from "../../sqlite-jsonl-budget-fqAzjI-v.mjs";
import { o as selectActiveTranscriptEventRows, s as selectActiveTranscriptIdentityRows } from "../../session-accessor.sqlite-projection-read-C0I_zpfK.mjs";
import { t as bindSqliteWorkerDatabase } from "../../sqlite-worker-binding-B4BB5u5i.mjs";
import { n as isRetryableContextEngineTurnReadFailure } from "../../context-engine-turn-outbox-BIFi2Z96.mjs";
import { toUSVString } from "node:util";
//#region src/config/sessions/session-accessor.transcript-range.worker.ts
function anchorsShareTarget(e) {
const { admission: t, terminal: n } = e;
return t.agentId === n.agentId && t.sessionId === n.sessionId && t.sessionKey === n.sessionKey && t.storePath === n.storePath && t.generation === n.generation;
}
function validateAnchorRow(e, t) {
return Boolean(t && t.generation === e.generation && t.seq === e.rawSeq && t.parent_id === e.effectiveParentId && t.message_position === e.activeMessagePosition);
}
function validateTerminalAncestry(e) {
if (e.terminalEntryId === e.admissionEntryId) return "descendant";
if (!(e.maxDepth > 0)) return "too-large";
if (e.terminalParentId === e.admissionEntryId) return "descendant";
if (e.terminalParentId === null || e.terminalParentId === e.terminalEntryId) return "non-descendant";
const t = getSessionKysely(e.database);
const n = Math.ceil(e.maxDepth);
const r = toUSVString(e.admissionEntryId) === e.admissionEntryId;
const i = toUSVString(e.terminalEntryId) === e.terminalEntryId;
const a = isPostgresSqlConnection(e.database);
const o = t.withRecursive("turn_ancestors", (t) => t.selectFrom("transcript_event_identities").select(["event_id", "parent_id"]).where("session_id", "=", e.sessionId).where("event_id", "=", e.terminalParentId).union(t.selectFrom("transcript_event_identities as identity").innerJoin("turn_ancestors as previous", "identity.event_id", "previous.parent_id").select(["identity.event_id", "identity.parent_id"]).where("identity.session_id", "=", e.sessionId).$if(r, (t) => t.where("previous.parent_id", "!=", e.admissionEntryId)).$if(i, (t) => t.where("identity.event_id", "!=", e.terminalEntryId))).$if(!a, (e) => e.limit(Number.isSafeInteger(n) ? n : -1)));
const s = a ? o.selectFrom((e) => e.selectFrom("turn_ancestors").selectAll().$if(Number.isSafeInteger(n), (e) => e.limit(n)).as("turn_ancestors")) : o.selectFrom("turn_ancestors");
const c = executeSqliteQueryTakeFirstSync(e.database, s.select((t) => [t.fn.countAll().as("depth"), t.fn.max(t.case().when(t.and([a ? sql.lit(r) : t.val(r ? 1 : 0), t("parent_id", "=", e.admissionEntryId)])).then(1).else(0).end()).as("found")]));
if (c.depth >= n) return "too-large";
return c.found === 1 ? "descendant" : "non-descendant";
}
/** Reads a closed turn through the caller's connection, such as an agent database worker's. */
function readClosedTranscriptTurnInDatabase(e, t) {
if (!anchorsShareTarget(t.boundary)) return { kind: "session-rebound" };
const n = t.boundary.admission;
return runSqliteReadSnapshotSync(e, () => {
const r = getSessionKysely(e);
if (!executeSqliteQueryTakeFirstSync(e, r.selectFrom("session_windows").select(["session_id"]).where("session_id", "=", n.sessionId).where("session_key", "=", n.sessionKey).limit(1))) return { kind: "session-rebound" };
const i = executeSqliteQueryTakeFirstSync(e, r.selectFrom("transcript_events").select("seq").where("session_id", "=", n.sessionId).orderBy("seq", "desc").limit(1))?.seq;
const a = executeSqliteQueryTakeFirstSync(e, r.selectFrom("session_transcript_index_state").select(["indexed_seq", "needs_rebuild"]).where("session_id", "=", n.sessionId));
if (i === void 0 || !a || a.needs_rebuild !== 0 || a.indexed_seq !== i) return { kind: "projection-unavailable" };
const readAnchor = (t) => executeSqliteQueryTakeFirstSync(e, selectActiveTranscriptIdentityRows({ db: e }).innerJoin("transcript_rewrite_watermarks as rewrite", (e) => e.onRef("rewrite.session_id", "=", "identity.session_id")).innerJoin("transcript_events as event", (e) => e.onRef("event.session_id", "=", "identity.session_id").onRef("event.seq", "=", "identity.seq")).select([
"identity.seq",
"identity.parent_id",
"active.message_position",
"rewrite.generation",
transcriptEventNavigationSql(e, "event").as("event_json")
]).where("identity.session_id", "=", n.sessionId).where("identity.event_id", "=", t.entryId).limit(1));
const o = readAnchor(t.boundary.admission);
const s = readAnchor(t.boundary.terminal);
if (!validateAnchorRow(t.boundary.admission, o) || !validateAnchorRow(t.boundary.terminal, s)) return { kind: "stale" };
const c = JSON.parse(o.event_json);
if (c.type !== "message" || c.message?.role !== "user") return { kind: "stale" };
const l = validateTerminalAncestry({
database: e,
sessionId: n.sessionId,
admissionEntryId: t.boundary.admission.entryId,
terminalEntryId: t.boundary.terminal.entryId,
terminalParentId: s.parent_id,
maxDepth: t.maxEvents
});
if (l !== "descendant") return { kind: l };
const u = selectActiveTranscriptEventRows({ db: e }).where("active.session_id", "=", n.sessionId).where("active.message_position", "is not", null).where("active.message_position", ">=", t.boundary.admission.activeMessagePosition).where("active.message_position", "<=", t.boundary.terminal.activeMessagePosition).orderBy("active.message_position", "asc");
try {
assertSqliteJsonlReadBudget(e, u.clearOrderBy().select(["event.event_json", "event.event_utf8_bytes"]).as("events"), t.maxBytes, "Closed transcript turn", {
separatorBytes: 0,
maxRows: t.maxEvents
});
} catch (e) {
if (e instanceof SqliteJsonlReadBudgetExceededError) return { kind: "too-large" };
throw e;
}
return {
kind: "ok",
messages: executeSqliteQuerySync(e, u.select(transcriptEventJsonSql(e, "event").as("event_json"))).rows.flatMap((e) => {
const t = JSON.parse(e.event_json);
return t.type === "message" && t.message ? [t.message] : [];
})
};
}, {
databaseLabel: n.storePath,
operationLabel: "session transcript accepted turn read"
});
}
//#endregion
//#region src/agents/harness/context-engine-turn-outbox.kernel.worker.ts
const RECOVERED_TURN_MAX_EVENTS = 2e4;
const RECOVERED_TURN_MAX_BYTES = 8388608;
function outboxPayloadRequiresAdvancement() {
return sql`context_engine_turn_outbox.payload_state IS DISTINCT FROM 'blocked'`;
}
function outboxDb(e) {
ensureContextEngineTurnOutboxSchema(e.db);
return getNodeSqliteKysely(e.db);
}
function assertMatchingOutboxOwner(e, t, n) {
if (e.engine_id !== t.engineId || e.owner_plugin_id !== (t.ownerPluginId ?? null)) throw new Error(`context-engine advancement key collision: ${n}`);
}
function writeContextEngineTurnOutboxPayload(e) {
const t = outboxDb(e.database);
const n = e.payload.state === "admitted" ? e.payload.admission : e.payload.boundary.admission;
const r = n.logicalTurnId;
const i = JSON.stringify(e.payload);
const a = executeSqliteQueryTakeFirstSync(e.database.db, t.selectFrom("context_engine_turn_outbox").select([
"engine_id",
"owner_plugin_id",
"payload_json"
]).where("advancement_key", "=", r));
if (a) {
assertMatchingOutboxOwner(a, e, r);
const o = JSON.parse(a.payload_json);
if (e.payload.state === "accepted" && o.state === "admitted" && o.admission.entryId === n.entryId || (e.payload.state === "blocked" || e.payload.state === "ready") && o.state === "accepted" && o.boundary.admission.entryId === n.entryId && o.boundary.terminal.entryId === e.payload.boundary.terminal.entryId) {
executeSqliteQuerySync(e.database.db, t.updateTable("context_engine_turn_outbox").set({
attempt_count: 0,
last_attempt_at: null,
last_error: null,
payload_json: i,
payload_state: e.payload.state
}).where("advancement_key", "=", r));
return;
}
if (a.payload_json !== i) throw new Error(`context-engine advancement key collision: ${r}`);
return;
}
executeSqliteQuerySync(e.database.db, t.insertInto("context_engine_turn_outbox").values({
advancement_key: r,
engine_id: e.engineId,
owner_plugin_id: e.ownerPluginId ?? null,
session_id: n.sessionId,
payload_json: i,
payload_state: e.payload.state,
created_at: Date.now(),
last_attempt_at: null,
last_error: null
}).onConflict((e) => e.column("advancement_key").doNothing()));
}
function enqueueContextEngineTurnIntent(e) {
writeContextEngineTurnOutboxPayload({
...e,
payload: {
admission: e.admission,
state: "admitted"
}
});
}
function acceptContextEngineTurnIntent(e) {
writeContextEngineTurnOutboxPayload({
...e,
payload: {
boundary: e.boundary,
state: "accepted",
runtimeContext: e.runtimeContext
}
});
}
function enqueueContextEngineTurnCommit(e) {
writeContextEngineTurnOutboxPayload({
...e,
payload: {
...e.payload,
state: "ready"
}
});
}
function blockContextEngineTurnIntent(e) {
writeContextEngineTurnOutboxPayload({
...e,
payload: {
boundary: e.boundary,
failure: e.failure,
state: "blocked"
}
});
}
function discardContextEngineTurnIntent(e) {
const t = outboxDb(e.database);
const n = executeSqliteQuerySync(e.database.db, t.deleteFrom("context_engine_turn_outbox").where("advancement_key", "=", e.admission.logicalTurnId).where("engine_id", "=", e.engineId).where("payload_state", "=", "admitted").where("owner_plugin_id", e.ownerPluginId ? "=" : "is", e.ownerPluginId ?? null));
return n.numAffectedRows !== void 0 && n.numAffectedRows > 0n;
}
/**
* Reads an accepted turn's bounded range and publishes it as ready or blocked.
* The acceptance commits first in its own transaction, so a failed read or
* publication leaves the turn accepted and the next recovery advances it.
*/
function publishClosedContextEngineTurn(e) {
return advanceAcceptedContextEngineTurn(e, e, e);
}
function advanceAcceptedContextEngineTurn(e, t, n, r) {
const i = readClosedTranscriptTurnInDatabase(e.database.db, {
boundary: t.boundary,
maxEvents: n.maxEvents,
maxBytes: n.maxBytes
});
if (i.kind !== "ok") {
r?.(i.kind);
if (!isRetryableContextEngineTurnReadFailure(i.kind)) blockContextEngineTurnIntent({
boundary: t.boundary,
database: e.database,
engineId: e.engineId,
failure: i.kind,
ownerPluginId: e.ownerPluginId
});
return i.kind;
}
enqueueContextEngineTurnCommit({
database: e.database,
engineId: e.engineId,
ownerPluginId: e.ownerPluginId,
payload: {
boundary: t.boundary,
messages: i.messages,
runtimeContext: t.runtimeContext
}
});
return i.kind;
}
function recoverContextEngineTurnOutbox(e) {
const t = outboxDb(e.database);
const n = executeSqliteQuerySync(e.database.db, t.selectFrom("context_engine_turn_outbox").select(["advancement_key", "payload_json"]).where("engine_id", "=", e.engineId).where("owner_plugin_id", e.ownerPluginId ? "=" : "is", e.ownerPluginId ?? null).where("session_id", "=", e.sessionId).where(outboxPayloadRequiresAdvancement()).orderBy("enqueue_sequence", "asc")).rows;
let r = false;
for (const t of n) {
const n = JSON.parse(t.payload_json);
if (n.state === "ready") {
r = true;
continue;
}
if (n.state === "admitted") {
discardContextEngineTurnIntent({
admission: n.admission,
database: e.database,
engineId: e.engineId,
ownerPluginId: e.ownerPluginId
});
e.warn(`[context-engine] discarded unaccepted turn advancement: ${t.advancement_key}: recovery found no host acceptance`);
continue;
}
const i = advanceAcceptedContextEngineTurn(e, n, {
maxEvents: RECOVERED_TURN_MAX_EVENTS,
maxBytes: RECOVERED_TURN_MAX_BYTES
}, (n) => e.warn(isRetryableContextEngineTurnReadFailure(n) ? `[context-engine] durable turn recovery remains queued: ${t.advancement_key}: transcript range is ${n}` : `[context-engine] blocked unrecoverable turn advancement: ${t.advancement_key}: transcript range is ${n}`));
r ||= i === "ok" || isRetryableContextEngineTurnReadFailure(i);
}
return r;
}
function completeContextEngineTurn(e, t) {
executeSqliteQuerySync(e.db, outboxDb(e).deleteFrom("context_engine_turn_outbox").where("advancement_key", "=", t));
}
function recordContextEngineTurnFailure(e, t, n, r) {
executeSqliteQuerySync(e.db, outboxDb(e).updateTable("context_engine_turn_outbox").set((e) => ({
attempt_count: e("attempt_count", "+", 1),
last_attempt_at: r,
last_error: n
})).where("advancement_key", "=", t));
}
function pendingContextEngineTurns(e, t, n) {
const r = outboxDb(e).selectFrom("context_engine_turn_outbox").where("engine_id", "=", t.engineId).where("owner_plugin_id", t.ownerPluginId ? "=" : "is", t.ownerPluginId ?? null).where(outboxPayloadRequiresAdvancement());
return n === void 0 ? r : r.where("session_id", "=", n);
}
function hasPendingContextEngineTurn(e, t) {
const n = pendingContextEngineTurns(e, t, t.sessionId || void 0).select("advancement_key");
return executeSqliteQueryTakeFirstSync(e.db, n.limit(1)) !== void 0;
}
/**
* Recovers a session's outbox before a run and, when nothing remains to
* advance, records the known admission in the same transaction. The common
* turn start therefore needs one database round trip.
*/
function prepareContextEngineTurnRun(e) {
const t = [];
const n = recoverContextEngineTurnOutbox({
...e,
warn: (e) => t.push(e)
});
if (n || !e.admission) return {
warnings: t,
pending: n,
admitted: false
};
enqueueContextEngineTurnIntent({
...e,
admission: e.admission
});
return {
warnings: t,
pending: n,
admitted: true
};
}
/** Runs one outbox command's kernel on the borrowed connection. */
function executeContextEngineTurnOutboxCommand(e, t) {
const n = { db: e };
switch (t.type) {
case "prepareRun": return prepareContextEngineTurnRun({
...t.input,
database: n
});
case "listPendingSessions": {
const e = t.input;
const r = pendingContextEngineTurns(n, e, e.sessionId || void 0);
const i = r.select((e) => e.fn.min("enqueue_sequence").as("head")).groupBy("session_id");
return executeSqliteQuerySync(n.db, r.select("session_id").where("payload_state", "=", "ready").where("enqueue_sequence", "in", i).orderBy("enqueue_sequence", "asc").limit(e.limit)).rows.map(({ session_id: e }) => e);
}
case "readNextPending": {
const e = t.input;
return executeSqliteQueryTakeFirstSync(n.db, pendingContextEngineTurns(n, e, e.sessionId).select([
"advancement_key",
"payload_json",
"session_id"
]).orderBy("enqueue_sequence", "asc").limit(1));
}
case "complete":
completeContextEngineTurn(n, t.input.advancementKey);
return;
case "recordFailure":
recordContextEngineTurnFailure(n, t.input.advancementKey, t.input.message, t.input.attemptedAt);
return;
case "hasPending": return hasPendingContextEngineTurn(n, t.input);
case "enqueueIntent":
enqueueContextEngineTurnIntent({
...t.input,
database: n
});
return;
case "acceptIntent":
acceptContextEngineTurnIntent({
...t.input,
database: n
});
return;
case "publishClosedTurn": return publishClosedContextEngineTurn({
...t.input,
database: n
});
case "discardIntent": return discardContextEngineTurnIntent({
...t.input,
database: n
});
}
throw new Error("Unknown context-engine turn outbox command");
}
//#endregion
//#region src/agents/harness/context-engine-turn-outbox.worker.ts
/** Borrows the canonical agent connection for one admitted outbox operation. */
function bindSqliteWorkerBackend(e, t) {
const n = t.database;
return bindSqliteWorkerDatabase(n, { execute(e) {
return runSqliteWorkerTransactionSync(t, () => executeContextEngineTurnOutboxCommand(n, e), {
operationLabel: `context-engine.turn-outbox.${e.type}`,
busyTimeoutMs: OPENCLAW_SQLITE_BUSY_TIMEOUT_MS,
databaseLabel: t.databasePath
});
} });
}
//#endregion
export { bindSqliteWorkerBackend };