UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

179 lines (178 loc) • 6.82 kB
import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs"; import { _ as sql, s as getNodeSqliteKysely, t as compileSqliteQueryBindings } from "./kysely-sync-YJo2lmGV.mjs"; import { Et as _enum, Jn as string, Nt as array, Pn as number, Sn as looseObject, sr as unknown, xn as literal } from "./schemas-Cy6abvsu.mjs"; import { i as openOpenClawAgentDatabase } from "./openclaw-agent-db-CwXW4hGa.mjs"; import { t as BoundedSerialQueue } from "./bounded-serial-queue-6-ks67fw.mjs"; //#region src/talk/voice-transcript.ts /** Transcript row identity shared by persistence and live relay captions. */ function voiceTranscriptEventId(e, t) { return `voice:${e}:${t}`; } function buildPersistedVoiceMessage(e) { const t = { kind: "realtime_voice", sourceChannel: "talk" }; if (e.role === "user") return { role: "user", content: [{ type: "text", text: e.text }], timestamp: e.timestamp, provenance: t }; return { role: "assistant", content: [{ type: "text", text: e.text }], api: "realtime", provider: e.provider, model: "realtime-voice", stopReason: "stop", ...e.providerOwned ? { __openclaw: { voiceTranscript: "provider-owned" } } : {}, timestamp: e.timestamp, provenance: t }; } const VOICE_TRANSCRIPT_MAX_CHARS = 8e3; const VOICE_TRANSCRIPT_QUEUE_MAX_PENDING = 40; const VOICE_TRANSCRIPT_QUEUE_MAX_PENDING_CHARS = VOICE_TRANSCRIPT_QUEUE_MAX_PENDING * VOICE_TRANSCRIPT_MAX_CHARS; const VOICE_TRANSCRIPT_QUEUE_OVERFLOW_MESSAGE = "Voice transcript persistence could not keep up; the realtime session was stopped."; function normalizeVoiceTranscriptText(e) { return truncateUtf16Safe(e.trim(), VOICE_TRANSCRIPT_MAX_CHARS); } const VOICE_TRANSCRIPT_QUEUE_POLICY = { maxPendingCount: VOICE_TRANSCRIPT_QUEUE_MAX_PENDING, maxEntryChars: VOICE_TRANSCRIPT_MAX_CHARS, overflowMessage: VOICE_TRANSCRIPT_QUEUE_OVERFLOW_MESSAGE, createQueue: () => new BoundedSerialQueue({ maxPendingCount: VOICE_TRANSCRIPT_QUEUE_MAX_PENDING, maxPendingWeight: VOICE_TRANSCRIPT_QUEUE_MAX_PENDING_CHARS }) }; var VoiceTranscriptOperationRegistry = class { constructor() { this.owners = /* @__PURE__ */ new Map(); } getOrCreate(e) { const t = this.owners.get(e); if (t) return t; const n = { queue: VOICE_TRANSCRIPT_QUEUE_POLICY.createQueue() }; this.owners.set(e, n); return n; } cleanup(e, t) { if (this.owners.get(e) === t && !t.closePromise && t.queue.isIdle && !t.queue.didOverflow) this.owners.delete(e); } async run(e, t, n = {}) { const r = this.getOrCreate(e); if (r.closePromise) throw new Error("voice transcript persistence session is closing"); const i = r.queue.enqueue(t, n); if (i.accepted) { i.completion.then(() => this.cleanup(e, r), () => this.cleanup(e, r)); return await i.completion; } throw new Error(r.queue.didOverflow ? "voice transcript persistence queue capacity exceeded" : "voice transcript persistence session is closed"); } async close(e, t) { const n = this.getOrCreate(e); if (!n.closePromise) { n.queue.seal(); n.closePromise = n.queue.flush({ requireSuccess: true }).then(t); } try { await n.closePromise; } finally { if (this.owners.get(e) === n) this.owners.delete(e); } } async flush(e) { await this.owners.get(e)?.queue.flush({ requireSuccess: true }); } clear() { this.owners.clear(); } }; //#endregion //#region src/talk/client-voice-session-store.ts const VOICE_SESSION_CACHE_SCOPE = "talk-client-voice-sessions"; const VOICE_SESSION_RECORD_VERSION = 1; const VOICE_SESSION_STALE_AFTER_MS = 216e5; const TRANSCRIPT_FAILURE_KEY_PATTERN = /^[0-9a-f]{64}$/; const clientVoiceToolEffectSchema = looseObject({ runId: string(), toolName: string(), startedAt: number(), status: _enum([ "started", "succeeded", "failed", "cancelled", "blocked" ]) }); const clientVoiceSessionRecordSchema = looseObject({ version: literal(1), voiceSessionId: string(), agentId: string(), sessionKey: string(), provider: string().refine((e) => e.trim().length > 0).transform((e) => e.trim()).optional(), origin: _enum(["client", "relay"]), status: _enum(["open", "closed"]), createdAt: number(), updatedAt: number(), consultRunIds: unknown().optional().transform((e) => Array.isArray(e) ? e.filter((e) => typeof e === "string") : []), effects: unknown().optional().transform((e) => Array.isArray(e) ? e.flatMap((e) => { const t = clientVoiceToolEffectSchema.safeParse(e); return t.success ? [t.data] : []; }) : []), /** Bounded hashes of transcript entries that must succeed before close can commit. */ transcriptFailureKeys: unknown().optional().transform((e) => e ?? []).pipe(array(string().regex(TRANSCRIPT_FAILURE_KEY_PATTERN)).max(41).refine((e) => new Set(e).size === e.length)) }); function parseStoredVoiceSessionRecord(e) { if (typeof e !== "string") return; try { const t = clientVoiceSessionRecordSchema.safeParse(JSON.parse(e)); return t.success ? t.data : void 0; } catch { return; } } function readVoiceSessionRecord(e, t, n) { return readVoiceSessionRecordInTransaction(openOpenClawAgentDatabase({ ...n, agentId: e }), t); } function voiceSessionRowsQuery(e) { return getNodeSqliteKysely(e.db).selectFrom("cache_entries").select("value_json").where("scope", "=", sql.lit(VOICE_SESSION_CACHE_SCOPE)); } function readVoiceSessionRecordInTransaction(e, t) { const { compiled: n, bind: r } = compileSqliteQueryBindings(() => voiceSessionRowsQuery(e).where("key", "=", t)); return parseStoredVoiceSessionRecord(e.db.prepare(n.sql).get(...r())?.value_json); } function writeVoiceSessionRecordInTransaction(e, t) { const { compiled: n, bind: r } = compileSqliteQueryBindings((t) => getNodeSqliteKysely(e.db).insertInto("cache_entries").values({ scope: VOICE_SESSION_CACHE_SCOPE, key: t((e) => e.voiceSessionId), value_json: t((e) => JSON.stringify(e)), blob: null, expires_at: null, updated_at: t((e) => e.updatedAt) }).onConflict((e) => e.columns(["scope", "key"]).doUpdateSet((e) => ({ value_json: e.ref("excluded.value_json"), updated_at: e.ref("excluded.updated_at") })))); e.db.prepare(n.sql).run(...r(t)); } function assertVoiceSessionOwnership(e, t) { if (e.agentId !== t.agentId || e.sessionKey !== t.sessionKey) throw new Error("voice session does not belong to this agent session"); } function operationKey(e, t) { return `${e}\0${t}`; } //#endregion export { readVoiceSessionRecord as a, writeVoiceSessionRecordInTransaction as c, buildPersistedVoiceMessage as d, normalizeVoiceTranscriptText as f, parseStoredVoiceSessionRecord as i, VOICE_TRANSCRIPT_QUEUE_POLICY as l, assertVoiceSessionOwnership as n, readVoiceSessionRecordInTransaction as o, voiceTranscriptEventId as p, operationKey as r, voiceSessionRowsQuery as s, VOICE_SESSION_STALE_AFTER_MS as t, VoiceTranscriptOperationRegistry as u };