UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

640 lines (639 loc) • 22 kB
import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs"; import "./utils-C8YECn2Q.mjs"; import { a as throwIfSettledRejected, i as throwCollectedErrors } from "./error-graph-internal-DdjdM90N.mjs"; import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs"; import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs"; import { n as createRuntimeConfigReader } from "./runtime-snapshot-WbwbY5b7.mjs"; import { m as runPluginCleanup } from "./plugin-instance-scope-oezVdCr2.mjs"; import { o as resolveAgentRoute } from "./resolve-route-DBnTWpM6.mjs"; import { t as isTranscriptArtifactText } from "./transcription-text-ie9Q72wO.mjs"; import { t as acquirePluginCapabilityProviders } from "./capability-provider-acquisition-gEC12OmD.mjs"; import { c as startingSessions, i as createStartupAbortScope, n as activeSessions, r as assertTranscriptCaptureEnabled, s as revokeTranscriptStartRetries, t as TranscriptStartError } from "./capture-startup-BofmyDmE.mjs"; import { i as TranscriptsSummaryChangedError, r as TranscriptSessionConflictError } from "./store-export-state-BNN9x7Fs.mjs"; import { i as readSummaryCaptureLiveness, r as persistTranscriptSummary, t as createTranscriptSummaryUpdates } from "./capture-summary-B0LBaZEh.mjs"; import { t as TranscriptsStore } from "./store-SDevoi8g.mjs"; import { t as resolveTranscriptsConfig } from "./config-htoIOq74.mjs"; import { t as getTranscriptSourceProvider } from "./provider-registry-Yp2-AYu0.mjs"; import { _ as readTranscriptStringParam, v as sanitizeTranscriptSourceLocator, y as sourceFromParams } from "./store-read-CnSuQ-FE.mjs"; import path from "node:path"; import { randomUUID } from "node:crypto"; //#region src/transcripts/capture-appends.ts /** Accepted speech belongs to its capture until the store has settled it. */ function createTranscriptCaptureAppends(e) { let t = Promise.resolve(); const n = /* @__PURE__ */ new Set(); return { async run(r) { const i = t; const a = createDeferredCore(); let o = true; n.add(a.promise); t = i.then(() => a.promise).then(() => void 0); const assertAccepted = () => { if (!o) throw new Error("Transcript append has already settled"); e(); }; const schedule = (e) => i.then(() => { assertAccepted(); return e(assertAccepted); }); const finish = (e) => { o = false; n.delete(a.promise); a.resolve(e); }; try { await r(schedule); finish({ ok: true }); } catch (e) { finish({ ok: false, error: e }); throw e; } }, async drain() { const e = (await Promise.all(n)).flatMap((e) => e.ok ? [] : [e.error]); throwCollectedErrors(e, "Accepted transcript appends failed"); } }; } //#endregion //#region src/transcripts/manual-source.ts /** * This provider turns pasted text into final transcript utterances, optionally * splitting "Speaker: text" prefixes into speaker labels. */ function parseSpeakerLine(e) { const t = /^([^:\n]{1,80}):\s+(.+)$/.exec(e.trim()); if (!t) return { text: e.trim() }; return { speakerLabel: t[1]?.trim(), text: t[2]?.trim() ?? "" }; } /** Built-in provider for post-hoc transcript text imports. */ const manualTranscriptSourceProvider = { id: "manual-transcript", aliases: ["import", "transcript"], name: "Manual Transcript Import", sourceKinds: ["posthoc-transcript"], async importTranscript(e) { const t = (/* @__PURE__ */ new Date()).toISOString(); return e.text.split(/\r?\n/).map((e) => parseSpeakerLine(e)).filter((e) => e.text).map((n, r) => ({ id: `${e.session.sessionId}-${r + 1}`, sessionId: e.session.sessionId, startedAt: t, final: true, speaker: { label: n.speakerLabel ?? e.speakerLabel ?? "Speaker" }, text: n.text })); } }; //#endregion //#region src/transcripts/capture.ts const ACCOUNT_ID_OUTPUT_MAX_CHARS = 64; function formatTranscriptAccountId(e) { return JSON.stringify(truncateUtf16Safe(e, ACCOUNT_ID_OUTPUT_MAX_CHARS)); } function isTranscriptSelectionOwned(e) { return activeSessions.get(e.session.sessionId) === e.activeCandidate; } async function isTranscriptSelectionCurrent(e, t) { if (!isTranscriptSelectionOwned(e)) return false; if (e.selectedActive) return true; if (e.historicalRevision === void 0) return false; const n = await t.readSummaryInputRevision(e.session); return isTranscriptSelectionOwned(e) && n === e.historicalRevision; } /** Read-only process facts; a retained stop/cleanup owner does not prove capture is armed. */ function readTranscriptCaptureSnapshot() { return [...[...activeSessions.values()].filter((e) => e.phase !== "terminal" && e.phase !== "failed").map((e) => ({ session: { sessionId: e.session.sessionId, startedAt: e.session.startedAt, source: { ...e.session.source } }, providerId: e.providerId, configuredSource: e.configuredSource ? { ...e.configuredSource } : void 0, lifecycleToken: e.lifecycleToken, state: e.phase === "active" && !e.stopping && !e.cleanupPending ? "armed" : "unknown" })), ...readSummaryCaptureLiveness().filter(({ session: e }) => activeSessions.get(e.sessionId)?.session.startedAt !== e.startedAt)]; } function isTranscriptSessionActive(e) { const t = activeSessions.get(e.sessionId); return t?.session.startedAt === e.startedAt ? t.phase !== "terminal" : readSummaryCaptureLiveness().some(({ session: t }) => t.sessionId === e.sessionId && t.startedAt === e.startedAt); } function isTranscriptSessionStarting(e) { return startingSessions.has(e); } async function settleTranscriptCaptureWork(e) { const t = await Promise.allSettled([e.appends.drain(), e.summaryUpdates?.stop()]); throwIfSettledRejected(t, "Transcript append and summary shutdown failed"); } function finalizeTranscriptCapture(e) { const { entry: t } = e; t.phase = "terminal"; t.session = { ...t.session, stoppedAt: t.session.stoppedAt ?? (/* @__PURE__ */ new Date()).toISOString() }; if (!t.finalization) { const n = (async () => { await settleTranscriptCaptureWork(t); const assertCurrent = () => { if (activeSessions.get(t.session.sessionId) !== t) throw new TranscriptsSummaryChangedError(); }; await e.store.writeSession(t.session, { assertCurrent }); return await persistTranscriptSummary({ config: resolveTranscriptsConfig(e.ctx.config?.transcripts), cfg: e.ctx.config, stateDir: e.ctx.stateDir, store: e.store, session: t.session, assertCurrent }); })(); const r = n.then(async (e) => { await t.releaseProvider(); if (!t.stopping && activeSessions.get(t.session.sessionId) === t) activeSessions.delete(t.session.sessionId); return e; }).catch((n) => { delete t.finalization; e.ctx.logger.warn(`transcripts finalization failed session=${t.session.sessionId}; capture ended, use transcripts stop to retry: ${String(n)}`); throw n; }); t.finalization = { persisted: n, released: r }; r.catch(() => {}); } const { persisted: n, released: r } = t.finalization; return e.providerCallback ? n.then((e) => t.providerStopping ? e : r) : r; } function createTranscriptSessionId() { return `transcript-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}-${randomUUID().slice(0, 8)}`; } function resolveSourceProvider(e, t) { return e === manualTranscriptSourceProvider.id ? manualTranscriptSourceProvider : getTranscriptSourceProvider(e, t.config); } async function authorizeTranscriptSource(e) { e.ctx.assertCallerActive?.(); const t = e.provider.accessControl; if (!t) return; const n = e.ctx.caller; if (!n) throw new Error("transcripts caller authorization is unavailable"); const r = await t.authorize({ action: e.action, caller: n, cfg: e.ctx.config, source: e.source }); e.ctx.assertCallerActive?.(); if (!r.ok) throw new Error(r.error); } function resolveTranscriptSourceOwnership(e) { const t = e.provider.accessControl; const n = e.ctx.caller; let r; if (t && n?.kind !== "operator") { const i = t.channelId.trim().toLowerCase(); if (!i) throw new Error(`transcripts provider ${e.provider.id} has an invalid account owner channel`); const a = n?.channel?.trim().toLowerCase(); r = n?.accountId?.trim(); if (a && a !== i) throw new Error(`transcripts provider ${e.provider.id} can only ${e.operation} from ${i} or a channel-less local tool`); if (a && !r) throw new Error(`transcripts provider ${e.provider.id} requires trusted account context from ${a}`); } const i = r ? { ...e.source, accountId: r } : e.source; const a = t?.resolveAccountId({ cfg: e.ctx.config, source: i }); if (a && !a.ok) throw new Error(a.error); const o = a ? a.value?.trim() : i.accountId?.trim(); if (r && o !== r) throw new Error(`transcripts provider ${e.provider.id} could not use trusted account ${formatTranscriptAccountId(r)}`); const s = t ? { ...i, accountId: o } : i; if (e.configuredLifecycle && t && !o) throw new Error(`transcripts provider ${e.provider.id} could not resolve an account for configured auto-start`); const c = t?.channelId; if (e.configuredLifecycle && !e.ctx.agentId && e.ctx.config && c && s.channelId) s.agentId = resolveAgentRoute({ cfg: e.ctx.config, channel: c, accountId: s.accountId, guildId: s.guildId, peer: { kind: "channel", id: s.channelId } }).agentId; return s; } function stopTranscriptProviderCapture(e) { const { entry: t } = e; if (t.phase === "terminal") return Promise.resolve(void 0); return t.providerStopping ??= (async () => { const n = t.summaryUpdates?.stop(); let r; try { const n = await t.stopProvider({ cfg: e.ctx.config, sessionId: t.session.sessionId, source: t.session.source, reason: e.reason }); r = n.ok ? void 0 : n.error; } catch (e) { r = e instanceof Error ? e.message : String(e); } finally { await n; } if (r !== void 0 && activeSessions.get(t.session.sessionId) === t && t.phase !== "terminal") t.cleanupPending = true; return r; })().finally(() => { delete t.providerStopping; }); } async function startTranscripts(e) { try { var t = _usingCtx(); const n = e.retry?.session ?? e.existingSession; const r = e.retry ? { expectedInputRevision: e.retry.revision, assertCurrent: e.retry.assertCurrent } : e.existingSessionCondition; const i = createRuntimeConfigReader(e.ctx.config ?? {}); const assertEnabled = () => assertTranscriptCaptureEnabled({ ...e.ctx, config: i() }); assertEnabled(); if (e.abortSignal?.aborted) throw new Error("transcripts start aborted"); const a = { ...sourceFromParams(e.rawParams), ...e.ctx.agentId ? { agentId: e.ctx.agentId } : {} }; const o = e.configuredLifecycle ? { providerId: a.providerId, accountId: a.accountId, guildId: a.guildId, channelId: a.channelId, meetingUrl: Boolean(a.meetingUrl) } : void 0; const s = await acquirePluginCapabilityProviders({ key: "transcriptSourceProviders", providerId: a.providerId, cfg: e.ctx.config }); const c = t.a(new AsyncDisposableStack()); c.defer(s.release); const l = s.providers[0]; const u = l?.start; if (!l || !u) throw new Error(`transcripts provider ${a.providerId} cannot start live capture`); const d = resolveTranscriptSourceOwnership({ ctx: e.ctx, operation: "start", provider: l, source: a, configuredLifecycle: e.configuredLifecycle }); const f = e.ctx.agentId ?? d.agentId; if (n && f !== void 0 && (n.metadata?.agentId ?? "main") !== f) throw new TranscriptStartError("id-conflict", /* @__PURE__ */ new Error("transcripts capture belongs to a different agent; start a new capture")); if (!e.configuredLifecycle) await authorizeTranscriptSource({ action: "start", ctx: e.ctx, provider: l, source: d }); assertEnabled(); const p = readTranscriptStringParam(e.rawParams, "sessionId"); const m = { sessionId: n?.sessionId ?? p ?? createTranscriptSessionId(), title: n ? n.title : readTranscriptStringParam(e.rawParams, "title"), source: n?.source ?? sanitizeTranscriptSourceLocator(d), startedAt: n?.startedAt ?? (/* @__PURE__ */ new Date()).toISOString(), metadata: n ? n.metadata : { ...f ? { agentId: f } : {}, sessionIdOrigin: e.sessionIdOrigin ?? (p ? "supplied" : "generated") } }; if (activeSessions.has(m.sessionId) || startingSessions.has(m.sessionId)) throw new TranscriptStartError("id-conflict", /* @__PURE__ */ new Error(`transcripts session already active: ${m.sessionId}`)); const h = createStartupAbortScope(e.abortSignal); const g = createDeferredCore(); const _ = { abortStartup: h.abort, appends: createTranscriptCaptureAppends(() => { const e = activeSessions.get(m.sessionId); if (e !== _ && (e !== void 0 || startingSessions.get(m.sessionId) !== _)) throw new Error("Transcript capture no longer owns its accepted append"); }), session: m, providerId: l.id, stopProvider: (e) => s.run(() => runPluginCleanup(l, () => { const t = l.stop; if (!t) throw new Error(`transcripts provider ${l.id} cannot stop live capture`); return t.call(l, e); })), releaseProvider: s.release, phase: "starting", configuredSource: o, lifecycleToken: e.lifecycleToken }; if (!e.configuredLifecycle) _.directCapture = { stateDir: e.ctx.stateDir, async drain() { await g.promise; if (activeSessions.get(m.sessionId) !== _) return; const t = await stopTranscriptProviderCapture({ ctx: e.ctx, entry: _, reason: "capture-disabled" }); if (t !== void 0 && _.phase !== "terminal") throw new Error(`transcripts provider cleanup failed: ${t}`); await finalizeTranscriptCapture({ ...e, entry: _ }); } }; startingSessions.set(m.sessionId, _); let v; let y; try { try { v = await e.store.writeSession(m, r); } catch (e) { if (e instanceof TranscriptsSummaryChangedError) throw new TranscriptStartError("id-conflict", e); throw e; } if (!e.retry) revokeTranscriptStartRetries(e.ctx.stateDir, m); let t; try { assertEnabled(); h.signal.throwIfAborted(); _.summaryUpdates = await createTranscriptSummaryUpdates({ config: resolveTranscriptsConfig(e.ctx.config?.transcripts), cfg: e.ctx.config, stateDir: e.ctx.stateDir, store: e.store, session: m, logger: e.ctx.logger, assertCurrent: () => { if (activeSessions.get(m.sessionId) !== _ || _.phase !== "active" || _.stopping || _.cleanupPending) throw new TranscriptsSummaryChangedError(); } }); assertEnabled(); s.assertOpen(); h.signal.throwIfAborted(); t = await s.run(() => u.call(l, { cfg: e.ctx.config, session: { ...m, source: { ...d }, metadata: { ...m.metadata } }, abortSignal: h.signal, startupWaitMs: e.startupWaitMs, onUtterance: async (t) => { if (isTranscriptArtifactText(t.text) || _.phase === "terminal" || _.phase === "failed" || _.cleanupPending || (_.phase === "starting" ? h.signal?.aborted : activeSessions.get(m.sessionId) !== _)) return; await _.appends.run((n) => e.store.appendUtteranceForSession(m, t, n)); }, onStatus: async (t) => { if (t.active || _.phase === "failed" || _.phase === "terminal") return; if (_.phase !== "starting" && activeSessions.get(m.sessionId) !== _) return; _.phase = "terminal"; _.session = { ...m, stoppedAt: (/* @__PURE__ */ new Date()).toISOString() }; if (activeSessions.get(m.sessionId) === _) try { await finalizeTranscriptCapture({ ...e, entry: _, providerCallback: true }); } finally { if (!_.stopping) e.onCaptureEnded?.(); } } })); if (!t.ok) throw new Error(t.error); } catch (e) { _.phase = "failed"; throw e; } c.move(); activeSessions.set(m.sessionId, _); if (!n && !m.title) { const n = truncateUtf16Safe(t.session.title?.trim() ?? "", 120); if (n) { m.title = n; _.session = { ..._.session, title: n }; await e.store.writeSession(_.session); } } if (h.signal?.aborted) { _.cleanupPending = true; const t = await stopTranscriptProviderCapture({ ctx: e.ctx, entry: _, reason: "service-stop" }); if (t !== void 0) throw new Error(`transcripts start aborted; provider cleanup failed: ${t}`); await finalizeTranscriptCapture({ ...e, entry: _ }); throw new Error("transcripts start aborted"); } if (_.phase === "terminal") { await finalizeTranscriptCapture({ ...e, entry: _ }); return { status: "ended", session: _.session }; } _.phase = "active"; _.summaryUpdates.start(); return { status: "active", session: m, providerId: l.id }; } catch (t) { const r = _.cleanupPending; _.cleanupPending = true; let i = t; let a = false; try { await settleTranscriptCaptureWork(_); } catch (e) { a = true; i = new AggregateError([t, e], "Transcript startup and capture settlement failed"); } try { if (_.phase === "starting" && !r && activeSessions.get(m.sessionId) === _) { const n = await stopTranscriptProviderCapture({ ctx: e.ctx, entry: _, reason: "startup-failed" }); if (n !== void 0) throw new Error(`transcripts start failed session=${m.sessionId}; provider cleanup failed: ${n}`, { cause: t }); await finalizeTranscriptCapture({ ...e, entry: _ }); } if (_.phase === "failed" && v) { const t = n ?? { ...m, stoppedAt: (/* @__PURE__ */ new Date()).toISOString() }; const { inputRevision: r } = await e.store.writeSession(t, { expectedSessionRevision: v.sessionRevision }); y = { session: t, revision: r, discardOnAbandon: v.inserted }; } } catch (e) { i = a ? new AggregateError([i, e], "Transcript startup restoration failed") : e; y = void 0; } if (!v && i instanceof TranscriptSessionConflictError) throw new TranscriptStartError("id-conflict", i); throw v ? new TranscriptStartError("admitted-start-failed", i, y) : i; } finally { h.detach(); try { await c.disposeAsync(); } finally { g.resolve(); delete _.abortStartup; if (startingSessions.get(m.sessionId) === _) startingSessions.delete(m.sessionId); } } } catch (e) { t.e = e; } finally { await t.d(); } } //#endregion //#region src/transcripts/capture-operations.ts function createTranscriptsStore(e) { return new TranscriptsStore(path.join(e.stateDir, "transcripts"), { env: { ...process.env, OPENCLAW_STATE_DIR: e.stateDir } }); } async function exportTranscriptSummary(e, t, { summary: n, intendedSummaryPath: r }) { try { return { summary: n, summaryPath: (await e.materializeSessionArtifacts(t, "all")).summaryPath }; } catch (e) { return { summary: n, intendedSummaryPath: r, summaryExportError: String(e) }; } } async function stopTranscriptCapture(e) { const { selection: t } = e; const { session: n, selector: r, selectedActive: i } = t; const a = n.sessionId; const skip = (e) => ({ status: "skipped", reason: e, sessionId: a, selector: r }); const o = await isTranscriptSelectionCurrent(t, e.store); e.ctx.assertCallerActive?.(); if (!o || !isTranscriptSelectionOwned(t)) return skip("inactive"); if (isTranscriptSessionStarting(a)) return skip("starting"); if (i?.stopping) return skip("stopping"); revokeTranscriptStartRetries(e.ctx.stateDir, n); if (i) i.stopping = true; let s = false; try { let o; if (i && i.phase !== "terminal") { o = await stopTranscriptProviderCapture({ ctx: e.ctx, entry: i, reason: "tool-stop" }); if (activeSessions.get(a) !== i) return skip("inactive"); } if (o !== void 0 && i?.phase !== "terminal") throw new Error(`transcripts provider cleanup failed: ${o}. Use transcripts stop to retry.`); let c; let l; if (i) { c = await finalizeTranscriptCapture({ ...e, entry: i }); l = i.session; s = true; } else { const assertCurrent = () => { e.ctx.assertCallerActive?.(); if (!isTranscriptSelectionOwned(t) || isTranscriptSessionStarting(a)) throw new TranscriptsSummaryChangedError(); }; l = { ...n, stoppedAt: n.stoppedAt ?? (/* @__PURE__ */ new Date()).toISOString() }; if (!n.stoppedAt) try { await e.store.writeSession(l, { expectedInputRevision: t.historicalRevision, assertCurrent }); } catch (e) { if (e instanceof TranscriptsSummaryChangedError) return skip("inactive"); throw e; } c = await persistTranscriptSummary({ config: resolveTranscriptsConfig(e.ctx.config?.transcripts), cfg: e.ctx.config, stateDir: e.ctx.stateDir, store: e.store, session: l, expectedInputRevision: n.stoppedAt ? t.historicalRevision : void 0, assertCurrent }); } const { summaryPath: u, intendedSummaryPath: d, summary: f, summaryExportError: p } = await exportTranscriptSummary(e.store, l, c); return { status: "stopped", sessionId: a, selector: r, ...o !== void 0 ? { providerStopError: o } : {}, ...p ? { summaryExportError: p } : {}, ...d ? { intendedSummaryPath: d } : {}, summary: f, ...u ? { summaryPath: u } : {} }; } finally { if (i && activeSessions.get(a) === i) { delete i.stopping; if (s) activeSessions.delete(a); } } } //#endregion export { createTranscriptSessionId as a, isTranscriptSelectionOwned as c, readTranscriptCaptureSnapshot as d, resolveSourceProvider as f, manualTranscriptSourceProvider as h, authorizeTranscriptSource as i, isTranscriptSessionActive as l, startTranscripts as m, exportTranscriptSummary as n, formatTranscriptAccountId as o, resolveTranscriptSourceOwnership as p, stopTranscriptCapture as r, isTranscriptSelectionCurrent as s, createTranscriptsStore as t, isTranscriptSessionStarting as u };