openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
544 lines (543 loc) • 18.2 kB
JavaScript
import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs";
import { n as sanitizeTerminalText } from "./safe-text-C80HAQ2e.mjs";
import "./utils-C8YECn2Q.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { i as throwCollectedErrors, o as throwSettledAggregate } from "./error-graph-internal-DdjdM90N.mjs";
import { n as awaitWithinDeadline, t as ABSOLUTE_DEADLINE_EXPIRED } from "./absolute-deadline-kK4DcdPs.mjs";
import { m as runPluginCleanup } from "./plugin-instance-scope-oezVdCr2.mjs";
import { i as normalizeCapabilityProviderId } from "./provider-registry-shared-C3T4TYXW.mjs";
import { n as monotonicNow } from "./monotonic-time-Cc4T2fkU.mjs";
import { n as activeSessions, o as retainTranscriptStartRetry, t as TranscriptStartError } from "./capture-startup-BofmyDmE.mjs";
import { i as TranscriptsSummaryChangedError } from "./store-export-state-BNN9x7Fs.mjs";
import "./store-SDevoi8g.mjs";
import { a as createTranscriptSessionId, f as resolveSourceProvider, m as startTranscripts, p as resolveTranscriptSourceOwnership, r as stopTranscriptCapture, t as createTranscriptsStore, u as isTranscriptSessionStarting } from "./capture-operations-DyaUgdfk.mjs";
import { t as resolveTranscriptsConfig } from "./config-htoIOq74.mjs";
import { v as sanitizeTranscriptSourceLocator, y as sourceFromParams } from "./store-read-CnSuQ-FE.mjs";
import { x as transcriptSessionSelector } from "./store-sqlite-Bq-TS7na.mjs";
import { t as beginConfiguredTranscriptStarts } from "./configured-start-status-oKRXv6a-.mjs";
import { isDeepStrictEqual } from "node:util";
//#region src/transcripts/auto-start-retry.ts
/** Own one configured entry's failed admission through retry and abandonment. */
function createTranscriptAutoStartRetry(e) {
let t;
const clear = () => {
t?.release();
t = void 0;
};
return {
get current() {
return t;
},
clear,
async retainFailure(n, r, i) {
const a = n.retry;
try {
if (a) {
r?.assertCurrent();
const n = a.discardOnAbandon || r?.discardOnAbandon === true && r.session.sessionId === a.session.sessionId && r.session.startedAt === a.session.startedAt;
clear();
t = retainTranscriptStartRetry(e.stateDir, {
...a,
discardOnAbandon: n
});
} else clear();
} catch (e) {
clear();
throw e;
}
if (!r && i && n.code === "id-conflict" && n.cause instanceof TranscriptsSummaryChangedError && !await e.store.readSession(transcriptSessionSelector(i))) throw new Error("transcript reopen candidate was discarded before admission", { cause: n });
},
async discard() {
const n = t;
if (!n) return;
try {
if (n.discardOnAbandon) await e.store.deleteEmptySessionCandidate(n.session, {
expectedInputRevision: n.revision,
assertCurrent: () => {
n.assertCurrent();
if (t !== n || activeSessions.has(n.session.sessionId) || isTranscriptSessionStarting(n.session.sessionId)) throw new TranscriptStartError("id-conflict", /* @__PURE__ */ new Error("transcript candidate has a new capture owner"));
}
});
} catch (t) {
if (!(t instanceof TranscriptStartError || t instanceof TranscriptsSummaryChangedError)) e.warn(t);
} finally {
n.release();
if (t === n) t = void 0;
}
}
};
}
//#endregion
//#region src/transcripts/config-reload.ts
function withoutTitles(e) {
return e && {
...e,
...e.autoStart && { autoStart: e.autoStart.map(({ title: e, ...t }) => t) }
};
}
/** Compare full source intent before reading titles, without borrowing new routing authority. */
function hasSameTranscriptCaptureIntent(e, t) {
return isDeepStrictEqual(withoutTitles(e), withoutTitles(t));
}
//#endregion
//#region src/transcripts/auto-start.ts
const AUTO_START_RETRY_ATTEMPTS = 12;
const AUTO_START_RETRY_MS = 5e3;
const AUTO_START_STOP_TIMEOUT_MS = 5e3;
const AUTO_START_PROVIDER_READY_TIMEOUT_MS = 3e4;
const AUTO_START_OCCUPANCY_EMPTY_GRACE_MS = 3e4;
const AUTO_START_OCCUPANCY_REOPEN_WINDOW_MS = 6e5;
function formatAutoStopDiagnostic(e) {
return JSON.stringify(truncateUtf16Safe(sanitizeTerminalText(formatErrorMessage(e)), 300));
}
function matchesConfiguredSource(e, t, n) {
return hasSameTranscriptCaptureIntent({ autoStart: e.config?.transcripts?.autoStart?.slice(e.index, e.index + 1) }, { autoStart: t?.transcripts?.autoStart?.slice(n, n + 1) });
}
/** Own configured captures independently of the room's provider connection. */
function createTranscriptsAutoStartService(e, t) {
const n = /* @__PURE__ */ new Set();
const r = /* @__PURE__ */ new Map();
const i = /* @__PURE__ */ new Map();
let a = false;
let o;
return {
start(s = e.config) {
if (a) return { settled: Promise.resolve() };
o = beginConfiguredTranscriptStarts();
const c = resolveTranscriptsConfig(s?.transcripts);
if (!c.enabled) return { settled: Promise.resolve() };
const l = new Set(n);
for (const [a, u] of c.autoStart.entries()) {
const c = [...l].find((e) => matchesConfiguredSource(e.owner, s, a));
if (c) {
c.owner.index = a;
c.owner.config = s;
if (c.owner.diagnostic) {
c.owner.diagnostic[0] = a;
o.record(...c.owner.diagnostic);
}
l.delete(c);
continue;
}
const d = normalizeCapabilityProviderId(u.providerId);
const f = {
index: a,
config: s
};
n.add({
owner: f,
providerId: d,
...startTranscriptsAutoStartEntry({
...e,
config: s
}, u, f, r, i, (e, t) => {
f.diagnostic = [
f.index,
e,
t
];
o?.record(...f.diagnostic);
}, t ?? (() => f.config))
});
}
return { settled: Promise.allSettled([...n].flatMap((e) => Array.from(e.pendingStarts))).then(() => void 0) };
},
async stop(t, i) {
a ||= t === void 0;
if (a) o?.clear();
const s = resolveTranscriptsConfig(i?.transcripts);
const c = new Set(s.enabled ? s.autoStart.map((e, t) => t) : []);
const l = [...n].filter((e) => {
if (!t || e.providerId && t.has(e.providerId)) return true;
if (!i) return false;
const n = [...c].find((t) => matchesConfiguredSource(e.owner, i, t));
if (n === void 0) return true;
c.delete(n);
return false;
});
const u = Promise.allSettled(l.map(async (e) => {
e.stopping ??= e.stop(t !== void 0).finally(() => {
e.stopping = void 0;
});
if (!await e.stopping) {
if (t) throw new Error("Transcript auto-start capture cleanup remains pending");
return;
}
n.delete(e);
for (const [t, n] of r) if (n === e.owner) r.delete(t);
}));
if (await awaitWithinDeadline(() => Promise.allSettled(l.flatMap((e) => Array.from(e.pendingStarts))), monotonicNow() + AUTO_START_STOP_TIMEOUT_MS, monotonicNow) === ABSOLUTE_DEADLINE_EXPIRED) {
u.then((t) => {
for (const n of t) if (n.status === "rejected") e.logger.warn(`transcripts autoStart cleanup failed: ${formatAutoStopDiagnostic(n.reason)}`);
});
if (t) throw new Error("Transcript auto-start stop timed out waiting for pending starts; retry after the provider finishes stopping");
e.logger.warn(`transcripts autoStart stop timed out waiting for pending starts`);
return;
}
throwSettledAggregate(await u, "Transcript auto-start cleanup failed");
}
};
}
function startTranscriptsAutoStartEntry(e, t, n, r, i, a, o) {
let s = false;
const c = createTranscriptsStore(e);
const l = /* @__PURE__ */ new Set();
let u;
let d;
const f = /* @__PURE__ */ new Map();
const p = /* @__PURE__ */ new Set();
const m = /* @__PURE__ */ new Set();
let h;
const g = createTranscriptAutoStartRetry({
stateDir: e.stateDir,
store: c,
warn: (t) => e.logger.warn(`transcripts autoStart empty candidate cleanup failed: ${formatAutoStopDiagnostic(t)}`)
});
const futureTitle = () => {
const e = o();
const t = hasSameTranscriptCaptureIntent(n.config?.transcripts, e?.transcripts) ? e : n.config;
return resolveTranscriptsConfig(t?.transcripts).autoStart[n.index]?.title;
};
const terminalDiagnostic = (e) => e instanceof TranscriptStartError && !e.retry ? e.code : void 0;
const schedule = (e, t) => {
const n = setTimeout(() => {
l.delete(n);
e();
}, t);
n.unref();
l.add(n);
return n;
};
const cancel = (e) => {
if (e) {
clearTimeout(e);
l.delete(e);
}
};
const runPending = (e) => {
const t = new AbortController();
p.add(t);
const n = e(t).finally(() => {
p.delete(t);
m.delete(n);
});
m.add(n);
return n;
};
const ownsCapture = (e) => activeSessions.get(e.sessionId)?.lifecycleToken === e.lifecycleToken;
const forgetCapture = (e) => {
if (!ownsCapture(e) && f.get(e.sessionId) === e.lifecycleToken) {
f.delete(e.sessionId);
if (i.get(e.sessionId) === e.lifecycleToken) i.delete(e.sessionId);
}
};
const stopCapture = async (t, n = false) => {
const r = [];
try {
const i = activeSessions.get(t.sessionId);
if (!i || i.lifecycleToken !== t.lifecycleToken) {
forgetCapture(t);
return;
}
const a = await stopTranscriptCapture({
ctx: e,
store: c,
selection: {
session: i.session,
selector: transcriptSessionSelector(i.session),
activeCandidate: i,
selectedActive: i,
historicalRevision: void 0
}
});
if (a.status === "skipped") {
if (n && a.reason !== "inactive") throw new Error(`Transcripts session stop still in progress: ${t.sessionId}`);
forgetCapture(t);
return;
}
if (typeof a.summaryExportError === "string") r.push(`summary saved; export failed intendedSummaryPath=${formatAutoStopDiagnostic(a.intendedSummaryPath)}: ${formatAutoStopDiagnostic(a.summaryExportError)}. Correct the export destination, then run openclaw transcripts path <session> or openclaw transcripts show <session>.`);
if (typeof a.providerStopError === "string") r.push(`provider stop failed: ${formatAutoStopDiagnostic(a.providerStopError)}. Check the provider capture status and connection.`);
} catch (e) {
if (n) throw e;
r.push(`stop failed: ${formatAutoStopDiagnostic(e)}`);
}
for (const n of r) e.logger.warn(`transcripts autoStart session=${formatAutoStopDiagnostic(t.sessionId)}: ${n}`);
forgetCapture(t);
};
const startCapture = async (t, n) => {
a(t.lifecycleToken, "starting");
const r = g.current;
try {
const i = await startTranscripts({
...n,
retry: r,
ctx: e,
store: c,
startupWaitMs: AUTO_START_PROVIDER_READY_TIMEOUT_MS,
configuredLifecycle: true,
lifecycleToken: t.lifecycleToken,
rawParams: {
...n.rawParams,
sessionId: t.sessionId
}
});
g.clear();
if (!s) a(t.lifecycleToken, i.status === "ended" ? "ended" : void 0);
return i;
} catch (e) {
if (e instanceof TranscriptStartError) await g.retainFailure(e, r, n.existingSession);
throw e;
} finally {
if (ownsCapture(t)) {
f.set(t.sessionId, t.lifecycleToken);
i.set(t.sessionId, t.lifecycleToken);
}
}
};
const startContinuous = (r) => {
if (s) return;
const o = {
sessionId: g.current?.session.sessionId ?? t.sessionId ?? createTranscriptSessionId(),
lifecycleToken: Symbol(t.sessionId)
};
runPending(async (c) => {
try {
if (i.has(t.sessionId ?? "")) throw new TranscriptStartError("id-conflict", /* @__PURE__ */ new Error("transcripts session already started by this service"));
await startCapture(o, {
sessionIdOrigin: t.sessionId ? "supplied" : "generated",
abortSignal: c.signal,
rawParams: {
...t,
title: futureTitle()
}
});
} catch (t) {
if (s) return;
const i = terminalDiagnostic(t);
const c = ownsCapture(o);
if (i || c || r >= AUTO_START_RETRY_ATTEMPTS) {
await g.discard();
if (s) return;
const t = i ?? "start-failed";
a(o.lifecycleToken, t);
e.logger.warn(`transcripts autoStart source ${n.index + 1}: ${t}. Check Meeting capture health in Settings.`);
} else {
a(o.lifecycleToken, "retrying");
schedule(() => startContinuous(r + 1), AUTO_START_RETRY_MS);
}
}
});
};
const watchEntry = async () => {
let o = false;
let l = false;
let f;
let p;
let m;
let _;
let v;
let y;
let b = Symbol(`transcripts occupancy ${n.index}`);
const label = () => `transcripts autoStart[${n.index}] provider=${t.providerId}`;
const retry = async (t, n, r, i) => {
if (s) return;
const o = terminalDiagnostic(r);
if (o || n >= AUTO_START_RETRY_ATTEMPTS) {
await g.discard();
if (s) return;
a(b, o ?? "start-failed");
e.logger.warn(`${label()} failed: ${formatAutoStopDiagnostic(r)}; check the entry and provider connection. ${i === "watch" ? "Reload the provider plugin to retry occupancy watching." : "Waiting for the next occupancy transition."}`);
return;
}
a(b, "retrying");
cancel(v);
v = schedule(t, AUTO_START_RETRY_MS);
};
const begin = (n) => {
if (s || !l || !o || p || h) return;
if (f && ownsCapture(f) && activeSessions.get(f.sessionId)?.phase === "active") return;
p = runPending(async (r) => {
m = r;
try {
if (f) {
await stopCapture(f);
if (ownsCapture(f)) throw new Error("previous capture still awaits finalization");
}
if (s || !o || r.signal.aborted) return;
const n = Date.now();
const a = g.current;
const l = a ? {
session: a.session,
inputRevision: a.revision
} : await c.readRecentStoppedSession(sanitizeTranscriptSourceLocator(y), (/* @__PURE__ */ new Date(n - AUTO_START_OCCUPANCY_REOPEN_WINDOW_MS)).toISOString(), new Date(n).toISOString());
if (s || !o || r.signal.aborted) return;
const u = l && l.session.metadata?.sessionIdOrigin === "generated" && (!(y.agentId ?? e.agentId) || (l.session.metadata?.agentId ?? "main") === (y.agentId ?? e.agentId)) && !activeSessions.has(l.session.sessionId) && !isTranscriptSessionStarting(l.session.sessionId) && !i.has(l.session.sessionId) ? l : void 0;
const d = {
sessionId: u?.session.sessionId ?? createTranscriptSessionId(),
lifecycleToken: Symbol(label())
};
b = d.lifecycleToken;
f = d;
if ((await startCapture(d, {
sessionIdOrigin: "generated",
abortSignal: r.signal,
existingSession: u?.session,
existingSessionCondition: u ? {
expectedInputRevision: u.inputRevision,
assertCurrent: () => {
if (s || !o || r.signal.aborted || f !== d) throw new TranscriptStartError("id-conflict", /* @__PURE__ */ new Error("transcript occupancy changed before reopening"));
}
} : void 0,
rawParams: {
...t,
...y,
title: futureTitle()
},
onCaptureEnded: () => {
if (f !== d || s || !o) return;
forgetCapture(d);
cancel(v);
v = schedule(() => begin(1), AUTO_START_RETRY_MS);
}
})).status === "ended") throw new Error("capture ended during startup");
} catch (e) {
if (f && !ownsCapture(f)) f = void 0;
if (o && !r.signal.aborted) await retry(() => begin(n + 1), n, e, "capture");
} finally {
m = void 0;
}
}).finally(() => {
p = void 0;
});
};
const end = () => {
if (h) return;
h = (async () => {
m?.abort();
await p;
await g.discard();
if (f) {
await stopCapture(f);
if (!ownsCapture(f)) f = void 0;
}
if (!f) a(b);
})().finally(() => {
h = void 0;
if (o && !s) begin(1);
});
};
const arm = (i) => {
if (s) return;
d = runPending(async (c) => {
try {
const i = resolveSourceProvider(t.providerId, e);
if (!i) throw new Error("provider is not available");
if (!i.watchOccupancy) {
a(b, "start-failed");
e.logger.warn(`${label()} cannot report occupancy; remove whenOccupied or select a provider that supports occupancy watching.`);
return;
}
g.clear();
y = resolveTranscriptSourceOwnership({
ctx: e,
operation: "start",
provider: i,
source: {
...sourceFromParams(t),
providerId: i.id
},
configuredLifecycle: true
});
if (y.guildId) {
const t = JSON.stringify([
i.id,
y.accountId,
y.guildId
]);
const o = r.get(t);
if (o !== void 0 && o !== n) {
a(b, "start-failed");
e.logger.warn(`${label()} skipped: autoStart[${o.index}] already owns this provider account and guild; configure only one whenOccupied entry per account and guild.`);
return;
}
r.set(t, n);
}
const d = await i.watchOccupancy({
cfg: e.config,
source: y,
abortSignal: c.signal,
startupWaitMs: AUTO_START_PROVIDER_READY_TIMEOUT_MS,
onOccupied: () => {
if (s || c.signal.aborted || o) return;
o = true;
cancel(_);
cancel(v);
begin(1);
},
onEmpty: () => {
if (s || c.signal.aborted || !o) return;
o = false;
cancel(v);
cancel(_);
_ = schedule(end, AUTO_START_OCCUPANCY_EMPTY_GRACE_MS);
}
});
if (!d.ok) throw new Error(d.error);
u = d.value;
if (s) return;
l = true;
a(b);
begin(1);
} catch (e) {
c.abort();
o = false;
cancel(_);
await retry(() => arm(i + 1), i, e, "watch");
}
});
};
arm(1);
await d;
await p;
};
if (t.whenOccupied) {
const e = watchEntry().finally(() => m.delete(e));
m.add(e);
} else startContinuous(1);
const stop = async (e) => {
s = true;
for (const e of l) clearTimeout(e);
l.clear();
for (const e of p) e.abort();
await d;
const t = [];
if (u) {
const e = u;
try {
await runPluginCleanup(e.stop, () => e.stop());
u = void 0;
} catch (e) {
t.push(e);
}
}
await Promise.allSettled(m);
await Promise.allSettled(h ? [h] : []);
await g.discard();
for (const [n, r] of f) try {
await stopCapture({
sessionId: n,
lifecycleToken: r
}, e);
} catch (e) {
t.push(e);
}
throwCollectedErrors(t, "Transcript entry cleanup failed");
return f.size === 0;
};
return {
stop,
pendingStarts: m
};
}
//#endregion
export { createTranscriptsAutoStartService };