openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
399 lines (398 loc) • 12.8 kB
JavaScript
import { t as LruCache } from "./lru-cache-wquJPIr-.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { o as sessionChanges } from "./session-row-changes-BA4BqVwF.mjs";
import { c as onUserProfilesChanged, s as onUserProfileEmailBindingChanged } from "./user-profile-events-BhLFevt9.mjs";
import { y as registerConfigWriteListener } from "./io.runtime-DsJ2dLCQ.mjs";
import { c as bindWorkerTurnGitHubGrant } from "./placement-turn-claim-events-B3vHelmp.mjs";
import { o as runWithSessionActorStorage, t as captureSessionActorStorageOwner } from "./session-actor-storage-binding-DMwpDsij.mjs";
import { o as WORKER_GITHUB_REFRESH_PROTOCOL_FEATURE } from "./worker-admission-1P4EM7n_.mjs";
import "./config-CMA-J084.mjs";
import { a as githubIdentityChanges } from "./github-read-identity-DyhbpOtm.mjs";
import { f as resolveConfiguredGitHubToolIdentity, y as onManagedGitHubProfileChanged } from "./github-tool-identity-41SK6r8O.mjs";
import { a as managedWorktrees } from "./service-Co_CyVnF.mjs";
import { n as parseWorkerGitHubLaunchBinding } from "./launch-descriptor-BUjz-ttq.mjs";
import { a as prepareCurrentGitHubPublicationIdentity, i as matchesCurrentGitHubPublicationIdentity, l as prepareGitHubPublicationWorkspaceOwner, n as currentGitHubPublicationConfig, p as sameGitHubPublicationWorkspace } from "./github-publication-availability-BPmIEgKL.mjs";
import { t as parseGitHubRemoteUrl } from "./github-remote-xiDM0pdC.mjs";
import { n as StaleWorkerBuildError } from "./admission-at35Y6MN.mjs";
import { t as raceNodeWorkerOperation } from "./node-worker-abort-BCKtSFqU.mjs";
import { AsyncLocalStorage } from "node:async_hooks";
//#region src/gateway/worker-environments/worker-github-binding.ts
function workspaceKey(e) {
return JSON.stringify(e.kind === "repository" ? [
e.kind,
e.workspace.workspaceId,
e.workspace.url,
e.workspace.branch
] : [
e.kind,
e.worktree.id,
e.worktree.repoFingerprint,
e.worktree.branch
]);
}
async function prepareGitHubPublicationFact(e) {
try {
try {
var t = _usingCtx();
if (e.assertCurrent?.() === false) return;
const n = await prepareGitHubPublicationWorkspaceOwner(e);
t.u({ [Symbol.dispose]: () => n.release() });
const r = n.initial;
const i = await prepareCurrentGitHubPublicationIdentity(e.agentId);
const a = r.kind === "repository" ? r.workspace.url : (await managedWorktrees.resolveRepositoryIdentity(r.worktree.path)).originUrl;
const o = await n.read();
if (e.assertCurrent?.() === false || !sameGitHubPublicationWorkspace(r, o) || !matchesCurrentGitHubPublicationIdentity({
agentId: e.agentId,
identity: i
})) return;
const s = parseGitHubRemoteUrl(a);
const c = s && /^[A-Za-z0-9_.-]+$/u.test(s.owner) && /^[A-Za-z0-9_.-]+$/u.test(s.repo) ? `https://github.com/${s.owner}/${s.repo}.git` : void 0;
const l = i.source === "agent-override" ? "agent" : i.source === "system-configured" ? "system" : void 0;
const u = l ? resolveConfiguredGitHubToolIdentity({
config: currentGitHubPublicationConfig(),
agentId: e.agentId,
scope: l
})?.gitAuthor : void 0;
const d = parseWorkerGitHubLaunchBinding({
token: i.env.GH_TOKEN,
login: i.account.login,
branch: r.kind === "repository" ? r.workspace.branch : r.worktree.branch,
...c ? { remoteUrl: c } : {},
...u ? { gitAuthor: u } : {}
});
return {
available: Boolean(i.env.GH_TOKEN),
...d ? {
github: d,
identity: i,
workspaceKey: workspaceKey(r)
} : {}
};
} catch (e) {
t.e = e;
} finally {
t.d();
}
} catch {
return;
}
}
const log = createSubsystemLogger("gateway/worker-github");
/** Discovery prepared the account off the turn path; admission binds only local live authority. */
async function prepareWorkerGitHubBindingGrant(e) {
const t = new AbortController();
const n = AbortSignal.any([e.signal, t.signal]);
const assertRun = () => {
n.throwIfAborted();
e.assertCurrent();
};
assertRun();
if (e.identity.accessExpiresAtMs !== void 0 && e.identity.accessExpiresAtMs <= Date.now()) throw new Error("Prepared GitHub credential expired; retry after background refresh");
const r = await prepareGitHubPublicationWorkspaceOwner(e, {
sessionTarget: e.sessionTarget,
assertCurrent: assertRun
});
const i = r.initial;
const a = i.kind === "repository" ? i.workspace.branch : i.worktree.branch;
if (workspaceKey(i) !== e.workspaceKey || a !== e.github.branch || e.identity.env.GH_TOKEN !== e.github.token) {
r.release();
throw new Error("Prepared GitHub workspace or identity changed");
}
let o = 0;
let s = 0;
let c = Date.now();
let l = 0;
let u;
let d = e.github.token;
let f = e.identity.accessExpiresAtMs;
let p;
let m = false;
const h = [];
const revoke = async () => {
if (m) return;
m = true;
n.removeEventListener("abort", onAbort);
h.splice(0).forEach((e) => e());
r.release();
t.abort(/* @__PURE__ */ new Error("Worker GitHub credential authority closed"));
};
const onAbort = () => {
revoke();
};
const assertCurrent = () => {
try {
assertRun();
if (!sameGitHubPublicationWorkspace(i, r.current()) || !matchesCurrentGitHubPublicationIdentity({
agentId: e.agentId,
identity: e.identity
})) throw new Error("Worker GitHub credential authority changed");
} catch (e) {
t.abort(e);
throw e;
}
};
const changed = () => {
try {
assertCurrent();
} catch {}
};
try {
n.addEventListener("abort", onAbort, { once: true });
h.push(registerConfigWriteListener(changed), onUserProfilesChanged(changed), onUserProfileEmailBindingChanged(changed), onManagedGitHubProfileChanged(({ profileDir: n, kind: r }) => {
if (n === e.identity.env.GH_CONFIG_DIR) {
if (r === "removed") t.abort(/* @__PURE__ */ new Error("Selected GitHub profile removed"));
else o++;
}
}));
assertCurrent();
} catch (e) {
await revoke();
throw e;
}
return {
binding: e.github,
signal: n,
assertCurrent,
revoke,
refresh(a) {
p ??= (async () => {
assertCurrent();
if (u && a === u.generation) {
d = u.token;
f = u.expiresAtMs;
u = void 0;
}
if (u?.expiresAtMs !== void 0 && u.expiresAtMs <= Date.now()) u = void 0;
if (Date.now() - c < 6e4 && o === s && (f === void 0 || f > Date.now() + 6e4)) return u;
const p = o;
const m = await prepareCurrentGitHubPublicationIdentity(e.agentId, assertCurrent);
const h = await r.read();
assertCurrent();
if (!sameGitHubPublicationWorkspace(i, h) || m.source !== e.identity.source || m.profileId !== e.identity.profileId || m.account.accountId !== e.identity.account.accountId || m.account.login.toLowerCase() !== e.identity.account.login.toLowerCase()) {
t.abort(/* @__PURE__ */ new Error("Selected GitHub account changed; start a new turn"));
n.throwIfAborted();
}
const g = m.env.GH_TOKEN;
if (!g || m.accessExpiresAtMs !== void 0 && m.accessExpiresAtMs <= Date.now()) throw new Error("Selected GitHub credential expired or unavailable");
c = Date.now();
s = p;
if (g !== (u?.token ?? d)) u = {
generation: ++l,
token: g,
expiresAtMs: m.accessExpiresAtMs
};
return u;
})().catch((e) => {
assertCurrent();
if (f !== void 0 && f <= Date.now()) {
t.abort(e);
n.throwIfAborted();
}
log.warn("Worker GitHub renewal failed; retrying while the current credential remains usable.");
return u;
}).finally(() => {
p = void 0;
});
return p;
}
};
}
/** Attach the background fact to this admitted turn without running identity discovery. */
async function bindWorkerGitHubTurn(e) {
const { github: t, identity: n, workspaceKey: r } = e.fact ?? {};
if (!t || !n || !r) return;
if (!e.protocolFeatures.includes("worker-github-refresh")) throw new StaleWorkerBuildError();
const i = prepareWorkerGitHubBindingGrant({
...e.session,
github: t,
identity: n,
workspaceKey: r,
sessionTarget: e.sessionTarget,
signal: e.signal,
assertCurrent: e.assertCurrent
}).then((t) => {
if (e.signal.aborted) t.revoke();
return t;
});
const a = await raceNodeWorkerOperation(i, e.signal);
try {
bindWorkerTurnGitHubGrant(e.store, e.claim, a);
} catch (e) {
await a.revoke();
throw e;
}
return a;
}
//#endregion
//#region src/gateway/github-publication-discovery.ts
const unavailable = { available: false };
const PUBLICATION_FACT_MAX_AGE_MS = 6e4;
let readPublished;
/** Discovery can lag a refresh; publication and process launch still validate at the effect. */
function readGitHubPublicationFact(e) {
return readPublished?.(e) ?? unavailable;
}
function startGitHubPublicationDiscovery(e) {
const t = AsyncLocalStorage.snapshot();
const n = e.scheduler.scope();
const r = new LruCache(256);
let i;
let a;
const isCurrent = (e, t) => !n.signal.aborted && r.peek(e) === t;
const store = (e, t) => {
if (t) r.set(e, t);
else r.delete(e);
if (a && !isCurrent(a.key, a.entry)) {
a.release();
a = void 0;
}
};
const keyOf = (e) => `${e.agentId}\0${e.sessionKey}`;
const refresh = (e, o = false) => {
const s = r.peek(e);
if (!s || n.signal.aborted) return;
const c = {
...s,
fact: o ? { available: s.fact.available } : s.fact,
refreshAfterMs: n.now() + PUBLICATION_FACT_MAX_AGE_MS
};
store(e, c);
t(() => n.schedule({
id: `github-publication:${e}`,
delayMs: 0,
run: async () => {
try {
var t = _usingCtx();
const r = i;
const o = createDeferredCore();
i = o.promise;
t.u({ [Symbol.dispose]: () => {
if (a?.entry === c) a = void 0;
if (i === o.promise) i = void 0;
o.resolve();
} });
if (r) {
await r;
if (!isCurrent(e, c)) return;
}
a = {
key: e,
entry: c,
release: o.resolve
};
const prepare = () => prepareGitHubPublicationFact({
...c.session,
assertCurrent: () => isCurrent(e, c)
});
let s;
if (c.incognito) {
const assertCurrent = () => n.signal.throwIfAborted();
try {
const e = await c.incognito.owner?.acquireExisting(c.session.sessionKey, {
assertCurrent,
assertReadable: assertCurrent
});
if (e) try {
s = await runWithSessionActorStorage({
actor: e,
agentId: c.incognito.agentId,
path: c.incognito.path,
authority: {
assertCurrent,
authorize: assertCurrent
}
}, prepare);
} finally {
await e.release();
}
} catch {
s = void 0;
}
} else s = await prepare();
if (isCurrent(e, c)) c.fact = s ?? unavailable;
} catch (e) {
t.e = e;
} finally {
t.d();
}
}
}));
return c;
};
const read = (e) => {
const t = keyOf(e);
let i = r.get(t);
if (!i || i.session.sessionId !== e.sessionId) {
i = {
session: { ...e },
incognito: captureSessionActorStorageOwner(e, {
assertCurrent: () => n.signal.throwIfAborted(),
authorize() {}
}),
fact: unavailable,
refreshAfterMs: 0
};
store(t, i);
refresh(t);
} else if (i.refreshAfterMs <= n.now()) i = refresh(t, true) ?? i;
return i.fact;
};
readPublished = read;
const refreshAll = (e = false) => {
const t = [...r.keys()];
for (const n of t) refresh(n, e);
};
const o = onManagedGitHubProfileChanged(() => refreshAll(true));
githubIdentityChanges.onChange = () => refreshAll(true);
const s = sessionChanges.subscribe((e) => {
if ("all" in e && e.scope === "config") refreshAll(true);
});
const observe = (e) => {
if (n.signal.aborted) return;
const t = {
agentId: e.agentId,
sessionKey: e.key,
sessionId: e.entry.sessionId
};
const i = keyOf(t);
const a = r.peek(i);
if (!a) return;
if (!e.entry.repositoryWorkspaceId && !e.entry.worktree?.id) {
store(i);
return;
}
const o = JSON.stringify([
e.entry.lifecycleRevision,
e.entry.worktree,
e.entry.repositoryWorkspaceId
]);
if (a.session.sessionId !== t.sessionId || a.binding !== o) {
store(i, {
session: t,
binding: o,
fact: unavailable,
refreshAfterMs: 0
});
refresh(i);
}
};
e.projection?.onSelectionChange((e) => {
if (e.kind === "row" && e.row) observe(e.row);
});
return {
name: "github-publication-discovery",
stop: async () => {
n.beginClose();
githubIdentityChanges.onChange = void 0;
o();
s();
if (readPublished === read) readPublished = void 0;
r.clear();
await n.stop();
}
};
}
//#endregion
export { startGitHubPublicationDiscovery as n, bindWorkerGitHubTurn as r, readGitHubPublicationFact as t };