UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

568 lines (567 loc) • 21.5 kB
import { t as OPENCLAW_AGENT_SCHEMA_VERSION } from "./openclaw-schema-versions-E_10NoI6.mjs"; import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs"; import { n as isArtifactPreservingStateRead } from "./artifact-preserving-state-reads-BfhmBr-V.mjs"; import { s as registerOpenClawAgentDatabaseReadCandidateResource } from "./openclaw-agent-db-resources-Dp8HvLsg.mjs"; import { n as SessionWorktreeSourceChangedError } from "./errors-CJd09ymz.mjs"; import { n as executeExistingOpenClawStateRead } from "./openclaw-state-db-readonly-B6YHb1oF.mjs"; import "./openclaw-agent-db-contract-aCH9b8Uc.mjs"; import { r as captureOpenClawStateWorkerContext, t as captureOpenClawStateReadContext } from "./openclaw-state-worker-context-DAKL_dnZ.mjs"; import { h as readRuntimeConfig } from "./runtime-snapshot-WbwbY5b7.mjs"; import { d as prepareOpenClawAgentDatabaseRegistrySnapshotRead } from "./openclaw-agent-db-registry-listing-CbXBL50a.mjs"; import { a as getActiveSecretsRuntimeConfigSnapshot } from "./runtime-state-Dq_fFDZp.mjs"; import { l as withSessionEntryReadOnlyInWorker } from "./session-entry-read-runtime-1Fp1sybj.mjs"; import { a as readCapturedSessionActorEntry, t as captureSessionActorStorageOwner } from "./session-actor-storage-binding-DMwpDsij.mjs"; import { _ as retainPreparedSessionEntryPredicate } from "./session-accessor.sqlite-entry-cache-publication-state-B4mkg2yK.mjs"; import { k as getSessionRepositoryWorkspaceStore } from "./session-accessor.sqlite-entry-store-DmqxH0lm.mjs"; import { t as captureGitHubPublicationLifecycle } from "./github-publication-receipts-DrGMcoy5.mjs"; import { a as resolveSessionStoreIdentity } from "./session-store-key-CEwU3noi.mjs"; import "./config-CMA-J084.mjs"; import { t as findCanonicalStoreMatch } from "./session-utils-store-selection-B-u2328z.mjs"; import { t as loadGatewaySessionEntryReadOnlyInWorker } from "./session-utils-store-worker-BU_tdh8T.mjs"; import { t as createStaleWhileRevalidateCache } from "./stale-while-revalidate-cache-BRZEfv_f.mjs"; import { n as resolveGitHubHost } from "./github-host-runtime-CMm44VF1.mjs"; import { a as prepareGitHubPublicationIdentity, i as matchesPreparedGitHubPublicationIdentity, o as prepareGitHubPublicationOptionsIdentity } from "./github-tool-identity-41SK6r8O.mjs"; import { r as requestCurrentGitHubOAuthRefresh } from "./github-oauth-lifecycle-6AnTmFkw.mjs"; import { c as readLiveRegistryWorktreeByOwner, t as captureWorktreeRegistryReadGuard } from "./registry-read-DAFI5cQY.mjs"; import { a as managedWorktrees } from "./service-Co_CyVnF.mjs"; import { f as GitHubPublicationWorkspaceChangedError, m as rejectGitHubPublicationSelection, t as GitHubPublicationRecoveryPendingError, u as GitHubPublicationSessionChangedError } from "./github-publication-git-index-DZcaQ_xd.mjs"; import { t as parseGitHubRemoteUrl } from "./github-remote-xiDM0pdC.mjs"; import { isDeepStrictEqual } from "node:util"; //#region src/state/github-publication-session-lifecycles.ts /** Retain the immutable binding separately from request status and other authority owners. */ async function prepareGitHubPublicationSessionLifecycle(e) { const t = captureGitHubPublicationLifecycle(captureOpenClawStateReadContext(), e); if (!t.loaded) t.observe(await readGitHubPublicationSessionLifecycleInWorker(e)); return { readCurrent: t.readCurrent }; } async function readGitHubPublicationSessionLifecycleInWorker(e) { const { publicationKind: t, requestId: n } = e; const r = await executeExistingOpenClawStateRead({}, { type: "githubPublication.lifecycle", publicationKind: t, requestId: n }, { current: true }); if (!r) throw new Error("GitHub publication requester metadata is unavailable."); return r.lifecycle; } //#endregion //#region src/gateway/github-publication-worktree-owner.ts function requirePublicationSessionOwner(e, t, n = false) { const r = t.entry; if (t.agentId !== e.agentId || t.canonicalKey !== e.sessionKey || r?.sessionId !== e.sessionId || !n && r.archivedAt !== void 0 || e.lifecycleRevision !== void 0 && (r.lifecycleRevision ?? null) !== e.lifecycleRevision) throw new GitHubPublicationSessionChangedError(); return { ...t, entry: r }; } function requirePublicationWorktreeOwner(e, t, n, r = false) { const i = e.entry; const a = i.worktree?.githubPullRequest; if (a && (!r || !a.preparedHeadCommit || a.preparedHeadCommit !== a.head.commit)) throw new GitHubPublicationWorkspaceChangedError(r ? "Finish preparing the original PR source before publication; saved work was preserved." : "This publication path cannot update an imported PR; use shared publication after preparation."); if (!i.worktree?.id || !t || t.removedAt !== void 0 || t.id !== i.worktree.id || t.ownerKind !== "session" || t.ownerId !== e.canonicalKey || t.branch !== i.worktree.branch || t.repoRoot !== i.worktree.repoRoot) throw new GitHubPublicationSessionChangedError(); if (n && (t.id !== n.worktreeId || t.repoFingerprint !== n.repositoryFingerprint || (a?.head.branch ?? t.branch) !== n.branch)) throw new GitHubPublicationWorkspaceChangedError("GitHub publication workspace authority changed."); return { loaded: e, worktree: t, publicationBranch: a?.head.branch ?? t.branch }; } function rejectChangedPublicationWorktree(e) { if (e instanceof SessionWorktreeSourceChangedError) throw new GitHubPublicationWorkspaceChangedError(e.message); throw e; } function preparePublicationWorktreeRead(e, t, n, r, i = false) { const a = { sessionId: e.entry.sessionId, sessionKey: e.canonicalKey, agentId: e.agentId, lifecycleRevision: e.entry.lifecycleRevision ?? null }; const o = e.entry.repositoryWorkspaceId; const s = r ? { ...r } : void 0; return async () => { const e = captureWorktreeRegistryReadGuard(t, "publication"); const r = await readLiveRegistryWorktreeByOwner(t, "session", a.sessionKey); let c; try { c = e(r); } catch (e) { rejectChangedPublicationWorktree(e); } t.admission.assertCurrent(); if (!r) throw new GitHubPublicationSessionChangedError(); const l = requirePublicationSessionOwner(a, n()); if (l.entry.repositoryWorkspaceId !== o) throw new GitHubPublicationSessionChangedError(); const assertCurrent = () => { t.admission.assertCurrent(); const e = requirePublicationSessionOwner(a, n()); if (e.entry.repositoryWorkspaceId !== o) throw new GitHubPublicationSessionChangedError(); try { c(); } catch (e) { rejectChangedPublicationWorktree(e); } return requirePublicationWorktreeOwner(e, r, s, i); }; return { ...requirePublicationWorktreeOwner(l, r, s, i), assertCurrent, assertRegistryCurrent: c }; }; } //#endregion //#region src/gateway/github-publication-availability.ts const repositoryTargets = createStaleWhileRevalidateCache({ maxEntries: 256, maxPending: Number.POSITIVE_INFINITY, ttlMs: 15e3, cacheable: (e) => e }); function publicationConfigSnapshot() { const e = getActiveSecretsRuntimeConfigSnapshot(); if (e) return e; const t = readRuntimeConfig(); return { config: t, sourceConfig: t }; } function assertExpectedSharedGitHubPublisher(e, t, n) { if (t.source === "personal" || e && (e.source !== t.source || e.accountId !== t.accountId || e.login.toLowerCase() !== t.login.toLowerCase())) rejectGitHubPublicationSelection("GitHub publication identity changed; review the current shared account and try again.", n); } function currentGitHubPublicationConfig() { return publicationConfigSnapshot().config; } async function prepareCurrentGitHubPublicationIdentity(e, t) { t?.(); await requestCurrentGitHubOAuthRefresh(e); t?.(); const n = publicationConfigSnapshot(); return await prepareGitHubPublicationIdentity({ config: n.config, sourceConfig: n.sourceConfig, agentId: e, assertCurrent: t }); } async function prepareCurrentGitHubPublicationOptionsIdentity(e, t) { t?.(); await requestCurrentGitHubOAuthRefresh(e); t?.(); const n = publicationConfigSnapshot(); return await prepareGitHubPublicationOptionsIdentity({ config: n.config, sourceConfig: n.sourceConfig, agentId: e, assertCurrent: t }); } function matchesCurrentGitHubPublicationIdentity(e) { return matchesPreparedGitHubPublicationIdentity({ config: currentGitHubPublicationConfig(), ...e }); } /** The selected publication metadata is invalidated by the session writer's receipts. */ async function prepareGitHubPublicationSession(e, t = {}) { const n = t.projection ?? []; const r = [...t.fields ?? [ "sessionId", "lifecycleRevision", "archivedAt", "repositoryWorkspaceId", "worktree", "owner", "createdActor", "visibility", "incognito" ], ...t.target?.expectedWriterRunId !== void 0 ? ["activeWriterRunId"] : []]; let i; let a = true; let o; let s; const retire = () => { a = false; i?.release(); }; const c = { sessionKey: e, agentId: t.agentId, storePath: t.target?.storePath }; const assertCurrent = () => t.assertCurrent?.(); const l = captureSessionActorStorageOwner(c, { assertCurrent, authorize: assertCurrent }); const u = l && (() => ({ canonicalKey: e, agentId: l.agentId, storePath: l.path, entry: readCapturedSessionActorEntry(l, e) })); const retain = (e, t, n) => { if (typeof e?.databaseIdentity !== "string") return; const { path: a, agentId: c } = e; const l = `file:${e.databaseIdentity}`; if (isArtifactPreservingStateRead()) { s = prepareOpenClawAgentDatabaseRegistrySnapshotRead({}, (e) => e.sources.every((t) => t.path !== a && t.physicalPath !== a && t.identity !== l || e.kind === "upsert" && t.agentId === c && t.identity === l && t.schemaVersion === 38)).assertCurrent; o = registerOpenClawAgentDatabaseReadCandidateResource({ path: a, revoke: retire, close: async () => retire() }); } i = retainPreparedSessionEntryPredicate({ databaseIdentity: l, sessionKey: t, entry: n, matches: (e, t) => r.every((n) => isDeepStrictEqual(e?.[n], t?.[n])) }); }; let d; try { if (u) d = u(); else if (t.target?.storePath && t.target.agentId) { const r = t.target.storePath; const i = t.target.agentId; const a = t.target.sessionKey ?? e; d = await withSessionEntryReadOnlyInWorker({ agentId: i, sessionKey: a, storePath: r, projection: n }, () => t.assertCurrent?.(), async (t, n) => { if (!t.ok) throw t.error; retain(n.source, a, t.value); return { agentId: i, canonicalKey: e, storePath: r, entry: t.value }; }); } else d = await loadGatewaySessionEntryReadOnlyInWorker({ cfg: t.cfg ?? readRuntimeConfig(), key: e, agentId: t.agentId, projection: n, assertActive: t.assertCurrent, onSelected(e) { retain(e.capturedReadSource, e.canonicalKey, findCanonicalStoreMatch(e.store, e.storeKeys)?.entry); } }); } catch (e) { retire(); o?.(); throw e; } const release = () => { retire(); o?.(); }; return { loaded: d, readCurrent: () => { t.assertCurrent?.(); s?.(); if (!a || i && !i.isCurrent()) throw new GitHubPublicationSessionChangedError(); return u ? u() : { ...d, entry: i ? i.readRetainedEntry() : d.entry }; }, release, [Symbol.dispose]: release }; } async function readGitHubPublicationWorktreeOwner(e) { const t = captureOpenClawStateWorkerContext(); const n = await prepareGitHubPublicationSession(e.sessionKey, { agentId: e.agentId, assertCurrent: () => t.admission.assertCurrent() }); try { return { ...await preparePublicationWorktreeRead(requirePublicationSessionOwner(e, n.readCurrent()), t, n.readCurrent, e.expected, e.allowExistingPullRequest)(), release: n.release, [Symbol.dispose]: n.release }; } catch (e) { n.release(); throw e; } } function resolveGitHubPublicationWorkspaceOwner(e, t, n) { const r = requirePublicationSessionOwner(e, n()); const i = r.entry.repositoryWorkspaceId; if (!i) throw new GitHubPublicationSessionChangedError(); const a = t?.current(); if (!a || a.workspaceId !== i || a.agentId !== e.agentId || a.sessionKey !== e.sessionKey) throw new GitHubPublicationWorkspaceChangedError("GitHub publication session repository owner changed."); return { kind: "repository", loaded: r, workspace: a }; } async function prepareGitHubPublicationWorkspaceOwner(e, t = {}) { const n = captureOpenClawStateWorkerContext(); const assertCurrent = () => { n.admission.assertCurrent(); t.assertCurrent?.(); }; assertCurrent(); const r = t.sessionTarget ? { ...t.sessionTarget } : void 0; if (r) { const t = r.sessionKey && resolveSessionStoreIdentity({ cfg: readRuntimeConfig(), sessionKey: r.sessionKey, agentId: r.agentId }); if (!r.storePath || !t || t.agentId !== e.agentId || t.canonicalKey !== e.sessionKey) throw new GitHubPublicationSessionChangedError(); } const i = await prepareGitHubPublicationSession(e.sessionKey, { agentId: e.agentId, assertCurrent, target: r }); try { const a = i.readCurrent(); if (r && (r.agentId !== e.agentId || r.sessionId !== e.sessionId || r.expectedLifecycleRevision !== void 0 && a.entry?.lifecycleRevision !== r.expectedLifecycleRevision || r.expectedWriterRunId !== void 0 && a.entry?.activeWriterRunId !== r.expectedWriterRunId)) throw new GitHubPublicationSessionChangedError(); const o = requirePublicationSessionOwner(e, a); const s = o.entry.repositoryWorkspaceId; if (!s && !o.entry.worktree?.id) throw new GitHubPublicationSessionChangedError(); const c = { ...e, lifecycleRevision: o.entry.lifecycleRevision ?? null }; const l = preparePublicationWorktreeRead(o, n, i.readCurrent, void 0, t.allowExistingPullRequest); const u = s ? await getSessionRepositoryWorkspaceStore().prepare(s) : void 0; const validate = (e) => { assertCurrent(); if (e.loaded.storePath !== o.storePath || e.loaded.entry.repositoryWorkspaceId !== s || r?.expectedWriterRunId !== void 0 && e.loaded.entry.activeWriterRunId !== r.expectedWriterRunId) throw new GitHubPublicationSessionChangedError(); return e; }; let d; const current = () => { if (s) return validate(resolveGitHubPublicationWorkspaceOwner(c, u, i.readCurrent)); if (!d) throw new GitHubPublicationSessionChangedError(); return validate({ kind: "worktree", ...d, ...d.assertCurrent() }); }; const read = async () => { if (!s) d = await l(); return current(); }; return { initial: await read(), read, current, currentRepository: () => validate(resolveGitHubPublicationWorkspaceOwner(c, u, i.readCurrent)), release: i.release, [Symbol.dispose]: i.release }; } catch (e) { i.release(); throw e; } } async function hasGitHubPublicationRepositoryWorkspace(e) { try { var t = _usingCtx(); const n = await prepareGitHubPublicationWorkspaceOwner(e, { allowExistingPullRequest: true }); t.u({ [Symbol.dispose]: () => n.release() }); return n.initial.kind === "repository"; } catch (e) { t.e = e; } finally { t.d(); } } function sameGitHubPublicationWorkspace(e, t) { if (e.loaded.entry?.lifecycleRevision !== t.loaded.entry?.lifecycleRevision) return false; return e.kind === "repository" ? t.kind === "repository" && t.workspace.workspaceId === e.workspace.workspaceId && t.workspace.url === e.workspace.url && t.workspace.branch === e.workspace.branch : t.kind === "worktree" && t.worktree.id === e.worktree.id && t.worktree.repoFingerprint === e.worktree.repoFingerprint && t.worktree.branch === e.worktree.branch; } async function localGitHubPublicationSessionIdentity(e) { const t = await prepareGitHubPublicationSessionLifecycle({ publicationKind: e.identity_source === "personal" ? "personal" : "shared", requestId: e.request_id }).catch((e) => { throw new GitHubPublicationRecoveryPendingError("GitHub publication lifecycle authority is unavailable; retry recovery.", { cause: e }); }); const readLifecycle = () => { try { return t.readCurrent(); } catch (e) { throw new GitHubPublicationRecoveryPendingError("GitHub publication lifecycle authority is unavailable; retry recovery.", { cause: e }); } }; const n = readLifecycle(); if (!n) throw new GitHubPublicationSessionChangedError(); return { sessionId: e.session_id, sessionKey: e.session_key, agentId: e.agent_id, lifecycleRevision: n.lifecycle_revision, assertLifecycleCurrent: readLifecycle, expected: { worktreeId: e.worktree_id, repositoryFingerprint: e.repository_fingerprint, branch: e.branch } }; } async function readLocalGitHubPublicationWorktreeOwner(e) { const t = await localGitHubPublicationSessionIdentity(e); const n = await readGitHubPublicationWorktreeOwner({ ...t, allowExistingPullRequest: e.identity_source !== "personal" }); return { ...n, assertCurrent: () => { t.assertLifecycleCurrent(); return n.assertCurrent(); } }; } /** Discovery validates the same registered repository identity as publication, without GitHub I/O. */ async function prepareGitHubPublicationRepositoryIdentity(e) { const { worktree: t, assertCurrent: n } = e; n(); const r = await managedWorktrees.resolveRepositoryIdentity(t.path); n(); if (r.checkoutRoot !== t.path || r.repoRoot !== t.repoRoot || r.fingerprint !== t.repoFingerprint) throw new GitHubPublicationWorkspaceChangedError("GitHub publication workspace repository changed."); return r; } function isSupportedGitHubOrigin(e, t) { const n = parseGitHubRemoteUrl(e, t); return Boolean(n && /^[A-Za-z0-9_.-]+$/u.test(n.owner) && /^[A-Za-z0-9_.-]+$/u.test(n.repo)); } /** One target qualifier serves observation and legacy discovery; effects still requalify. */ async function qualifyGitHubPublicationSource(e, t, n, r = {}) { const i = resolveGitHubHost(); const checkSession = () => { t(); return requirePublicationSessionOwner(e, n(), true); }; try { const a = captureOpenClawStateWorkerContext(); const o = checkSession(); a.admission.assertCurrent(); if (o.entry.archivedAt !== void 0) return { ok: true, custody: { kind: "archived" }, target: { kind: "unknown", reason: "not-qualified" }, assertCurrent: checkSession }; const s = o.entry.repositoryWorkspaceId; if (s) { const a = await getSessionRepositoryWorkspaceStore().prepare(s, r.readMode ? { mode: r.readMode, owner: { agentId: e.agentId, sessionKey: e.sessionKey } } : void 0); const current = () => { t(); return resolveGitHubPublicationWorkspaceOwner(e, a, n); }; const o = current(); return { ok: true, custody: { kind: "qualified", source: "repository" }, target: isSupportedGitHubOrigin(o.workspace.url, i) ? { kind: "supported", basis: "repository-url", freshness: "observed" } : { kind: "unsupported" }, assertCurrent: () => { const e = current(); if (e.workspace.workspaceId !== s || e.workspace.revision !== o.workspace.revision) throw new GitHubPublicationWorkspaceChangedError("GitHub publication session repository owner changed."); } }; } if (!o.entry.worktree?.id) return { ok: true, custody: { kind: "unbound_workspace" }, target: { kind: "unknown", reason: "not-qualified" }, assertCurrent: () => { const e = checkSession(); if (e.entry.worktree?.id || e.entry.repositoryWorkspaceId || e.entry.archivedAt !== void 0) throw new GitHubPublicationSessionChangedError(); } }; const c = await preparePublicationWorktreeRead(o, a, n, void 0, true)(); const check = () => { t(); c.assertCurrent(); }; check(); if (o.entry.worktree.githubPullRequest) return { ok: true, custody: { kind: "qualified", source: "imported-pr" }, target: { kind: "supported", basis: "prepared-imported-pr", freshness: "observed" }, assertCurrent: check }; const { repoRoot: l, repoFingerprint: u } = c.worktree; const d = JSON.stringify([ a.admission.identity.key, i, l, u ]); let f = false; const p = await repositoryTargets.read(d, async () => { const e = await prepareGitHubPublicationRepositoryIdentity({ worktree: c.worktree, assertCurrent: () => a.admission.assertCurrent() }); f = true; return isSupportedGitHubOrigin(e.originUrl, i); }, { allowStale: false }); check(); return { ok: true, custody: { kind: "qualified", source: "worktree" }, target: p.value ? { kind: "supported", basis: "registered-repository", freshness: f ? "observed" : "cached" } : { kind: "unsupported" }, assertCurrent: check }; } catch (e) { t(); return { ok: false, kind: e instanceof GitHubPublicationSessionChangedError || e instanceof GitHubPublicationWorkspaceChangedError ? "changed" : "unavailable", cause: e }; } } //#endregion export { prepareCurrentGitHubPublicationIdentity as a, prepareGitHubPublicationSession as c, readGitHubPublicationWorktreeOwner as d, readLocalGitHubPublicationWorktreeOwner as f, readGitHubPublicationSessionLifecycleInWorker as h, matchesCurrentGitHubPublicationIdentity as i, prepareGitHubPublicationWorkspaceOwner as l, prepareGitHubPublicationSessionLifecycle as m, currentGitHubPublicationConfig as n, prepareCurrentGitHubPublicationOptionsIdentity as o, sameGitHubPublicationWorkspace as p, hasGitHubPublicationRepositoryWorkspace as r, prepareGitHubPublicationRepositoryIdentity as s, assertExpectedSharedGitHubPublisher as t, qualifyGitHubPublicationSource as u };