UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

216 lines (215 loc) • 6.78 kB
import { t as truncateUtf8Prefix } from "./utf8-truncate-BH7Ecfuh.mjs"; import { createHash } from "node:crypto"; import { spawn } from "node:child_process"; //#region src/infra/github-issue.ts /** Prepares and submits bounded issue content to openclaw/openclaw. */ const GITHUB_REPOSITORY = "github.com/openclaw/openclaw"; const GITHUB_REPOSITORY_ISSUES_API = "repos/openclaw/openclaw/issues"; const GITHUB_ISSUE_CREATE_TIMEOUT_MS = 3e4; const GITHUB_OUTPUT_MAX_BYTES = 1048576; const GITHUB_ISSUE_BODY_MAX_BYTES = 2e4; const GITHUB_ISSUE_TITLE_MAX_BYTES = 512; const GITHUB_PREFILL_URL_MAX_BYTES = 8e3; const GITHUB_BODY_TRUNCATED_SUFFIX = "\n\n...<truncated>"; const GITHUB_MARKER_RE = /^openclaw-report:[a-f0-9]{64}$/u; const GITHUB_AUTH_ARGS = [ "auth", "status", "--active", "--hostname", "github.com" ]; const inflightSubmissions = /* @__PURE__ */ new Map(); function boundUtf8(e, t) { if (Buffer.byteLength(e, "utf8") <= t) return e; const n = Buffer.byteLength(GITHUB_BODY_TRUNCATED_SUFFIX, "utf8"); return `${truncateUtf8Prefix(e, Math.max(0, t - n))}${GITHUB_BODY_TRUNCATED_SUFFIX}`; } /** Builds an exact browser fallback when its encoded request stays within a safe bound. */ function prepareGithubIssueBrowserFallback(e, t) { const n = `https://github.com/openclaw/openclaw/issues/new?${new URLSearchParams({ body: t, title: e }).toString()}`; if (Buffer.byteLength(n, "utf8") > GITHUB_PREFILL_URL_MAX_BYTES) return { reason: "url-too-long", status: "unavailable" }; return { status: "available", url: n }; } /** Bounds sanitized content and adds the stable marker used for reconciliation. */ function prepareGithubIssue(e) { const t = boundUtf8(e.title, GITHUB_ISSUE_TITLE_MAX_BYTES); const n = boundUtf8(e.body, GITHUB_ISSUE_BODY_MAX_BYTES); const r = `openclaw-report:${createHash("sha256").update(t).update("\0").update(n).digest("hex")}`; const i = `\n\n<!-- ${r} -->\n`; const a = `${boundUtf8(n.trimEnd(), GITHUB_ISSUE_BODY_MAX_BYTES - Buffer.byteLength(i, "utf8"))}${i}`; return { body: a, browserFallback: prepareGithubIssueBrowserFallback(t, a), marker: r, title: t }; } function browserFallbackResult(e, t) { return e.browserFallback.status === "available" ? { reason: t, status: "browser-fallback", url: e.browserFallback.url } : { cause: t, reason: "fallback-url-too-long", status: "fallback-unavailable" }; } function createdIssueUrl(e) { if (typeof e !== "string") return; try { const t = new URL(e); if (t.origin === "https://github.com" && !t.search && !t.hash && /^\/openclaw\/openclaw\/issues\/\d+$/u.test(t.pathname)) return t.toString(); } catch {} } /** Looks up one exact prepared issue without creating or mutating remote state. */ async function reconcileGithubIssue(e, t = runGithubCli, n = {}) { if (!GITHUB_MARKER_RE.test(e.marker)) return { status: "unavailable" }; await n.beforeIssueLookup?.(); const r = await t([ "issue", "list", "--repo", GITHUB_REPOSITORY, "--state", "all", "--search", `"${e.marker}" in:body`, "--limit", "100", "--json", "url,title,body" ], { input: "" }); if (r.errorCode || r.status !== 0) return { status: "unavailable" }; let i; try { i = JSON.parse(r.stdout.toString("utf8")); } catch { return { status: "unavailable" }; } if (!Array.isArray(i)) return { status: "unavailable" }; for (const t of i) { if (typeof t !== "object" || t === null || !("body" in t) || t.body !== e.body || !("title" in t) || t.title !== e.title || !("url" in t)) continue; const n = createdIssueUrl(t.url); if (n) return { status: "created", url: n }; } return { status: "not-found" }; } async function submitGithubIssueOnce(e, t, n) { const r = await t(GITHUB_AUTH_ARGS, { input: "" }); await n.afterAuthPreflight?.(); if (r.errorCode || r.status !== 0) return browserFallbackResult(e, r.errorCode === "ENOENT" || r.errorCode === "EACCES" || r.errorCode === "EPERM" ? "cli-unavailable" : "authentication-unavailable"); (await n.beforeIssueCreate?.())?.(); const i = await t([ "api", "--hostname", "github.com", "--include", "--method", "POST", GITHUB_REPOSITORY_ISSUES_API, "--input", "-", "--jq", ".html_url" ], { input: JSON.stringify({ body: e.body, title: e.title }) }); const a = [...i.stdout.toString("utf8").matchAll(/^HTTP\/\S+\s+(\d{3})(?:\s|$)/gmu)]; const o = Number(a.at(-1)?.[1]); const s = Number.isInteger(o) ? o : void 0; const c = s === void 0 || s === 201 ? createdIssueUrl(i.stdout.toString("utf8").trim().split(/\r?\n/u).at(-1)) : void 0; if (c) return { status: "created", url: c }; if (!i.started && i.errorCode) return browserFallbackResult(e, "transport-unavailable"); if (s !== void 0 && s >= 400 && s < 500 && s !== 408 && s !== 499) return browserFallbackResult(e, s === 401 ? "authentication-unavailable" : "transport-unavailable"); const l = await reconcileGithubIssue(e, t, n).catch(() => ({ status: "unavailable" })); return l.status === "created" ? l : { reason: "creation-outcome-unknown", status: "outcome-unknown" }; } /** Coalesces unguarded callers; guarded callers own a durable pre-create reservation. */ function submitGithubIssue(e, t = runGithubCli, n = {}) { if (n.beforeIssueCreate) return submitGithubIssueOnce(e, t, n); const r = inflightSubmissions.get(e.marker); if (r) return r; const i = submitGithubIssueOnce(e, t, n).finally(() => { if (inflightSubmissions.get(e.marker) === i) inflightSubmissions.delete(e.marker); }); inflightSubmissions.set(e.marker, i); return i; } async function runGithubCli(e, t) { if (process.env.VITEST || false) return { errorCode: "EPERM", started: false, status: null, stdout: Buffer.alloc(0) }; return await new Promise((n) => { const r = spawn("gh", [...e], { stdio: [ "pipe", "pipe", "ignore" ] }); const i = []; let a = 0; let o; let s = false; let c = false; const settle = (e) => { if (c) return; c = true; clearTimeout(l); n({ ...o ? { errorCode: o } : {}, started: s, status: e, stdout: Buffer.concat(i) }); }; r.stdout.on("data", (e) => { const t = GITHUB_OUTPUT_MAX_BYTES - a; if (t > 0) { i.push(e.subarray(0, t)); a += Math.min(e.byteLength, t); } }); r.on("spawn", () => { s = true; }); r.on("error", (e) => { o = e.code ?? "SPAWN_FAILED"; }); r.on("close", settle); r.stdin.on("error", () => {}); const l = setTimeout(() => { o = "ETIMEDOUT"; r.kill("SIGKILL"); r.stdin.destroy(); r.stdout.destroy(); r.unref(); settle(null); }, GITHUB_ISSUE_CREATE_TIMEOUT_MS).unref(); r.stdin.end(t.input); }); } //#endregion export { submitGithubIssue as i, prepareGithubIssue as n, reconcileGithubIssue as r, browserFallbackResult as t };