openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1,544 lines • 52.2 kB
JavaScript
import { t as hasErrnoCode } from "./errno-DFcoqIT9.mjs";
import { o as registerSecretValueForRedaction } from "./secret-redaction-registry-Cy0acctn.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { t as settlesWithin } from "./settle-within-Bj8A0Tzk.mjs";
import { o as resolveExecutablePath } from "./executable-path-D8oWZRS5.mjs";
import { i as listAgentIds, m as withAgentRosterFactsBatch } from "./agent-roster-t1ooUdXp.mjs";
import { r as resolveAgentConfig, y as resolveMutableAgentEntry } from "./agent-scope-config-DmXgFGKP.mjs";
import { s as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-R3ArRCcz.mjs";
import { i as getOrCreatePromise } from "./lazy-promise-DiCvjz9w.mjs";
import { a as observeSqliteWorkerCommittedFacts, i as createSqliteWorkerOperationAdmission } from "./sqlite-worker-operation-admission-9E_X-oRy.mjs";
import { b as registerOpenClawStateDatabaseAsyncResource, x as registerOpenClawStateDatabaseLifecycleListener } from "./openclaw-state-db-cache-CkwtTqzF.mjs";
import { m as withExistingOpenClawStateDatabaseReadOnly, n as executeExistingOpenClawStateRead } from "./openclaw-state-db-readonly-B6YHb1oF.mjs";
import { n as captureOpenClawStateReadWorkerContext, r as captureOpenClawStateWorkerContext } from "./openclaw-state-worker-context-DAKL_dnZ.mjs";
import { i as runOpenClawStateWorkerOperation } from "./openclaw-state-worker-store-2LoAv_8B.mjs";
import { l as runOpenClawStateWriteTransaction } from "./openclaw-state-db-ARhwdPJg.mjs";
import { v as registerRuntimeConfigWriteListener } from "./runtime-snapshot-WbwbY5b7.mjs";
import { n as captureUserProfileAuthorityRead } from "./user-profile-events-BhLFevt9.mjs";
import { i as unsetConfigValueAtPath } from "./config-paths-DTAbnrwT.mjs";
import "./agent-scope-BwB8YH6y.mjs";
import { o as publishSecretStoreChange, s as subscribeSecretStoreChanges } from "./secret-store-hidden-github-qvQ-BJHF.mjs";
import { t as warnPluginSdkDeprecation } from "./sdk-deprecation-D5N9acnu.mjs";
import { n as withOpenClawStateLeaseAsync } from "./openclaw-state-lease-Cn13CM0c.mjs";
import { a as matchesAgentLifecycleBinding, i as captureAgentLifecycleBinding, o as matchesAgentLifecycleBindingAsync } from "./agent-lifecycle-registry-CdPY7sE9.mjs";
import { r as isRecoverableOAuthRefreshFailure, t as createOAuthRefreshError } from "./oauth-refresh-outcome-DGKa-Dzy.mjs";
import { n as mutateConfigFileWithRetry } from "./mutate-DhAOi0-2.mjs";
import "./config-CMA-J084.mjs";
import { r as clearNativeGitHubTokenCache } from "./github-read-identity-DyhbpOtm.mjs";
import { A as parseGitHubDeviceAuthorizationRecord, C as deleteGitHubOAuthRecord, D as listGitHubAuthorizationRecords, E as inspectGitHubOAuthRecord, F as clearGitHubCredentialVerificationCache, I as pollGitHubOAuthDeviceToken, L as refreshGitHubOAuthToken, M as readGitHubDeviceAuthorizationRecord, N as writeGitHubDeviceAuthorizationRecord, O as listGitHubDeviceAuthorizationRecords, P as writeGitHubOAuthRecord, R as requestGitHubOAuthDeviceCode, S as deleteGitHubDeviceAuthorizationRecord, T as githubOAuthRecordName, _ as resolveManagedGitHubProfileRoot, d as removeManagedGitHubProfile, f as resolveConfiguredGitHubToolIdentity, g as resolveManagedGitHubProfileDir, j as parseGitHubOAuthRecord, l as preparePersonalGitHubPublicationIdentity, n as createManagedGitHubProfileId, p as resolveGitHubToolIdentityStatus, r as installManagedGitHubProfile, t as GitHubAccountMismatchError, u as refreshManagedGitHubProfile, w as githubDeviceRecordName, x as createGitHubOAuthRecord } from "./github-tool-identity-41SK6r8O.mjs";
import { i as readHiddenGitHubSecretInDatabase, n as deleteHiddenGitHubSecretInDatabase } from "./secret-store-hidden-github.kernel-HJgT6QTj.mjs";
import { t as createPendingPromiseTracker } from "./pending-promises-DNsYFS1E.mjs";
import { i as publishUserGitHubConnectionCommit, n as observeUserGitHubConnectionAuthority, r as observeUserGitHubProfileRetirement, t as invalidateUserGitHubConnectionAuthority } from "./user-github-connection-events-BNVmTSdt.mjs";
import { f as requirePendingUserGitHubConnection, n as disconnectUserGitHubConnectionInDatabase, s as registerUserGitHubConnectionSecrets, t as cancelUserGitHubAuthorizationInDatabase, u as isUserGitHubConnectionCommit } from "./user-github-connections.kernel-Cwmk1b8b.mjs";
import { t as applyAgentConfig } from "./agents.config-T4w0h7rr.mjs";
import { randomBytes, randomUUID } from "node:crypto";
import fs from "node:fs/promises";
import { isDeepStrictEqual } from "node:util";
//#region src/agents/github-oauth-records.native.ts
/** Retained only for the deprecated synchronous Gateway Plugin SDK service. */
function readGitHubDeviceAuthorizationRecordNative(e) {
const t = githubDeviceRecordName(e);
const n = withExistingOpenClawStateDatabaseReadOnly(({ db: e }) => readHiddenGitHubSecretInDatabase(e, t, Date.now()));
if (n !== void 0) registerSecretValueForRedaction(n);
return parseGitHubDeviceAuthorizationRecord(n, e);
}
function remove(e) {
try {
runOpenClawStateWriteTransaction(({ db: t }) => deleteHiddenGitHubSecretInDatabase(t, e), void 0, { operationLabel: "secrets.store.delete-hidden-github" });
} finally {
publishSecretStoreChange(resolveOpenClawStateSqlitePath(), [e]);
}
}
/** Retained only for the deprecated synchronous Gateway Plugin SDK service. */
function deleteGitHubDeviceAuthorizationRecordNative(e) {
remove(githubDeviceRecordName(e));
}
/** Retained only for the deprecated synchronous Gateway Plugin SDK service. */
function deleteGitHubOAuthRecordNative(e) {
remove(githubOAuthRecordName(e));
}
//#endregion
//#region src/gateway/github-cli-preflight.ts
const GITHUB_CLI_REQUIRED_MESSAGE = "GitHub CLI (`gh`) is required on the Gateway host. Install it and retry.";
var GitHubCliUnavailableError = class extends Error {
constructor() {
super(GITHUB_CLI_REQUIRED_MESSAGE);
this.name = "GitHubCliUnavailableError";
}
};
function assertGitHubCliAvailable(e = process.env) {
if (!resolveExecutablePath("gh", {
env: e,
useCache: false
})) throw new GitHubCliUnavailableError();
}
//#endregion
//#region src/gateway/github-oauth-device-flow.ts
/** Transport and scheduling are shared; the caller owns identity, TTL/CAS, and installation. */
async function startGitHubDeviceFlow(e) {
const t = Date.now();
const n = await requestGitHubOAuthDeviceCode({ signal: e });
if (n.expiresInSeconds > 900 || n.intervalSeconds > 60) throw new Error("GitHub device authorization timing is outside the supported bounds.");
const r = n.intervalSeconds * 1e3;
return {
deviceCode: n.deviceCode,
userCode: n.userCode,
verificationUri: n.verificationUri,
createdAtMs: t,
expiresAtMs: t + n.expiresInSeconds * 1e3,
pollIntervalMs: r,
nextPollAtMs: t + r
};
}
async function pollGitHubDeviceFlow(e, t) {
const n = Date.now();
if (e.expiresAtMs <= n) return {
kind: "terminal",
result: { status: "expired" }
};
if (n < e.nextPollAtMs) return {
kind: "waiting",
result: {
status: "pending",
retryAfterMs: e.nextPollAtMs - n
},
pollIntervalMs: e.pollIntervalMs,
nextPollAtMs: e.nextPollAtMs
};
let r;
try {
r = await pollGitHubOAuthDeviceToken({
deviceCode: e.deviceCode,
signal: t
});
} catch {
const t = Math.min(e.expiresAtMs, Date.now() + e.pollIntervalMs);
return {
kind: "waiting",
result: {
status: "network_error",
retryAfterMs: Math.max(1, t - Date.now())
},
pollIntervalMs: e.pollIntervalMs,
nextPollAtMs: t
};
}
if (r.status === "authorized") return {
kind: "authorized",
tokens: r.tokens
};
if (r.status === "authorization_pending" || r.status === "slow_down") {
const t = r.status === "slow_down" ? Math.min(6e4, Math.max(e.pollIntervalMs + 5e3, (r.intervalSeconds ?? 0) * 1e3)) : e.pollIntervalMs;
const n = Math.min(e.expiresAtMs, Date.now() + t);
return {
kind: "waiting",
pollIntervalMs: t,
nextPollAtMs: n,
result: {
status: r.status === "slow_down" ? "slow_down" : "pending",
retryAfterMs: Math.max(1, n - Date.now())
}
};
}
if (r.status === "access_denied") return {
kind: "terminal",
result: { status: "access_denied" }
};
if (r.status === "expired_token") return {
kind: "terminal",
result: { status: "expired" }
};
return {
kind: "terminal",
result: r.code === "incorrect_device_code" || r.code === "bad_verification_code" ? { status: "incorrect_device_code" } : {
status: "failed",
reason: "setup_failed"
}
};
}
//#endregion
//#region src/gateway/github-oauth-lifecycle-helpers.ts
const REFRESH_SKEW_MS = 6e5;
const MAINTENANCE_INTERVAL_MS = 6e4;
const SHUTDOWN_DRAIN_TIMEOUT_MS = 31e3;
function createGitHubOAuthInventoryReader(e) {
let t = true;
let n;
let r;
const invalidate = () => {
t = true;
e();
};
const i = subscribeSecretStoreChanges((e) => {
if (e.githubOAuth && e.databasePath === resolveOpenClawStateSqlitePath()) invalidate();
});
const a = registerOpenClawStateDatabaseAsyncResource({ async close() {
r = void 0;
invalidate();
} });
const o = registerOpenClawStateDatabaseLifecycleListener((e) => {
if (e.kind !== "opened" && e.path === resolveOpenClawStateSqlitePath()) {
r = void 0;
invalidate();
}
});
return {
async read() {
const e = resolveOpenClawStateSqlitePath();
if (r && !t && n === e) return r;
n = e;
t = false;
try {
r = await listGitHubAuthorizationRecords();
return r;
} catch (e) {
t = true;
throw e;
}
},
get dirty() {
return t;
},
close() {
i();
o();
a();
r = void 0;
}
};
}
/** Device authorization snapshots must never persist an App signing key. */
function captureGitHubOAuthAuthorizationIdentity(e, t) {
const n = resolveConfiguredGitHubToolIdentity({
config: e,
...t
});
if (n?.kind === "app-installation") throw new Error("Remove the selected GitHub App identity before connecting an OAuth identity.");
return structuredClone(n ?? null);
}
function identityStillSelected(e, t, n) {
const r = resolveConfiguredGitHubToolIdentity({
config: e,
...t
});
return isDeepStrictEqual(r ?? null, n);
}
function authorizationStillOwned(e, t) {
return identityStillSelected(e, t, t.expectedIdentity) && (t.scope === "system" || t.agentLifecycleBinding !== void 0 && matchesAgentLifecycleBinding(e, t.agentLifecycleBinding));
}
async function authorizationStillOwnedAsync(e, t) {
if (t.scope !== "system" && (!t.agentLifecycleBinding || !await matchesAgentLifecycleBindingAsync(e, t.agentLifecycleBinding))) return false;
return identityStillSelected(e(), t, t.expectedIdentity);
}
function configuredOAuthIdentities(e) {
return withAgentRosterFactsBatch(e, () => {
const t = [];
const n = e.tools?.github;
if (n?.kind === "oauth") t.push({
scope: "system",
agentId: "system",
identity: {
...n,
kind: "oauth"
}
});
for (const n of listAgentIds(e).toSorted()) {
const r = resolveAgentConfig(e, n)?.tools?.github;
if (r?.kind === "oauth") t.push({
scope: "agent",
agentId: n,
identity: {
...r,
kind: "oauth"
}
});
}
return t;
});
}
function nextGitHubOAuthMaintenanceAtMs(e, t) {
const n = t + MAINTENANCE_INTERVAL_MS;
let r = Number.POSITIVE_INFINITY;
for (const { record: i } of e.deviceRecords) if (i) r = Math.min(r, i.expiresAtMs > t ? i.expiresAtMs : n);
for (const { record: i } of e.oauthRecords) {
if (!i) continue;
if (i.pendingInitial || i.pendingRefresh || i.refreshFailure === "failed") r = Math.min(r, n);
else if (i.refreshFailure !== "expired" && i.refreshExpiresAtMs > t) r = Math.min(r, Math.max(n, i.accessExpiresAtMs - REFRESH_SKEW_MS));
}
return r;
}
async function assertInitialOAuthRecordCurrent(e, t, n, r) {
const i = await inspectGitHubOAuthRecord(t.profileId);
if (e() !== n || !isDeepStrictEqual(n, r) || i.state !== "valid" || !isDeepStrictEqual(i.record, t)) throw new Error("GitHub OAuth initial reconciliation was superseded.");
}
async function pendingInitialOAuthIdentitySelected(e, t) {
const n = resolveConfiguredGitHubToolIdentity({
config: e,
...t
});
const r = t.pendingInitial?.agentLifecycleBinding;
return (t.scope === "system" || r !== void 0 && await matchesAgentLifecycleBindingAsync(() => e, r)) && n?.profileId === t.profileId && n.kind === "oauth";
}
async function settleGitHubOAuthRefreshRecord(e, t) {
try {
await writeGitHubOAuthRecord(e, t);
} catch (t) {
const n = await inspectGitHubOAuthRecord(e.profileId);
if (n.state !== "valid" || !isDeepStrictEqual(n.record, parseGitHubOAuthRecord(JSON.stringify(e), e.profileId))) throw t;
}
}
function assertGitHubOAuthIdentitySelected(e, t) {
const n = resolveConfiguredGitHubToolIdentity({
config: e(),
...t
});
if (n?.kind !== "oauth" || n.profileId !== t.profileId) throw new Error("GitHub OAuth identity changed");
}
async function applyPendingGitHubOAuthRefresh(e, t, n) {
const r = resolveManagedGitHubProfileDir({
agentId: t.agentId,
scope: t.scope,
profileId: t.profileId
});
let i;
try {
i = await refreshManagedGitHubProfile({
profileDir: r,
token: n,
expectedAccountId: t.accountId,
assertCurrent: () => assertGitHubOAuthIdentitySelected(e, t)
});
} catch (e) {
if (e instanceof GitHubAccountMismatchError) await settleGitHubOAuthRefreshRecord({
...t,
pendingRefresh: void 0,
refreshFailure: "expired"
}, t);
return;
}
assertGitHubOAuthIdentitySelected(e, t);
await settleGitHubOAuthRefreshRecord({
...t,
login: i.login,
pendingRefresh: void 0,
refreshFailure: void 0
}, t);
}
//#endregion
//#region src/state/user-github-connections.ts
var UserGitHubConnectionAuthorityChangedError = class extends Error {
constructor() {
super("My GitHub connection changed; reload its status.");
}
};
/** Native adapter for the released synchronous personal OAuth service contract. */
function cancelUserGitHubAuthorizationSync(e, t, n) {
return runOpenClawStateWriteTransaction(({ db: r }) => {
n();
return Boolean(cancelUserGitHubAuthorizationInDatabase(r, e, t));
}, void 0, { operationLabel: "users.github.cancel" });
}
/** Native adapter for the released synchronous personal OAuth service contract. */
function disconnectUserGitHubConnectionSync(e, t) {
runOpenClawStateWriteTransaction(({ db: n }) => {
t();
disconnectUserGitHubConnectionInDatabase(n, e);
}, void 0, { operationLabel: "users.github.disconnect" });
}
async function readUserGitHubConnectionAsync(e) {
return (await prepareUserGitHubConnection(e)).read();
}
async function readCanonicalUserGitHubConnectionAsync(e) {
return (await executeExistingOpenClawStateRead({}, {
type: "userGitHubConnections.readCanonical",
input: { profile: e }
}, { current: true }))?.canonical;
}
const connectionReads = /* @__PURE__ */ new Map();
registerOpenClawStateDatabaseLifecycleListener((e) => {
if (e.kind === "opened") return;
for (const [t, n] of connectionReads) if (n.databasePath === e.path) {
n.valid = false;
connectionReads.delete(t);
}
});
observeUserGitHubConnectionAuthority(({ databasePath: e, changedOwners: t }) => {
for (const [n, r] of connectionReads) if (r.databasePath === e && t.includes(r.owner)) {
r.valid = false;
connectionReads.delete(n);
}
});
/** Retained effect guards consume the same worker snapshot until its owner publishes a write. */
async function prepareUserGitHubConnection(e) {
const t = captureOpenClawStateReadWorkerContext();
const n = JSON.stringify([t.admission.identity.key, e]);
const r = connectionReads.get(n);
if (r) {
const e = await r.prepared;
try {
e.read();
return e;
} catch {
r.valid = false;
connectionReads.delete(n);
}
}
const i = {
databasePath: t.admission.databasePath,
owner: e,
valid: true,
prepared: Promise.resolve({ read: () => void 0 })
};
connectionReads.set(n, i);
i.prepared = (async () => {
const n = await captureUserProfileAuthorityRead(t.admission);
const r = (await executeExistingOpenClawStateRead({
path: t.admission.databasePath,
env: t.environment
}, {
type: "userGitHubConnections.read",
input: { owner: e }
}, {
current: true,
context: t
}))?.connection;
const a = n.bind(e);
const o = r ? registerUserGitHubConnectionSecrets(r) : void 0;
const read = () => {
t.admission.assertCurrent();
if (!i.valid || !a?.()) throw new UserGitHubConnectionAuthorityChangedError();
return o ? structuredClone(o) : void 0;
};
read();
return { read };
})();
try {
return await i.prepared;
} catch (e) {
if (connectionReads.get(n) === i) connectionReads.delete(n);
throw e;
}
}
async function listUserGitHubConnectionsAsync() {
return ((await executeExistingOpenClawStateRead({}, {
type: "userGitHubConnections.list",
input: void 0
}, { current: true }))?.connections ?? []).map(({ owner: e, connection: t }) => ({
owner: e,
connection: registerUserGitHubConnectionSecrets(t)
}));
}
async function write(e, t, n) {
const r = captureOpenClawStateWorkerContext();
const i = structuredClone(t);
const a = /* @__PURE__ */ new Set([i.owner]);
try {
return await runOpenClawStateWorkerOperation(r, (t) => t.execute({
type: e,
input: i
}), {
assertCurrent: n,
createAdmission: () => {
const e = createSqliteWorkerOperationAdmission((e, t) => {
r.admission.assertCurrent();
n();
if (e.stage === "commit") {
if (!isUserGitHubConnectionCommit(e.facts)) throw new Error("Personal GitHub connection returned invalid commit facts");
for (const t of e.facts.changedOwners) a.add(t);
}
t();
});
observeSqliteWorkerCommittedFacts(e, ({ facts: e }) => {
if (!isUserGitHubConnectionCommit(e)) throw new Error("Personal GitHub connection returned an invalid commit receipt");
publishUserGitHubConnectionCommit(r.admission.databasePath, e);
});
return {
admission: e,
nativeLocations: [r.admission.databasePath]
};
}
});
} catch (e) {
invalidateUserGitHubConnectionAuthority(r.admission.databasePath, [...a]);
throw e;
}
}
async function mutateUserGitHubConnection(e, t, n) {
const r = await write("userGitHubConnections.mutate", {
owner: e,
mutation: t
}, n);
return r ? registerUserGitHubConnectionSecrets(r) : void 0;
}
/** An exact remote rotation follows profile transfer; its receipt grants no external authority. */
async function updateUserGitHubRefreshAsync(e, t) {
return await write("userGitHubConnections.refresh", e, t);
}
//#endregion
//#region src/gateway/github-personal-status.ts
function projectPending(e) {
return {
requestId: e.requestId,
userCode: e.userCode,
verificationUri: e.verificationUri,
expiresInMs: Math.max(0, e.expiresAtMs - Date.now()),
pollAfterMs: Math.max(1, Math.min(6e4, e.nextPollAtMs - Date.now()))
};
}
const statusAuthorities = /* @__PURE__ */ new WeakMap();
function unavailablePersonalGitHubStatus() {
return {
state: "unavailable",
generation: null,
account: null,
accessExpiresAtMs: null,
refreshState: "failed",
pending: null
};
}
async function personalGitHubStatusAsync(e) {
e.assertCurrent();
try {
const t = await prepareUserGitHubConnection(e.owner);
e.assertCurrent();
const n = projectPersonalGitHubStatus(t.read());
statusAuthorities.set(n, t.read);
return n;
} catch {
e.assertCurrent();
return unavailablePersonalGitHubStatus();
}
}
function projectPersonalGitHubStatus(e) {
const t = e?.selection;
const n = t?.kind === "connected" ? t : void 0;
return {
state: n ? "connected" : "disconnected",
generation: e?.generation ?? null,
account: n ? {
accountId: n.accountId,
login: n.login
} : null,
accessExpiresAtMs: n?.accessExpiresAtMs ?? null,
refreshState: !n ? "not_applicable" : n.refresh ? "refreshing" : n.refreshFailure ?? (n.refreshExpiresAtMs <= Date.now() ? "expired" : "available"),
pending: e?.pending?.kind === "device" && e.pending.expiresAtMs > Date.now() ? projectPending(e.pending) : null
};
}
function revalidatePersonalGitHubStatus(e, t) {
e.assertCurrent();
statusAuthorities.get(t)?.();
return t;
}
async function resolvePersonalGitHubStatus(e) {
e.assertCurrent();
let t;
try {
t = await prepareUserGitHubConnection(e.owner);
} catch {
e.assertCurrent();
return unavailablePersonalGitHubStatus();
}
e.assertCurrent();
const n = t.read();
const r = projectPersonalGitHubStatus(n);
statusAuthorities.set(r, t.read);
if (n?.selection.kind !== "connected") return r;
const assertCurrent = () => {
revalidatePersonalGitHubStatus(e, r);
};
try {
const i = await preparePersonalGitHubPublicationIdentity({
profileId: n.selection.profileId,
accountId: n.selection.accountId,
assertCurrent,
forDisplay: true
});
const a = {
...revalidatePersonalGitHubStatus(e, r),
...i.stale ? { stale: true } : {}
};
statusAuthorities.set(a, t.read);
return a;
} catch {
const n = {
...revalidatePersonalGitHubStatus(e, r),
state: "unavailable"
};
statusAuthorities.set(n, t.read);
return n;
}
}
//#endregion
//#region src/gateway/github-publication-deprecation.ts
const replacements = {
confirmPersonal: "confirmPersonalV2",
deferClaimPreparation: "deferClaimPreparationAsync",
deferOrphanedRequests: "deferOrphanedRequestsAsync",
listUnreportedResults: "listUnreportedResultsAsync",
markReported: "markReportedAsync",
"personal.cancelAuthorization": "personal.cancelAuthorizationAsync",
"personal.disconnect": "personal.disconnectAsync",
personalStatus: "personalStatusAsync",
requestForClaim: "requestForClaimV2",
requestForSession: "requestForSessionV2",
requestPersonalForSession: "requestPersonalForSessionV2"
};
/** Keep the shared publication compatibility family and replacement pairs in one place. */
function warnGitHubPublicationDeprecation(e) {
warnPluginSdkDeprecation({
family: "github-publication",
method: e,
replacement: replacements[e]
});
}
//#endregion
//#region src/gateway/github-personal-oauth.ts
const profileDir = (e) => resolveManagedGitHubProfileDir({
agentId: "",
scope: "personal",
profileId: e
});
const withProfileLease = (e, t) => withOpenClawStateLeaseAsync({
scope: "personal-github-profile",
key: e,
leaseMs: 6e4,
waitMs: 3e4,
heartbeat: "worker"
}, captureOpenClawStateWorkerContext(), t);
function needsRefresh(e) {
return Boolean(e.refresh?.tokens) || e.refreshFailure !== "expired" && e.refreshExpiresAtMs > Date.now() && (Boolean(e.refresh) || e.accessExpiresAtMs <= Date.now() + 6e5);
}
/** Personal adapters share device transport and profile materialization with System/agent OAuth. */
function createPersonalGitHubOAuthLifecycle() {
const e = new AbortController();
const t = /* @__PURE__ */ new Map();
const n = /* @__PURE__ */ new Map();
const r = /* @__PURE__ */ new Map();
const i = /* @__PURE__ */ new Set();
const a = createPendingPromiseTracker(i);
const mutateUserGitHubConnection$1 = (...e) => a(mutateUserGitHubConnection(...e));
const updateUserGitHubRefreshAsync$1 = (...e) => a(updateUserGitHubRefreshAsync(...e));
const o = /* @__PURE__ */ new Set();
const s = /* @__PURE__ */ new Map();
let c = false;
let l = false;
let u;
const d = observeUserGitHubConnectionAuthority(({ databasePath: e }) => {
if (u?.databasePath === e) u.current = false;
});
const profileIsReferenced = async (e) => (await listUserGitHubConnectionsAsync()).some(({ connection: t }) => t.selection.kind === "connected" && t.selection.profileId === e || t.pending?.kind === "device" && t.pending.candidate?.profileId === e);
const assertRunning = () => {
if (c) throw new Error("GitHub authorization is stopping.");
};
const retire = async (e) => {
await getOrCreatePromise(s, e, () => withProfileLease(e, async (t) => {
if (await profileIsReferenced(e)) return;
await t.assertOwned();
t.assertCurrent();
await removeManagedGitHubProfile(profileDir(e));
}).then(() => {
o.delete(e);
}, () => {
o.add(e);
}), { evictOnSettled: true });
};
const f = observeUserGitHubProfileRetirement((e) => {
for (const t of e) {
o.add(t);
retire(t);
}
});
const guard = (e) => {
assertRunning();
e.assertCurrent();
};
const install = async (e, t, n) => {
const r = n.candidate;
if (!r) throw new Error("My GitHub authorization has no candidate.");
try {
const i = await prepareUserGitHubConnection(e.owner);
const assertCurrent = () => {
guard(e);
const a = requirePendingUserGitHubConnection(i.read(), t, n.requestId);
if (a.pending.kind !== "device" || a.pending.candidate?.profileId !== r.profileId) throw new Error("My GitHub authorization changed.");
};
await withProfileLease(r.profileId, async (i) => {
const assertInstall = () => {
i.assertCurrent();
assertCurrent();
};
await i.assertOwned();
assertInstall();
await removeManagedGitHubProfile(profileDir(r.profileId));
await i.assertOwned();
assertInstall();
await installManagedGitHubProfile({
profileDir: profileDir(r.profileId),
token: r.tokens.accessToken,
assertCurrent: assertInstall,
prepareEffect: () => i.assertOwned(),
commitConfig: async (a) => {
await i.assertOwned();
await mutateUserGitHubConnection$1(e.owner, {
kind: "connect",
generation: t,
requestId: n.requestId,
profileId: r.profileId,
accountId: a.accountId,
login: a.login
}, () => {
i.assertCurrent();
guard(e);
});
}
});
});
guard(e);
return {
status: "success",
personal: await personalGitHubStatusAsync(e)
};
} catch {
guard(e);
return {
status: "failed",
reason: "setup_failed"
};
}
};
const pollOnce = async (t, n, r) => {
const i = n.pending;
if (!i || i.requestId !== r || i.expiresAtMs <= Date.now()) return { status: "expired" };
if (i.kind === "starting") return {
status: "pending",
retryAfterMs: 1e3
};
if (i.candidate) return await install(t, n.generation, i);
const a = await pollGitHubDeviceFlow(i, e.signal);
guard(t);
let o;
try {
const e = await mutateUserGitHubConnection$1(t.owner, {
kind: "poll",
generation: n.generation,
requestId: r,
deviceCode: i.deviceCode,
result: a.kind === "terminal" ? { kind: "terminal" } : a.kind === "authorized" ? {
kind: "candidate",
candidate: {
receivedAtMs: Date.now(),
profileId: createManagedGitHubProfileId(),
tokens: a.tokens
}
} : {
kind: "pending",
pollIntervalMs: a.pollIntervalMs,
nextPollAtMs: a.nextPollAtMs
}
}, () => guard(t));
if (!e) throw new Error("My GitHub authorization changed.");
o = e;
} catch {
guard(t);
return {
status: "failed",
reason: "identity_changed"
};
}
if (a.kind !== "authorized") return a.result;
if (o.pending?.kind !== "device") throw new Error("My GitHub authorization changed.");
return await install(t, o.generation, o.pending);
};
const persistRotation = (e) => updateUserGitHubRefreshAsync$1({
owner: e.owner,
profileId: e.profileId,
operationId: e.operationId,
result: {
kind: "rotated",
tokens: e.tokens,
receivedAtMs: e.receivedAtMs
}
}, () => {});
const materializeRefresh = async (e, t, n, r) => {
const i = await readCanonicalUserGitHubConnectionAsync(e);
if (!i) throw new Error("My GitHub refresh ownership changed.");
const a = await prepareUserGitHubConnection(i.owner);
const readExact = () => {
r.assertCurrent();
const e = a.read()?.selection;
if (e?.kind !== "connected" || e.profileId !== t || e.refresh?.operationId !== n || !e.refresh.tokens) throw new Error("My GitHub refresh ownership changed.");
return e;
};
await r.assertOwned();
const o = readExact();
const s = await refreshManagedGitHubProfile({
profileDir: profileDir(t),
token: o.refresh.tokens.accessToken,
expectedAccountId: o.accountId,
assertCurrent: () => {
readExact();
},
prepareEffect: () => r.assertOwned()
});
await r.assertOwned();
await updateUserGitHubRefreshAsync$1({
owner: e,
profileId: t,
operationId: n,
result: {
kind: "materialized",
login: s.login
}
}, r.assertCurrent);
};
const refresh = async (e) => {
assertRunning();
const t = (await readUserGitHubConnectionAsync(e))?.selection;
assertRunning();
if (t?.kind !== "connected") return;
const i = t.profileId;
if (!r.has(i) && !needsRefresh(t)) return;
await getOrCreatePromise(n, i, () => withProfileLease(i, async (t) => {
const n = r.get(i);
if (n) {
if (!await persistRotation(n)) {
r.delete(i);
return;
}
r.delete(i);
}
const a = await readUserGitHubConnectionAsync(e);
const o = a?.selection;
if (!a || o?.kind !== "connected" || o.profileId !== i || !needsRefresh(o)) return;
if (o.refresh?.tokens) {
await materializeRefresh(e, i, o.refresh.operationId, t);
return;
}
if (o.refresh) return;
const s = randomUUID();
await t.assertOwned();
await mutateUserGitHubConnection$1(e, {
kind: "beginRefresh",
generation: a.generation,
profileId: i,
operationId: s
}, t.assertCurrent);
t.assertCurrent();
let c;
try {
const n = await prepareUserGitHubConnection(e).catch((e) => {
throw createOAuthRefreshError("My GitHub refresh preparation failed before dispatch.", {
version: 1,
phase: "before-dispatch",
outcome: "not-attempted",
recovery: {
kind: "later",
evidence: "dispatch-not-started"
}
}, { cause: e });
});
c = await refreshGitHubOAuthToken({
refreshToken: o.refreshToken,
assertCurrent: async () => {
await t.assertOwned();
t.assertCurrent();
const e = n.read()?.selection;
if (e?.kind !== "connected" || e.profileId !== i || e.refresh?.operationId !== s) throw new Error("My GitHub refresh ownership changed.");
}
});
} catch (n) {
await t.assertOwned();
await updateUserGitHubRefreshAsync$1({
owner: e,
profileId: i,
operationId: s,
result: {
kind: "failed",
failure: "failed",
restore: isRecoverableOAuthRefreshFailure(n)
}
}, t.assertCurrent);
return;
}
if (c.status === "error") {
await t.assertOwned();
await updateUserGitHubRefreshAsync$1({
owner: e,
profileId: i,
operationId: s,
result: {
kind: "failed",
failure: c.code === "bad_refresh_token" ? "expired" : "failed",
restore: isRecoverableOAuthRefreshFailure(c.failure)
}
}, t.assertCurrent);
return;
}
const l = {
owner: e,
profileId: i,
operationId: s,
tokens: c.tokens,
receivedAtMs: Date.now()
};
r.set(i, l);
if (!await persistRotation(l)) {
r.delete(i);
return;
}
r.delete(i);
await materializeRefresh(e, i, s, t);
}), { evictOnSettled: true });
};
let p;
const runMaintenance = async () => {
if (!l) {
const e = resolveManagedGitHubProfileRoot({
agentId: "",
scope: "personal"
});
const t = await fs.readdir(e, { withFileTypes: true }).catch((e) => {
if (hasErrnoCode(e, "ENOENT")) return [];
throw e;
});
for (const e of t) if (e.isDirectory() && /^ghp_[a-f0-9]{32}$/u.test(e.name) && !await profileIsReferenced(e.name)) o.add(e.name);
l = true;
}
for (const e of r.values()) try {
await persistRotation(e);
r.delete(e.profileId);
} catch {}
for (const e of o) await retire(e);
const e = resolveOpenClawStateSqlitePath();
if (u?.databasePath === e && u.current && u.empty) return;
const t = {
databasePath: e,
current: true,
empty: false
};
u = t;
const n = await listUserGitHubConnectionsAsync();
t.empty = n.length === 0;
for (const { owner: e, connection: t } of n) {
if (c) break;
if (t.pending && t.pending.expiresAtMs <= Date.now()) await mutateUserGitHubConnection$1(e, {
kind: "expire",
nowMs: Date.now()
}, assertRunning);
try {
await refresh(e);
} catch {}
}
};
return {
status: resolvePersonalGitHubStatus,
revalidateStatus: revalidatePersonalGitHubStatus,
async startAuthorization(t) {
guard(t);
assertGitHubCliAvailable();
const n = randomUUID();
const r = Date.now();
const i = await mutateUserGitHubConnection$1(t.owner, {
kind: "start",
requestId: n,
createdAtMs: r,
expiresAtMs: r + 9e5
}, () => guard(t));
if (!i) throw new Error("My GitHub authorization changed.");
guard(t);
const a = await startGitHubDeviceFlow(e.signal);
guard(t);
if (a.expiresAtMs <= Date.now()) throw new Error("My GitHub authorization expired while starting; start again.");
const o = await mutateUserGitHubConnection$1(t.owner, {
kind: "device",
generation: i.generation,
requestId: n,
device: {
...a,
kind: "device",
requestId: n
}
}, () => guard(t));
if (o?.pending?.kind !== "device") throw new Error("My GitHub authorization changed.");
return projectPending(o.pending);
},
async pollAuthorization(e, n) {
guard(e);
const r = await readUserGitHubConnectionAsync(e.owner);
guard(e);
if (r?.pending?.requestId !== n) return { status: "expired" };
const i = `${e.owner}\0${n}`;
const a = await getOrCreatePromise(t, i, () => pollOnce(e, r, n), { evictOnSettled: true });
guard(e);
return a;
},
/** @deprecated Use cancelAuthorizationAsync; final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
cancelAuthorization(e, t) {
warnGitHubPublicationDeprecation("personal.cancelAuthorization");
return cancelUserGitHubAuthorizationSync(e.owner, t, () => guard(e));
},
async cancelAuthorizationAsync(e, t) {
guard(e);
return Boolean(await mutateUserGitHubConnection$1(e.owner, {
kind: "cancel",
requestId: t
}, () => guard(e)));
},
/** @deprecated Use disconnectAsync; final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
disconnect(e) {
warnGitHubPublicationDeprecation("personal.disconnect");
disconnectUserGitHubConnectionSync(e.owner, () => guard(e));
clearNativeGitHubTokenCache();
},
async disconnectAsync(e) {
guard(e);
await mutateUserGitHubConnection$1(e.owner, { kind: "disconnect" }, () => guard(e));
clearNativeGitHubTokenCache();
},
refresh,
maintain() {
if (c) return Promise.resolve();
p ??= runMaintenance().finally(() => {
p = void 0;
});
return p;
},
async stop() {
c = true;
e.abort();
f();
d();
await Promise.allSettled([
...p ? [p] : [],
...i,
...t.values(),
...n.values(),
...s.values()
]);
for (const e of r.values()) try {
await persistRotation(e);
} catch {}
}
};
}
//#endregion
//#region src/gateway/github-tool-identity-config.ts
async function updateGitHubToolIdentityConfig(e) {
return (await mutateConfigFileWithRetry({
afterWrite: { mode: "auto" },
mutate: async (t) => {
if (e.scope === "system") {
if (e.expectedIdentity !== void 0 && !isDeepStrictEqual(t.tools?.github ?? null, e.expectedIdentity)) throw new Error("GitHub identity changed while setup was in progress.");
t.tools ??= {};
if (e.identity) t.tools.github = e.identity;
else unsetConfigValueAtPath(t, ["tools", "github"]);
return;
}
if (e.agentLifecycleBinding && (!await matchesAgentLifecycleBindingAsync(() => t, e.agentLifecycleBinding) || !matchesAgentLifecycleBinding(t, e.agentLifecycleBinding))) throw new Error("Agent changed while GitHub setup was in progress.");
let n = resolveMutableAgentEntry(t, e.agentId);
if (e.agentLifecycleBinding && !n) throw new Error("Agent changed while GitHub setup was in progress.");
if (e.expectedIdentity !== void 0 && !isDeepStrictEqual(n?.tools?.github ?? null, e.expectedIdentity)) throw new Error("GitHub identity changed while setup was in progress.");
if (!n && e.identity && !e.agentLifecycleBinding) {
Object.assign(t, applyAgentConfig(t, { agentId: e.agentId }));
n = resolveMutableAgentEntry(t, e.agentId);
}
if (!n) return;
n.tools ??= {};
if (e.identity) n.tools.github = n.tools.github?.allowInSandbox === void 0 ? e.identity : {
...e.identity,
allowInSandbox: n.tools.github.allowInSandbox
};
else unsetConfigValueAtPath(n, ["tools", "github"]);
}
})).nextConfig;
}
//#endregion
//#region src/gateway/github-oauth-lifecycle.ts
let activeLifecycle;
function installActiveGitHubOAuthLifecycle(e) {
activeLifecycle = e;
return () => {
if (activeLifecycle === e) activeLifecycle = void 0;
};
}
async function requestCurrentGitHubOAuthRefresh(e) {
await activeLifecycle?.refreshEffectiveIdentity(e);
}
async function requestCurrentPersonalGitHubRefresh(e) {
if (!activeLifecycle) throw new Error("My GitHub lifecycle is unavailable; retry after Gateway startup.");
await activeLifecycle.personal.refresh(e);
}
function createGitHubOAuthLifecycle(e) {
const t = createPersonalGitHubOAuthLifecycle();
const n = new AbortController();
const r = /* @__PURE__ */ new Map();
const i = /* @__PURE__ */ new Set();
const a = /* @__PURE__ */ new Map();
const o = /* @__PURE__ */ new Map();
const s = /* @__PURE__ */ new Set();
let c;
let l;
let u = false;
let d = Number.POSITIVE_INFINITY;
const f = createGitHubOAuthInventoryReader(() => {
scheduleMaintenance(Date.now() + MAINTENANCE_INTERVAL_MS);
});
const p = registerRuntimeConfigWriteListener(() => {
scheduleMaintenance(Date.now());
});
function scheduleMaintenance(e) {
if (!u && Number.isFinite(e)) l?.schedule({
id: "maintenance:github-oauth",
atMs: e,
mode: "earliest",
run: maintain
});
}
const warnMaintenanceError = (t) => e.warn(`GitHub OAuth maintenance failed; will retry: ${formatErrorMessage(t)}`);
const queueDeviceCleanup = async (e) => {
try {
await deleteGitHubDeviceAuthorizationRecord(e);
s.delete(e);
} catch {
s.add(e);
}
};
const queueOAuthCleanup = async (e) => {
clearNativeGitHubTokenCache();
try {
await deleteGitHubOAuthRecord(e);
} catch {}
};
const status = (t, n) => resolveGitHubToolIdentityStatus({
config: e.getConfig(),
agentId: t,
selectedScope: n
});
const installDeviceTokens = async (t, n) => {
if (!await authorizationStillOwnedAsync(e.getConfig, t)) {
await queueDeviceCleanup(t.requestId);
return {
status: "failed",
reason: "identity_changed"
};
}
const r = e.getConfig();
const a = createManagedGitHubProfileId();
const o = resolveManagedGitHubProfileDir({
agentId: t.agentId,
scope: t.scope,
profileId: a
});
let s = r;
let c;
const completeAuthorization = async (e) => {
await queueDeviceCleanup(t.requestId);
if (t.expectedIdentity?.kind === "oauth") await queueOAuthCleanup(t.expectedIdentity.profileId);
return {
status: "success",
githubStatus: await resolveGitHubToolIdentityStatus({
config: e,
agentId: t.agentId,
selectedScope: t.scope
})
};
};
try {
await installManagedGitHubProfile({
profileDir: o,
token: n.accessToken,
retainProfileOnCommitFailure: true,
commitConfig: async (r) => {
const o = await readGitHubDeviceAuthorizationRecord(t.requestId);
if (!o || o.createdAtMs !== t.createdAtMs || o.deviceCode !== t.deviceCode || !isDeepStrictEqual(o.expectedIdentity, t.expectedIdentity) || !authorizationStillOwned(e.getConfig(), t)) throw new Error("GitHub authorization is no longer pending.");
i.add(t.requestId);
const l = {
requestId: t.requestId,
scope: t.scope,
agentId: t.agentId,
expectedIdentity: t.expectedIdentity,
...t.agentLifecycleBinding ? { agentLifecycleBinding: t.agentLifecycleBinding } : {}
};
const u = createGitHubOAuthRecord({
profileId: a,
scope: t.scope,
agentId: t.agentId,
account: r,
tokens: n,
now: Date.now(),
pendingInitial: l
});
await writeGitHubOAuthRecord(u);
c = u;
const d = {
profileId: a,
kind: "oauth",
gitAuthor: t.expectedIdentity?.gitAuthor ? structuredClone(t.expectedIdentity.gitAuthor) : {
name: r.login,
email: `${r.accountId}+${r.login}@users.noreply.github.com`
}
};
s = await updateGitHubToolIdentityConfig({
scope: t.scope,
agentId: t.agentId,
identity: d,
expectedIdentity: t.expectedIdentity,
...t.agentLifecycleBinding ? { agentLifecycleBinding: t.agentLifecycleBinding } : {}
});
const f = await inspectGitHubOAuthRecord(a);
if (f.state !== "valid" || !f.record.pendingInitial) throw new Error("GitHub OAuth initial record is unavailable.");
const { pendingInitial: p, ...m } = f.record;
await writeGitHubOAuthRecord(m);
c = m;
}
});
} catch {
if (c) try {
const n = e.getConfig();
const r = structuredClone(n);
const i = await e.getPersistedConfig?.();
if (!i) throw new Error("Authoritative persisted config is unavailable.");
await assertInitialOAuthRecordCurrent(e.getConfig, c, n, r);
const o = resolveConfiguredGitHubToolIdentity({
config: i,
scope: t.scope,
agentId: t.agentId
});
if (o?.profileId === a && o.kind === "oauth") {
if (c.pendingInitial) await writeGitHubOAuthRecord({
...c,
pendingInitial: void 0
});
return await completeAuthorization(i);
}
} catch {
await queueDeviceCleanup(t.requestId);
return {
status: "failed",
reason: "setup_failed"
};
}
if (c) await queueOAuthCleanup(a);
await removeManagedGitHubProfile(o).catch(() => void 0);
await queueDeviceCleanup(t.requestId);
return {
status: "failed",
reason: "setup_failed"
};
} finally {
i.delete(t.requestId);
}
return await completeAuthorization(s);
};
const pollOnce = async (t) => {
const r = await readGitHubDeviceAuthorizationRecord(t);
const i = Date.now();
if (!r || r.expiresAtMs <= i) {
await queueDeviceCleanup(t);
return { status: "expired" };
}
if (!await authorizationStillOwnedAsync(e.getConfig, r)) {
await queueDeviceCleanup(t);
return {
status: "failed",
reason: "identity_changed"
};
}
const a = await pollGitHubDeviceFlow(r, n.signal);
const o = await readGitHubDeviceAuthorizationRecord(t);
if (!o) return { status: "expired" };
if (o.deviceCode !== r.deviceCode || o.createdAtMs !== r.createdAtMs || !isDeepStrictEqual(o.expectedIdentity, r.expectedIdentity)) {
await queueDeviceCleanup(t);
return {
status: "failed",
reason: "identity_changed"
};
}
if (a.kind === "authorized") return await installDeviceTokens(o, a.tokens);
if (a.kind === "waiting") await writeGitHubDeviceAuthorizationRecord({
...o,
pollIntervalMs: a.pollIntervalMs,
nextPollAtMs: a.nextPollAtMs
});
else await queueDeviceCleanup(t);
return a.result;
};
const refreshOne = async (t) => {
const n = t.identity.profileId;
const r = await inspectGitHubOAuthRecord(n);
if (r.state !== "valid") return;
const i = r.record;
if (i.pendingInitial || i.refreshClaim) return;
const a = Date.now();
if (i.refreshFailure === "expired" || i.refreshExpiresAtMs <= a) return;
if (!i.pendingRefresh && i.accessExpiresAtMs > a + 6e5) return;
const s = resolveConfiguredGitHubToolIdentity({
config: e.getConfig(),
...i
});
if (s?.kind !== "oauth" || s.profileId !== n) return;
const c = {
...i,
refreshClaim: randomUUID()
};
await settleGitHubOAuthRefreshRecord(c, i);
let l;
try {
l = await refreshGitHubOAuthToken({
refreshToken: i.refreshToken,
assertCurrent: async () => {
const t = await inspectGitHubOAuthRecord(n);
assertGitHubOAuthIdentitySelected(e.getConfig, i);
if (t.state !== "valid" || !isDeepStrictEqual(t.record, c)) throw new Error("GitHub OAuth refresh ownership changed before dispatch.");
}
});
} catch (e) {
await settleGitHubOAuthRefreshRecord({
...c,
pendingRefresh: void 0,
refreshFailure: "failed",
...isRecoverableOAuthRefreshFailure(e) ? { refreshClaim: void 0 } : {}
}, c);
return;
}
if (l.status === "error") {
const e = l.code === "bad_refresh_token" ? "expired" : "failed";
await settleGitHubOAuthRefreshRecord({
...c,
pendingRefresh: void 0,
refreshFailure: e,
...isRecoverableOAuthRefreshFailure(l.failure) ? { refreshClaim: void 0 } : {}
}, c);
return;
}
const u = {
...i,
refreshToken: l.tokens.refreshToken,
accessExpiresAtMs: a + l.tokens.expiresInSeconds * 1e3,
refreshExpiresAtMs: a + l.tokens.refreshTokenExpiresInSeconds * 1e3,
scopes: l.tokens.scopes,
pendingRefresh: true,
pendingInitial: void 0,
refreshFailure: void 0
};
o.set(n, {
record: u,
expected: c,
accessToken: l.tokens.accessToken
});
try {
await settleGitHubOAuthRefreshRecord(u, c);
} catch {
return;
}
o.delete(n);
await applyPendingGitHubOAuthRefresh(e.getConfig, u, l.tokens.accessToken);
};
const requestRefresh = (t) => getOrCreatePromise(a, t.identity.profileId, () => refreshOne(t).catch((t) => {
e.warn(`GitHub OAuth refresh failed; will retry: ${formatErrorMessage(t)}`);
}), { evictOnSettled: true });
const reconcileRecords = async () => {
const t = await f.read();
const { deviceRecords: n, oauthRecords: r } = t;
d = nextGitHubOAuthMaintenanceAtMs(t, Date.now());
for (const { requestId: e, record: t } of n) if (!t || t.expiresAtMs <= Date.now()) await queueDeviceCleanup(e);
for (const { profileId: t, record: n } of r) {
if (!n) {
await queueOAuthCleanup(t);
continue;
}
if (n.pendingInitial) {
if (i.has(n.pendingInitial.requestId)) continue;
let r;
try {
const t = e.getConfig();
const a = structuredClone(t);
const o = await e.getPersistedConfig?.();
if (!o) continue;
await assertInitialOAuthRecordCurrent(e.getConfig, n, t, a);
if (i.has(n.pendingInitial.requestId)) continue;
r = o;
} catch {
continue;
}
if (await pendingInitialOAuthIdentitySelected(r, n)) {
await writeGitHubOAuthRecord({
...n,
pendingInitial: void 0
});
if (n.pendingInitial.expectedIdentity?.kind === "oauth") await queueOAuthCleanup(n.pendingInitial.expectedIdentity.profileId);
continue;
}
await queueOAuthCleanup(t);
await removeManagedGitHubProfile(resolveManagedGitHubProfileDir({
agentId: n.agentId,
scope: n.scope,
profileId: t
})).catch(() => void 0);
continue;
}
const r = resolveConfiguredGitHubToolIdentity({
config: e.getConfig(),
...n
});
if (r?.profileId !== t || r.kind !== "oauth") {
await queueOAuthCleanup(t);
continue;
}
if (n.pendingRefresh && !u) await requestRefresh({
scope: n.scope,
agentId: n.agentId,
identity: {
...r,
kind: "oauth"
}
});
}
};
const runMaintenance = async () => {
for (const e of s) await queueDeviceCleanup(e);
for (const [t, n] of [...o].toSorted(([e], [t]) => e.localeCompare(t))) try {
await settleGitHubOAuthRefreshRecord(n.record, n.expected);
o.delete(t);
await applyPendingGitHubOAuthRefresh(e.getConfig, n.record, n.accessToken);
} catch {}
await reconcileRecords();
for (const t of configuredOAuthIdentities(e.getConfig())) {
if (u) break;
await requestRefresh(t);
}
};
const maintain = () => {
if (u && !c) return Promise.resolve();
c ??= runMaintenance().catch((e) => {
d = Date.now() + MAINTENANCE_INTERVAL_MS;
warnMaintenanceError(e);
}).finally(() => {
c = void 0;
if (f.dirty || s.size > 0 || o.size > 0) d = Math.min(d, Date.now() + MAINTENANCE_INTERVAL_MS);
scheduleMaintenance(Math.max(Date.now() + 1, d));
});
return c;
};
return {
personal: t,
startAuthorization: async (t) => {
if (u) throw new Error("GitHub authorization lifecycle is stopping.");
assertGitHubCliAvailable();
const r = captureGitHubOAuthAuthorizationIdentity(e.getConfig(), t);
const i = t.scope === "agent" ? await captureAgentLifecycleBinding(e.getConfig, t.agentId) : void 0;
if (t.scope === "agent" && !i) throw new Error("GitHub authorization requires an active agent.");
if (!identityStillSelected(e.getConfig(), t, r)) throw new Error("GitHub identity changed while authorization was starting.");
n.signal.throwIfAborted();
const a = await startGitHubDeviceFlow(n.signal);
if (!identityStillSelected(e.getConfig(), t, r) || i !== void 0 && !await matchesAgentLifecycleBindingAsync(e.getConfig, i)) throw new Error("GitHub identity changed while authorization was starting.");
for (const e of await listGitHubDeviceAuthorizationRecords()) if (e.record?.scope === t.scope && e.record.agentId === t.agentId) await queueDeviceCleanup(e.requestId);
const o = `github-device-${randomBytes(16).toString("hex")}`;
await writeGitHubDeviceAuthorizationRecord({
version: 1,
requestId: o,
...a,
agentId: t.agentId,
scope: t.scope,
expectedIdentity: r,
...i ? { agentLifecycleBinding: i } : {}
});
return {
requestId: o,
userCode: a.userCode,
verificationUri: a.verificationUri,
expiresInMs: Math.max(0, a.expiresAtMs - Date.now()),
pollAfterMs: a.pollIntervalMs
};
},
pollAuthorization: (e) => getOrCreatePromise(r, e, () => pollOnce(e), { evictOnSettled: true }),
/** @deprecated Use cancelAuthorizationAsync; final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
cancelAuthorization(e) {
warnPluginSdkDeprecation({
family: "github-publication",
method: "cancelAuthorization",
replacement: "cancelAuthorizationAsync"
});
if (i.has(e)) return false;
const t = readGitHubDeviceAuthorizationRecordNative(e) !== void 0;
try {
deleteGitHubDeviceAuthorizationRecordNative(e);
s.delete(e);
} catch {
s.add(e);
}
return t;
},
cancelAuthorizationAsync: async (e) => {
const t = await readGitHubDeviceAuthorizationRecord(e) !== void 0;
if (i.has(e)) return false;
await queueDeviceCleanup(e);
return t;
},
status,
/** @deprecated Use retireProfileAsync; final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
retireProfile(e) {
warnPluginSdkDeprecation({
family: "github-publication",
method: "retireProfile",
replacement: "retireProfileAsync"
});
clearNativeGitHubTokenCache();
try {
deleteGitHubOAuthRecordNative(e);
} catch {}
},
retireProfileAsync: queueOAuthCleanup,
refreshEffectiveIdentity: async (t) => {
if (u) return;
const n = e.getConfig();
const r = resolveAgentConfig(n, t)?.tools?.github;
const i = r ?? n.tools?.github;
if (i?.kind !== "oauth") return;
await requestRefresh({
scope: r ? "agent" : "system",
agentId: t,
identity: {
...i,
kind: "oauth"
}
});
},
maintain: async () => {
await Promise.all([maintain(), t.maintain()]).catch(warnMaintenanceError);
},
start: () => {
if (u || l) return;
l = e.scheduler.scope();
scheduleMaintenance(Date.now());
l.schedule({
id: "maintenance:github-personal-oauth",
delayMs: 0,
everyMs: MAINTENANCE_INTERVAL_MS,
run: () => t.maintain().catch(warnMaintenanceError)
});
},
stop: async () => {
clearGitHubCredentialVerificationCache();
u = true;
f.close();
p();
l?.beginClose();
n.abort();
const e = (async () => {
await Promise.allSettled([
t.stop(),
l?.stop(),
c,
...r.values(),
...a.values()
]);
if (o.size > 0) await runMaintenance();
})();
await settlesWithin(e, SHUTDOWN_DRAIN_TIMEOUT_MS);
}
};
}
//#endregion
export { updateGitHubToolIdentityConfig as a, prepareUserGitHubConnection as c, requestCurrentPersonalGitHubRefresh as i, GitHubCliUnavailableError as l, installActiveGitHubOAuthLifecycle as n, personalGitHubStatusAsync as o, requestCurrentGitHubOAuthRefresh as r, UserGitHubConnectionAuthorityChangedError as s, createGitHubOAuthLifecycle as t };