UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

430 lines (429 loc) • 17.9 kB
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import { h as readRuntimeConfig } from "./runtime-snapshot-WbwbY5b7.mjs"; import { n as enqueueKeyedTask } from "./keyed-async-queue-DewLnYvW.mjs"; import "./runtime-config-snapshot-Dy0VFqWf.mjs"; import { i as resolveBrowserConfig, r as isLocalManagedProfile, s as resolveProfile } from "./config-ccOD-Wrr.mjs"; import "./runtime-env-D-Pa5lD6.mjs"; import { C as withoutBrowserSessionTabCleanup, J as getOptionalBrowserStateRuntime, Y as isBrowserStateRuntimeCurrent, _ as readBrowserDashboardTabs, f as parseBrowserSessionTabRecord, g as readBrowserDashboardStopIntents, h as readBrowserDashboardStopIntent, n as deleteBrowserDashboardStopIntent, p as persistBrowserDashboardStopIntent, q as getBrowserStateRuntime, r as deleteBrowserSessionTabIf, v as sameBrowserSessionTabRecord, y as updateBrowserSessionTab } from "./session-tab-store-B94ME8MA.mjs"; import { n as resolveCdpControlPolicy } from "./cdp-reachability-policy-DB0QjzXP.mjs"; import { f as resolveCdpTabOwnership, r as closeTrackedCdpTarget } from "./cdp.helpers-Bxe-G5Kr.mjs"; import { n as withBrowserRequestScope } from "./request-scope-M3R1qmlo.mjs"; import { a as trackSessionBrowserTab, s as withBrowserDashboardRegistration } from "./session-tab-tracking-eplXIJry.mjs"; import { t as closeBrowserDashboardTabs } from "./session-tab-registry-BPlTdnvh.mjs"; import { a as browserOpenTab, f as browserTabs } from "./client-CFLgsue5.mjs"; import { n as sameBrowserDashboardDefinition, t as readBrowserDashboardDefinition } from "./browser-dashboard-definition-C69ubA6g.mjs"; //#region extensions/browser/src/browser-dashboard-records.ts const logger = createSubsystemLogger("browser"); function emitDashboardChanged(e, t) { try { t.runtime?.dashboardEvents?.emit("dashboard_changed", { sessionKey: e.sessionKey, name: e.name, instanceId: e.instanceId }, { scope: "operator.admin" }); } catch (e) { logger.warn(`Browser dashboard invalidation unavailable: ${String(e)}`); } } async function tabsForDefinition(e, t, n) { return (await readBrowserDashboardTabs(n, t)).filter((t) => t.dashboard?.sessionKey === e.sessionKey && t.dashboard?.instanceId === e.instanceId && t.dashboard?.agentId === e.agentId && t.dashboard?.name === e.name).toSorted((e, t) => Number(t.dashboard?.state === "active") - Number(e.dashboard?.state === "active")); } function definitionOwnsTab(e, t) { return Boolean(e && e.profile === t.profile && e.url === t.dashboard?.url && e.instanceId === t.dashboard?.instanceId && e.sessionKey === t.dashboard?.sessionKey); } async function changeTabState(e, t, n) { const r = await updateBrowserSessionTab(e.storageKey, (n) => { const r = parseBrowserSessionTabRecord(n); if (!r?.dashboard || !sameBrowserSessionTabRecord(r, e)) return; return { ...withoutBrowserSessionTabCleanup(r), dashboard: { ...r.dashboard, state: t } }; }, n); return r ? { ...r, storageKey: e.storageKey } : void 0; } async function deleteStoppedTab(e, t) { return await deleteBrowserSessionTabIf(e.storageKey, (t) => { const n = parseBrowserSessionTabRecord(t); return Boolean(n && sameBrowserSessionTabRecord(n, e)); }, t); } async function releaseTab(e, t, n = {}) { if (n.prepareCurrent && !await n.prepareCurrent() || n.isCurrent?.() === false) return { released: false, closed: 0 }; const r = { ...t, ...n.sessionEntryCurrent ? { sessionEntryCurrent: n.sessionEntryCurrent } : {}, assertCurrent: () => { t.assertCurrent?.(); if (n.isCurrent?.() === false) throw new Error("Browser dashboard cleanup caller changed"); } }; if (e.dashboard?.state === "stopped") return { released: await deleteStoppedTab(e, r), closed: 0 }; const i = e.dashboard?.state === "released" ? e : await changeTabState(e, "released", r); const a = i ? await closeBrowserDashboardTabs([i], { ...n, authority: t }) : 0; return { released: (await readBrowserDashboardTabs(e.storageKey, { runtime: t.runtime })).length === 0, closed: a }; } async function closeStoppingTab(e, t, n, r = {}) { const i = await closeBrowserDashboardTabs([e], { ...r, authority: n }); if ((await readBrowserDashboardTabs(e.storageKey, { runtime: n.runtime })).some((e) => e.dashboard?.state === "stopped")) emitDashboardChanged(t, n); return i; } //#endregion //#region extensions/browser/src/browser-dashboard.ts function assertAuthority(e) { e.signal?.throwIfAborted(); e.assertCurrent?.(); } function bindDashboardAuthority(e) { const t = e.runtime ?? getBrowserStateRuntime(); return { ...e, runtime: t, assertCurrent: () => { assertAuthority(e); if (getOptionalBrowserStateRuntime() !== t) throw new Error("Browser dashboard runtime changed"); } }; } function operationKey(e) { return JSON.stringify([ e.sessionKey, e.agentId, e.instanceId ]); } function responseFor(e, t, n = false) { const r = t?.dashboard?.state === "stopped" || t?.dashboard?.state === "stopping" || !t && n; return { sessionKey: e.sessionKey, name: e.name, instanceId: e.instanceId, revision: e.revision, paused: r, stopping: t?.dashboard?.state === "stopping", url: e.url, ...e.title ? { title: e.title } : {}, ...t?.dashboard?.state === "active" ? { browserTab: { target: "host", profile: t.profile, targetId: t.nativeTargetId } } : {} }; } async function requireDefinition(e, t) { assertAuthority(t); const n = await readBrowserDashboardDefinition(e); assertAuthority(t); if (!n) throw new Error(`Browser dashboard ${e.name} is missing, invalid, or was replaced. Read the dashboard; repair it with widget_put using an HTTP(S) URL and a local managed profile, or remove the widget.`); return n; } async function assertDefinitionCurrent(e, t) { const n = await readBrowserDashboardDefinition(e); assertAuthority(t); if (!sameBrowserDashboardDefinition(e, n)) throw new Error(`Browser dashboard ${e.name} changed during this operation. Retry with its current definition.`); } async function resolveManagedProfile(e) { const { getBrowserControlState: t } = await import("./browser-control-state-DxvDusRL.mjs"); const n = t(); const r = n ? void 0 : readRuntimeConfig(); const i = n?.resolved ?? resolveBrowserConfig(r?.browser, r); const a = resolveProfile(i, e.profile); if (!a || !isLocalManagedProfile(a)) throw new Error(`Browser dashboard ${e.name} requires a local managed profile; ${e.profile} cannot be attached or routed to another host.`); return { profile: a, resolved: i, ssrfPolicy: resolveCdpControlPolicy(a, i.ssrfPolicy) }; } async function observeExistingTab(e, t, n) { const { profile: r, resolved: i, ssrfPolicy: a } = await resolveManagedProfile(e); assertAuthority(n); const o = await browserTabs(void 0, { profile: r.name, signal: n.signal }); assertAuthority(n); if (!o.running) return "unreachable"; if (!o.tabs.some((e) => e.targetId === t.nativeTargetId)) return "missing"; const s = await resolveCdpTabOwnership({ profileName: r.name, cdpUrl: r.cdpUrl, nativeTargetId: t.nativeTargetId, ssrfPolicy: a, timeoutMs: i.remoteCdpTimeoutMs, signal: n.signal }); assertAuthority(n); if (s.status !== "durable") throw new Error(`Could not verify the current browser instance for dashboard ${e.name}. Retry when the browser is available; its existing tab has been kept.`); return s.profileFingerprint === t.profileFingerprint && s.browserInstanceFingerprint === t.browserInstanceFingerprint ? "present" : "different-browser"; } async function materialize(e, t, n) { const { profile: r, resolved: i, ssrfPolicy: a } = await resolveManagedProfile(e); assertAuthority(n); const o = await readBrowserDashboardStopIntent(e, n); assertAuthority(n); const s = []; const c = await tabsForDefinition(e, n); assertAuthority(n); for (const r of c) { if (!definitionOwnsTab(e, r) || r.dashboard?.state === "released") { s.push({ tab: r, wasUnreachable: false }); continue; } if (r.dashboard?.state === "stopping" || r.dashboard?.state === "stopped") { if (!t) { await assertDefinitionCurrent(e, n); return responseFor(e, r); } s.push({ tab: r, wasUnreachable: false }); continue; } const i = await observeExistingTab(e, r, n); if (i === "present") { await assertDefinitionCurrent(e, n); const t = (await tabsForDefinition(e, n, r.storageKey))[0]; assertAuthority(n); if (!t || t.dashboard?.state !== "active") throw new Error("Dashboard tab stopped during this operation"); return responseFor(e, t); } s.push({ tab: r, wasUnreachable: i === "unreachable" }); } await assertDefinitionCurrent(e, n); if (!t && o && sameBrowserDashboardDefinition(o, e)) return responseFor(e, void 0, true); const l = await browserOpenTab(void 0, e.url, { profile: r.name, signal: n.signal, managedOnly: true }); const u = l.ownership; let d; try { if (u?.status !== "durable" || l.resolvedProfile !== r.name) throw new Error("Browser could not verify durable ownership for this dashboard tab"); d = await withBrowserDashboardRegistration(u.nativeTargetId, r.name, n, async (t) => { await assertDefinitionCurrent(e, t); if (s.some(({ tab: e, wasUnreachable: t }) => t && e.profileFingerprint === u.profileFingerprint && e.browserInstanceFingerprint === u.browserInstanceFingerprint)) throw new Error(`Browser dashboard ${e.name} was temporarily unreachable. Retry; its existing tab has been kept.`); for (const n of s) { if (n.tab.dashboard?.state === "stopping" && definitionOwnsTab(e, n.tab)) { await closeStoppingTab(n.tab, e, t); assertAuthority(t); const r = (await tabsForDefinition(e, t, n.tab.storageKey)).find((e) => e.dashboard?.state === "stopped"); assertAuthority(t); if (!r) throw new Error("Previous dashboard tab could not stop; retry when its browser is available"); n.tab = r; } if (n.tab.dashboard?.state === "stopped") continue; if (!(await releaseTab(n.tab, t)).released) throw new Error("Previous dashboard tab could not be released; retry when its browser is available"); assertAuthority(t); } await assertDefinitionCurrent(e, t); const n = await trackSessionBrowserTab({ sessionKey: e.sessionKey, targetId: u.nativeTargetId, profile: r.name, ownership: u, authority: t, dashboard: { name: e.name, sessionKey: e.sessionKey, instanceId: e.instanceId, agentId: e.agentId, url: e.url, state: "active" } }); if (!n) throw new Error("Browser dashboard target registration failed"); return n; }); } catch (e) { if (u?.status === "durable") try { const t = await closeTrackedCdpTarget({ profileName: r.name, cdpUrl: r.cdpUrl, nativeTargetId: u.nativeTargetId, expectedProfileFingerprint: u.profileFingerprint, expectedBrowserInstanceFingerprint: u.browserInstanceFingerprint, timeoutMs: i.remoteCdpTimeoutMs, ssrfPolicy: a }); if (t.status === "unavailable" || t.status === "cancelled") throw new Error(`New dashboard tab cleanup ${t.status}`, { cause: e }); } catch (t) { throw new AggregateError([e, t], "Dashboard creation failed; close its newly opened tab manually.", { cause: t }); } throw e; } assertAuthority(n); emitDashboardChanged(e, n); for (const { tab: e } of s) if (e.dashboard?.state === "stopped") await deleteStoppedTab(e, n); if (o) await deleteBrowserDashboardStopIntent(o, n); assertAuthority(n); return responseFor(e, d); } /** Re-resolve immediately before a model action crosses into Browser's normal dispatch. */ async function assertBrowserDashboardTargetCurrent(e, t, n = {}, r) { const i = bindDashboardAuthority(n); const a = await requireDefinition({ ...e, agentId: t }, i); const o = e.browserTab; if (!o) throw new Error("Dashboard has no active browser target"); const s = (await tabsForDefinition(a, i)).find((e) => definitionOwnsTab(a, e) && e.dashboard?.state === "active" && e.nativeTargetId === o.targetId && e.profile === o.profile); assertAuthority(i); if (!s) throw new Error("Dashboard browser target changed or stopped; resolve the dashboard again"); if (r) { if (r.name !== s.profile || !isLocalManagedProfile(r)) throw new Error("Dashboard browser profile changed; resolve the dashboard again"); const e = await resolveCdpTabOwnership({ profileName: r.name, cdpUrl: r.cdpUrl, nativeTargetId: s.nativeTargetId, signal: i.signal }); await assertDefinitionCurrent(a, i); const t = (await tabsForDefinition(a, i, s.storageKey)).find((e) => e.dashboard?.state === "active" && definitionOwnsTab(a, e)); assertAuthority(i); if (!t || e.status !== "durable" || e.profileFingerprint !== t.profileFingerprint || e.browserInstanceFingerprint !== t.browserInstanceFingerprint) throw new Error("Dashboard browser instance changed; reopen the dashboard before interacting"); } } async function serializeDashboardOperation(e, t, n) { const r = bindDashboardAuthority(t); const i = r.runtime; const a = await requireDefinition(e, r); const o = i.dashboardOperations; const s = operationKey(a); return await enqueueKeyedTask({ tails: o, key: s, task: async () => { return await n(await requireDefinition(a, r), r); } }); } /** Materialize once per board instance; hidden views do not own the target lifetime. */ async function requestBrowserDashboard(e, t = {}) { return await serializeDashboardOperation(e, t, (t, n) => withBrowserRequestScope({ assertCurrent: () => assertDefinitionCurrent(t, n) }, async () => await materialize(t, e.resume === true, n))); } /** Read saved Browser lifetime without opening or resuming a target. */ async function inspectBrowserDashboard(e, t = {}) { const n = bindDashboardAuthority(t); const r = await requireDefinition(e, n); const i = await readBrowserDashboardStopIntent(r, n); const a = (await tabsForDefinition(r, n)).find((e) => definitionOwnsTab(r, e) && e.dashboard?.state !== "released"); assertAuthority(n); return responseFor(r, a, sameBrowserDashboardDefinition(r, i)); } /** Explicit Stop follows all admitted opens and resumes before closing the owned target. */ async function stopBrowserDashboard(e, t = {}) { return await serializeDashboardOperation(e, t, stopMaterializedDashboard); } async function stopMaterializedDashboard(e, t) { await assertDefinitionCurrent(e, t); const n = await tabsForDefinition(e, t); assertAuthority(t); for (const r of n) { if (!definitionOwnsTab(e, r)) continue; const n = r.dashboard?.state === "stopped" ? void 0 : await changeTabState(r, "stopping", t); assertAuthority(t); if (!n && r.dashboard?.state !== "stopped") throw new Error("Dashboard target changed while stopping; retry Stop"); if (n) { emitDashboardChanged(e, t); await closeStoppingTab(n, e, t); assertAuthority(t); if ((await readBrowserDashboardTabs(n.storageKey, t)).some((e) => e.dashboard?.state === "stopping")) throw new Error("Dashboard is paused, but its browser tab could not close yet; cleanup will retry"); } } await assertDefinitionCurrent(e, t); const r = (await tabsForDefinition(e, t)).find((t) => definitionOwnsTab(e, t) && t.dashboard?.state !== "released"); assertAuthority(t); if (!r) { await persistBrowserDashboardStopIntent(e, t); assertAuthority(t); emitDashboardChanged(e, t); } return responseFor(e, r, !r); } /** Existing cleanup cycle reconciles dashboard removal, replacement, and explicit stop. */ async function reconcileBrowserDashboards(e = {}) { const t = getOptionalBrowserStateRuntime(); if (!t?.gateway) return 0; const isCurrent = () => isBrowserStateRuntimeCurrent(t, e.isCurrent); const n = { runtime: t, assertCurrent: () => { if (!isBrowserStateRuntimeCurrent(t)) throw new Error("Browser dashboard cleanup is no longer current"); } }; let r = 0; if (!isCurrent()) return r; const i = await readBrowserDashboardTabs(void 0, { runtime: t }); if (!isCurrent()) return r; for (const t of i) { if (!t.dashboard || e.sessionKeys && !e.sessionKeys.includes(t.dashboard.sessionKey)) continue; try { const i = await readBrowserDashboardDefinition({ ...t.dashboard }); if (!isCurrent()) return r; if (!definitionOwnsTab(i, t) || t.dashboard.state === "released") r += (await releaseTab(t, n, e)).closed; else if (i && t.dashboard.state === "stopping") r += await closeStoppingTab(t, i, n, e); else if (i && t.dashboard.state === "stopped" && (await tabsForDefinition(i, n)).some((e) => e.dashboard?.state === "active" && definitionOwnsTab(i, e))) await releaseTab(t, n, e); } catch (n) { if (!isCurrent()) return r; e.onWarn?.(`Could not reconcile Browser dashboard ${t.dashboard.name}: ${String(n)}`); } } if (!isCurrent()) return r; const a = await readBrowserDashboardStopIntents({ runtime: t }); if (!isCurrent()) return r; for (const t of a) { if (e.sessionKeys && !e.sessionKeys.includes(t.sessionKey)) continue; try { const i = await readBrowserDashboardDefinition(t); if (!isCurrent()) return r; if (!sameBrowserDashboardDefinition(t, i) || i && (await tabsForDefinition(i, n)).some((e) => e.dashboard?.state === "active" && definitionOwnsTab(i, e))) { if (e.prepareCurrent && !await e.prepareCurrent() || !isCurrent()) return r; await deleteBrowserDashboardStopIntent(t, { ...n, sessionEntryCurrent: e.sessionEntryCurrent, assertCurrent: () => { n.assertCurrent?.(); if (!isCurrent()) throw new Error("Browser dashboard cleanup caller changed"); } }); } } catch (n) { if (!isCurrent()) return r; e.onWarn?.(`Could not reconcile Browser dashboard ${t.name}: ${String(n)}`); } } return r; } //#endregion export { assertBrowserDashboardTargetCurrent, inspectBrowserDashboard, reconcileBrowserDashboards, requestBrowserDashboard, stopBrowserDashboard };